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.

269517 lines
8.0MB

  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 <Carbon/Carbon.h>
  579. #include <sys/dir.h>
  580. #include <sys/socket.h>
  581. #endif
  582. #include <sys/sysctl.h>
  583. #include <sys/stat.h>
  584. #include <sys/param.h>
  585. #include <sys/mount.h>
  586. #include <fnmatch.h>
  587. #include <utime.h>
  588. #include <dlfcn.h>
  589. #include <ifaddrs.h>
  590. #include <net/if_dl.h>
  591. #include <mach/mach_time.h>
  592. #if MACOS_10_4_OR_EARLIER
  593. #include <GLUT/glut.h>
  594. #endif
  595. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  596. /********* End of inlined file: juce_mac_NativeIncludes.h *********/
  597. #else
  598. #error "Unknown platform!"
  599. #endif
  600. //==============================================================================
  601. #define DONT_SET_USING_JUCE_NAMESPACE 1
  602. #include "juce_amalgamated.h"
  603. #define NO_DUMMY_DECL
  604. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  605. #pragma warning (disable: 4309 4305)
  606. #endif
  607. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  608. BEGIN_JUCE_NAMESPACE
  609. /********* Start of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  610. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  611. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  612. /**
  613. Creates a floating carbon window that can be used to hold a carbon UI.
  614. This is a handy class that's designed to be inlined where needed, e.g.
  615. in the audio plugin hosting code.
  616. */
  617. class CarbonViewWrapperComponent : public Component,
  618. public ComponentMovementWatcher,
  619. public Timer
  620. {
  621. public:
  622. CarbonViewWrapperComponent()
  623. : ComponentMovementWatcher (this),
  624. wrapperWindow (0),
  625. embeddedView (0),
  626. recursiveResize (false)
  627. {
  628. }
  629. virtual ~CarbonViewWrapperComponent()
  630. {
  631. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  632. }
  633. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  634. virtual void removeView (HIViewRef embeddedView) = 0;
  635. virtual void mouseDown (int x, int y) {}
  636. virtual void paint() {}
  637. virtual bool getEmbeddedViewSize (int& w, int& h)
  638. {
  639. if (embeddedView == 0)
  640. return false;
  641. HIRect bounds;
  642. HIViewGetBounds (embeddedView, &bounds);
  643. w = jmax (1, roundFloatToInt (bounds.size.width));
  644. h = jmax (1, roundFloatToInt (bounds.size.height));
  645. return true;
  646. }
  647. void createWindow()
  648. {
  649. if (wrapperWindow == 0)
  650. {
  651. Rect r;
  652. r.left = getScreenX();
  653. r.top = getScreenY();
  654. r.right = r.left + getWidth();
  655. r.bottom = r.top + getHeight();
  656. CreateNewWindow (kDocumentWindowClass,
  657. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  658. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  659. &r, &wrapperWindow);
  660. jassert (wrapperWindow != 0);
  661. if (wrapperWindow == 0)
  662. return;
  663. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  664. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  665. [ownerWindow addChildWindow: carbonWindow
  666. ordered: NSWindowAbove];
  667. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  668. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  669. { kEventClassWindow, kEventWindowHandleDeactivate } };
  670. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  671. InstallWindowEventHandler (wrapperWindow, upp,
  672. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  673. windowEventTypes, this, &eventHandlerRef);
  674. setOurSizeToEmbeddedViewSize();
  675. setEmbeddedWindowToOurSize();
  676. creationTime = Time::getCurrentTime();
  677. }
  678. }
  679. void deleteWindow()
  680. {
  681. removeView (embeddedView);
  682. embeddedView = 0;
  683. if (wrapperWindow != 0)
  684. {
  685. RemoveEventHandler (eventHandlerRef);
  686. DisposeWindow (wrapperWindow);
  687. wrapperWindow = 0;
  688. }
  689. }
  690. void setOurSizeToEmbeddedViewSize()
  691. {
  692. int w, h;
  693. if (getEmbeddedViewSize (w, h))
  694. {
  695. if (w != getWidth() || h != getHeight())
  696. {
  697. startTimer (50);
  698. setSize (w, h);
  699. if (getParentComponent() != 0)
  700. getParentComponent()->setSize (w, h);
  701. }
  702. else
  703. {
  704. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  705. }
  706. }
  707. else
  708. {
  709. stopTimer();
  710. }
  711. }
  712. void setEmbeddedWindowToOurSize()
  713. {
  714. if (! recursiveResize)
  715. {
  716. recursiveResize = true;
  717. if (embeddedView != 0)
  718. {
  719. HIRect r;
  720. r.origin.x = 0;
  721. r.origin.y = 0;
  722. r.size.width = (float) getWidth();
  723. r.size.height = (float) getHeight();
  724. HIViewSetFrame (embeddedView, &r);
  725. }
  726. if (wrapperWindow != 0)
  727. {
  728. Rect wr;
  729. wr.left = getScreenX();
  730. wr.top = getScreenY();
  731. wr.right = wr.left + getWidth();
  732. wr.bottom = wr.top + getHeight();
  733. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  734. ShowWindow (wrapperWindow);
  735. }
  736. recursiveResize = false;
  737. }
  738. }
  739. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  740. {
  741. setEmbeddedWindowToOurSize();
  742. }
  743. void componentPeerChanged()
  744. {
  745. deleteWindow();
  746. createWindow();
  747. }
  748. void componentVisibilityChanged (Component&)
  749. {
  750. if (isShowing())
  751. createWindow();
  752. else
  753. deleteWindow();
  754. setEmbeddedWindowToOurSize();
  755. }
  756. static void recursiveHIViewRepaint (HIViewRef view) throw()
  757. {
  758. HIViewSetNeedsDisplay (view, true);
  759. HIViewRef child = HIViewGetFirstSubview (view);
  760. while (child != 0)
  761. {
  762. recursiveHIViewRepaint (child);
  763. child = HIViewGetNextView (child);
  764. }
  765. }
  766. void timerCallback()
  767. {
  768. setOurSizeToEmbeddedViewSize();
  769. // To avoid strange overpainting problems when the UI is first opened, we'll
  770. // repaint it a few times during the first second that it's on-screen..
  771. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  772. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  773. }
  774. OSStatus carbonEventHandler (EventHandlerCallRef nextHandlerRef,
  775. EventRef event)
  776. {
  777. switch (GetEventKind (event))
  778. {
  779. case kEventWindowHandleDeactivate:
  780. ActivateWindow (wrapperWindow, TRUE);
  781. break;
  782. case kEventWindowGetClickActivation:
  783. {
  784. getTopLevelComponent()->toFront (false);
  785. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  786. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  787. sizeof (ClickActivationResult), &howToHandleClick);
  788. HIViewSetNeedsDisplay (embeddedView, true);
  789. }
  790. break;
  791. }
  792. return noErr;
  793. }
  794. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  795. EventRef event, void* userData)
  796. {
  797. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  798. }
  799. protected:
  800. WindowRef wrapperWindow;
  801. HIViewRef embeddedView;
  802. bool recursiveResize;
  803. Time creationTime;
  804. EventHandlerRef eventHandlerRef;
  805. };
  806. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  807. /********* End of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  808. END_JUCE_NAMESPACE
  809. #endif
  810. #define JUCE_AMALGAMATED_TEMPLATE 1
  811. //==============================================================================
  812. /********* Start of inlined file: juce_FileLogger.cpp *********/
  813. BEGIN_JUCE_NAMESPACE
  814. FileLogger::FileLogger (const File& logFile_,
  815. const String& welcomeMessage,
  816. const int maxInitialFileSizeBytes)
  817. : logFile (logFile_)
  818. {
  819. if (maxInitialFileSizeBytes >= 0)
  820. trimFileSize (maxInitialFileSizeBytes);
  821. if (! logFile_.exists())
  822. {
  823. // do this so that the parent directories get created..
  824. logFile_.create();
  825. }
  826. logStream = logFile_.createOutputStream (256);
  827. jassert (logStream != 0);
  828. String welcome;
  829. welcome << "\r\n**********************************************************\r\n"
  830. << welcomeMessage
  831. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  832. << "\r\n";
  833. logMessage (welcome);
  834. }
  835. FileLogger::~FileLogger()
  836. {
  837. deleteAndZero (logStream);
  838. }
  839. void FileLogger::logMessage (const String& message)
  840. {
  841. if (logStream != 0)
  842. {
  843. Logger::outputDebugString (message);
  844. const ScopedLock sl (logLock);
  845. (*logStream) << message << T("\r\n");
  846. logStream->flush();
  847. }
  848. }
  849. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  850. {
  851. if (maxFileSizeBytes <= 0)
  852. {
  853. logFile.deleteFile();
  854. }
  855. else
  856. {
  857. const int64 fileSize = logFile.getSize();
  858. if (fileSize > maxFileSizeBytes)
  859. {
  860. FileInputStream* const in = logFile.createInputStream();
  861. jassert (in != 0);
  862. if (in != 0)
  863. {
  864. in->setPosition (fileSize - maxFileSizeBytes);
  865. String content;
  866. {
  867. MemoryBlock contentToSave;
  868. contentToSave.setSize (maxFileSizeBytes + 4);
  869. contentToSave.fillWith (0);
  870. in->read (contentToSave.getData(), maxFileSizeBytes);
  871. delete in;
  872. content = contentToSave.toString();
  873. }
  874. int newStart = 0;
  875. while (newStart < fileSize
  876. && content[newStart] != '\n'
  877. && content[newStart] != '\r')
  878. ++newStart;
  879. logFile.deleteFile();
  880. logFile.appendText (content.substring (newStart), false, false);
  881. }
  882. }
  883. }
  884. }
  885. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  886. const String& logFileName,
  887. const String& welcomeMessage,
  888. const int maxInitialFileSizeBytes)
  889. {
  890. #if JUCE_MAC
  891. File logFile ("~/Library/Logs");
  892. logFile = logFile.getChildFile (logFileName);
  893. #else
  894. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  895. if (logFile.isDirectory())
  896. {
  897. logFile = logFile.getChildFile (logFileSubDirectoryName)
  898. .getChildFile (logFileName);
  899. }
  900. #endif
  901. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  902. }
  903. END_JUCE_NAMESPACE
  904. /********* End of inlined file: juce_FileLogger.cpp *********/
  905. /********* Start of inlined file: juce_Logger.cpp *********/
  906. BEGIN_JUCE_NAMESPACE
  907. Logger::Logger()
  908. {
  909. }
  910. Logger::~Logger()
  911. {
  912. }
  913. static Logger* currentLogger = 0;
  914. void Logger::setCurrentLogger (Logger* const newLogger,
  915. const bool deleteOldLogger)
  916. {
  917. Logger* const oldLogger = currentLogger;
  918. currentLogger = newLogger;
  919. if (deleteOldLogger && (oldLogger != 0))
  920. delete oldLogger;
  921. }
  922. void Logger::writeToLog (const String& message)
  923. {
  924. if (currentLogger != 0)
  925. currentLogger->logMessage (message);
  926. else
  927. outputDebugString (message);
  928. }
  929. #if JUCE_LOG_ASSERTIONS
  930. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  931. {
  932. String m ("JUCE Assertion failure in ");
  933. m << filename << ", line " << lineNum;
  934. Logger::writeToLog (m);
  935. }
  936. #endif
  937. END_JUCE_NAMESPACE
  938. /********* End of inlined file: juce_Logger.cpp *********/
  939. /********* Start of inlined file: juce_Random.cpp *********/
  940. BEGIN_JUCE_NAMESPACE
  941. Random::Random (const int64 seedValue) throw()
  942. : seed (seedValue)
  943. {
  944. }
  945. Random::~Random() throw()
  946. {
  947. }
  948. void Random::setSeed (const int64 newSeed) throw()
  949. {
  950. seed = newSeed;
  951. }
  952. void Random::setSeedRandomly()
  953. {
  954. Random r1 (Time::getMillisecondCounter());
  955. Random r2 (Time::getHighResolutionTicks());
  956. Random r3 (Time::getHighResolutionTicksPerSecond());
  957. Random r4 (Time::currentTimeMillis());
  958. setSeed (nextInt64() ^ r1.nextInt64() ^ r2.nextInt64()
  959. ^ r3.nextInt64() ^ r4.nextInt64());
  960. }
  961. int Random::nextInt() throw()
  962. {
  963. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  964. return (int) (seed >> 16);
  965. }
  966. int Random::nextInt (const int maxValue) throw()
  967. {
  968. jassert (maxValue > 0);
  969. return (nextInt() & 0x7fffffff) % maxValue;
  970. }
  971. int64 Random::nextInt64() throw()
  972. {
  973. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  974. }
  975. bool Random::nextBool() throw()
  976. {
  977. return (nextInt() & 0x80000000) != 0;
  978. }
  979. float Random::nextFloat() throw()
  980. {
  981. return ((uint32) nextInt()) / (float) 0xffffffff;
  982. }
  983. double Random::nextDouble() throw()
  984. {
  985. return ((uint32) nextInt()) / (double) 0xffffffff;
  986. }
  987. const BitArray Random::nextLargeNumber (const BitArray& maximumValue) throw()
  988. {
  989. BitArray n;
  990. do
  991. {
  992. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  993. }
  994. while (n.compare (maximumValue) >= 0);
  995. return n;
  996. }
  997. void Random::fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw()
  998. {
  999. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1000. while ((startBit & 31) != 0 && numBits > 0)
  1001. {
  1002. arrayToChange.setBit (startBit++, nextBool());
  1003. --numBits;
  1004. }
  1005. while (numBits >= 32)
  1006. {
  1007. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1008. startBit += 32;
  1009. numBits -= 32;
  1010. }
  1011. while (--numBits >= 0)
  1012. arrayToChange.setBit (startBit + numBits, nextBool());
  1013. }
  1014. Random& Random::getSystemRandom() throw()
  1015. {
  1016. static Random sysRand (1);
  1017. return sysRand;
  1018. }
  1019. END_JUCE_NAMESPACE
  1020. /********* End of inlined file: juce_Random.cpp *********/
  1021. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  1022. BEGIN_JUCE_NAMESPACE
  1023. RelativeTime::RelativeTime (const double seconds_) throw()
  1024. : seconds (seconds_)
  1025. {
  1026. }
  1027. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1028. : seconds (other.seconds)
  1029. {
  1030. }
  1031. RelativeTime::~RelativeTime() throw()
  1032. {
  1033. }
  1034. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1035. {
  1036. return RelativeTime (milliseconds * 0.001);
  1037. }
  1038. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1039. {
  1040. return RelativeTime (milliseconds * 0.001);
  1041. }
  1042. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1043. {
  1044. return RelativeTime (numberOfMinutes * 60.0);
  1045. }
  1046. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1047. {
  1048. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1049. }
  1050. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1051. {
  1052. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1053. }
  1054. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1055. {
  1056. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1057. }
  1058. int64 RelativeTime::inMilliseconds() const throw()
  1059. {
  1060. return (int64)(seconds * 1000.0);
  1061. }
  1062. double RelativeTime::inMinutes() const throw()
  1063. {
  1064. return seconds / 60.0;
  1065. }
  1066. double RelativeTime::inHours() const throw()
  1067. {
  1068. return seconds / (60.0 * 60.0);
  1069. }
  1070. double RelativeTime::inDays() const throw()
  1071. {
  1072. return seconds / (60.0 * 60.0 * 24.0);
  1073. }
  1074. double RelativeTime::inWeeks() const throw()
  1075. {
  1076. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1077. }
  1078. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1079. {
  1080. if (seconds < 0.001 && seconds > -0.001)
  1081. return returnValueForZeroTime;
  1082. String result;
  1083. if (seconds < 0)
  1084. result = T("-");
  1085. int fieldsShown = 0;
  1086. int n = abs ((int) inWeeks());
  1087. if (n > 0)
  1088. {
  1089. result << n << ((n == 1) ? TRANS(" week ")
  1090. : TRANS(" weeks "));
  1091. ++fieldsShown;
  1092. }
  1093. n = abs ((int) inDays()) % 7;
  1094. if (n > 0)
  1095. {
  1096. result << n << ((n == 1) ? TRANS(" day ")
  1097. : TRANS(" days "));
  1098. ++fieldsShown;
  1099. }
  1100. if (fieldsShown < 2)
  1101. {
  1102. n = abs ((int) inHours()) % 24;
  1103. if (n > 0)
  1104. {
  1105. result << n << ((n == 1) ? TRANS(" hr ")
  1106. : TRANS(" hrs "));
  1107. ++fieldsShown;
  1108. }
  1109. if (fieldsShown < 2)
  1110. {
  1111. n = abs ((int) inMinutes()) % 60;
  1112. if (n > 0)
  1113. {
  1114. result << n << ((n == 1) ? TRANS(" min ")
  1115. : TRANS(" mins "));
  1116. ++fieldsShown;
  1117. }
  1118. if (fieldsShown < 2)
  1119. {
  1120. n = abs ((int) inSeconds()) % 60;
  1121. if (n > 0)
  1122. {
  1123. result << n << ((n == 1) ? TRANS(" sec ")
  1124. : TRANS(" secs "));
  1125. ++fieldsShown;
  1126. }
  1127. if (fieldsShown < 1)
  1128. {
  1129. n = abs ((int) inMilliseconds()) % 1000;
  1130. if (n > 0)
  1131. {
  1132. result << n << TRANS(" ms");
  1133. ++fieldsShown;
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. return result.trimEnd();
  1140. }
  1141. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1142. {
  1143. seconds = other.seconds;
  1144. return *this;
  1145. }
  1146. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1147. {
  1148. return seconds == other.seconds;
  1149. }
  1150. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1151. {
  1152. return seconds != other.seconds;
  1153. }
  1154. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1155. {
  1156. return seconds > other.seconds;
  1157. }
  1158. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1159. {
  1160. return seconds < other.seconds;
  1161. }
  1162. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1163. {
  1164. return seconds >= other.seconds;
  1165. }
  1166. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1167. {
  1168. return seconds <= other.seconds;
  1169. }
  1170. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1171. {
  1172. return RelativeTime (seconds + timeToAdd.seconds);
  1173. }
  1174. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1175. {
  1176. return RelativeTime (seconds - timeToSubtract.seconds);
  1177. }
  1178. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1179. {
  1180. return RelativeTime (seconds + secondsToAdd);
  1181. }
  1182. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1183. {
  1184. return RelativeTime (seconds - secondsToSubtract);
  1185. }
  1186. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1187. {
  1188. seconds += timeToAdd.seconds;
  1189. return *this;
  1190. }
  1191. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1192. {
  1193. seconds -= timeToSubtract.seconds;
  1194. return *this;
  1195. }
  1196. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1197. {
  1198. seconds += secondsToAdd;
  1199. return *this;
  1200. }
  1201. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1202. {
  1203. seconds -= secondsToSubtract;
  1204. return *this;
  1205. }
  1206. END_JUCE_NAMESPACE
  1207. /********* End of inlined file: juce_RelativeTime.cpp *********/
  1208. /********* Start of inlined file: juce_SystemStats.cpp *********/
  1209. BEGIN_JUCE_NAMESPACE
  1210. void juce_initialiseStrings();
  1211. const String SystemStats::getJUCEVersion() throw()
  1212. {
  1213. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  1214. }
  1215. static bool juceInitialisedNonGUI = false;
  1216. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1217. {
  1218. if (! juceInitialisedNonGUI)
  1219. {
  1220. #if JUCE_MAC || JUCE_IPHONE
  1221. const ScopedAutoReleasePool pool;
  1222. #endif
  1223. #ifdef JUCE_DEBUG
  1224. // Some simple test code to keep an eye on things and make sure these functions
  1225. // work ok on all platforms. Let me know if any of these assertions fail!
  1226. int n = 1;
  1227. atomicIncrement (n);
  1228. jassert (atomicIncrementAndReturn (n) == 3);
  1229. atomicDecrement (n);
  1230. jassert (atomicDecrementAndReturn (n) == 1);
  1231. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  1232. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  1233. SystemStats* nullPointer = 0;
  1234. juce_free (nullPointer);
  1235. delete[] nullPointer;
  1236. delete nullPointer;
  1237. #endif
  1238. // Now the real initialisation..
  1239. juceInitialisedNonGUI = true;
  1240. DBG (SystemStats::getJUCEVersion());
  1241. juce_initialiseStrings();
  1242. SystemStats::initialiseStats();
  1243. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1244. }
  1245. }
  1246. #if JUCE_WINDOWS
  1247. // This is imported from the sockets code..
  1248. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1249. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1250. #endif
  1251. #if JUCE_DEBUG
  1252. extern void juce_CheckForDanglingStreams();
  1253. #endif
  1254. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1255. {
  1256. if (juceInitialisedNonGUI)
  1257. {
  1258. #if JUCE_MAC || JUCE_IPHONE
  1259. const ScopedAutoReleasePool pool;
  1260. #endif
  1261. #if JUCE_WINDOWS
  1262. // need to shut down sockets if they were used..
  1263. if (juce_CloseWin32SocketLib != 0)
  1264. (*juce_CloseWin32SocketLib)();
  1265. #endif
  1266. LocalisedStrings::setCurrentMappings (0);
  1267. Thread::stopAllThreads (3000);
  1268. #if JUCE_DEBUG
  1269. juce_CheckForDanglingStreams();
  1270. #endif
  1271. juceInitialisedNonGUI = false;
  1272. }
  1273. }
  1274. #ifdef JUCE_DLL
  1275. void* juce_Malloc (const int size)
  1276. {
  1277. return malloc (size);
  1278. }
  1279. void* juce_Calloc (const int size)
  1280. {
  1281. return calloc (1, size);
  1282. }
  1283. void* juce_Realloc (void* const block, const int size)
  1284. {
  1285. return realloc (block, size);
  1286. }
  1287. void juce_Free (void* const block)
  1288. {
  1289. free (block);
  1290. }
  1291. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1292. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1293. {
  1294. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1295. }
  1296. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1297. {
  1298. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1299. }
  1300. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1301. {
  1302. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1303. }
  1304. void juce_DebugFree (void* const block)
  1305. {
  1306. _free_dbg (block, _NORMAL_BLOCK);
  1307. }
  1308. #endif
  1309. #endif
  1310. END_JUCE_NAMESPACE
  1311. /********* End of inlined file: juce_SystemStats.cpp *********/
  1312. /********* Start of inlined file: juce_Time.cpp *********/
  1313. #ifdef _MSC_VER
  1314. #pragma warning (disable: 4514)
  1315. #pragma warning (push)
  1316. #endif
  1317. #ifndef JUCE_WINDOWS
  1318. #include <sys/time.h>
  1319. #else
  1320. #include <ctime>
  1321. #endif
  1322. #include <sys/timeb.h>
  1323. BEGIN_JUCE_NAMESPACE
  1324. #ifdef _MSC_VER
  1325. #pragma warning (pop)
  1326. #ifdef _INC_TIME_INL
  1327. #define USE_NEW_SECURE_TIME_FNS
  1328. #endif
  1329. #endif
  1330. static void millisToLocal (const int64 millis, struct tm& result) throw()
  1331. {
  1332. const int64 seconds = millis / 1000;
  1333. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1334. {
  1335. // use extended maths for dates beyond 1970 to 2037..
  1336. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1337. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1338. const int days = (int) (jdm / literal64bit (86400));
  1339. const int a = 32044 + days;
  1340. const int b = (4 * a + 3) / 146097;
  1341. const int c = a - (b * 146097) / 4;
  1342. const int d = (4 * c + 3) / 1461;
  1343. const int e = c - (d * 1461) / 4;
  1344. const int m = (5 * e + 2) / 153;
  1345. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1346. result.tm_mon = m + 2 - 12 * (m / 10);
  1347. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1348. result.tm_wday = (days + 1) % 7;
  1349. result.tm_yday = -1;
  1350. int t = (int) (jdm % literal64bit (86400));
  1351. result.tm_hour = t / 3600;
  1352. t %= 3600;
  1353. result.tm_min = t / 60;
  1354. result.tm_sec = t % 60;
  1355. result.tm_isdst = -1;
  1356. }
  1357. else
  1358. {
  1359. time_t now = (time_t) (seconds);
  1360. #if JUCE_WINDOWS
  1361. #ifdef USE_NEW_SECURE_TIME_FNS
  1362. if (now >= 0 && now <= 0x793406fff)
  1363. localtime_s (&result, &now);
  1364. else
  1365. zeromem (&result, sizeof (result));
  1366. #else
  1367. result = *localtime (&now);
  1368. #endif
  1369. #else
  1370. // more thread-safe
  1371. localtime_r (&now, &result);
  1372. #endif
  1373. }
  1374. }
  1375. Time::Time() throw()
  1376. : millisSinceEpoch (0)
  1377. {
  1378. }
  1379. Time::Time (const Time& other) throw()
  1380. : millisSinceEpoch (other.millisSinceEpoch)
  1381. {
  1382. }
  1383. Time::Time (const int64 ms) throw()
  1384. : millisSinceEpoch (ms)
  1385. {
  1386. }
  1387. Time::Time (const int year,
  1388. const int month,
  1389. const int day,
  1390. const int hours,
  1391. const int minutes,
  1392. const int seconds,
  1393. const int milliseconds,
  1394. const bool useLocalTime) throw()
  1395. {
  1396. jassert (year > 100); // year must be a 4-digit version
  1397. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1398. {
  1399. // use extended maths for dates beyond 1970 to 2037..
  1400. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1401. : 0;
  1402. const int a = (13 - month) / 12;
  1403. const int y = year + 4800 - a;
  1404. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1405. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1406. - 32045;
  1407. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1408. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1409. + milliseconds;
  1410. }
  1411. else
  1412. {
  1413. struct tm t;
  1414. t.tm_year = year - 1900;
  1415. t.tm_mon = month;
  1416. t.tm_mday = day;
  1417. t.tm_hour = hours;
  1418. t.tm_min = minutes;
  1419. t.tm_sec = seconds;
  1420. t.tm_isdst = -1;
  1421. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1422. if (millisSinceEpoch < 0)
  1423. millisSinceEpoch = 0;
  1424. else
  1425. millisSinceEpoch += milliseconds;
  1426. }
  1427. }
  1428. Time::~Time() throw()
  1429. {
  1430. }
  1431. const Time& Time::operator= (const Time& other) throw()
  1432. {
  1433. millisSinceEpoch = other.millisSinceEpoch;
  1434. return *this;
  1435. }
  1436. int64 Time::currentTimeMillis() throw()
  1437. {
  1438. static uint32 lastCounterResult = 0xffffffff;
  1439. static int64 correction = 0;
  1440. const uint32 now = getMillisecondCounter();
  1441. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1442. if (now < lastCounterResult)
  1443. {
  1444. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1445. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1446. {
  1447. // get the time once using normal library calls, and store the difference needed to
  1448. // turn the millisecond counter into a real time.
  1449. #if JUCE_WINDOWS
  1450. struct _timeb t;
  1451. #ifdef USE_NEW_SECURE_TIME_FNS
  1452. _ftime_s (&t);
  1453. #else
  1454. _ftime (&t);
  1455. #endif
  1456. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1457. #else
  1458. struct timeval tv;
  1459. struct timezone tz;
  1460. gettimeofday (&tv, &tz);
  1461. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1462. #endif
  1463. }
  1464. }
  1465. lastCounterResult = now;
  1466. return correction + now;
  1467. }
  1468. uint32 juce_millisecondsSinceStartup() throw();
  1469. static uint32 lastMSCounterValue = 0;
  1470. uint32 Time::getMillisecondCounter() throw()
  1471. {
  1472. const uint32 now = juce_millisecondsSinceStartup();
  1473. if (now < lastMSCounterValue)
  1474. {
  1475. // in multi-threaded apps this might be called concurrently, so
  1476. // make sure that our last counter value only increases and doesn't
  1477. // go backwards..
  1478. if (now < lastMSCounterValue - 1000)
  1479. lastMSCounterValue = now;
  1480. }
  1481. else
  1482. {
  1483. lastMSCounterValue = now;
  1484. }
  1485. return now;
  1486. }
  1487. uint32 Time::getApproximateMillisecondCounter() throw()
  1488. {
  1489. jassert (lastMSCounterValue != 0);
  1490. return lastMSCounterValue;
  1491. }
  1492. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1493. {
  1494. for (;;)
  1495. {
  1496. const uint32 now = getMillisecondCounter();
  1497. if (now >= targetTime)
  1498. break;
  1499. const int toWait = targetTime - now;
  1500. if (toWait > 2)
  1501. {
  1502. Thread::sleep (jmin (20, toWait >> 1));
  1503. }
  1504. else
  1505. {
  1506. // xxx should consider using mutex_pause on the mac as it apparently
  1507. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1508. for (int i = 10; --i >= 0;)
  1509. Thread::yield();
  1510. }
  1511. }
  1512. }
  1513. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1514. {
  1515. return ticks / (double) getHighResolutionTicksPerSecond();
  1516. }
  1517. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1518. {
  1519. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1520. }
  1521. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1522. {
  1523. return Time (currentTimeMillis());
  1524. }
  1525. const String Time::toString (const bool includeDate,
  1526. const bool includeTime,
  1527. const bool includeSeconds,
  1528. const bool use24HourClock) const throw()
  1529. {
  1530. String result;
  1531. if (includeDate)
  1532. {
  1533. result << getDayOfMonth() << ' '
  1534. << getMonthName (true) << ' '
  1535. << getYear();
  1536. if (includeTime)
  1537. result << ' ';
  1538. }
  1539. if (includeTime)
  1540. {
  1541. if (includeSeconds)
  1542. {
  1543. result += String::formatted (T("%d:%02d:%02d "),
  1544. (use24HourClock) ? getHours()
  1545. : getHoursInAmPmFormat(),
  1546. getMinutes(),
  1547. getSeconds());
  1548. }
  1549. else
  1550. {
  1551. result += String::formatted (T("%d.%02d"),
  1552. (use24HourClock) ? getHours()
  1553. : getHoursInAmPmFormat(),
  1554. getMinutes());
  1555. }
  1556. if (! use24HourClock)
  1557. result << (isAfternoon() ? "pm" : "am");
  1558. }
  1559. return result.trimEnd();
  1560. }
  1561. const String Time::formatted (const tchar* const format) const throw()
  1562. {
  1563. tchar buffer[80];
  1564. struct tm t;
  1565. millisToLocal (millisSinceEpoch, t);
  1566. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  1567. {
  1568. int bufferSize = 128;
  1569. for (;;)
  1570. {
  1571. MemoryBlock mb (bufferSize * sizeof (tchar));
  1572. tchar* const b = (tchar*) mb.getData();
  1573. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  1574. return String (b);
  1575. bufferSize += 128;
  1576. }
  1577. }
  1578. return String (buffer);
  1579. }
  1580. int Time::getYear() const throw()
  1581. {
  1582. struct tm t;
  1583. millisToLocal (millisSinceEpoch, t);
  1584. return t.tm_year + 1900;
  1585. }
  1586. int Time::getMonth() const throw()
  1587. {
  1588. struct tm t;
  1589. millisToLocal (millisSinceEpoch, t);
  1590. return t.tm_mon;
  1591. }
  1592. int Time::getDayOfMonth() const throw()
  1593. {
  1594. struct tm t;
  1595. millisToLocal (millisSinceEpoch, t);
  1596. return t.tm_mday;
  1597. }
  1598. int Time::getDayOfWeek() const throw()
  1599. {
  1600. struct tm t;
  1601. millisToLocal (millisSinceEpoch, t);
  1602. return t.tm_wday;
  1603. }
  1604. int Time::getHours() const throw()
  1605. {
  1606. struct tm t;
  1607. millisToLocal (millisSinceEpoch, t);
  1608. return t.tm_hour;
  1609. }
  1610. int Time::getHoursInAmPmFormat() const throw()
  1611. {
  1612. const int hours = getHours();
  1613. if (hours == 0)
  1614. return 12;
  1615. else if (hours <= 12)
  1616. return hours;
  1617. else
  1618. return hours - 12;
  1619. }
  1620. bool Time::isAfternoon() const throw()
  1621. {
  1622. return getHours() >= 12;
  1623. }
  1624. static int extendedModulo (const int64 value, const int modulo) throw()
  1625. {
  1626. return (int) (value >= 0 ? (value % modulo)
  1627. : (value - ((value / modulo) + 1) * modulo));
  1628. }
  1629. int Time::getMinutes() const throw()
  1630. {
  1631. struct tm t;
  1632. millisToLocal (millisSinceEpoch, t);
  1633. return t.tm_min;
  1634. }
  1635. int Time::getSeconds() const throw()
  1636. {
  1637. return extendedModulo (millisSinceEpoch / 1000, 60);
  1638. }
  1639. int Time::getMilliseconds() const throw()
  1640. {
  1641. return extendedModulo (millisSinceEpoch, 1000);
  1642. }
  1643. bool Time::isDaylightSavingTime() const throw()
  1644. {
  1645. struct tm t;
  1646. millisToLocal (millisSinceEpoch, t);
  1647. return t.tm_isdst != 0;
  1648. }
  1649. const String Time::getTimeZone() const throw()
  1650. {
  1651. String zone[2];
  1652. #if JUCE_WINDOWS
  1653. _tzset();
  1654. #ifdef USE_NEW_SECURE_TIME_FNS
  1655. {
  1656. char name [128];
  1657. size_t length;
  1658. for (int i = 0; i < 2; ++i)
  1659. {
  1660. zeromem (name, sizeof (name));
  1661. _get_tzname (&length, name, 127, i);
  1662. zone[i] = name;
  1663. }
  1664. }
  1665. #else
  1666. const char** const zonePtr = (const char**) _tzname;
  1667. zone[0] = zonePtr[0];
  1668. zone[1] = zonePtr[1];
  1669. #endif
  1670. #else
  1671. tzset();
  1672. const char** const zonePtr = (const char**) tzname;
  1673. zone[0] = zonePtr[0];
  1674. zone[1] = zonePtr[1];
  1675. #endif
  1676. if (isDaylightSavingTime())
  1677. {
  1678. zone[0] = zone[1];
  1679. if (zone[0].length() > 3
  1680. && zone[0].containsIgnoreCase (T("daylight"))
  1681. && zone[0].contains (T("GMT")))
  1682. zone[0] = "BST";
  1683. }
  1684. return zone[0].substring (0, 3);
  1685. }
  1686. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1687. {
  1688. return getMonthName (getMonth(), threeLetterVersion);
  1689. }
  1690. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1691. {
  1692. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1693. }
  1694. const String Time::getMonthName (int monthNumber,
  1695. const bool threeLetterVersion) throw()
  1696. {
  1697. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1698. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1699. monthNumber %= 12;
  1700. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1701. : longMonthNames [monthNumber]);
  1702. }
  1703. const String Time::getWeekdayName (int day,
  1704. const bool threeLetterVersion) throw()
  1705. {
  1706. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1707. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1708. day %= 7;
  1709. return TRANS (threeLetterVersion ? shortDayNames [day]
  1710. : longDayNames [day]);
  1711. }
  1712. END_JUCE_NAMESPACE
  1713. /********* End of inlined file: juce_Time.cpp *********/
  1714. /********* Start of inlined file: juce_BitArray.cpp *********/
  1715. BEGIN_JUCE_NAMESPACE
  1716. BitArray::BitArray() throw()
  1717. : numValues (4),
  1718. highestBit (-1),
  1719. negative (false)
  1720. {
  1721. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1722. }
  1723. BitArray::BitArray (const int value) throw()
  1724. : numValues (4),
  1725. highestBit (31),
  1726. negative (value < 0)
  1727. {
  1728. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1729. values[0] = abs (value);
  1730. highestBit = getHighestBit();
  1731. }
  1732. BitArray::BitArray (int64 value) throw()
  1733. : numValues (4),
  1734. highestBit (63),
  1735. negative (value < 0)
  1736. {
  1737. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1738. if (value < 0)
  1739. value = -value;
  1740. values[0] = (unsigned int) value;
  1741. values[1] = (unsigned int) (value >> 32);
  1742. highestBit = getHighestBit();
  1743. }
  1744. BitArray::BitArray (const unsigned int value) throw()
  1745. : numValues (4),
  1746. highestBit (31),
  1747. negative (false)
  1748. {
  1749. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1750. values[0] = value;
  1751. highestBit = getHighestBit();
  1752. }
  1753. BitArray::BitArray (const BitArray& other) throw()
  1754. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1755. highestBit (other.getHighestBit()),
  1756. negative (other.negative)
  1757. {
  1758. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1759. values = (unsigned int*) juce_malloc (bytes);
  1760. memcpy (values, other.values, bytes);
  1761. }
  1762. BitArray::~BitArray() throw()
  1763. {
  1764. juce_free (values);
  1765. }
  1766. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1767. {
  1768. if (this != &other)
  1769. {
  1770. juce_free (values);
  1771. highestBit = other.getHighestBit();
  1772. numValues = jmax (4, (highestBit >> 5) + 1);
  1773. negative = other.negative;
  1774. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1775. values = (unsigned int*)juce_malloc (memSize);
  1776. memcpy (values, other.values, memSize);
  1777. }
  1778. return *this;
  1779. }
  1780. // result == 0 = the same
  1781. // result < 0 = this number is smaller
  1782. // result > 0 = this number is bigger
  1783. int BitArray::compare (const BitArray& other) const throw()
  1784. {
  1785. if (isNegative() == other.isNegative())
  1786. {
  1787. const int absComp = compareAbsolute (other);
  1788. return isNegative() ? -absComp : absComp;
  1789. }
  1790. else
  1791. {
  1792. return isNegative() ? -1 : 1;
  1793. }
  1794. }
  1795. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1796. {
  1797. const int h1 = getHighestBit();
  1798. const int h2 = other.getHighestBit();
  1799. if (h1 > h2)
  1800. return 1;
  1801. else if (h1 < h2)
  1802. return -1;
  1803. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1804. if (values[i] != other.values[i])
  1805. return (values[i] > other.values[i]) ? 1 : -1;
  1806. return 0;
  1807. }
  1808. bool BitArray::operator== (const BitArray& other) const throw()
  1809. {
  1810. return compare (other) == 0;
  1811. }
  1812. bool BitArray::operator!= (const BitArray& other) const throw()
  1813. {
  1814. return compare (other) != 0;
  1815. }
  1816. bool BitArray::operator[] (const int bit) const throw()
  1817. {
  1818. return bit >= 0 && bit <= highestBit
  1819. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1820. }
  1821. bool BitArray::isEmpty() const throw()
  1822. {
  1823. return getHighestBit() < 0;
  1824. }
  1825. void BitArray::clear() throw()
  1826. {
  1827. if (numValues > 16)
  1828. {
  1829. juce_free (values);
  1830. numValues = 4;
  1831. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1832. }
  1833. else
  1834. {
  1835. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1836. }
  1837. highestBit = -1;
  1838. negative = false;
  1839. }
  1840. void BitArray::setBit (const int bit) throw()
  1841. {
  1842. if (bit >= 0)
  1843. {
  1844. if (bit > highestBit)
  1845. {
  1846. ensureSize (bit >> 5);
  1847. highestBit = bit;
  1848. }
  1849. values [bit >> 5] |= (1 << (bit & 31));
  1850. }
  1851. }
  1852. void BitArray::setBit (const int bit,
  1853. const bool shouldBeSet) throw()
  1854. {
  1855. if (shouldBeSet)
  1856. setBit (bit);
  1857. else
  1858. clearBit (bit);
  1859. }
  1860. void BitArray::clearBit (const int bit) throw()
  1861. {
  1862. if (bit >= 0 && bit <= highestBit)
  1863. values [bit >> 5] &= ~(1 << (bit & 31));
  1864. }
  1865. void BitArray::setRange (int startBit,
  1866. int numBits,
  1867. const bool shouldBeSet) throw()
  1868. {
  1869. while (--numBits >= 0)
  1870. setBit (startBit++, shouldBeSet);
  1871. }
  1872. void BitArray::insertBit (const int bit,
  1873. const bool shouldBeSet) throw()
  1874. {
  1875. if (bit >= 0)
  1876. shiftBits (1, bit);
  1877. setBit (bit, shouldBeSet);
  1878. }
  1879. void BitArray::andWith (const BitArray& other) throw()
  1880. {
  1881. // this operation will only work with the absolute values
  1882. jassert (isNegative() == other.isNegative());
  1883. int n = numValues;
  1884. while (n > other.numValues)
  1885. values[--n] = 0;
  1886. while (--n >= 0)
  1887. values[n] &= other.values[n];
  1888. if (other.highestBit < highestBit)
  1889. highestBit = other.highestBit;
  1890. highestBit = getHighestBit();
  1891. }
  1892. void BitArray::orWith (const BitArray& other) throw()
  1893. {
  1894. if (other.highestBit < 0)
  1895. return;
  1896. // this operation will only work with the absolute values
  1897. jassert (isNegative() == other.isNegative());
  1898. ensureSize (other.highestBit >> 5);
  1899. int n = (other.highestBit >> 5) + 1;
  1900. while (--n >= 0)
  1901. values[n] |= other.values[n];
  1902. if (other.highestBit > highestBit)
  1903. highestBit = other.highestBit;
  1904. highestBit = getHighestBit();
  1905. }
  1906. void BitArray::xorWith (const BitArray& other) throw()
  1907. {
  1908. if (other.highestBit < 0)
  1909. return;
  1910. // this operation will only work with the absolute values
  1911. jassert (isNegative() == other.isNegative());
  1912. ensureSize (other.highestBit >> 5);
  1913. int n = (other.highestBit >> 5) + 1;
  1914. while (--n >= 0)
  1915. values[n] ^= other.values[n];
  1916. if (other.highestBit > highestBit)
  1917. highestBit = other.highestBit;
  1918. highestBit = getHighestBit();
  1919. }
  1920. void BitArray::add (const BitArray& other) throw()
  1921. {
  1922. if (other.isNegative())
  1923. {
  1924. BitArray o (other);
  1925. o.negate();
  1926. subtract (o);
  1927. return;
  1928. }
  1929. if (isNegative())
  1930. {
  1931. if (compareAbsolute (other) < 0)
  1932. {
  1933. BitArray temp (*this);
  1934. temp.negate();
  1935. *this = other;
  1936. subtract (temp);
  1937. }
  1938. else
  1939. {
  1940. negate();
  1941. subtract (other);
  1942. negate();
  1943. }
  1944. return;
  1945. }
  1946. if (other.highestBit > highestBit)
  1947. highestBit = other.highestBit;
  1948. ++highestBit;
  1949. const int numInts = (highestBit >> 5) + 1;
  1950. ensureSize (numInts);
  1951. int64 remainder = 0;
  1952. for (int i = 0; i <= numInts; ++i)
  1953. {
  1954. if (i < numValues)
  1955. remainder += values[i];
  1956. if (i < other.numValues)
  1957. remainder += other.values[i];
  1958. values[i] = (unsigned int) remainder;
  1959. remainder >>= 32;
  1960. }
  1961. jassert (remainder == 0);
  1962. highestBit = getHighestBit();
  1963. }
  1964. void BitArray::subtract (const BitArray& other) throw()
  1965. {
  1966. if (other.isNegative())
  1967. {
  1968. BitArray o (other);
  1969. o.negate();
  1970. add (o);
  1971. return;
  1972. }
  1973. if (! isNegative())
  1974. {
  1975. if (compareAbsolute (other) < 0)
  1976. {
  1977. BitArray temp (*this);
  1978. *this = other;
  1979. subtract (temp);
  1980. negate();
  1981. return;
  1982. }
  1983. }
  1984. else
  1985. {
  1986. negate();
  1987. add (other);
  1988. negate();
  1989. return;
  1990. }
  1991. const int numInts = (highestBit >> 5) + 1;
  1992. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1993. int64 amountToSubtract = 0;
  1994. for (int i = 0; i <= numInts; ++i)
  1995. {
  1996. if (i <= maxOtherInts)
  1997. amountToSubtract += (int64)other.values[i];
  1998. if (values[i] >= amountToSubtract)
  1999. {
  2000. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2001. amountToSubtract = 0;
  2002. }
  2003. else
  2004. {
  2005. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2006. values[i] = (unsigned int) n;
  2007. amountToSubtract = 1;
  2008. }
  2009. }
  2010. }
  2011. void BitArray::multiplyBy (const BitArray& other) throw()
  2012. {
  2013. BitArray total;
  2014. highestBit = getHighestBit();
  2015. const bool wasNegative = isNegative();
  2016. setNegative (false);
  2017. for (int i = 0; i <= highestBit; ++i)
  2018. {
  2019. if (operator[](i))
  2020. {
  2021. BitArray n (other);
  2022. n.setNegative (false);
  2023. n.shiftBits (i);
  2024. total.add (n);
  2025. }
  2026. }
  2027. *this = total;
  2028. negative = wasNegative ^ other.isNegative();
  2029. }
  2030. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  2031. {
  2032. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2033. const int divHB = divisor.getHighestBit();
  2034. const int ourHB = getHighestBit();
  2035. if (divHB < 0 || ourHB < 0)
  2036. {
  2037. // division by zero
  2038. remainder.clear();
  2039. clear();
  2040. }
  2041. else
  2042. {
  2043. remainder = *this;
  2044. remainder.setNegative (false);
  2045. const bool wasNegative = isNegative();
  2046. clear();
  2047. BitArray temp (divisor);
  2048. temp.setNegative (false);
  2049. int leftShift = ourHB - divHB;
  2050. temp.shiftBits (leftShift);
  2051. while (leftShift >= 0)
  2052. {
  2053. if (remainder.compareAbsolute (temp) >= 0)
  2054. {
  2055. remainder.subtract (temp);
  2056. setBit (leftShift);
  2057. }
  2058. if (--leftShift >= 0)
  2059. temp.shiftBits (-1);
  2060. }
  2061. negative = wasNegative ^ divisor.isNegative();
  2062. remainder.setNegative (wasNegative);
  2063. }
  2064. }
  2065. void BitArray::modulo (const BitArray& divisor) throw()
  2066. {
  2067. BitArray remainder;
  2068. divideBy (divisor, remainder);
  2069. *this = remainder;
  2070. }
  2071. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  2072. {
  2073. while (! m->isEmpty())
  2074. {
  2075. if (n->compareAbsolute (*m) > 0)
  2076. swapVariables (m, n);
  2077. m->subtract (*n);
  2078. }
  2079. return *n;
  2080. }
  2081. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  2082. {
  2083. BitArray m (*this);
  2084. while (! n.isEmpty())
  2085. {
  2086. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2087. return simpleGCD (&m, &n);
  2088. BitArray temp1 (m), temp2;
  2089. temp1.divideBy (n, temp2);
  2090. m = n;
  2091. n = temp2;
  2092. }
  2093. return m;
  2094. }
  2095. void BitArray::exponentModulo (const BitArray& exponent,
  2096. const BitArray& modulus) throw()
  2097. {
  2098. BitArray exp (exponent);
  2099. exp.modulo (modulus);
  2100. BitArray value (*this);
  2101. value.modulo (modulus);
  2102. clear();
  2103. setBit (0);
  2104. while (! exp.isEmpty())
  2105. {
  2106. if (exp [0])
  2107. {
  2108. multiplyBy (value);
  2109. this->modulo (modulus);
  2110. }
  2111. value.multiplyBy (value);
  2112. value.modulo (modulus);
  2113. exp.shiftBits (-1);
  2114. }
  2115. }
  2116. void BitArray::inverseModulo (const BitArray& modulus) throw()
  2117. {
  2118. const BitArray one (1);
  2119. if (modulus == one || modulus.isNegative())
  2120. {
  2121. clear();
  2122. return;
  2123. }
  2124. if (isNegative() || compareAbsolute (modulus) >= 0)
  2125. this->modulo (modulus);
  2126. if (*this == one)
  2127. return;
  2128. if (! (*this)[0])
  2129. {
  2130. // not invertible
  2131. clear();
  2132. return;
  2133. }
  2134. BitArray a1 (modulus);
  2135. BitArray a2 (*this);
  2136. BitArray b1 (modulus);
  2137. BitArray b2 (1);
  2138. while (a2 != one)
  2139. {
  2140. BitArray temp1, temp2, multiplier (a1);
  2141. multiplier.divideBy (a2, temp1);
  2142. temp1 = a2;
  2143. temp1.multiplyBy (multiplier);
  2144. temp2 = a1;
  2145. temp2.subtract (temp1);
  2146. a1 = a2;
  2147. a2 = temp2;
  2148. temp1 = b2;
  2149. temp1.multiplyBy (multiplier);
  2150. temp2 = b1;
  2151. temp2.subtract (temp1);
  2152. b1 = b2;
  2153. b2 = temp2;
  2154. }
  2155. while (b2.isNegative())
  2156. b2.add (modulus);
  2157. b2.modulo (modulus);
  2158. *this = b2;
  2159. }
  2160. void BitArray::shiftBits (int bits, const int startBit) throw()
  2161. {
  2162. if (highestBit < 0)
  2163. return;
  2164. if (startBit > 0)
  2165. {
  2166. if (bits < 0)
  2167. {
  2168. // right shift
  2169. for (int i = startBit; i <= highestBit; ++i)
  2170. setBit (i, operator[] (i - bits));
  2171. highestBit = getHighestBit();
  2172. }
  2173. else if (bits > 0)
  2174. {
  2175. // left shift
  2176. for (int i = highestBit + 1; --i >= startBit;)
  2177. setBit (i + bits, operator[] (i));
  2178. while (--bits >= 0)
  2179. clearBit (bits + startBit);
  2180. }
  2181. }
  2182. else
  2183. {
  2184. if (bits < 0)
  2185. {
  2186. // right shift
  2187. bits = -bits;
  2188. if (bits > highestBit)
  2189. {
  2190. clear();
  2191. }
  2192. else
  2193. {
  2194. const int wordsToMove = bits >> 5;
  2195. int top = 1 + (highestBit >> 5) - wordsToMove;
  2196. highestBit -= bits;
  2197. if (wordsToMove > 0)
  2198. {
  2199. int i;
  2200. for (i = 0; i < top; ++i)
  2201. values [i] = values [i + wordsToMove];
  2202. for (i = 0; i < wordsToMove; ++i)
  2203. values [top + i] = 0;
  2204. bits &= 31;
  2205. }
  2206. if (bits != 0)
  2207. {
  2208. const int invBits = 32 - bits;
  2209. --top;
  2210. for (int i = 0; i < top; ++i)
  2211. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2212. values[top] = (values[top] >> bits);
  2213. }
  2214. highestBit = getHighestBit();
  2215. }
  2216. }
  2217. else if (bits > 0)
  2218. {
  2219. // left shift
  2220. ensureSize (((highestBit + bits) >> 5) + 1);
  2221. const int wordsToMove = bits >> 5;
  2222. int top = 1 + (highestBit >> 5);
  2223. highestBit += bits;
  2224. if (wordsToMove > 0)
  2225. {
  2226. int i;
  2227. for (i = top; --i >= 0;)
  2228. values [i + wordsToMove] = values [i];
  2229. for (i = 0; i < wordsToMove; ++i)
  2230. values [i] = 0;
  2231. bits &= 31;
  2232. }
  2233. if (bits != 0)
  2234. {
  2235. const int invBits = 32 - bits;
  2236. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2237. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2238. values [wordsToMove] = values [wordsToMove] << bits;
  2239. }
  2240. highestBit = getHighestBit();
  2241. }
  2242. }
  2243. }
  2244. const BitArray BitArray::getBitRange (int startBit, int numBits) const throw()
  2245. {
  2246. BitArray r;
  2247. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2248. r.ensureSize (numBits >> 5);
  2249. r.highestBit = numBits;
  2250. int i = 0;
  2251. while (numBits > 0)
  2252. {
  2253. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2254. numBits -= 32;
  2255. startBit += 32;
  2256. }
  2257. r.highestBit = r.getHighestBit();
  2258. return r;
  2259. }
  2260. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2261. {
  2262. if (numBits > 32)
  2263. {
  2264. jassertfalse // use getBitRange() if you need more than 32 bits..
  2265. numBits = 32;
  2266. }
  2267. numBits = jmin (numBits, highestBit + 1 - startBit);
  2268. if (numBits <= 0)
  2269. return 0;
  2270. const int pos = startBit >> 5;
  2271. const int offset = startBit & 31;
  2272. const int endSpace = 32 - numBits;
  2273. uint32 n = ((uint32) values [pos]) >> offset;
  2274. if (offset > endSpace)
  2275. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2276. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2277. }
  2278. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  2279. {
  2280. if (numBits > 32)
  2281. {
  2282. jassertfalse
  2283. numBits = 32;
  2284. }
  2285. for (int i = 0; i < numBits; ++i)
  2286. {
  2287. setBit (startBit + i, (valueToSet & 1) != 0);
  2288. valueToSet >>= 1;
  2289. }
  2290. }
  2291. bool BitArray::isNegative() const throw()
  2292. {
  2293. return negative && ! isEmpty();
  2294. }
  2295. void BitArray::setNegative (const bool neg) throw()
  2296. {
  2297. negative = neg;
  2298. }
  2299. void BitArray::negate() throw()
  2300. {
  2301. negative = (! negative) && ! isEmpty();
  2302. }
  2303. int BitArray::countNumberOfSetBits() const throw()
  2304. {
  2305. int total = 0;
  2306. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2307. {
  2308. unsigned int n = values[i];
  2309. if (n == 0xffffffff)
  2310. {
  2311. total += 32;
  2312. }
  2313. else
  2314. {
  2315. while (n != 0)
  2316. {
  2317. total += (n & 1);
  2318. n >>= 1;
  2319. }
  2320. }
  2321. }
  2322. return total;
  2323. }
  2324. int BitArray::getHighestBit() const throw()
  2325. {
  2326. for (int i = highestBit + 1; --i >= 0;)
  2327. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2328. return i;
  2329. return -1;
  2330. }
  2331. int BitArray::findNextSetBit (int i) const throw()
  2332. {
  2333. for (; i <= highestBit; ++i)
  2334. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2335. return i;
  2336. return -1;
  2337. }
  2338. int BitArray::findNextClearBit (int i) const throw()
  2339. {
  2340. for (; i <= highestBit; ++i)
  2341. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2342. break;
  2343. return i;
  2344. }
  2345. void BitArray::ensureSize (const int numVals) throw()
  2346. {
  2347. if (numVals + 2 >= numValues)
  2348. {
  2349. int oldSize = numValues;
  2350. numValues = ((numVals + 2) * 3) / 2;
  2351. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  2352. while (oldSize < numValues)
  2353. values [oldSize++] = 0;
  2354. }
  2355. }
  2356. const String BitArray::toString (const int base, const int minimumNumCharacters) const throw()
  2357. {
  2358. String s;
  2359. BitArray v (*this);
  2360. if (base == 2 || base == 8 || base == 16)
  2361. {
  2362. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2363. static const tchar* const hexDigits = T("0123456789abcdef");
  2364. for (;;)
  2365. {
  2366. const int remainder = v.getBitRangeAsInt (0, bits);
  2367. v.shiftBits (-bits);
  2368. if (remainder == 0 && v.isEmpty())
  2369. break;
  2370. s = String::charToString (hexDigits [remainder]) + s;
  2371. }
  2372. }
  2373. else if (base == 10)
  2374. {
  2375. const BitArray ten (10);
  2376. BitArray remainder;
  2377. for (;;)
  2378. {
  2379. v.divideBy (ten, remainder);
  2380. if (remainder.isEmpty() && v.isEmpty())
  2381. break;
  2382. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2383. }
  2384. }
  2385. else
  2386. {
  2387. jassertfalse // can't do the specified base
  2388. return String::empty;
  2389. }
  2390. const int length = s.length();
  2391. if (length < minimumNumCharacters)
  2392. s = String::repeatedString (T("0"), minimumNumCharacters - length);
  2393. return isNegative() ? T("-") + s : s;
  2394. }
  2395. void BitArray::parseString (const String& text,
  2396. const int base) throw()
  2397. {
  2398. clear();
  2399. const tchar* t = (const tchar*) text;
  2400. if (base == 2 || base == 8 || base == 16)
  2401. {
  2402. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2403. for (;;)
  2404. {
  2405. const tchar c = *t++;
  2406. const int digit = CharacterFunctions::getHexDigitValue (c);
  2407. if (((unsigned int) digit) < (unsigned int) base)
  2408. {
  2409. shiftBits (bits);
  2410. add (digit);
  2411. }
  2412. else if (c == 0)
  2413. {
  2414. break;
  2415. }
  2416. }
  2417. }
  2418. else if (base == 10)
  2419. {
  2420. const BitArray ten ((unsigned int) 10);
  2421. for (;;)
  2422. {
  2423. const tchar c = *t++;
  2424. if (c >= T('0') && c <= T('9'))
  2425. {
  2426. multiplyBy (ten);
  2427. add ((int) (c - T('0')));
  2428. }
  2429. else if (c == 0)
  2430. {
  2431. break;
  2432. }
  2433. }
  2434. }
  2435. setNegative (text.trimStart().startsWithChar (T('-')));
  2436. }
  2437. const MemoryBlock BitArray::toMemoryBlock() const throw()
  2438. {
  2439. const int numBytes = (getHighestBit() + 8) >> 3;
  2440. MemoryBlock mb (numBytes);
  2441. for (int i = 0; i < numBytes; ++i)
  2442. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2443. return mb;
  2444. }
  2445. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  2446. {
  2447. clear();
  2448. for (int i = data.getSize(); --i >= 0;)
  2449. this->setBitRangeAsInt (i << 3, 8, data [i]);
  2450. }
  2451. END_JUCE_NAMESPACE
  2452. /********* End of inlined file: juce_BitArray.cpp *********/
  2453. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  2454. BEGIN_JUCE_NAMESPACE
  2455. MemoryBlock::MemoryBlock() throw()
  2456. : data (0),
  2457. size (0)
  2458. {
  2459. }
  2460. MemoryBlock::MemoryBlock (const int initialSize,
  2461. const bool initialiseToZero) throw()
  2462. {
  2463. if (initialSize > 0)
  2464. {
  2465. size = initialSize;
  2466. if (initialiseToZero)
  2467. data = (char*) juce_calloc (initialSize);
  2468. else
  2469. data = (char*) juce_malloc (initialSize);
  2470. }
  2471. else
  2472. {
  2473. data = 0;
  2474. size = 0;
  2475. }
  2476. }
  2477. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2478. : data (0),
  2479. size (other.size)
  2480. {
  2481. if (size > 0)
  2482. {
  2483. jassert (other.data != 0);
  2484. data = (char*) juce_malloc (size);
  2485. memcpy (data, other.data, size);
  2486. }
  2487. }
  2488. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2489. const int sizeInBytes) throw()
  2490. : data (0),
  2491. size (jmax (0, sizeInBytes))
  2492. {
  2493. jassert (sizeInBytes >= 0);
  2494. if (size > 0)
  2495. {
  2496. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2497. data = (char*) juce_malloc (size);
  2498. if (dataToInitialiseFrom != 0)
  2499. memcpy (data, dataToInitialiseFrom, size);
  2500. }
  2501. }
  2502. MemoryBlock::~MemoryBlock() throw()
  2503. {
  2504. jassert (size >= 0); // should never happen
  2505. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2506. juce_free (data);
  2507. }
  2508. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2509. {
  2510. if (this != &other)
  2511. {
  2512. setSize (other.size, false);
  2513. memcpy (data, other.data, size);
  2514. }
  2515. return *this;
  2516. }
  2517. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2518. {
  2519. return (size == other.size)
  2520. && (memcmp (data, other.data, size) == 0);
  2521. }
  2522. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2523. {
  2524. return ! operator== (other);
  2525. }
  2526. // this will resize the block to this size
  2527. void MemoryBlock::setSize (const int newSize,
  2528. const bool initialiseToZero) throw()
  2529. {
  2530. if (size != newSize)
  2531. {
  2532. if (newSize <= 0)
  2533. {
  2534. juce_free (data);
  2535. data = 0;
  2536. size = 0;
  2537. }
  2538. else
  2539. {
  2540. if (data != 0)
  2541. {
  2542. data = (char*) juce_realloc (data, newSize);
  2543. if (initialiseToZero && (newSize > size))
  2544. zeromem (data + size, newSize - size);
  2545. }
  2546. else
  2547. {
  2548. if (initialiseToZero)
  2549. data = (char*) juce_calloc (newSize);
  2550. else
  2551. data = (char*) juce_malloc (newSize);
  2552. }
  2553. size = newSize;
  2554. }
  2555. }
  2556. }
  2557. void MemoryBlock::ensureSize (const int minimumSize,
  2558. const bool initialiseToZero) throw()
  2559. {
  2560. if (size < minimumSize)
  2561. setSize (minimumSize, initialiseToZero);
  2562. }
  2563. void MemoryBlock::fillWith (const uint8 value) throw()
  2564. {
  2565. memset (data, (int) value, size);
  2566. }
  2567. void MemoryBlock::append (const void* const srcData,
  2568. const int numBytes) throw()
  2569. {
  2570. if (numBytes > 0)
  2571. {
  2572. const int oldSize = size;
  2573. setSize (size + numBytes);
  2574. memcpy (data + oldSize, srcData, numBytes);
  2575. }
  2576. }
  2577. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  2578. {
  2579. const char* d = (const char*) src;
  2580. if (offset < 0)
  2581. {
  2582. d -= offset;
  2583. num -= offset;
  2584. offset = 0;
  2585. }
  2586. if (offset + num > size)
  2587. num = size - offset;
  2588. if (num > 0)
  2589. memcpy (data + offset, d, num);
  2590. }
  2591. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  2592. {
  2593. char* d = (char*) dst;
  2594. if (offset < 0)
  2595. {
  2596. zeromem (d, -offset);
  2597. d -= offset;
  2598. num += offset;
  2599. offset = 0;
  2600. }
  2601. if (offset + num > size)
  2602. {
  2603. const int newNum = size - offset;
  2604. zeromem (d + newNum, num - newNum);
  2605. num = newNum;
  2606. }
  2607. if (num > 0)
  2608. memcpy (d, data + offset, num);
  2609. }
  2610. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  2611. {
  2612. if (startByte < 0)
  2613. {
  2614. numBytesToRemove += startByte;
  2615. startByte = 0;
  2616. }
  2617. if (startByte + numBytesToRemove >= size)
  2618. {
  2619. setSize (startByte);
  2620. }
  2621. else if (numBytesToRemove > 0)
  2622. {
  2623. memmove (data + startByte,
  2624. data + startByte + numBytesToRemove,
  2625. size - (startByte + numBytesToRemove));
  2626. setSize (size - numBytesToRemove);
  2627. }
  2628. }
  2629. const String MemoryBlock::toString() const throw()
  2630. {
  2631. return String (data, size);
  2632. }
  2633. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  2634. {
  2635. int res = 0;
  2636. int byte = bitRangeStart >> 3;
  2637. int offsetInByte = bitRangeStart & 7;
  2638. int bitsSoFar = 0;
  2639. while (numBits > 0 && byte < size)
  2640. {
  2641. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2642. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2643. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2644. bitsSoFar += bitsThisTime;
  2645. numBits -= bitsThisTime;
  2646. ++byte;
  2647. offsetInByte = 0;
  2648. }
  2649. return res;
  2650. }
  2651. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  2652. {
  2653. int byte = bitRangeStart >> 3;
  2654. int offsetInByte = bitRangeStart & 7;
  2655. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2656. while (numBits > 0 && byte < size)
  2657. {
  2658. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2659. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  2660. const unsigned int tempBits = bitsToSet << offsetInByte;
  2661. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  2662. ++byte;
  2663. numBits -= bitsThisTime;
  2664. bitsToSet >>= bitsThisTime;
  2665. mask >>= bitsThisTime;
  2666. offsetInByte = 0;
  2667. }
  2668. }
  2669. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2670. {
  2671. ensureSize (hex.length() >> 1);
  2672. char* dest = data;
  2673. int i = 0;
  2674. for (;;)
  2675. {
  2676. int byte = 0;
  2677. for (int loop = 2; --loop >= 0;)
  2678. {
  2679. byte <<= 4;
  2680. for (;;)
  2681. {
  2682. const tchar c = hex [i++];
  2683. if (c >= T('0') && c <= T('9'))
  2684. {
  2685. byte |= c - T('0');
  2686. break;
  2687. }
  2688. else if (c >= T('a') && c <= T('z'))
  2689. {
  2690. byte |= c - (T('a') - 10);
  2691. break;
  2692. }
  2693. else if (c >= T('A') && c <= T('Z'))
  2694. {
  2695. byte |= c - (T('A') - 10);
  2696. break;
  2697. }
  2698. else if (c == 0)
  2699. {
  2700. setSize ((int) (dest - data));
  2701. return;
  2702. }
  2703. }
  2704. }
  2705. *dest++ = (char) byte;
  2706. }
  2707. }
  2708. static const char* const encodingTable
  2709. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2710. const String MemoryBlock::toBase64Encoding() const throw()
  2711. {
  2712. const int numChars = ((size << 3) + 5) / 6;
  2713. String destString (size); // store the length, followed by a '.', and then the data.
  2714. const int initialLen = destString.length();
  2715. destString.preallocateStorage (initialLen + 2 + numChars);
  2716. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  2717. *d++ = T('.');
  2718. for (int i = 0; i < numChars; ++i)
  2719. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2720. *d++ = 0;
  2721. return destString;
  2722. }
  2723. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2724. {
  2725. const int startPos = s.indexOfChar (T('.')) + 1;
  2726. if (startPos <= 0)
  2727. return false;
  2728. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2729. setSize (numBytesNeeded, true);
  2730. const int numChars = s.length() - startPos;
  2731. const tchar* const srcChars = ((const tchar*) s) + startPos;
  2732. int pos = 0;
  2733. for (int i = 0; i < numChars; ++i)
  2734. {
  2735. const char c = (char) srcChars[i];
  2736. for (int j = 0; j < 64; ++j)
  2737. {
  2738. if (encodingTable[j] == c)
  2739. {
  2740. setBitRange (pos, 6, j);
  2741. pos += 6;
  2742. break;
  2743. }
  2744. }
  2745. }
  2746. return true;
  2747. }
  2748. END_JUCE_NAMESPACE
  2749. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2750. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2751. BEGIN_JUCE_NAMESPACE
  2752. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2753. : properties (ignoreCaseOfKeyNames),
  2754. fallbackProperties (0),
  2755. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2756. {
  2757. }
  2758. PropertySet::PropertySet (const PropertySet& other) throw()
  2759. : properties (other.properties),
  2760. fallbackProperties (other.fallbackProperties),
  2761. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2762. {
  2763. }
  2764. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2765. {
  2766. properties = other.properties;
  2767. fallbackProperties = other.fallbackProperties;
  2768. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2769. propertyChanged();
  2770. return *this;
  2771. }
  2772. PropertySet::~PropertySet()
  2773. {
  2774. }
  2775. void PropertySet::clear()
  2776. {
  2777. const ScopedLock sl (lock);
  2778. if (properties.size() > 0)
  2779. {
  2780. properties.clear();
  2781. propertyChanged();
  2782. }
  2783. }
  2784. const String PropertySet::getValue (const String& keyName,
  2785. const String& defaultValue) const throw()
  2786. {
  2787. const ScopedLock sl (lock);
  2788. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2789. if (index >= 0)
  2790. return properties.getAllValues() [index];
  2791. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2792. : defaultValue;
  2793. }
  2794. int PropertySet::getIntValue (const String& keyName,
  2795. const int defaultValue) const throw()
  2796. {
  2797. const ScopedLock sl (lock);
  2798. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2799. if (index >= 0)
  2800. return properties.getAllValues() [index].getIntValue();
  2801. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2802. : defaultValue;
  2803. }
  2804. double PropertySet::getDoubleValue (const String& keyName,
  2805. const double defaultValue) const throw()
  2806. {
  2807. const ScopedLock sl (lock);
  2808. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2809. if (index >= 0)
  2810. return properties.getAllValues()[index].getDoubleValue();
  2811. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2812. : defaultValue;
  2813. }
  2814. bool PropertySet::getBoolValue (const String& keyName,
  2815. const bool defaultValue) const throw()
  2816. {
  2817. const ScopedLock sl (lock);
  2818. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2819. if (index >= 0)
  2820. return properties.getAllValues() [index].getIntValue() != 0;
  2821. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2822. : defaultValue;
  2823. }
  2824. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2825. {
  2826. XmlDocument doc (getValue (keyName));
  2827. return doc.getDocumentElement();
  2828. }
  2829. void PropertySet::setValue (const String& keyName,
  2830. const String& value) throw()
  2831. {
  2832. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2833. if (keyName.isNotEmpty())
  2834. {
  2835. const ScopedLock sl (lock);
  2836. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2837. if (index < 0 || properties.getAllValues() [index] != value)
  2838. {
  2839. properties.set (keyName, value);
  2840. propertyChanged();
  2841. }
  2842. }
  2843. }
  2844. void PropertySet::removeValue (const String& keyName) throw()
  2845. {
  2846. if (keyName.isNotEmpty())
  2847. {
  2848. const ScopedLock sl (lock);
  2849. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2850. if (index >= 0)
  2851. {
  2852. properties.remove (keyName);
  2853. propertyChanged();
  2854. }
  2855. }
  2856. }
  2857. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2858. {
  2859. setValue (keyName, String (value));
  2860. }
  2861. void PropertySet::setValue (const String& keyName, const int value) throw()
  2862. {
  2863. setValue (keyName, String (value));
  2864. }
  2865. void PropertySet::setValue (const String& keyName, const double value) throw()
  2866. {
  2867. setValue (keyName, String (value));
  2868. }
  2869. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2870. {
  2871. setValue (keyName, String ((value) ? T("1") : T("0")));
  2872. }
  2873. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2874. {
  2875. setValue (keyName, (xml == 0) ? String::empty
  2876. : xml->createDocument (String::empty, true));
  2877. }
  2878. bool PropertySet::containsKey (const String& keyName) const throw()
  2879. {
  2880. const ScopedLock sl (lock);
  2881. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2882. }
  2883. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2884. {
  2885. const ScopedLock sl (lock);
  2886. fallbackProperties = fallbackProperties_;
  2887. }
  2888. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2889. {
  2890. const ScopedLock sl (lock);
  2891. XmlElement* const xml = new XmlElement (nodeName);
  2892. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2893. {
  2894. XmlElement* const e = new XmlElement (T("VALUE"));
  2895. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2896. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2897. xml->addChildElement (e);
  2898. }
  2899. return xml;
  2900. }
  2901. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2902. {
  2903. const ScopedLock sl (lock);
  2904. clear();
  2905. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2906. {
  2907. if (e->hasAttribute (T("name"))
  2908. && e->hasAttribute (T("val")))
  2909. {
  2910. properties.set (e->getStringAttribute (T("name")),
  2911. e->getStringAttribute (T("val")));
  2912. }
  2913. }
  2914. if (properties.size() > 0)
  2915. propertyChanged();
  2916. }
  2917. void PropertySet::propertyChanged()
  2918. {
  2919. }
  2920. END_JUCE_NAMESPACE
  2921. /********* End of inlined file: juce_PropertySet.cpp *********/
  2922. /********* Start of inlined file: juce_Variant.cpp *********/
  2923. BEGIN_JUCE_NAMESPACE
  2924. var::var() throw()
  2925. : type (voidType)
  2926. {
  2927. value.doubleValue = 0;
  2928. }
  2929. void var::releaseValue() throw()
  2930. {
  2931. if (type == stringType)
  2932. delete value.stringValue;
  2933. else if (type == objectType && value.objectValue != 0)
  2934. value.objectValue->decReferenceCount();
  2935. }
  2936. var::~var()
  2937. {
  2938. releaseValue();
  2939. }
  2940. var::var (const var& valueToCopy) throw()
  2941. : type (valueToCopy.type),
  2942. value (valueToCopy.value)
  2943. {
  2944. if (type == stringType)
  2945. value.stringValue = new String (*(value.stringValue));
  2946. else if (type == objectType && value.objectValue != 0)
  2947. value.objectValue->incReferenceCount();
  2948. }
  2949. var::var (const int value_) throw()
  2950. : type (intType)
  2951. {
  2952. value.intValue = value_;
  2953. }
  2954. var::var (const bool value_) throw()
  2955. : type (boolType)
  2956. {
  2957. value.boolValue = value_;
  2958. }
  2959. var::var (const double value_) throw()
  2960. : type (doubleType)
  2961. {
  2962. value.doubleValue = value_;
  2963. }
  2964. var::var (const String& value_) throw()
  2965. : type (stringType)
  2966. {
  2967. value.stringValue = new String (value_);
  2968. }
  2969. var::var (const char* const value_) throw()
  2970. : type (stringType)
  2971. {
  2972. value.stringValue = new String (value_);
  2973. }
  2974. var::var (const juce_wchar* const value_) throw()
  2975. : type (stringType)
  2976. {
  2977. value.stringValue = new String (value_);
  2978. }
  2979. var::var (DynamicObject* const object) throw()
  2980. : type (objectType)
  2981. {
  2982. value.objectValue = object;
  2983. if (object != 0)
  2984. object->incReferenceCount();
  2985. }
  2986. var::var (MethodFunction method_) throw()
  2987. : type (methodType)
  2988. {
  2989. value.methodValue = method_;
  2990. }
  2991. const var& var::operator= (const var& valueToCopy) throw()
  2992. {
  2993. if (this != &valueToCopy)
  2994. {
  2995. if (type == stringType)
  2996. delete value.stringValue;
  2997. DynamicObject* const oldObject = getObject();
  2998. type = valueToCopy.type;
  2999. value = valueToCopy.value;
  3000. if (type == stringType)
  3001. value.stringValue = new String (*(value.stringValue));
  3002. else if (type == objectType && value.objectValue != 0)
  3003. value.objectValue->incReferenceCount();
  3004. if (oldObject != 0)
  3005. oldObject->decReferenceCount();
  3006. }
  3007. return *this;
  3008. }
  3009. const var& var::operator= (const int value_) throw()
  3010. {
  3011. releaseValue();
  3012. type = intType;
  3013. value.intValue = value_;
  3014. return *this;
  3015. }
  3016. const var& var::operator= (const bool value_) throw()
  3017. {
  3018. releaseValue();
  3019. type = boolType;
  3020. value.boolValue = value_;
  3021. return *this;
  3022. }
  3023. const var& var::operator= (const double value_) throw()
  3024. {
  3025. releaseValue();
  3026. type = doubleType;
  3027. value.doubleValue = value_;
  3028. return *this;
  3029. }
  3030. const var& var::operator= (const char* const value_) throw()
  3031. {
  3032. releaseValue();
  3033. type = stringType;
  3034. value.stringValue = new String (value_);
  3035. return *this;
  3036. }
  3037. const var& var::operator= (const juce_wchar* const value_) throw()
  3038. {
  3039. releaseValue();
  3040. type = stringType;
  3041. value.stringValue = new String (value_);
  3042. return *this;
  3043. }
  3044. const var& var::operator= (const String& value_) throw()
  3045. {
  3046. releaseValue();
  3047. type = stringType;
  3048. value.stringValue = new String (value_);
  3049. return *this;
  3050. }
  3051. const var& var::operator= (DynamicObject* const value_) throw()
  3052. {
  3053. value_->incReferenceCount();
  3054. releaseValue();
  3055. type = objectType;
  3056. value.objectValue = value_;
  3057. return *this;
  3058. }
  3059. const var& var::operator= (MethodFunction method_) throw()
  3060. {
  3061. releaseValue();
  3062. type = doubleType;
  3063. value.methodValue = method_;
  3064. return *this;
  3065. }
  3066. var::operator int() const throw()
  3067. {
  3068. switch (type)
  3069. {
  3070. case voidType:
  3071. case objectType: break;
  3072. case intType: return value.intValue;
  3073. case boolType: return value.boolValue ? 1 : 0;
  3074. case doubleType: return (int) value.doubleValue;
  3075. case stringType: return value.stringValue->getIntValue();
  3076. default: jassertfalse; break;
  3077. }
  3078. return 0;
  3079. }
  3080. var::operator bool() const throw()
  3081. {
  3082. switch (type)
  3083. {
  3084. case voidType: break;
  3085. case objectType: return value.objectValue != 0;
  3086. case intType: return value.intValue != 0;
  3087. case boolType: return value.boolValue;
  3088. case doubleType: return value.doubleValue != 0;
  3089. case stringType: return value.stringValue->getIntValue() != 0
  3090. || value.stringValue->trim().equalsIgnoreCase (T("true"))
  3091. || value.stringValue->trim().equalsIgnoreCase (T("yes"));
  3092. default: jassertfalse; break;
  3093. }
  3094. return false;
  3095. }
  3096. var::operator double() const throw()
  3097. {
  3098. switch (type)
  3099. {
  3100. case voidType:
  3101. case objectType: break;
  3102. case intType: return value.intValue;
  3103. case boolType: return value.boolValue ? 1.0 : 0.0;
  3104. case doubleType: return value.doubleValue;
  3105. case stringType: return value.stringValue->getDoubleValue();
  3106. default: jassertfalse; break;
  3107. }
  3108. return 0;
  3109. }
  3110. const String var::toString() const throw()
  3111. {
  3112. switch (type)
  3113. {
  3114. case voidType:
  3115. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3116. case intType: return String (value.intValue);
  3117. case boolType: return value.boolValue ? T("1") : T("0");
  3118. case doubleType: return String (value.doubleValue);
  3119. case stringType: return *(value.stringValue);
  3120. default: jassertfalse; break;
  3121. }
  3122. return String::empty;
  3123. }
  3124. var::operator const String() const throw()
  3125. {
  3126. return toString();
  3127. }
  3128. DynamicObject* var::getObject() const throw()
  3129. {
  3130. return type == objectType ? value.objectValue : 0;
  3131. }
  3132. const var var::operator[] (const var::identifier& propertyName) const throw()
  3133. {
  3134. if (type == objectType && value.objectValue != 0)
  3135. return value.objectValue->getProperty (propertyName);
  3136. return var();
  3137. }
  3138. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3139. {
  3140. if (type == objectType && value.objectValue != 0)
  3141. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3142. return var();
  3143. }
  3144. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3145. {
  3146. if (isMethod())
  3147. {
  3148. DynamicObject* const target = targetObject.getObject();
  3149. if (target != 0)
  3150. return (target->*(value.methodValue)) (arguments, numArguments);
  3151. }
  3152. return var();
  3153. }
  3154. const var var::call (const var::identifier& method) const
  3155. {
  3156. return invoke (method, 0, 0);
  3157. }
  3158. const var var::call (const var::identifier& method, const var& arg1) const
  3159. {
  3160. return invoke (method, &arg1, 1);
  3161. }
  3162. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3163. {
  3164. var args[] = { arg1, arg2 };
  3165. return invoke (method, args, 2);
  3166. }
  3167. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3168. {
  3169. var args[] = { arg1, arg2, arg3 };
  3170. return invoke (method, args, 3);
  3171. }
  3172. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3173. {
  3174. var args[] = { arg1, arg2, arg3, arg4 };
  3175. return invoke (method, args, 4);
  3176. }
  3177. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3178. {
  3179. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3180. return invoke (method, args, 5);
  3181. }
  3182. var::identifier::identifier (const String& name_) throw()
  3183. : name (name_),
  3184. hashCode (name_.hashCode())
  3185. {
  3186. }
  3187. var::identifier::identifier (const char* const name_) throw()
  3188. : name (name_),
  3189. hashCode (name.hashCode())
  3190. {
  3191. }
  3192. var::identifier::~identifier() throw()
  3193. {
  3194. }
  3195. DynamicObject::DynamicObject()
  3196. {
  3197. }
  3198. DynamicObject::~DynamicObject()
  3199. {
  3200. }
  3201. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3202. {
  3203. const int index = propertyIds.indexOf (propertyName.hashCode);
  3204. return index >= 0 && ! propertyValues.getUnchecked (index)->isMethod();
  3205. }
  3206. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3207. {
  3208. const int index = propertyIds.indexOf (propertyName.hashCode);
  3209. if (index >= 0)
  3210. return *propertyValues.getUnchecked (index);
  3211. return var();
  3212. }
  3213. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3214. {
  3215. const int index = propertyIds.indexOf (propertyName.hashCode);
  3216. if (index >= 0)
  3217. {
  3218. propertyValues.set (index, new var (newValue));
  3219. }
  3220. else
  3221. {
  3222. propertyIds.add (propertyName.hashCode);
  3223. propertyValues.add (new var (newValue));
  3224. }
  3225. }
  3226. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3227. {
  3228. const int index = propertyIds.indexOf (propertyName.hashCode);
  3229. if (index >= 0)
  3230. {
  3231. propertyIds.remove (index);
  3232. propertyValues.remove (index);
  3233. }
  3234. }
  3235. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3236. {
  3237. return getProperty (methodName).isMethod();
  3238. }
  3239. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3240. const var* parameters,
  3241. int numParameters)
  3242. {
  3243. return getProperty (methodName).invoke (this, parameters, numParameters);
  3244. }
  3245. void DynamicObject::setMethod (const var::identifier& name,
  3246. var::MethodFunction methodFunction)
  3247. {
  3248. setProperty (name, methodFunction);
  3249. }
  3250. void DynamicObject::clear()
  3251. {
  3252. propertyIds.clear();
  3253. propertyValues.clear();
  3254. }
  3255. END_JUCE_NAMESPACE
  3256. /********* End of inlined file: juce_Variant.cpp *********/
  3257. /********* Start of inlined file: juce_BlowFish.cpp *********/
  3258. BEGIN_JUCE_NAMESPACE
  3259. static const uint32 initialPValues [18] =
  3260. {
  3261. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  3262. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3263. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  3264. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3265. 0x9216d5d9, 0x8979fb1b
  3266. };
  3267. static const uint32 initialSValues [4 * 256] =
  3268. {
  3269. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  3270. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3271. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  3272. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3273. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  3274. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3275. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  3276. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3277. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  3278. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3279. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  3280. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3281. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  3282. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3283. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  3284. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3285. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  3286. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3287. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  3288. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3289. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  3290. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3291. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  3292. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3293. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  3294. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3295. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  3296. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3297. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  3298. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3299. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  3300. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3301. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  3302. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3303. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  3304. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3305. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  3306. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3307. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  3308. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3309. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  3310. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3311. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  3312. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3313. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  3314. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3315. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  3316. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3317. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  3318. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3319. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  3320. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3321. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  3322. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3323. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  3324. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3325. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  3326. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3327. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  3328. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3329. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  3330. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3331. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  3332. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3333. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  3334. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3335. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  3336. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3337. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  3338. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3339. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  3340. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3341. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  3342. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3343. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  3344. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3345. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  3346. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3347. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  3348. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3349. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  3350. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3351. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  3352. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3353. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  3354. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3355. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  3356. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3357. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  3358. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3359. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  3360. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3361. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  3362. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3363. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  3364. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3365. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  3366. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3367. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  3368. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3369. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  3370. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3371. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  3372. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3373. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  3374. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3375. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  3376. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3377. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  3378. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3379. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  3380. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3381. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  3382. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3383. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  3384. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3385. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  3386. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3387. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  3388. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3389. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  3390. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3391. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  3392. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3393. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  3394. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3395. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  3396. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3397. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  3398. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3399. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  3400. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3401. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  3402. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3403. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  3404. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3405. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  3406. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3407. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  3408. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3409. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  3410. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3411. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  3412. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3413. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  3414. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3415. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  3416. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3417. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  3418. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3419. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  3420. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3421. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  3422. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3423. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  3424. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3425. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  3426. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3427. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  3428. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3429. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  3430. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3431. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  3432. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3433. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  3434. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3435. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  3436. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3437. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  3438. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3439. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  3440. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3441. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  3442. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3443. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  3444. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3445. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  3446. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3447. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  3448. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3449. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  3450. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3451. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  3452. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3453. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  3454. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3455. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  3456. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3457. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  3458. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3459. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  3460. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3461. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  3462. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3463. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  3464. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3465. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  3466. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3467. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  3468. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3469. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  3470. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3471. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  3472. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3473. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  3474. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3475. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  3476. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3477. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  3478. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3479. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  3480. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3481. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  3482. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3483. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  3484. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3485. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  3486. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3487. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  3488. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3489. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  3490. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3491. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  3492. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3493. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  3494. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3495. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  3496. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3497. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  3498. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3499. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  3500. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3501. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  3502. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3503. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  3504. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3505. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  3506. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3507. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  3508. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3509. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  3510. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3511. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  3512. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3513. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  3514. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3515. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  3516. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3517. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  3518. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3519. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  3520. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3521. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  3522. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3523. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  3524. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3525. };
  3526. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  3527. {
  3528. memcpy (p, initialPValues, sizeof (p));
  3529. int i, j;
  3530. for (i = 4; --i >= 0;)
  3531. {
  3532. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3533. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3534. }
  3535. j = 0;
  3536. for (i = 0; i < 18; ++i)
  3537. {
  3538. uint32 d = 0;
  3539. for (int k = 0; k < 4; ++k)
  3540. {
  3541. d = (d << 8) | keyData[j];
  3542. if (++j >= keyBytes)
  3543. j = 0;
  3544. }
  3545. p[i] = initialPValues[i] ^ d;
  3546. }
  3547. uint32 l = 0, r = 0;
  3548. for (i = 0; i < 18; i += 2)
  3549. {
  3550. encrypt (l, r);
  3551. p[i] = l;
  3552. p[i + 1] = r;
  3553. }
  3554. for (i = 0; i < 4; ++i)
  3555. {
  3556. for (j = 0; j < 256; j += 2)
  3557. {
  3558. encrypt (l, r);
  3559. s[i][j] = l;
  3560. s[i][j + 1] = r;
  3561. }
  3562. }
  3563. }
  3564. BlowFish::BlowFish (const BlowFish& other)
  3565. {
  3566. for (int i = 4; --i >= 0;)
  3567. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3568. operator= (other);
  3569. }
  3570. const BlowFish& BlowFish::operator= (const BlowFish& other)
  3571. {
  3572. memcpy (p, other.p, sizeof (p));
  3573. for (int i = 4; --i >= 0;)
  3574. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3575. return *this;
  3576. }
  3577. BlowFish::~BlowFish()
  3578. {
  3579. for (int i = 4; --i >= 0;)
  3580. juce_free (s[i]);
  3581. }
  3582. uint32 BlowFish::F (uint32 x) const
  3583. {
  3584. uint16 a, b, c, d;
  3585. uint32 y;
  3586. d = (uint16) (x & 0xff);
  3587. x >>= 8;
  3588. c = (uint16) (x & 0xff);
  3589. x >>= 8;
  3590. b = (uint16) (x & 0xff);
  3591. x >>= 8;
  3592. a = (uint16) (x & 0xff);
  3593. y = s[0][a] + s[1][b];
  3594. y = y ^ s[2][c];
  3595. y = y + s[3][d];
  3596. return y;
  3597. }
  3598. void BlowFish::encrypt (uint32& data1,
  3599. uint32& data2) const
  3600. {
  3601. uint32 l = data1;
  3602. uint32 r = data2;
  3603. for (int i = 0; i < 16; ++i)
  3604. {
  3605. l = l ^ p[i];
  3606. r = F (l) ^ r;
  3607. const uint32 temp = l;
  3608. l = r;
  3609. r = temp;
  3610. }
  3611. const uint32 temp = l;
  3612. l = r;
  3613. r = temp;
  3614. r = r ^ p[16];
  3615. l = l ^ p[17];
  3616. data1 = l;
  3617. data2 = r;
  3618. }
  3619. void BlowFish::decrypt (uint32& data1,
  3620. uint32& data2) const
  3621. {
  3622. uint32 l = data1;
  3623. uint32 r = data2;
  3624. for (int i = 17; i > 1; --i)
  3625. {
  3626. l =l ^ p[i];
  3627. r = F (l) ^ r;
  3628. const uint32 temp = l;
  3629. l = r;
  3630. r = temp;
  3631. }
  3632. const uint32 temp = l;
  3633. l = r;
  3634. r = temp;
  3635. r = r ^ p[1];
  3636. l = l ^ p[0];
  3637. data1 = l;
  3638. data2 = r;
  3639. }
  3640. END_JUCE_NAMESPACE
  3641. /********* End of inlined file: juce_BlowFish.cpp *********/
  3642. /********* Start of inlined file: juce_MD5.cpp *********/
  3643. BEGIN_JUCE_NAMESPACE
  3644. MD5::MD5()
  3645. {
  3646. zeromem (result, sizeof (result));
  3647. }
  3648. MD5::MD5 (const MD5& other)
  3649. {
  3650. memcpy (result, other.result, sizeof (result));
  3651. }
  3652. const MD5& MD5::operator= (const MD5& other)
  3653. {
  3654. memcpy (result, other.result, sizeof (result));
  3655. return *this;
  3656. }
  3657. MD5::MD5 (const MemoryBlock& data)
  3658. {
  3659. ProcessContext context;
  3660. context.processBlock ((const uint8*) data.getData(), data.getSize());
  3661. context.finish (result);
  3662. }
  3663. MD5::MD5 (const char* data, const int numBytes)
  3664. {
  3665. ProcessContext context;
  3666. context.processBlock ((const uint8*) data, numBytes);
  3667. context.finish (result);
  3668. }
  3669. MD5::MD5 (const String& text)
  3670. {
  3671. ProcessContext context;
  3672. const int len = text.length();
  3673. const juce_wchar* const t = text;
  3674. for (int i = 0; i < len; ++i)
  3675. {
  3676. // force the string into integer-sized unicode characters, to try to make it
  3677. // get the same results on all platforms + compilers.
  3678. uint32 unicodeChar = (uint32) t[i];
  3679. swapIfBigEndian (unicodeChar);
  3680. context.processBlock ((const uint8*) &unicodeChar,
  3681. sizeof (unicodeChar));
  3682. }
  3683. context.finish (result);
  3684. }
  3685. void MD5::processStream (InputStream& input, int numBytesToRead)
  3686. {
  3687. ProcessContext context;
  3688. if (numBytesToRead < 0)
  3689. numBytesToRead = INT_MAX;
  3690. while (numBytesToRead > 0)
  3691. {
  3692. char tempBuffer [512];
  3693. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  3694. if (bytesRead <= 0)
  3695. break;
  3696. numBytesToRead -= bytesRead;
  3697. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  3698. }
  3699. context.finish (result);
  3700. }
  3701. MD5::MD5 (InputStream& input, int numBytesToRead)
  3702. {
  3703. processStream (input, numBytesToRead);
  3704. }
  3705. MD5::MD5 (const File& file)
  3706. {
  3707. FileInputStream* const fin = file.createInputStream();
  3708. if (fin != 0)
  3709. {
  3710. processStream (*fin, -1);
  3711. delete fin;
  3712. }
  3713. else
  3714. {
  3715. zeromem (result, sizeof (result));
  3716. }
  3717. }
  3718. MD5::~MD5()
  3719. {
  3720. }
  3721. MD5::ProcessContext::ProcessContext()
  3722. {
  3723. state[0] = 0x67452301;
  3724. state[1] = 0xefcdab89;
  3725. state[2] = 0x98badcfe;
  3726. state[3] = 0x10325476;
  3727. count[0] = 0;
  3728. count[1] = 0;
  3729. }
  3730. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  3731. {
  3732. int bufferPos = ((count[0] >> 3) & 0x3F);
  3733. count[0] += (dataSize << 3);
  3734. if (count[0] < ((uint32) dataSize << 3))
  3735. count[1]++;
  3736. count[1] += (dataSize >> 29);
  3737. const int spaceLeft = 64 - bufferPos;
  3738. int i = 0;
  3739. if (dataSize >= spaceLeft)
  3740. {
  3741. memcpy (buffer + bufferPos, data, spaceLeft);
  3742. transform (buffer);
  3743. i = spaceLeft;
  3744. while (i < dataSize - 63)
  3745. {
  3746. transform (data + i);
  3747. i += 64;
  3748. }
  3749. bufferPos = 0;
  3750. }
  3751. memcpy (buffer + bufferPos, data + i, dataSize - i);
  3752. }
  3753. static void encode (uint8* const output,
  3754. const uint32* const input,
  3755. const int numBytes)
  3756. {
  3757. uint32* const o = (uint32*) output;
  3758. for (int i = 0; i < (numBytes >> 2); ++i)
  3759. o[i] = swapIfBigEndian (input [i]);
  3760. }
  3761. static void decode (uint32* const output,
  3762. const uint8* const input,
  3763. const int numBytes)
  3764. {
  3765. for (int i = 0; i < (numBytes >> 2); ++i)
  3766. output[i] = littleEndianInt ((const char*) input + (i << 2));
  3767. }
  3768. void MD5::ProcessContext::finish (uint8* const result)
  3769. {
  3770. unsigned char encodedLength[8];
  3771. encode (encodedLength, count, 8);
  3772. // Pad out to 56 mod 64.
  3773. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3774. const int paddingLength = (index < 56) ? (56 - index)
  3775. : (120 - index);
  3776. uint8 paddingBuffer [64];
  3777. zeromem (paddingBuffer, paddingLength);
  3778. paddingBuffer [0] = 0x80;
  3779. processBlock (paddingBuffer, paddingLength);
  3780. processBlock (encodedLength, 8);
  3781. encode (result, state, 16);
  3782. zeromem (buffer, sizeof (buffer));
  3783. }
  3784. #define S11 7
  3785. #define S12 12
  3786. #define S13 17
  3787. #define S14 22
  3788. #define S21 5
  3789. #define S22 9
  3790. #define S23 14
  3791. #define S24 20
  3792. #define S31 4
  3793. #define S32 11
  3794. #define S33 16
  3795. #define S34 23
  3796. #define S41 6
  3797. #define S42 10
  3798. #define S43 15
  3799. #define S44 21
  3800. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  3801. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  3802. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  3803. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  3804. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  3805. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3806. {
  3807. a += F (b, c, d) + x + ac;
  3808. a = rotateLeft (a, s) + b;
  3809. }
  3810. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3811. {
  3812. a += G (b, c, d) + x + ac;
  3813. a = rotateLeft (a, s) + b;
  3814. }
  3815. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3816. {
  3817. a += H (b, c, d) + x + ac;
  3818. a = rotateLeft (a, s) + b;
  3819. }
  3820. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3821. {
  3822. a += I (b, c, d) + x + ac;
  3823. a = rotateLeft (a, s) + b;
  3824. }
  3825. void MD5::ProcessContext::transform (const uint8* const buffer)
  3826. {
  3827. uint32 a = state[0];
  3828. uint32 b = state[1];
  3829. uint32 c = state[2];
  3830. uint32 d = state[3];
  3831. uint32 x[16];
  3832. decode (x, buffer, 64);
  3833. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  3834. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  3835. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  3836. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  3837. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  3838. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  3839. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  3840. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  3841. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  3842. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  3843. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  3844. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  3845. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  3846. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  3847. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  3848. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  3849. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  3850. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  3851. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  3852. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  3853. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  3854. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  3855. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  3856. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  3857. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  3858. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  3859. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  3860. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  3861. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  3862. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  3863. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  3864. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  3865. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  3866. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  3867. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  3868. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  3869. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  3870. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  3871. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  3872. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  3873. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  3874. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  3875. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  3876. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  3877. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  3878. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  3879. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  3880. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  3881. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  3882. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  3883. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  3884. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  3885. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  3886. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  3887. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  3888. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  3889. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  3890. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  3891. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  3892. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  3893. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  3894. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  3895. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  3896. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  3897. state[0] += a;
  3898. state[1] += b;
  3899. state[2] += c;
  3900. state[3] += d;
  3901. zeromem (x, sizeof (x));
  3902. }
  3903. const MemoryBlock MD5::getRawChecksumData() const
  3904. {
  3905. return MemoryBlock (result, 16);
  3906. }
  3907. const String MD5::toHexString() const
  3908. {
  3909. return String::toHexString (result, 16, 0);
  3910. }
  3911. bool MD5::operator== (const MD5& other) const
  3912. {
  3913. return memcmp (result, other.result, 16) == 0;
  3914. }
  3915. bool MD5::operator!= (const MD5& other) const
  3916. {
  3917. return ! operator== (other);
  3918. }
  3919. END_JUCE_NAMESPACE
  3920. /********* End of inlined file: juce_MD5.cpp *********/
  3921. /********* Start of inlined file: juce_Primes.cpp *********/
  3922. BEGIN_JUCE_NAMESPACE
  3923. static void createSmallSieve (const int numBits, BitArray& result) throw()
  3924. {
  3925. result.setBit (numBits);
  3926. result.clearBit (numBits); // to enlarge the array
  3927. result.setBit (0);
  3928. int n = 2;
  3929. do
  3930. {
  3931. for (int i = n + n; i < numBits; i += n)
  3932. result.setBit (i);
  3933. n = result.findNextClearBit (n + 1);
  3934. }
  3935. while (n <= (numBits >> 1));
  3936. }
  3937. static void bigSieve (const BitArray& base,
  3938. const int numBits,
  3939. BitArray& result,
  3940. const BitArray& smallSieve,
  3941. const int smallSieveSize) throw()
  3942. {
  3943. jassert (! base[0]); // must be even!
  3944. result.setBit (numBits);
  3945. result.clearBit (numBits); // to enlarge the array
  3946. int index = smallSieve.findNextClearBit (0);
  3947. do
  3948. {
  3949. const int prime = (index << 1) + 1;
  3950. BitArray r (base);
  3951. BitArray remainder;
  3952. r.divideBy (prime, remainder);
  3953. int i = prime - remainder.getBitRangeAsInt (0, 32);
  3954. if (r.isEmpty())
  3955. i += prime;
  3956. if ((i & 1) == 0)
  3957. i += prime;
  3958. i = (i - 1) >> 1;
  3959. while (i < numBits)
  3960. {
  3961. result.setBit (i);
  3962. i += prime;
  3963. }
  3964. index = smallSieve.findNextClearBit (index + 1);
  3965. }
  3966. while (index < smallSieveSize);
  3967. }
  3968. static bool findCandidate (const BitArray& base,
  3969. const BitArray& sieve,
  3970. const int numBits,
  3971. BitArray& result,
  3972. const int certainty) throw()
  3973. {
  3974. for (int i = 0; i < numBits; ++i)
  3975. {
  3976. if (! sieve[i])
  3977. {
  3978. result = base;
  3979. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  3980. if (Primes::isProbablyPrime (result, certainty))
  3981. return true;
  3982. }
  3983. }
  3984. return false;
  3985. }
  3986. const BitArray Primes::createProbablePrime (const int bitLength,
  3987. const int certainty,
  3988. const int* randomSeeds,
  3989. int numRandomSeeds) throw()
  3990. {
  3991. int defaultSeeds [16];
  3992. if (numRandomSeeds <= 0)
  3993. {
  3994. randomSeeds = defaultSeeds;
  3995. numRandomSeeds = numElementsInArray (defaultSeeds);
  3996. Random r (0);
  3997. for (int j = 10; --j >= 0;)
  3998. {
  3999. r.setSeedRandomly();
  4000. for (int i = numRandomSeeds; --i >= 0;)
  4001. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4002. }
  4003. }
  4004. BitArray smallSieve;
  4005. const int smallSieveSize = 15000;
  4006. createSmallSieve (smallSieveSize, smallSieve);
  4007. BitArray p;
  4008. for (int i = numRandomSeeds; --i >= 0;)
  4009. {
  4010. BitArray p2;
  4011. Random r (randomSeeds[i]);
  4012. r.fillBitsRandomly (p2, 0, bitLength);
  4013. p.xorWith (p2);
  4014. }
  4015. p.setBit (bitLength - 1);
  4016. p.clearBit (0);
  4017. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4018. while (p.getHighestBit() < bitLength)
  4019. {
  4020. p.add (2 * searchLen);
  4021. BitArray sieve;
  4022. bigSieve (p, searchLen, sieve,
  4023. smallSieve, smallSieveSize);
  4024. BitArray candidate;
  4025. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4026. return candidate;
  4027. }
  4028. jassertfalse
  4029. return BitArray();
  4030. }
  4031. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  4032. {
  4033. const BitArray one (1);
  4034. const BitArray two (2);
  4035. BitArray nMinusOne (n);
  4036. nMinusOne.subtract (one);
  4037. BitArray d (nMinusOne);
  4038. const int s = d.findNextSetBit (0);
  4039. d.shiftBits (-s);
  4040. BitArray smallPrimes;
  4041. int numBitsInSmallPrimes = 0;
  4042. for (;;)
  4043. {
  4044. numBitsInSmallPrimes += 256;
  4045. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4046. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4047. if (numPrimesFound > iterations + 1)
  4048. break;
  4049. }
  4050. int smallPrime = 2;
  4051. while (--iterations >= 0)
  4052. {
  4053. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4054. BitArray r (smallPrime);
  4055. //r.createRandomNumber (nMinusOne);
  4056. r.exponentModulo (d, n);
  4057. if (! (r == one || r == nMinusOne))
  4058. {
  4059. for (int j = 0; j < s; ++j)
  4060. {
  4061. r.exponentModulo (two, n);
  4062. if (r == nMinusOne)
  4063. break;
  4064. }
  4065. if (r != nMinusOne)
  4066. return false;
  4067. }
  4068. }
  4069. return true;
  4070. }
  4071. bool Primes::isProbablyPrime (const BitArray& number,
  4072. const int certainty) throw()
  4073. {
  4074. if (! number[0])
  4075. return false;
  4076. if (number.getHighestBit() <= 10)
  4077. {
  4078. const int num = number.getBitRangeAsInt (0, 10);
  4079. for (int i = num / 2; --i > 1;)
  4080. if (num % i == 0)
  4081. return false;
  4082. return true;
  4083. }
  4084. else
  4085. {
  4086. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  4087. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  4088. return false;
  4089. return passesMillerRabin (number, certainty);
  4090. }
  4091. }
  4092. END_JUCE_NAMESPACE
  4093. /********* End of inlined file: juce_Primes.cpp *********/
  4094. /********* Start of inlined file: juce_RSAKey.cpp *********/
  4095. BEGIN_JUCE_NAMESPACE
  4096. RSAKey::RSAKey() throw()
  4097. {
  4098. }
  4099. RSAKey::RSAKey (const String& s) throw()
  4100. {
  4101. if (s.containsChar (T(',')))
  4102. {
  4103. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  4104. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  4105. }
  4106. else
  4107. {
  4108. // the string needs to be two hex numbers, comma-separated..
  4109. jassertfalse;
  4110. }
  4111. }
  4112. RSAKey::~RSAKey() throw()
  4113. {
  4114. }
  4115. const String RSAKey::toString() const throw()
  4116. {
  4117. return part1.toString (16) + T(",") + part2.toString (16);
  4118. }
  4119. bool RSAKey::applyToValue (BitArray& value) const throw()
  4120. {
  4121. if (part1.isEmpty() || part2.isEmpty()
  4122. || value.compare (0) <= 0)
  4123. {
  4124. jassertfalse // using an uninitialised key
  4125. value.clear();
  4126. return false;
  4127. }
  4128. BitArray result;
  4129. while (! value.isEmpty())
  4130. {
  4131. result.multiplyBy (part2);
  4132. BitArray remainder;
  4133. value.divideBy (part2, remainder);
  4134. remainder.exponentModulo (part1, part2);
  4135. result.add (remainder);
  4136. }
  4137. value = result;
  4138. return true;
  4139. }
  4140. static const BitArray findBestCommonDivisor (const BitArray& p,
  4141. const BitArray& q) throw()
  4142. {
  4143. const BitArray one (1);
  4144. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4145. // are fast to divide + multiply
  4146. for (int i = 2; i <= 65536; i *= 2)
  4147. {
  4148. const BitArray e (1 + i);
  4149. if (e.findGreatestCommonDivisor (p) == one
  4150. && e.findGreatestCommonDivisor (q) == one)
  4151. {
  4152. return e;
  4153. }
  4154. }
  4155. BitArray e (4);
  4156. while (! (e.findGreatestCommonDivisor (p) == one
  4157. && e.findGreatestCommonDivisor (q) == one))
  4158. {
  4159. e.add (one);
  4160. }
  4161. return e;
  4162. }
  4163. void RSAKey::createKeyPair (RSAKey& publicKey,
  4164. RSAKey& privateKey,
  4165. const int numBits,
  4166. const int* randomSeeds,
  4167. const int numRandomSeeds) throw()
  4168. {
  4169. jassert (numBits > 16); // not much point using less than this..
  4170. BitArray p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4171. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4172. BitArray n (p);
  4173. n.multiplyBy (q); // n = pq
  4174. const BitArray one (1);
  4175. p.subtract (one);
  4176. q.subtract (one);
  4177. BitArray m (p);
  4178. m.multiplyBy (q); // m = (p - 1)(q - 1)
  4179. const BitArray e (findBestCommonDivisor (p, q));
  4180. BitArray d (e);
  4181. d.inverseModulo (m);
  4182. publicKey.part1 = e;
  4183. publicKey.part2 = n;
  4184. privateKey.part1 = d;
  4185. privateKey.part2 = n;
  4186. }
  4187. END_JUCE_NAMESPACE
  4188. /********* End of inlined file: juce_RSAKey.cpp *********/
  4189. /********* Start of inlined file: juce_InputStream.cpp *********/
  4190. BEGIN_JUCE_NAMESPACE
  4191. char InputStream::readByte()
  4192. {
  4193. char temp = 0;
  4194. read (&temp, 1);
  4195. return temp;
  4196. }
  4197. bool InputStream::readBool()
  4198. {
  4199. return readByte() != 0;
  4200. }
  4201. short InputStream::readShort()
  4202. {
  4203. char temp [2];
  4204. if (read (temp, 2) == 2)
  4205. return (short) littleEndianShort (temp);
  4206. else
  4207. return 0;
  4208. }
  4209. short InputStream::readShortBigEndian()
  4210. {
  4211. char temp [2];
  4212. if (read (temp, 2) == 2)
  4213. return (short) bigEndianShort (temp);
  4214. else
  4215. return 0;
  4216. }
  4217. int InputStream::readInt()
  4218. {
  4219. char temp [4];
  4220. if (read (temp, 4) == 4)
  4221. return (int) littleEndianInt (temp);
  4222. else
  4223. return 0;
  4224. }
  4225. int InputStream::readIntBigEndian()
  4226. {
  4227. char temp [4];
  4228. if (read (temp, 4) == 4)
  4229. return (int) bigEndianInt (temp);
  4230. else
  4231. return 0;
  4232. }
  4233. int InputStream::readCompressedInt()
  4234. {
  4235. int num = 0;
  4236. if (! isExhausted())
  4237. {
  4238. unsigned char numBytes = readByte();
  4239. const bool negative = (numBytes & 0x80) != 0;
  4240. numBytes &= 0x7f;
  4241. if (numBytes <= 4)
  4242. {
  4243. if (read (&num, numBytes) != numBytes)
  4244. return 0;
  4245. if (negative)
  4246. num = -num;
  4247. }
  4248. }
  4249. return num;
  4250. }
  4251. int64 InputStream::readInt64()
  4252. {
  4253. char temp [8];
  4254. if (read (temp, 8) == 8)
  4255. return (int64) swapIfBigEndian (*(uint64*)temp);
  4256. else
  4257. return 0;
  4258. }
  4259. int64 InputStream::readInt64BigEndian()
  4260. {
  4261. char temp [8];
  4262. if (read (temp, 8) == 8)
  4263. return (int64) swapIfLittleEndian (*(uint64*)temp);
  4264. else
  4265. return 0;
  4266. }
  4267. float InputStream::readFloat()
  4268. {
  4269. union { int asInt; float asFloat; } n;
  4270. n.asInt = readInt();
  4271. return n.asFloat;
  4272. }
  4273. float InputStream::readFloatBigEndian()
  4274. {
  4275. union { int asInt; float asFloat; } n;
  4276. n.asInt = readIntBigEndian();
  4277. return n.asFloat;
  4278. }
  4279. double InputStream::readDouble()
  4280. {
  4281. union { int64 asInt; double asDouble; } n;
  4282. n.asInt = readInt64();
  4283. return n.asDouble;
  4284. }
  4285. double InputStream::readDoubleBigEndian()
  4286. {
  4287. union { int64 asInt; double asDouble; } n;
  4288. n.asInt = readInt64BigEndian();
  4289. return n.asDouble;
  4290. }
  4291. const String InputStream::readString()
  4292. {
  4293. const int tempBufferSize = 256;
  4294. uint8 temp [tempBufferSize];
  4295. int i = 0;
  4296. while ((temp [i++] = readByte()) != 0)
  4297. {
  4298. if (i == tempBufferSize)
  4299. {
  4300. // too big for our quick buffer, so read it in blocks..
  4301. String result (String::fromUTF8 (temp, i));
  4302. i = 0;
  4303. for (;;)
  4304. {
  4305. if ((temp [i++] = readByte()) == 0)
  4306. {
  4307. result += String::fromUTF8 (temp, i - 1);
  4308. break;
  4309. }
  4310. else if (i == tempBufferSize)
  4311. {
  4312. result += String::fromUTF8 (temp, i);
  4313. i = 0;
  4314. }
  4315. }
  4316. return result;
  4317. }
  4318. }
  4319. return String::fromUTF8 (temp, i - 1);
  4320. }
  4321. const String InputStream::readNextLine()
  4322. {
  4323. String s;
  4324. const int maxChars = 256;
  4325. tchar buffer [maxChars];
  4326. int charsInBuffer = 0;
  4327. while (! isExhausted())
  4328. {
  4329. const uint8 c = readByte();
  4330. const int64 lastPos = getPosition();
  4331. if (c == '\n')
  4332. {
  4333. break;
  4334. }
  4335. else if (c == '\r')
  4336. {
  4337. if (readByte() != '\n')
  4338. setPosition (lastPos);
  4339. break;
  4340. }
  4341. buffer [charsInBuffer++] = c;
  4342. if (charsInBuffer == maxChars)
  4343. {
  4344. s.append (buffer, maxChars);
  4345. charsInBuffer = 0;
  4346. }
  4347. }
  4348. if (charsInBuffer > 0)
  4349. s.append (buffer, charsInBuffer);
  4350. return s;
  4351. }
  4352. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  4353. int numBytes)
  4354. {
  4355. const int64 totalLength = getTotalLength();
  4356. if (totalLength >= 0)
  4357. {
  4358. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4359. totalLength - getPosition());
  4360. if (numBytes < 0)
  4361. numBytes = totalBytesRemaining;
  4362. else if (numBytes > 0)
  4363. numBytes = jmin (numBytes, totalBytesRemaining);
  4364. else
  4365. return 0;
  4366. }
  4367. const int originalBlockSize = block.getSize();
  4368. int totalBytesRead = 0;
  4369. if (numBytes > 0)
  4370. {
  4371. // know how many bytes we want, so we can resize the block first..
  4372. block.setSize (originalBlockSize + numBytes, false);
  4373. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  4374. }
  4375. else
  4376. {
  4377. // read until end of stram..
  4378. const int chunkSize = 32768;
  4379. for (;;)
  4380. {
  4381. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4382. const int bytesJustIn = read (((char*) block.getData())
  4383. + originalBlockSize
  4384. + totalBytesRead,
  4385. chunkSize);
  4386. if (bytesJustIn == 0)
  4387. break;
  4388. totalBytesRead += bytesJustIn;
  4389. }
  4390. }
  4391. // trim off any excess left at the end
  4392. block.setSize (originalBlockSize + totalBytesRead, false);
  4393. return totalBytesRead;
  4394. }
  4395. const String InputStream::readEntireStreamAsString()
  4396. {
  4397. MemoryBlock mb;
  4398. const int size = readIntoMemoryBlock (mb);
  4399. return String::createStringFromData ((const char*) mb.getData(), size);
  4400. }
  4401. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4402. {
  4403. if (numBytesToSkip > 0)
  4404. {
  4405. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4406. MemoryBlock temp (skipBufferSize);
  4407. while ((numBytesToSkip > 0) && ! isExhausted())
  4408. {
  4409. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4410. }
  4411. }
  4412. }
  4413. END_JUCE_NAMESPACE
  4414. /********* End of inlined file: juce_InputStream.cpp *********/
  4415. /********* Start of inlined file: juce_OutputStream.cpp *********/
  4416. BEGIN_JUCE_NAMESPACE
  4417. #if JUCE_DEBUG
  4418. static CriticalSection activeStreamLock;
  4419. static VoidArray activeStreams;
  4420. void juce_CheckForDanglingStreams()
  4421. {
  4422. /*
  4423. It's always a bad idea to leak any object, but if you're leaking output
  4424. streams, then there's a good chance that you're failing to flush a file
  4425. to disk properly, which could result in corrupted data and other similar
  4426. nastiness..
  4427. */
  4428. jassert (activeStreams.size() == 0);
  4429. };
  4430. #endif
  4431. OutputStream::OutputStream() throw()
  4432. {
  4433. #if JUCE_DEBUG
  4434. activeStreamLock.enter();
  4435. activeStreams.add (this);
  4436. activeStreamLock.exit();
  4437. #endif
  4438. }
  4439. OutputStream::~OutputStream()
  4440. {
  4441. #if JUCE_DEBUG
  4442. activeStreamLock.enter();
  4443. activeStreams.removeValue (this);
  4444. activeStreamLock.exit();
  4445. #endif
  4446. }
  4447. void OutputStream::writeBool (bool b)
  4448. {
  4449. writeByte ((b) ? (char) 1
  4450. : (char) 0);
  4451. }
  4452. void OutputStream::writeByte (char byte)
  4453. {
  4454. write (&byte, 1);
  4455. }
  4456. void OutputStream::writeShort (short value)
  4457. {
  4458. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  4459. write (&v, 2);
  4460. }
  4461. void OutputStream::writeShortBigEndian (short value)
  4462. {
  4463. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  4464. write (&v, 2);
  4465. }
  4466. void OutputStream::writeInt (int value)
  4467. {
  4468. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  4469. write (&v, 4);
  4470. }
  4471. void OutputStream::writeIntBigEndian (int value)
  4472. {
  4473. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  4474. write (&v, 4);
  4475. }
  4476. void OutputStream::writeCompressedInt (int value)
  4477. {
  4478. unsigned int un = (value < 0) ? (unsigned int) -value
  4479. : (unsigned int) value;
  4480. unsigned int tn = un;
  4481. int numSigBytes = 0;
  4482. do
  4483. {
  4484. tn >>= 8;
  4485. numSigBytes++;
  4486. } while (tn & 0xff);
  4487. if (value < 0)
  4488. numSigBytes |= 0x80;
  4489. writeByte ((char) numSigBytes);
  4490. write (&un, numSigBytes);
  4491. }
  4492. void OutputStream::writeInt64 (int64 value)
  4493. {
  4494. const uint64 v = swapIfBigEndian ((uint64) value);
  4495. write (&v, 8);
  4496. }
  4497. void OutputStream::writeInt64BigEndian (int64 value)
  4498. {
  4499. const uint64 v = swapIfLittleEndian ((uint64) value);
  4500. write (&v, 8);
  4501. }
  4502. void OutputStream::writeFloat (float value)
  4503. {
  4504. union { int asInt; float asFloat; } n;
  4505. n.asFloat = value;
  4506. writeInt (n.asInt);
  4507. }
  4508. void OutputStream::writeFloatBigEndian (float value)
  4509. {
  4510. union { int asInt; float asFloat; } n;
  4511. n.asFloat = value;
  4512. writeIntBigEndian (n.asInt);
  4513. }
  4514. void OutputStream::writeDouble (double value)
  4515. {
  4516. union { int64 asInt; double asDouble; } n;
  4517. n.asDouble = value;
  4518. writeInt64 (n.asInt);
  4519. }
  4520. void OutputStream::writeDoubleBigEndian (double value)
  4521. {
  4522. union { int64 asInt; double asDouble; } n;
  4523. n.asDouble = value;
  4524. writeInt64BigEndian (n.asInt);
  4525. }
  4526. void OutputStream::writeString (const String& text)
  4527. {
  4528. const int numBytes = text.copyToUTF8 (0);
  4529. uint8* const temp = (uint8*) juce_malloc (numBytes);
  4530. text.copyToUTF8 (temp);
  4531. write (temp, numBytes); // (numBytes includes the terminating null).
  4532. juce_free (temp);
  4533. }
  4534. void OutputStream::printf (const char* pf, ...)
  4535. {
  4536. unsigned int bufSize = 256;
  4537. char* buf = (char*) juce_malloc (bufSize);
  4538. for (;;)
  4539. {
  4540. va_list list;
  4541. va_start (list, pf);
  4542. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  4543. va_end (list);
  4544. if (num > 0)
  4545. {
  4546. write (buf, num);
  4547. break;
  4548. }
  4549. else if (num == 0)
  4550. {
  4551. break;
  4552. }
  4553. juce_free (buf);
  4554. bufSize += 256;
  4555. buf = (char*) juce_malloc (bufSize);
  4556. }
  4557. juce_free (buf);
  4558. }
  4559. OutputStream& OutputStream::operator<< (const int number)
  4560. {
  4561. const String s (number);
  4562. write ((const char*) s, s.length());
  4563. return *this;
  4564. }
  4565. OutputStream& OutputStream::operator<< (const double number)
  4566. {
  4567. const String s (number);
  4568. write ((const char*) s, s.length());
  4569. return *this;
  4570. }
  4571. OutputStream& OutputStream::operator<< (const char character)
  4572. {
  4573. writeByte (character);
  4574. return *this;
  4575. }
  4576. OutputStream& OutputStream::operator<< (const char* const text)
  4577. {
  4578. write (text, (int) strlen (text));
  4579. return *this;
  4580. }
  4581. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  4582. {
  4583. const String s (text);
  4584. write ((const char*) s, s.length());
  4585. return *this;
  4586. }
  4587. OutputStream& OutputStream::operator<< (const String& text)
  4588. {
  4589. write ((const char*) text,
  4590. text.length());
  4591. return *this;
  4592. }
  4593. void OutputStream::writeText (const String& text,
  4594. const bool asUnicode,
  4595. const bool writeUnicodeHeaderBytes)
  4596. {
  4597. if (asUnicode)
  4598. {
  4599. if (writeUnicodeHeaderBytes)
  4600. write ("\x0ff\x0fe", 2);
  4601. const juce_wchar* src = (const juce_wchar*) text;
  4602. bool lastCharWasReturn = false;
  4603. while (*src != 0)
  4604. {
  4605. if (*src == L'\n' && ! lastCharWasReturn)
  4606. writeShort ((short) L'\r');
  4607. lastCharWasReturn = (*src == L'\r');
  4608. writeShort ((short) *src++);
  4609. }
  4610. }
  4611. else
  4612. {
  4613. const char* src = (const char*) text;
  4614. const char* t = src;
  4615. for (;;)
  4616. {
  4617. if (*t == '\n')
  4618. {
  4619. if (t > src)
  4620. write (src, (int) (t - src));
  4621. write ("\r\n", 2);
  4622. src = t + 1;
  4623. }
  4624. else if (*t == '\r')
  4625. {
  4626. if (t[1] == '\n')
  4627. ++t;
  4628. }
  4629. else if (*t == 0)
  4630. {
  4631. if (t > src)
  4632. write (src, (int) (t - src));
  4633. break;
  4634. }
  4635. ++t;
  4636. }
  4637. }
  4638. }
  4639. int OutputStream::writeFromInputStream (InputStream& source,
  4640. int numBytesToWrite)
  4641. {
  4642. if (numBytesToWrite < 0)
  4643. numBytesToWrite = 0x7fffffff;
  4644. int numWritten = 0;
  4645. while (numBytesToWrite > 0 && ! source.isExhausted())
  4646. {
  4647. char buffer [8192];
  4648. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  4649. if (num == 0)
  4650. break;
  4651. write (buffer, num);
  4652. numBytesToWrite -= num;
  4653. numWritten += num;
  4654. }
  4655. return numWritten;
  4656. }
  4657. END_JUCE_NAMESPACE
  4658. /********* End of inlined file: juce_OutputStream.cpp *********/
  4659. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  4660. BEGIN_JUCE_NAMESPACE
  4661. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4662. bool* isDirectory, bool* isHidden, int64* fileSize,
  4663. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4664. bool juce_findFileNext (void* handle, String& resultFile,
  4665. bool* isDirectory, bool* isHidden, int64* fileSize,
  4666. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4667. void juce_findFileClose (void* handle) throw();
  4668. DirectoryIterator::DirectoryIterator (const File& directory,
  4669. bool isRecursive,
  4670. const String& wc,
  4671. const int whatToLookFor_) throw()
  4672. : wildCard (wc),
  4673. index (-1),
  4674. whatToLookFor (whatToLookFor_),
  4675. subIterator (0)
  4676. {
  4677. // you have to specify the type of files you're looking for!
  4678. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4679. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4680. String path (directory.getFullPathName());
  4681. if (! path.endsWithChar (File::separator))
  4682. path += File::separator;
  4683. String filename;
  4684. bool isDirectory, isHidden;
  4685. void* const handle = juce_findFileStart (path,
  4686. isRecursive ? T("*") : wc,
  4687. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  4688. if (handle != 0)
  4689. {
  4690. do
  4691. {
  4692. if (! filename.containsOnly (T(".")))
  4693. {
  4694. bool addToList = false;
  4695. if (isDirectory)
  4696. {
  4697. if (isRecursive
  4698. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  4699. || ! isHidden))
  4700. {
  4701. dirsFound.add (new File (path + filename, 0));
  4702. }
  4703. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  4704. }
  4705. else
  4706. {
  4707. addToList = (whatToLookFor_ & File::findFiles) != 0;
  4708. }
  4709. // if it's recursive, we're not relying on the OS iterator
  4710. // to do the wildcard match, so do it now..
  4711. if (isRecursive && addToList)
  4712. addToList = filename.matchesWildcard (wc, true);
  4713. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  4714. addToList = ! isHidden;
  4715. if (addToList)
  4716. filesFound.add (new File (path + filename, 0));
  4717. }
  4718. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4719. juce_findFileClose (handle);
  4720. }
  4721. }
  4722. DirectoryIterator::~DirectoryIterator() throw()
  4723. {
  4724. if (subIterator != 0)
  4725. delete subIterator;
  4726. }
  4727. bool DirectoryIterator::next() throw()
  4728. {
  4729. if (subIterator != 0)
  4730. {
  4731. if (subIterator->next())
  4732. return true;
  4733. deleteAndZero (subIterator);
  4734. }
  4735. if (index >= filesFound.size() + dirsFound.size() - 1)
  4736. return false;
  4737. ++index;
  4738. if (index >= filesFound.size())
  4739. {
  4740. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  4741. true, wildCard, whatToLookFor);
  4742. return next();
  4743. }
  4744. return true;
  4745. }
  4746. const File DirectoryIterator::getFile() const throw()
  4747. {
  4748. if (subIterator != 0)
  4749. return subIterator->getFile();
  4750. const File* const f = filesFound [index];
  4751. return (f != 0) ? *f
  4752. : File::nonexistent;
  4753. }
  4754. float DirectoryIterator::getEstimatedProgress() const throw()
  4755. {
  4756. if (filesFound.size() + dirsFound.size() == 0)
  4757. {
  4758. return 0.0f;
  4759. }
  4760. else
  4761. {
  4762. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4763. : (float) index;
  4764. return detailedIndex / (filesFound.size() + dirsFound.size());
  4765. }
  4766. }
  4767. END_JUCE_NAMESPACE
  4768. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  4769. /********* Start of inlined file: juce_File.cpp *********/
  4770. #ifdef _MSC_VER
  4771. #pragma warning (disable: 4514)
  4772. #pragma warning (push)
  4773. #endif
  4774. #if ! JUCE_WINDOWS
  4775. #include <pwd.h>
  4776. #endif
  4777. BEGIN_JUCE_NAMESPACE
  4778. #ifdef _MSC_VER
  4779. #pragma warning (pop)
  4780. #endif
  4781. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4782. void juce_fileClose (void* handle) throw();
  4783. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4784. int64 juce_fileGetPosition (void* handle) throw();
  4785. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4786. void juce_fileFlush (void* handle) throw();
  4787. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  4788. bool juce_isDirectory (const String& fileName) throw();
  4789. int64 juce_getFileSize (const String& fileName) throw();
  4790. bool juce_canWriteToFile (const String& fileName) throw();
  4791. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  4792. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  4793. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  4794. bool juce_deleteFile (const String& fileName) throw();
  4795. bool juce_copyFile (const String& source, const String& dest) throw();
  4796. bool juce_moveFile (const String& source, const String& dest) throw();
  4797. // this must also create all paths involved in the directory.
  4798. void juce_createDirectory (const String& fileName) throw();
  4799. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  4800. const StringArray juce_getFileSystemRoots() throw();
  4801. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  4802. // starts a directory search operation with a wildcard, returning a handle for
  4803. // use in calls to juce_findFileNext.
  4804. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  4805. // the other pointers, if non-null, are set based on the properties of the file.
  4806. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4807. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  4808. Time* creationTime, bool* isReadOnly) throw();
  4809. // returns false when no more files are found
  4810. bool juce_findFileNext (void* handle, String& resultFile,
  4811. bool* isDirectory, bool* isHidden, int64* fileSize,
  4812. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4813. void juce_findFileClose (void* handle) throw();
  4814. static const String juce_addTrailingSeparator (const String& path) throw()
  4815. {
  4816. return path.endsWithChar (File::separator) ? path
  4817. : path + File::separator;
  4818. }
  4819. static const String parseAbsolutePath (String path) throw()
  4820. {
  4821. if (path.isEmpty())
  4822. return String::empty;
  4823. #if JUCE_WINDOWS
  4824. // Windows..
  4825. path = path.replaceCharacter (T('/'), T('\\'));
  4826. if (path.startsWithChar (File::separator))
  4827. {
  4828. if (path[1] != File::separator)
  4829. {
  4830. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  4831. // Windows, because it needs a drive letter, which in this case
  4832. // we'll take from the CWD.. but this is a bit of an assumption that
  4833. // could be wrong..
  4834. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4835. }
  4836. }
  4837. else if (path.indexOfChar (T(':')) < 0)
  4838. {
  4839. if (path.isEmpty())
  4840. return String::empty;
  4841. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4842. // we don't know what directory to put it in.
  4843. // Here we'll assume it's in the CWD, but this might not be what was
  4844. // intended..
  4845. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4846. }
  4847. #else
  4848. // Mac or Linux..
  4849. path = path.replaceCharacter (T('\\'), T('/'));
  4850. if (path.startsWithChar (T('~')))
  4851. {
  4852. const char* homeDir = 0;
  4853. if (path[1] == File::separator || path[1] == 0)
  4854. {
  4855. // expand a name of the form "~/abc"
  4856. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4857. + path.substring (1);
  4858. }
  4859. else
  4860. {
  4861. // expand a name of type "~dave/abc"
  4862. const String userName (path.substring (1)
  4863. .upToFirstOccurrenceOf (T("/"), false, false));
  4864. struct passwd* const pw = getpwnam (userName);
  4865. if (pw != 0)
  4866. {
  4867. String home (homeDir);
  4868. if (home.endsWithChar (File::separator))
  4869. home [home.length() - 1] = 0;
  4870. path = String (pw->pw_dir)
  4871. + path.substring (userName.length());
  4872. }
  4873. }
  4874. }
  4875. else if (! path.startsWithChar (File::separator))
  4876. {
  4877. while (path.startsWith (T("./")))
  4878. path = path.substring (2);
  4879. if (path.isEmpty())
  4880. return String::empty;
  4881. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4882. // we don't know what directory to put it in.
  4883. // Here we'll assume it's in the CWD, but this might not be what was
  4884. // intended..
  4885. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4886. }
  4887. #endif
  4888. int len = path.length();
  4889. while (--len > 0 && path [len] == File::separator)
  4890. path [len] = 0;
  4891. return path;
  4892. }
  4893. const File File::nonexistent;
  4894. File::File (const String& fullPathName) throw()
  4895. : fullPath (parseAbsolutePath (fullPathName))
  4896. {
  4897. }
  4898. File::File (const String& path, int) throw()
  4899. : fullPath (path)
  4900. {
  4901. }
  4902. File::File (const File& other) throw()
  4903. : fullPath (other.fullPath)
  4904. {
  4905. }
  4906. const File& File::operator= (const String& newPath) throw()
  4907. {
  4908. fullPath = parseAbsolutePath (newPath);
  4909. return *this;
  4910. }
  4911. const File& File::operator= (const File& other) throw()
  4912. {
  4913. fullPath = other.fullPath;
  4914. return *this;
  4915. }
  4916. #if JUCE_LINUX
  4917. #define NAMES_ARE_CASE_SENSITIVE 1
  4918. #endif
  4919. bool File::areFileNamesCaseSensitive()
  4920. {
  4921. #if NAMES_ARE_CASE_SENSITIVE
  4922. return true;
  4923. #else
  4924. return false;
  4925. #endif
  4926. }
  4927. bool File::operator== (const File& other) const throw()
  4928. {
  4929. // case-insensitive on Windows, but not on linux.
  4930. #if NAMES_ARE_CASE_SENSITIVE
  4931. return fullPath == other.fullPath;
  4932. #else
  4933. return fullPath.equalsIgnoreCase (other.fullPath);
  4934. #endif
  4935. }
  4936. bool File::operator!= (const File& other) const throw()
  4937. {
  4938. return ! operator== (other);
  4939. }
  4940. bool File::exists() const throw()
  4941. {
  4942. return juce_fileExists (fullPath, false);
  4943. }
  4944. bool File::existsAsFile() const throw()
  4945. {
  4946. return juce_fileExists (fullPath, true);
  4947. }
  4948. bool File::isDirectory() const throw()
  4949. {
  4950. return juce_isDirectory (fullPath);
  4951. }
  4952. bool File::hasWriteAccess() const throw()
  4953. {
  4954. if (exists())
  4955. return juce_canWriteToFile (fullPath);
  4956. #if ! JUCE_WINDOWS
  4957. else if ((! isDirectory()) && fullPath.containsChar (separator))
  4958. return getParentDirectory().hasWriteAccess();
  4959. else
  4960. return false;
  4961. #else
  4962. // on windows, it seems that even read-only directories can still be written into,
  4963. // so checking the parent directory's permissions would return the wrong result..
  4964. else
  4965. return true;
  4966. #endif
  4967. }
  4968. bool File::setReadOnly (const bool shouldBeReadOnly,
  4969. const bool applyRecursively) const throw()
  4970. {
  4971. bool worked = true;
  4972. if (applyRecursively && isDirectory())
  4973. {
  4974. OwnedArray <File> subFiles;
  4975. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4976. for (int i = subFiles.size(); --i >= 0;)
  4977. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  4978. }
  4979. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  4980. }
  4981. bool File::deleteFile() const throw()
  4982. {
  4983. return (! exists())
  4984. || juce_deleteFile (fullPath);
  4985. }
  4986. bool File::deleteRecursively() const throw()
  4987. {
  4988. bool worked = true;
  4989. if (isDirectory())
  4990. {
  4991. OwnedArray<File> subFiles;
  4992. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4993. for (int i = subFiles.size(); --i >= 0;)
  4994. worked = subFiles[i]->deleteRecursively() && worked;
  4995. }
  4996. return deleteFile() && worked;
  4997. }
  4998. bool File::moveFileTo (const File& newFile) const throw()
  4999. {
  5000. if (newFile.fullPath == fullPath)
  5001. return true;
  5002. #if ! NAMES_ARE_CASE_SENSITIVE
  5003. if (*this != newFile)
  5004. #endif
  5005. if (! newFile.deleteFile())
  5006. return false;
  5007. return juce_moveFile (fullPath, newFile.fullPath);
  5008. }
  5009. bool File::copyFileTo (const File& newFile) const throw()
  5010. {
  5011. if (*this == newFile)
  5012. return true;
  5013. if (! newFile.deleteFile())
  5014. return false;
  5015. return juce_copyFile (fullPath, newFile.fullPath);
  5016. }
  5017. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  5018. {
  5019. if (isDirectory() && newDirectory.createDirectory())
  5020. {
  5021. OwnedArray<File> subFiles;
  5022. findChildFiles (subFiles, File::findFiles, false);
  5023. int i;
  5024. for (i = 0; i < subFiles.size(); ++i)
  5025. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  5026. return false;
  5027. subFiles.clear();
  5028. findChildFiles (subFiles, File::findDirectories, false);
  5029. for (i = 0; i < subFiles.size(); ++i)
  5030. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  5031. return false;
  5032. return true;
  5033. }
  5034. return false;
  5035. }
  5036. const String File::getPathUpToLastSlash() const throw()
  5037. {
  5038. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5039. if (lastSlash > 0)
  5040. return fullPath.substring (0, lastSlash);
  5041. else if (lastSlash == 0)
  5042. return separatorString;
  5043. else
  5044. return fullPath;
  5045. }
  5046. const File File::getParentDirectory() const throw()
  5047. {
  5048. return File (getPathUpToLastSlash());
  5049. }
  5050. const String File::getFileName() const throw()
  5051. {
  5052. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5053. }
  5054. int File::hashCode() const throw()
  5055. {
  5056. return fullPath.hashCode();
  5057. }
  5058. int64 File::hashCode64() const throw()
  5059. {
  5060. return fullPath.hashCode64();
  5061. }
  5062. const String File::getFileNameWithoutExtension() const throw()
  5063. {
  5064. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5065. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  5066. if (lastDot > lastSlash)
  5067. return fullPath.substring (lastSlash, lastDot);
  5068. else
  5069. return fullPath.substring (lastSlash);
  5070. }
  5071. bool File::isAChildOf (const File& potentialParent) const throw()
  5072. {
  5073. const String ourPath (getPathUpToLastSlash());
  5074. #if NAMES_ARE_CASE_SENSITIVE
  5075. if (potentialParent.fullPath == ourPath)
  5076. #else
  5077. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5078. #endif
  5079. {
  5080. return true;
  5081. }
  5082. else if (potentialParent.fullPath.length() >= ourPath.length())
  5083. {
  5084. return false;
  5085. }
  5086. else
  5087. {
  5088. return getParentDirectory().isAChildOf (potentialParent);
  5089. }
  5090. }
  5091. bool File::isAbsolutePath (const String& path) throw()
  5092. {
  5093. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  5094. #if JUCE_WINDOWS
  5095. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  5096. #else
  5097. || path.startsWithChar (T('~'));
  5098. #endif
  5099. }
  5100. const File File::getChildFile (String relativePath) const throw()
  5101. {
  5102. if (isAbsolutePath (relativePath))
  5103. {
  5104. // the path is really absolute..
  5105. return File (relativePath);
  5106. }
  5107. else
  5108. {
  5109. // it's relative, so remove any ../ or ./ bits at the start.
  5110. String path (fullPath);
  5111. if (relativePath[0] == T('.'))
  5112. {
  5113. #if JUCE_WINDOWS
  5114. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  5115. #else
  5116. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  5117. #endif
  5118. while (relativePath[0] == T('.'))
  5119. {
  5120. if (relativePath[1] == T('.'))
  5121. {
  5122. if (relativePath [2] == 0 || relativePath[2] == separator)
  5123. {
  5124. const int lastSlash = path.lastIndexOfChar (separator);
  5125. if (lastSlash >= 0)
  5126. path = path.substring (0, lastSlash);
  5127. relativePath = relativePath.substring (3);
  5128. }
  5129. else
  5130. {
  5131. break;
  5132. }
  5133. }
  5134. else if (relativePath[1] == separator)
  5135. {
  5136. relativePath = relativePath.substring (2);
  5137. }
  5138. else
  5139. {
  5140. break;
  5141. }
  5142. }
  5143. }
  5144. return File (juce_addTrailingSeparator (path) + relativePath);
  5145. }
  5146. }
  5147. const File File::getSiblingFile (const String& fileName) const throw()
  5148. {
  5149. return getParentDirectory().getChildFile (fileName);
  5150. }
  5151. int64 File::getSize() const throw()
  5152. {
  5153. return juce_getFileSize (fullPath);
  5154. }
  5155. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5156. {
  5157. if (bytes == 1)
  5158. {
  5159. return "1 byte";
  5160. }
  5161. else if (bytes < 1024)
  5162. {
  5163. return String ((int) bytes) + " bytes";
  5164. }
  5165. else if (bytes < 1024 * 1024)
  5166. {
  5167. return String (bytes / 1024.0, 1) + " KB";
  5168. }
  5169. else if (bytes < 1024 * 1024 * 1024)
  5170. {
  5171. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5172. }
  5173. else
  5174. {
  5175. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5176. }
  5177. }
  5178. bool File::create() const throw()
  5179. {
  5180. if (! exists())
  5181. {
  5182. const File parentDir (getParentDirectory());
  5183. if (parentDir == *this || ! parentDir.createDirectory())
  5184. return false;
  5185. void* const fh = juce_fileOpen (fullPath, true);
  5186. if (fh == 0)
  5187. return false;
  5188. juce_fileClose (fh);
  5189. }
  5190. return true;
  5191. }
  5192. bool File::createDirectory() const throw()
  5193. {
  5194. if (! isDirectory())
  5195. {
  5196. const File parentDir (getParentDirectory());
  5197. if (parentDir == *this || ! parentDir.createDirectory())
  5198. return false;
  5199. String dir (fullPath);
  5200. while (dir.endsWithChar (separator))
  5201. dir [dir.length() - 1] = 0;
  5202. juce_createDirectory (dir);
  5203. return isDirectory();
  5204. }
  5205. return true;
  5206. }
  5207. const Time File::getCreationTime() const throw()
  5208. {
  5209. int64 m, a, c;
  5210. juce_getFileTimes (fullPath, m, a, c);
  5211. return Time (c);
  5212. }
  5213. bool File::setCreationTime (const Time& t) const throw()
  5214. {
  5215. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  5216. }
  5217. const Time File::getLastModificationTime() const throw()
  5218. {
  5219. int64 m, a, c;
  5220. juce_getFileTimes (fullPath, m, a, c);
  5221. return Time (m);
  5222. }
  5223. bool File::setLastModificationTime (const Time& t) const throw()
  5224. {
  5225. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  5226. }
  5227. const Time File::getLastAccessTime() const throw()
  5228. {
  5229. int64 m, a, c;
  5230. juce_getFileTimes (fullPath, m, a, c);
  5231. return Time (a);
  5232. }
  5233. bool File::setLastAccessTime (const Time& t) const throw()
  5234. {
  5235. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  5236. }
  5237. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  5238. {
  5239. if (! existsAsFile())
  5240. return false;
  5241. FileInputStream in (*this);
  5242. return getSize() == in.readIntoMemoryBlock (destBlock);
  5243. }
  5244. const String File::loadFileAsString() const throw()
  5245. {
  5246. if (! existsAsFile())
  5247. return String::empty;
  5248. FileInputStream in (*this);
  5249. return in.readEntireStreamAsString();
  5250. }
  5251. static inline bool fileTypeMatches (const int whatToLookFor,
  5252. const bool isDir,
  5253. const bool isHidden)
  5254. {
  5255. return (whatToLookFor & (isDir ? File::findDirectories
  5256. : File::findFiles)) != 0
  5257. && ((! isHidden)
  5258. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5259. }
  5260. int File::findChildFiles (OwnedArray<File>& results,
  5261. const int whatToLookFor,
  5262. const bool searchRecursively,
  5263. const String& wildCardPattern) const throw()
  5264. {
  5265. // you have to specify the type of files you're looking for!
  5266. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5267. int total = 0;
  5268. // find child files or directories in this directory first..
  5269. if (isDirectory())
  5270. {
  5271. const String path (juce_addTrailingSeparator (fullPath));
  5272. String filename;
  5273. bool isDirectory, isHidden;
  5274. void* const handle = juce_findFileStart (path,
  5275. wildCardPattern,
  5276. filename,
  5277. &isDirectory, &isHidden,
  5278. 0, 0, 0, 0);
  5279. if (handle != 0)
  5280. {
  5281. do
  5282. {
  5283. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5284. && ! filename.containsOnly (T(".")))
  5285. {
  5286. results.add (new File (path + filename, 0));
  5287. ++total;
  5288. }
  5289. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5290. juce_findFileClose (handle);
  5291. }
  5292. }
  5293. else
  5294. {
  5295. // trying to search for files inside a non-directory?
  5296. //jassertfalse
  5297. }
  5298. // and recurse down if required.
  5299. if (searchRecursively)
  5300. {
  5301. OwnedArray <File> subDirectories;
  5302. findChildFiles (subDirectories, File::findDirectories, false);
  5303. for (int i = 0; i < subDirectories.size(); ++i)
  5304. {
  5305. total += subDirectories.getUnchecked(i)
  5306. ->findChildFiles (results,
  5307. whatToLookFor,
  5308. true,
  5309. wildCardPattern);
  5310. }
  5311. }
  5312. return total;
  5313. }
  5314. int File::getNumberOfChildFiles (const int whatToLookFor,
  5315. const String& wildCardPattern) const throw()
  5316. {
  5317. // you have to specify the type of files you're looking for!
  5318. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5319. int count = 0;
  5320. if (isDirectory())
  5321. {
  5322. String filename;
  5323. bool isDirectory, isHidden;
  5324. void* const handle = juce_findFileStart (fullPath,
  5325. wildCardPattern,
  5326. filename,
  5327. &isDirectory, &isHidden,
  5328. 0, 0, 0, 0);
  5329. if (handle != 0)
  5330. {
  5331. do
  5332. {
  5333. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5334. && ! filename.containsOnly (T(".")))
  5335. {
  5336. ++count;
  5337. }
  5338. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5339. juce_findFileClose (handle);
  5340. }
  5341. }
  5342. else
  5343. {
  5344. // trying to search for files inside a non-directory?
  5345. jassertfalse
  5346. }
  5347. return count;
  5348. }
  5349. bool File::containsSubDirectories() const throw()
  5350. {
  5351. bool result = false;
  5352. if (isDirectory())
  5353. {
  5354. String filename;
  5355. bool isDirectory, isHidden;
  5356. void* const handle = juce_findFileStart (juce_addTrailingSeparator (fullPath),
  5357. T("*"), filename,
  5358. &isDirectory, &isHidden, 0, 0, 0, 0);
  5359. if (handle != 0)
  5360. {
  5361. do
  5362. {
  5363. if (isDirectory)
  5364. {
  5365. result = true;
  5366. break;
  5367. }
  5368. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5369. juce_findFileClose (handle);
  5370. }
  5371. }
  5372. return result;
  5373. }
  5374. const File File::getNonexistentChildFile (const String& prefix_,
  5375. const String& suffix,
  5376. bool putNumbersInBrackets) const throw()
  5377. {
  5378. File f (getChildFile (prefix_ + suffix));
  5379. if (f.exists())
  5380. {
  5381. int num = 2;
  5382. String prefix (prefix_);
  5383. // remove any bracketed numbers that may already be on the end..
  5384. if (prefix.trim().endsWithChar (T(')')))
  5385. {
  5386. putNumbersInBrackets = true;
  5387. const int openBracks = prefix.lastIndexOfChar (T('('));
  5388. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  5389. if (openBracks > 0
  5390. && closeBracks > openBracks
  5391. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  5392. {
  5393. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5394. prefix = prefix.substring (0, openBracks);
  5395. }
  5396. }
  5397. // also use brackets if it ends in a digit.
  5398. putNumbersInBrackets = putNumbersInBrackets
  5399. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5400. do
  5401. {
  5402. if (putNumbersInBrackets)
  5403. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  5404. else
  5405. f = getChildFile (prefix + String (num++) + suffix);
  5406. } while (f.exists());
  5407. }
  5408. return f;
  5409. }
  5410. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  5411. {
  5412. if (exists())
  5413. {
  5414. return getParentDirectory()
  5415. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5416. getFileExtension(),
  5417. putNumbersInBrackets);
  5418. }
  5419. else
  5420. {
  5421. return *this;
  5422. }
  5423. }
  5424. const String File::getFileExtension() const throw()
  5425. {
  5426. String ext;
  5427. if (! isDirectory())
  5428. {
  5429. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  5430. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5431. ext = fullPath.substring (indexOfDot);
  5432. }
  5433. return ext;
  5434. }
  5435. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  5436. {
  5437. if (possibleSuffix.isEmpty())
  5438. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  5439. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5440. {
  5441. if (possibleSuffix.startsWithChar (T('.')))
  5442. return true;
  5443. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5444. if (dotPos >= 0)
  5445. return fullPath [dotPos] == T('.');
  5446. }
  5447. return false;
  5448. }
  5449. const File File::withFileExtension (const String& newExtension) const throw()
  5450. {
  5451. if (fullPath.isEmpty())
  5452. return File::nonexistent;
  5453. String filePart (getFileName());
  5454. int i = filePart.lastIndexOfChar (T('.'));
  5455. if (i < 0)
  5456. i = filePart.length();
  5457. String newExt (newExtension);
  5458. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  5459. newExt = T(".") + newExt;
  5460. return getSiblingFile (filePart.substring (0, i) + newExt);
  5461. }
  5462. bool File::startAsProcess (const String& parameters) const throw()
  5463. {
  5464. return exists()
  5465. && juce_launchFile (fullPath, parameters);
  5466. }
  5467. FileInputStream* File::createInputStream() const throw()
  5468. {
  5469. if (existsAsFile())
  5470. return new FileInputStream (*this);
  5471. else
  5472. return 0;
  5473. }
  5474. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  5475. {
  5476. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  5477. if (out->failedToOpen())
  5478. {
  5479. delete out;
  5480. return 0;
  5481. }
  5482. else
  5483. {
  5484. return out;
  5485. }
  5486. }
  5487. bool File::appendData (const void* const dataToAppend,
  5488. const int numberOfBytes) const throw()
  5489. {
  5490. if (numberOfBytes > 0)
  5491. {
  5492. FileOutputStream* const out = createOutputStream();
  5493. if (out == 0)
  5494. return false;
  5495. out->write (dataToAppend, numberOfBytes);
  5496. delete out;
  5497. }
  5498. return true;
  5499. }
  5500. bool File::replaceWithData (const void* const dataToWrite,
  5501. const int numberOfBytes) const throw()
  5502. {
  5503. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5504. if (numberOfBytes <= 0)
  5505. return deleteFile();
  5506. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5507. if (tempFile.appendData (dataToWrite, numberOfBytes)
  5508. && tempFile.moveFileTo (*this))
  5509. {
  5510. return true;
  5511. }
  5512. tempFile.deleteFile();
  5513. return false;
  5514. }
  5515. bool File::appendText (const String& text,
  5516. const bool asUnicode,
  5517. const bool writeUnicodeHeaderBytes) const throw()
  5518. {
  5519. FileOutputStream* const out = createOutputStream();
  5520. if (out != 0)
  5521. {
  5522. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5523. delete out;
  5524. return true;
  5525. }
  5526. return false;
  5527. }
  5528. bool File::printf (const tchar* pf, ...) const throw()
  5529. {
  5530. va_list list;
  5531. va_start (list, pf);
  5532. String text;
  5533. text.vprintf (pf, list);
  5534. return appendData ((const char*) text, text.length());
  5535. }
  5536. bool File::replaceWithText (const String& textToWrite,
  5537. const bool asUnicode,
  5538. const bool writeUnicodeHeaderBytes) const throw()
  5539. {
  5540. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5541. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  5542. && tempFile.moveFileTo (*this))
  5543. {
  5544. return true;
  5545. }
  5546. tempFile.deleteFile();
  5547. return false;
  5548. }
  5549. const String File::createLegalPathName (const String& original) throw()
  5550. {
  5551. String s (original);
  5552. String start;
  5553. if (s[1] == T(':'))
  5554. {
  5555. start = s.substring (0, 2);
  5556. s = s.substring (2);
  5557. }
  5558. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  5559. .substring (0, 1024);
  5560. }
  5561. const String File::createLegalFileName (const String& original) throw()
  5562. {
  5563. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  5564. const int maxLength = 128; // only the length of the filename, not the whole path
  5565. const int len = s.length();
  5566. if (len > maxLength)
  5567. {
  5568. const int lastDot = s.lastIndexOfChar (T('.'));
  5569. if (lastDot > jmax (0, len - 12))
  5570. {
  5571. s = s.substring (0, maxLength - (len - lastDot))
  5572. + s.substring (lastDot);
  5573. }
  5574. else
  5575. {
  5576. s = s.substring (0, maxLength);
  5577. }
  5578. }
  5579. return s;
  5580. }
  5581. const String File::getRelativePathFrom (const File& dir) const throw()
  5582. {
  5583. String thisPath (fullPath);
  5584. {
  5585. int len = thisPath.length();
  5586. while (--len >= 0 && thisPath [len] == File::separator)
  5587. thisPath [len] = 0;
  5588. }
  5589. String dirPath (juce_addTrailingSeparator ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  5590. : dir.fullPath));
  5591. const int len = jmin (thisPath.length(), dirPath.length());
  5592. int commonBitLength = 0;
  5593. for (int i = 0; i < len; ++i)
  5594. {
  5595. #if NAMES_ARE_CASE_SENSITIVE
  5596. if (thisPath[i] != dirPath[i])
  5597. #else
  5598. if (CharacterFunctions::toLowerCase (thisPath[i])
  5599. != CharacterFunctions::toLowerCase (dirPath[i]))
  5600. #endif
  5601. {
  5602. break;
  5603. }
  5604. ++commonBitLength;
  5605. }
  5606. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5607. --commonBitLength;
  5608. // if the only common bit is the root, then just return the full path..
  5609. if (commonBitLength <= 0
  5610. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5611. return fullPath;
  5612. thisPath = thisPath.substring (commonBitLength);
  5613. dirPath = dirPath.substring (commonBitLength);
  5614. while (dirPath.isNotEmpty())
  5615. {
  5616. #if JUCE_WINDOWS
  5617. thisPath = T("..\\") + thisPath;
  5618. #else
  5619. thisPath = T("../") + thisPath;
  5620. #endif
  5621. const int sep = dirPath.indexOfChar (separator);
  5622. if (sep >= 0)
  5623. dirPath = dirPath.substring (sep + 1);
  5624. else
  5625. dirPath = String::empty;
  5626. }
  5627. return thisPath;
  5628. }
  5629. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  5630. {
  5631. const StringArray roots (juce_getFileSystemRoots());
  5632. for (int i = 0; i < roots.size(); ++i)
  5633. destArray.add (new File (roots[i]));
  5634. }
  5635. const String File::getVolumeLabel() const throw()
  5636. {
  5637. int serialNum;
  5638. return juce_getVolumeLabel (fullPath, serialNum);
  5639. }
  5640. int File::getVolumeSerialNumber() const throw()
  5641. {
  5642. int serialNum;
  5643. juce_getVolumeLabel (fullPath, serialNum);
  5644. return serialNum;
  5645. }
  5646. const File File::createTempFile (const String& fileNameEnding) throw()
  5647. {
  5648. String tempName (T("temp"));
  5649. static int tempNum = 0;
  5650. tempName << tempNum++ << fileNameEnding;
  5651. const File tempFile (getSpecialLocation (tempDirectory)
  5652. .getChildFile (tempName));
  5653. if (tempFile.exists())
  5654. return createTempFile (fileNameEnding);
  5655. else
  5656. return tempFile;
  5657. }
  5658. END_JUCE_NAMESPACE
  5659. /********* End of inlined file: juce_File.cpp *********/
  5660. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  5661. BEGIN_JUCE_NAMESPACE
  5662. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5663. void juce_fileClose (void* handle) throw();
  5664. int juce_fileRead (void* handle, void* buffer, int size) throw();
  5665. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5666. FileInputStream::FileInputStream (const File& f)
  5667. : file (f),
  5668. currentPosition (0),
  5669. needToSeek (true)
  5670. {
  5671. totalSize = f.getSize();
  5672. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  5673. }
  5674. FileInputStream::~FileInputStream()
  5675. {
  5676. juce_fileClose (fileHandle);
  5677. }
  5678. int64 FileInputStream::getTotalLength()
  5679. {
  5680. return totalSize;
  5681. }
  5682. int FileInputStream::read (void* buffer, int bytesToRead)
  5683. {
  5684. int num = 0;
  5685. if (needToSeek)
  5686. {
  5687. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5688. return 0;
  5689. needToSeek = false;
  5690. }
  5691. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5692. currentPosition += num;
  5693. return num;
  5694. }
  5695. bool FileInputStream::isExhausted()
  5696. {
  5697. return currentPosition >= totalSize;
  5698. }
  5699. int64 FileInputStream::getPosition()
  5700. {
  5701. return currentPosition;
  5702. }
  5703. bool FileInputStream::setPosition (int64 pos)
  5704. {
  5705. pos = jlimit ((int64) 0, totalSize, pos);
  5706. needToSeek |= (currentPosition != pos);
  5707. currentPosition = pos;
  5708. return true;
  5709. }
  5710. END_JUCE_NAMESPACE
  5711. /********* End of inlined file: juce_FileInputStream.cpp *********/
  5712. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  5713. BEGIN_JUCE_NAMESPACE
  5714. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5715. void juce_fileClose (void* handle) throw();
  5716. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  5717. void juce_fileFlush (void* handle) throw();
  5718. int64 juce_fileGetPosition (void* handle) throw();
  5719. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5720. FileOutputStream::FileOutputStream (const File& f,
  5721. const int bufferSize_)
  5722. : file (f),
  5723. bufferSize (bufferSize_),
  5724. bytesInBuffer (0)
  5725. {
  5726. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  5727. if (fileHandle != 0)
  5728. {
  5729. currentPosition = juce_fileGetPosition (fileHandle);
  5730. if (currentPosition < 0)
  5731. {
  5732. jassertfalse
  5733. juce_fileClose (fileHandle);
  5734. fileHandle = 0;
  5735. }
  5736. }
  5737. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  5738. }
  5739. FileOutputStream::~FileOutputStream()
  5740. {
  5741. flush();
  5742. juce_fileClose (fileHandle);
  5743. juce_free (buffer);
  5744. }
  5745. int64 FileOutputStream::getPosition()
  5746. {
  5747. return currentPosition;
  5748. }
  5749. bool FileOutputStream::setPosition (int64 newPosition)
  5750. {
  5751. if (newPosition != currentPosition)
  5752. {
  5753. flush();
  5754. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5755. }
  5756. return newPosition == currentPosition;
  5757. }
  5758. void FileOutputStream::flush()
  5759. {
  5760. if (bytesInBuffer > 0)
  5761. {
  5762. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5763. bytesInBuffer = 0;
  5764. }
  5765. juce_fileFlush (fileHandle);
  5766. }
  5767. bool FileOutputStream::write (const void* const src, const int numBytes)
  5768. {
  5769. if (bytesInBuffer + numBytes < bufferSize)
  5770. {
  5771. memcpy (buffer + bytesInBuffer, src, numBytes);
  5772. bytesInBuffer += numBytes;
  5773. currentPosition += numBytes;
  5774. }
  5775. else
  5776. {
  5777. if (bytesInBuffer > 0)
  5778. {
  5779. // flush the reservoir
  5780. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5781. bytesInBuffer = 0;
  5782. if (! wroteOk)
  5783. return false;
  5784. }
  5785. if (numBytes < bufferSize)
  5786. {
  5787. memcpy (buffer + bytesInBuffer, src, numBytes);
  5788. bytesInBuffer += numBytes;
  5789. currentPosition += numBytes;
  5790. }
  5791. else
  5792. {
  5793. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5794. currentPosition += bytesWritten;
  5795. return bytesWritten == numBytes;
  5796. }
  5797. }
  5798. return true;
  5799. }
  5800. END_JUCE_NAMESPACE
  5801. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  5802. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  5803. BEGIN_JUCE_NAMESPACE
  5804. FileSearchPath::FileSearchPath()
  5805. {
  5806. }
  5807. FileSearchPath::FileSearchPath (const String& path)
  5808. {
  5809. init (path);
  5810. }
  5811. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5812. : directories (other.directories)
  5813. {
  5814. }
  5815. FileSearchPath::~FileSearchPath()
  5816. {
  5817. }
  5818. const FileSearchPath& FileSearchPath::operator= (const String& path)
  5819. {
  5820. init (path);
  5821. return *this;
  5822. }
  5823. void FileSearchPath::init (const String& path)
  5824. {
  5825. directories.clear();
  5826. directories.addTokens (path, T(";"), T("\""));
  5827. directories.trim();
  5828. directories.removeEmptyStrings();
  5829. for (int i = directories.size(); --i >= 0;)
  5830. directories.set (i, directories[i].unquoted());
  5831. }
  5832. int FileSearchPath::getNumPaths() const
  5833. {
  5834. return directories.size();
  5835. }
  5836. const File FileSearchPath::operator[] (const int index) const
  5837. {
  5838. return File (directories [index]);
  5839. }
  5840. const String FileSearchPath::toString() const
  5841. {
  5842. StringArray directories2 (directories);
  5843. for (int i = directories2.size(); --i >= 0;)
  5844. if (directories2[i].containsChar (T(';')))
  5845. directories2.set (i, directories2[i].quoted());
  5846. return directories2.joinIntoString (T(";"));
  5847. }
  5848. void FileSearchPath::add (const File& dir, const int insertIndex)
  5849. {
  5850. directories.insert (insertIndex, dir.getFullPathName());
  5851. }
  5852. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5853. {
  5854. for (int i = 0; i < directories.size(); ++i)
  5855. if (File (directories[i]) == dir)
  5856. return;
  5857. add (dir);
  5858. }
  5859. void FileSearchPath::remove (const int index)
  5860. {
  5861. directories.remove (index);
  5862. }
  5863. void FileSearchPath::addPath (const FileSearchPath& other)
  5864. {
  5865. for (int i = 0; i < other.getNumPaths(); ++i)
  5866. addIfNotAlreadyThere (other[i]);
  5867. }
  5868. void FileSearchPath::removeRedundantPaths()
  5869. {
  5870. for (int i = directories.size(); --i >= 0;)
  5871. {
  5872. const File d1 (directories[i]);
  5873. for (int j = directories.size(); --j >= 0;)
  5874. {
  5875. const File d2 (directories[j]);
  5876. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5877. {
  5878. directories.remove (i);
  5879. break;
  5880. }
  5881. }
  5882. }
  5883. }
  5884. void FileSearchPath::removeNonExistentPaths()
  5885. {
  5886. for (int i = directories.size(); --i >= 0;)
  5887. if (! File (directories[i]).isDirectory())
  5888. directories.remove (i);
  5889. }
  5890. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  5891. const int whatToLookFor,
  5892. const bool searchRecursively,
  5893. const String& wildCardPattern) const
  5894. {
  5895. int total = 0;
  5896. for (int i = 0; i < directories.size(); ++i)
  5897. total += operator[] (i).findChildFiles (results,
  5898. whatToLookFor,
  5899. searchRecursively,
  5900. wildCardPattern);
  5901. return total;
  5902. }
  5903. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5904. const bool checkRecursively) const
  5905. {
  5906. for (int i = directories.size(); --i >= 0;)
  5907. {
  5908. const File d (directories[i]);
  5909. if (checkRecursively)
  5910. {
  5911. if (fileToCheck.isAChildOf (d))
  5912. return true;
  5913. }
  5914. else
  5915. {
  5916. if (fileToCheck.getParentDirectory() == d)
  5917. return true;
  5918. }
  5919. }
  5920. return false;
  5921. }
  5922. END_JUCE_NAMESPACE
  5923. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  5924. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  5925. BEGIN_JUCE_NAMESPACE
  5926. NamedPipe::NamedPipe()
  5927. : internal (0)
  5928. {
  5929. }
  5930. NamedPipe::~NamedPipe()
  5931. {
  5932. close();
  5933. }
  5934. bool NamedPipe::openExisting (const String& pipeName)
  5935. {
  5936. currentPipeName = pipeName;
  5937. return openInternal (pipeName, false);
  5938. }
  5939. bool NamedPipe::createNewPipe (const String& pipeName)
  5940. {
  5941. currentPipeName = pipeName;
  5942. return openInternal (pipeName, true);
  5943. }
  5944. bool NamedPipe::isOpen() const throw()
  5945. {
  5946. return internal != 0;
  5947. }
  5948. const String NamedPipe::getName() const throw()
  5949. {
  5950. return currentPipeName;
  5951. }
  5952. // other methods for this class are implemented in the platform-specific files
  5953. END_JUCE_NAMESPACE
  5954. /********* End of inlined file: juce_NamedPipe.cpp *********/
  5955. /********* Start of inlined file: juce_Socket.cpp *********/
  5956. #if JUCE_WINDOWS
  5957. #include <winsock2.h>
  5958. #ifdef _MSC_VER
  5959. #pragma warning (disable : 4127 4389 4018)
  5960. #endif
  5961. #else
  5962. #if JUCE_LINUX
  5963. #include <sys/types.h>
  5964. #include <sys/socket.h>
  5965. #include <sys/errno.h>
  5966. #include <unistd.h>
  5967. #include <netinet/in.h>
  5968. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5969. #include <CoreServices/CoreServices.h>
  5970. #endif
  5971. #include <fcntl.h>
  5972. #include <netdb.h>
  5973. #include <arpa/inet.h>
  5974. #include <netinet/tcp.h>
  5975. #endif
  5976. BEGIN_JUCE_NAMESPACE
  5977. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5978. typedef socklen_t juce_socklen_t;
  5979. #else
  5980. typedef int juce_socklen_t;
  5981. #endif
  5982. #if JUCE_WINDOWS
  5983. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5984. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5985. static void initWin32Sockets()
  5986. {
  5987. static CriticalSection lock;
  5988. const ScopedLock sl (lock);
  5989. if (juce_CloseWin32SocketLib == 0)
  5990. {
  5991. WSADATA wsaData;
  5992. const WORD wVersionRequested = MAKEWORD (1, 1);
  5993. WSAStartup (wVersionRequested, &wsaData);
  5994. juce_CloseWin32SocketLib = &WSACleanup;
  5995. }
  5996. }
  5997. #endif
  5998. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5999. {
  6000. const int sndBufSize = 65536;
  6001. const int rcvBufSize = 65536;
  6002. const int one = 1;
  6003. return handle > 0
  6004. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6005. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6006. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6007. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6008. }
  6009. static bool bindSocketToPort (const int handle, const int port) throw()
  6010. {
  6011. if (handle <= 0 || port <= 0)
  6012. return false;
  6013. struct sockaddr_in servTmpAddr;
  6014. zerostruct (servTmpAddr);
  6015. servTmpAddr.sin_family = PF_INET;
  6016. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6017. servTmpAddr.sin_port = htons ((uint16) port);
  6018. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6019. }
  6020. static int readSocket (const int handle,
  6021. void* const destBuffer, const int maxBytesToRead,
  6022. bool volatile& connected,
  6023. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6024. {
  6025. int bytesRead = 0;
  6026. while (bytesRead < maxBytesToRead)
  6027. {
  6028. int bytesThisTime;
  6029. #if JUCE_WINDOWS
  6030. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6031. #else
  6032. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6033. && errno == EINTR
  6034. && connected)
  6035. {
  6036. }
  6037. #endif
  6038. if (bytesThisTime <= 0 || ! connected)
  6039. {
  6040. if (bytesRead == 0)
  6041. bytesRead = -1;
  6042. break;
  6043. }
  6044. bytesRead += bytesThisTime;
  6045. if (! blockUntilSpecifiedAmountHasArrived)
  6046. break;
  6047. }
  6048. return bytesRead;
  6049. }
  6050. static int waitForReadiness (const int handle, const bool forReading,
  6051. const int timeoutMsecs) throw()
  6052. {
  6053. struct timeval timeout;
  6054. struct timeval* timeoutp;
  6055. if (timeoutMsecs >= 0)
  6056. {
  6057. timeout.tv_sec = timeoutMsecs / 1000;
  6058. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6059. timeoutp = &timeout;
  6060. }
  6061. else
  6062. {
  6063. timeoutp = 0;
  6064. }
  6065. fd_set rset, wset;
  6066. FD_ZERO (&rset);
  6067. FD_SET (handle, &rset);
  6068. FD_ZERO (&wset);
  6069. FD_SET (handle, &wset);
  6070. fd_set* const prset = forReading ? &rset : 0;
  6071. fd_set* const pwset = forReading ? 0 : &wset;
  6072. #if JUCE_WINDOWS
  6073. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6074. return -1;
  6075. #else
  6076. {
  6077. int result;
  6078. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6079. && errno == EINTR)
  6080. {
  6081. }
  6082. if (result < 0)
  6083. return -1;
  6084. }
  6085. #endif
  6086. {
  6087. int opt;
  6088. juce_socklen_t len = sizeof (opt);
  6089. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6090. || opt != 0)
  6091. return -1;
  6092. }
  6093. if ((forReading && FD_ISSET (handle, &rset))
  6094. || ((! forReading) && FD_ISSET (handle, &wset)))
  6095. return 1;
  6096. return 0;
  6097. }
  6098. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6099. {
  6100. #if JUCE_WINDOWS
  6101. u_long nonBlocking = shouldBlock ? 0 : 1;
  6102. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6103. return false;
  6104. #else
  6105. int socketFlags = fcntl (handle, F_GETFL, 0);
  6106. if (socketFlags == -1)
  6107. return false;
  6108. if (shouldBlock)
  6109. socketFlags &= ~O_NONBLOCK;
  6110. else
  6111. socketFlags |= O_NONBLOCK;
  6112. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6113. return false;
  6114. #endif
  6115. return true;
  6116. }
  6117. static bool connectSocket (int volatile& handle,
  6118. const bool isDatagram,
  6119. void** serverAddress,
  6120. const String& hostName,
  6121. const int portNumber,
  6122. const int timeOutMillisecs) throw()
  6123. {
  6124. struct hostent* const hostEnt = gethostbyname (hostName);
  6125. if (hostEnt == 0)
  6126. return false;
  6127. struct in_addr targetAddress;
  6128. memcpy (&targetAddress.s_addr,
  6129. *(hostEnt->h_addr_list),
  6130. sizeof (targetAddress.s_addr));
  6131. struct sockaddr_in servTmpAddr;
  6132. zerostruct (servTmpAddr);
  6133. servTmpAddr.sin_family = PF_INET;
  6134. servTmpAddr.sin_addr = targetAddress;
  6135. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6136. if (handle < 0)
  6137. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6138. if (handle < 0)
  6139. return false;
  6140. if (isDatagram)
  6141. {
  6142. *serverAddress = new struct sockaddr_in();
  6143. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6144. return true;
  6145. }
  6146. setSocketBlockingState (handle, false);
  6147. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6148. if (result < 0)
  6149. {
  6150. #if JUCE_WINDOWS
  6151. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6152. #else
  6153. if (errno == EINPROGRESS)
  6154. #endif
  6155. {
  6156. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6157. {
  6158. setSocketBlockingState (handle, true);
  6159. return false;
  6160. }
  6161. }
  6162. }
  6163. setSocketBlockingState (handle, true);
  6164. resetSocketOptions (handle, false, false);
  6165. return true;
  6166. }
  6167. StreamingSocket::StreamingSocket()
  6168. : portNumber (0),
  6169. handle (-1),
  6170. connected (false),
  6171. isListener (false)
  6172. {
  6173. #if JUCE_WINDOWS
  6174. initWin32Sockets();
  6175. #endif
  6176. }
  6177. StreamingSocket::StreamingSocket (const String& hostName_,
  6178. const int portNumber_,
  6179. const int handle_)
  6180. : hostName (hostName_),
  6181. portNumber (portNumber_),
  6182. handle (handle_),
  6183. connected (true),
  6184. isListener (false)
  6185. {
  6186. #if JUCE_WINDOWS
  6187. initWin32Sockets();
  6188. #endif
  6189. resetSocketOptions (handle_, false, false);
  6190. }
  6191. StreamingSocket::~StreamingSocket()
  6192. {
  6193. close();
  6194. }
  6195. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6196. {
  6197. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6198. : -1;
  6199. }
  6200. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6201. {
  6202. if (isListener || ! connected)
  6203. return -1;
  6204. #if JUCE_WINDOWS
  6205. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6206. #else
  6207. int result;
  6208. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6209. && errno == EINTR)
  6210. {
  6211. }
  6212. return result;
  6213. #endif
  6214. }
  6215. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6216. const int timeoutMsecs) const
  6217. {
  6218. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6219. : -1;
  6220. }
  6221. bool StreamingSocket::bindToPort (const int port)
  6222. {
  6223. return bindSocketToPort (handle, port);
  6224. }
  6225. bool StreamingSocket::connect (const String& remoteHostName,
  6226. const int remotePortNumber,
  6227. const int timeOutMillisecs)
  6228. {
  6229. if (isListener)
  6230. {
  6231. jassertfalse // a listener socket can't connect to another one!
  6232. return false;
  6233. }
  6234. if (connected)
  6235. close();
  6236. hostName = remoteHostName;
  6237. portNumber = remotePortNumber;
  6238. isListener = false;
  6239. connected = connectSocket (handle, false, 0, remoteHostName,
  6240. remotePortNumber, timeOutMillisecs);
  6241. if (! (connected && resetSocketOptions (handle, false, false)))
  6242. {
  6243. close();
  6244. return false;
  6245. }
  6246. return true;
  6247. }
  6248. void StreamingSocket::close()
  6249. {
  6250. #if JUCE_WINDOWS
  6251. closesocket (handle);
  6252. connected = false;
  6253. #else
  6254. if (connected)
  6255. {
  6256. connected = false;
  6257. if (isListener)
  6258. {
  6259. // need to do this to interrupt the accept() function..
  6260. StreamingSocket temp;
  6261. temp.connect ("localhost", portNumber, 1000);
  6262. }
  6263. }
  6264. ::close (handle);
  6265. #endif
  6266. hostName = String::empty;
  6267. portNumber = 0;
  6268. handle = -1;
  6269. isListener = false;
  6270. }
  6271. bool StreamingSocket::createListener (const int newPortNumber)
  6272. {
  6273. if (connected)
  6274. close();
  6275. hostName = "listener";
  6276. portNumber = newPortNumber;
  6277. isListener = true;
  6278. struct sockaddr_in servTmpAddr;
  6279. zerostruct (servTmpAddr);
  6280. servTmpAddr.sin_family = PF_INET;
  6281. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6282. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6283. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6284. if (handle < 0)
  6285. return false;
  6286. const int reuse = 1;
  6287. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6288. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6289. || listen (handle, SOMAXCONN) < 0)
  6290. {
  6291. close();
  6292. return false;
  6293. }
  6294. connected = true;
  6295. return true;
  6296. }
  6297. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6298. {
  6299. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6300. // prepare this socket as a listener.
  6301. if (connected && isListener)
  6302. {
  6303. struct sockaddr address;
  6304. juce_socklen_t len = sizeof (sockaddr);
  6305. const int newSocket = (int) accept (handle, &address, &len);
  6306. if (newSocket >= 0 && connected)
  6307. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6308. portNumber, newSocket);
  6309. }
  6310. return 0;
  6311. }
  6312. bool StreamingSocket::isLocal() const throw()
  6313. {
  6314. return hostName == T("127.0.0.1");
  6315. }
  6316. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6317. : portNumber (0),
  6318. handle (-1),
  6319. connected (true),
  6320. allowBroadcast (allowBroadcast_),
  6321. serverAddress (0)
  6322. {
  6323. #if JUCE_WINDOWS
  6324. initWin32Sockets();
  6325. #endif
  6326. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6327. bindToPort (localPortNumber);
  6328. }
  6329. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6330. const int handle_, const int localPortNumber)
  6331. : hostName (hostName_),
  6332. portNumber (portNumber_),
  6333. handle (handle_),
  6334. connected (true),
  6335. allowBroadcast (false),
  6336. serverAddress (0)
  6337. {
  6338. #if JUCE_WINDOWS
  6339. initWin32Sockets();
  6340. #endif
  6341. resetSocketOptions (handle_, true, allowBroadcast);
  6342. bindToPort (localPortNumber);
  6343. }
  6344. DatagramSocket::~DatagramSocket()
  6345. {
  6346. close();
  6347. delete ((struct sockaddr_in*) serverAddress);
  6348. serverAddress = 0;
  6349. }
  6350. void DatagramSocket::close()
  6351. {
  6352. #if JUCE_WINDOWS
  6353. closesocket (handle);
  6354. connected = false;
  6355. #else
  6356. connected = false;
  6357. ::close (handle);
  6358. #endif
  6359. hostName = String::empty;
  6360. portNumber = 0;
  6361. handle = -1;
  6362. }
  6363. bool DatagramSocket::bindToPort (const int port)
  6364. {
  6365. return bindSocketToPort (handle, port);
  6366. }
  6367. bool DatagramSocket::connect (const String& remoteHostName,
  6368. const int remotePortNumber,
  6369. const int timeOutMillisecs)
  6370. {
  6371. if (connected)
  6372. close();
  6373. hostName = remoteHostName;
  6374. portNumber = remotePortNumber;
  6375. connected = connectSocket (handle, true, &serverAddress,
  6376. remoteHostName, remotePortNumber,
  6377. timeOutMillisecs);
  6378. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6379. {
  6380. close();
  6381. return false;
  6382. }
  6383. return true;
  6384. }
  6385. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6386. {
  6387. struct sockaddr address;
  6388. juce_socklen_t len = sizeof (sockaddr);
  6389. while (waitUntilReady (true, -1) == 1)
  6390. {
  6391. char buf[1];
  6392. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6393. {
  6394. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6395. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6396. -1, -1);
  6397. }
  6398. }
  6399. return 0;
  6400. }
  6401. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6402. const int timeoutMsecs) const
  6403. {
  6404. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6405. : -1;
  6406. }
  6407. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6408. {
  6409. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6410. : -1;
  6411. }
  6412. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6413. {
  6414. // You need to call connect() first to set the server address..
  6415. jassert (serverAddress != 0 && connected);
  6416. return connected ? sendto (handle, (const char*) sourceBuffer,
  6417. numBytesToWrite, 0,
  6418. (const struct sockaddr*) serverAddress,
  6419. sizeof (struct sockaddr_in))
  6420. : -1;
  6421. }
  6422. bool DatagramSocket::isLocal() const throw()
  6423. {
  6424. return hostName == T("127.0.0.1");
  6425. }
  6426. END_JUCE_NAMESPACE
  6427. /********* End of inlined file: juce_Socket.cpp *********/
  6428. /********* Start of inlined file: juce_URL.cpp *********/
  6429. BEGIN_JUCE_NAMESPACE
  6430. URL::URL() throw()
  6431. {
  6432. }
  6433. URL::URL (const String& url_)
  6434. : url (url_)
  6435. {
  6436. int i = url.indexOfChar (T('?'));
  6437. if (i >= 0)
  6438. {
  6439. do
  6440. {
  6441. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  6442. const int equalsPos = url.indexOfChar (i + 1, T('='));
  6443. if (equalsPos > i + 1)
  6444. {
  6445. if (nextAmp < 0)
  6446. {
  6447. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6448. removeEscapeChars (url.substring (equalsPos + 1)));
  6449. }
  6450. else if (nextAmp > 0 && equalsPos < nextAmp)
  6451. {
  6452. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6453. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6454. }
  6455. }
  6456. i = nextAmp;
  6457. }
  6458. while (i >= 0);
  6459. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  6460. }
  6461. }
  6462. URL::URL (const URL& other)
  6463. : url (other.url),
  6464. postData (other.postData),
  6465. parameters (other.parameters),
  6466. filesToUpload (other.filesToUpload),
  6467. mimeTypes (other.mimeTypes)
  6468. {
  6469. }
  6470. const URL& URL::operator= (const URL& other)
  6471. {
  6472. url = other.url;
  6473. postData = other.postData;
  6474. parameters = other.parameters;
  6475. filesToUpload = other.filesToUpload;
  6476. mimeTypes = other.mimeTypes;
  6477. return *this;
  6478. }
  6479. URL::~URL() throw()
  6480. {
  6481. }
  6482. static const String getMangledParameters (const StringPairArray& parameters)
  6483. {
  6484. String p;
  6485. for (int i = 0; i < parameters.size(); ++i)
  6486. {
  6487. if (i > 0)
  6488. p += T("&");
  6489. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6490. << T("=")
  6491. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6492. }
  6493. return p;
  6494. }
  6495. const String URL::toString (const bool includeGetParameters) const
  6496. {
  6497. if (includeGetParameters && parameters.size() > 0)
  6498. return url + T("?") + getMangledParameters (parameters);
  6499. else
  6500. return url;
  6501. }
  6502. bool URL::isWellFormed() const
  6503. {
  6504. //xxx TODO
  6505. return url.isNotEmpty();
  6506. }
  6507. static int findStartOfDomain (const String& url)
  6508. {
  6509. int i = 0;
  6510. while (CharacterFunctions::isLetterOrDigit (url[i])
  6511. || CharacterFunctions::indexOfChar (T("+-."), url[i], false) >= 0)
  6512. ++i;
  6513. return url[i] == T(':') ? i + 1 : 0;
  6514. }
  6515. const String URL::getDomain() const
  6516. {
  6517. int start = findStartOfDomain (url);
  6518. while (url[start] == T('/'))
  6519. ++start;
  6520. const int end1 = url.indexOfChar (start, T('/'));
  6521. const int end2 = url.indexOfChar (start, T(':'));
  6522. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6523. : jmin (end1, end2);
  6524. return url.substring (start, end);
  6525. }
  6526. const String URL::getSubPath() const
  6527. {
  6528. int start = findStartOfDomain (url);
  6529. while (url[start] == T('/'))
  6530. ++start;
  6531. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6532. return startOfPath <= 0 ? String::empty
  6533. : url.substring (startOfPath);
  6534. }
  6535. const String URL::getScheme() const
  6536. {
  6537. return url.substring (0, findStartOfDomain (url) - 1);
  6538. }
  6539. const URL URL::withNewSubPath (const String& newPath) const
  6540. {
  6541. int start = findStartOfDomain (url);
  6542. while (url[start] == T('/'))
  6543. ++start;
  6544. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6545. URL u (*this);
  6546. if (startOfPath > 0)
  6547. u.url = url.substring (0, startOfPath);
  6548. if (! u.url.endsWithChar (T('/')))
  6549. u.url << '/';
  6550. if (newPath.startsWithChar (T('/')))
  6551. u.url << newPath.substring (1);
  6552. else
  6553. u.url << newPath;
  6554. return u;
  6555. }
  6556. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6557. {
  6558. if (possibleURL.startsWithIgnoreCase (T("http:"))
  6559. || possibleURL.startsWithIgnoreCase (T("ftp:")))
  6560. return true;
  6561. if (possibleURL.startsWithIgnoreCase (T("file:"))
  6562. || possibleURL.containsChar (T('@'))
  6563. || possibleURL.endsWithChar (T('.'))
  6564. || (! possibleURL.containsChar (T('.'))))
  6565. return false;
  6566. if (possibleURL.startsWithIgnoreCase (T("www."))
  6567. && possibleURL.substring (5).containsChar (T('.')))
  6568. return true;
  6569. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6570. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6571. if ((possibleURL + T("/")).containsIgnoreCase (T(".") + String (commonTLDs[i]) + T("/")))
  6572. return true;
  6573. return false;
  6574. }
  6575. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6576. {
  6577. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  6578. return atSign > 0
  6579. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  6580. && (! possibleEmailAddress.endsWithChar (T('.')));
  6581. }
  6582. void* juce_openInternetFile (const String& url,
  6583. const String& headers,
  6584. const MemoryBlock& optionalPostData,
  6585. const bool isPost,
  6586. URL::OpenStreamProgressCallback* callback,
  6587. void* callbackContext,
  6588. int timeOutMs);
  6589. void juce_closeInternetFile (void* handle);
  6590. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6591. int juce_seekInInternetFile (void* handle, int newPosition);
  6592. int64 juce_getInternetFileContentLength (void* handle);
  6593. class WebInputStream : public InputStream
  6594. {
  6595. public:
  6596. WebInputStream (const URL& url,
  6597. const bool isPost_,
  6598. URL::OpenStreamProgressCallback* const progressCallback_,
  6599. void* const progressCallbackContext_,
  6600. const String& extraHeaders,
  6601. int timeOutMs_)
  6602. : position (0),
  6603. finished (false),
  6604. isPost (isPost_),
  6605. progressCallback (progressCallback_),
  6606. progressCallbackContext (progressCallbackContext_),
  6607. timeOutMs (timeOutMs_)
  6608. {
  6609. server = url.toString (! isPost);
  6610. if (isPost_)
  6611. createHeadersAndPostData (url);
  6612. headers += extraHeaders;
  6613. if (! headers.endsWithChar (T('\n')))
  6614. headers << "\r\n";
  6615. handle = juce_openInternetFile (server, headers, postData, isPost,
  6616. progressCallback_, progressCallbackContext_,
  6617. timeOutMs);
  6618. }
  6619. ~WebInputStream()
  6620. {
  6621. juce_closeInternetFile (handle);
  6622. }
  6623. bool isError() const throw()
  6624. {
  6625. return handle == 0;
  6626. }
  6627. int64 getTotalLength()
  6628. {
  6629. return juce_getInternetFileContentLength (handle);
  6630. }
  6631. bool isExhausted()
  6632. {
  6633. return finished;
  6634. }
  6635. int read (void* dest, int bytes)
  6636. {
  6637. if (finished || isError())
  6638. {
  6639. return 0;
  6640. }
  6641. else
  6642. {
  6643. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6644. position += bytesRead;
  6645. if (bytesRead == 0)
  6646. finished = true;
  6647. return bytesRead;
  6648. }
  6649. }
  6650. int64 getPosition()
  6651. {
  6652. return position;
  6653. }
  6654. bool setPosition (int64 wantedPos)
  6655. {
  6656. if (wantedPos != position)
  6657. {
  6658. finished = false;
  6659. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6660. if (actualPos == wantedPos)
  6661. {
  6662. position = wantedPos;
  6663. }
  6664. else
  6665. {
  6666. if (wantedPos < position)
  6667. {
  6668. juce_closeInternetFile (handle);
  6669. position = 0;
  6670. finished = false;
  6671. handle = juce_openInternetFile (server, headers, postData, isPost,
  6672. progressCallback, progressCallbackContext,
  6673. timeOutMs);
  6674. }
  6675. skipNextBytes (wantedPos - position);
  6676. }
  6677. }
  6678. return true;
  6679. }
  6680. juce_UseDebuggingNewOperator
  6681. private:
  6682. String server, headers;
  6683. MemoryBlock postData;
  6684. int64 position;
  6685. bool finished;
  6686. const bool isPost;
  6687. void* handle;
  6688. URL::OpenStreamProgressCallback* const progressCallback;
  6689. void* const progressCallbackContext;
  6690. const int timeOutMs;
  6691. void createHeadersAndPostData (const URL& url)
  6692. {
  6693. if (url.getFilesToUpload().size() > 0)
  6694. {
  6695. // need to upload some files, so do it as multi-part...
  6696. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6697. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6698. appendUTF8ToPostData ("--" + boundary);
  6699. int i;
  6700. for (i = 0; i < url.getParameters().size(); ++i)
  6701. {
  6702. String s;
  6703. s << "\r\nContent-Disposition: form-data; name=\""
  6704. << url.getParameters().getAllKeys() [i]
  6705. << "\"\r\n\r\n"
  6706. << url.getParameters().getAllValues() [i]
  6707. << "\r\n--"
  6708. << boundary;
  6709. appendUTF8ToPostData (s);
  6710. }
  6711. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6712. {
  6713. const File f (url.getFilesToUpload().getAllValues() [i]);
  6714. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6715. String s;
  6716. s << "\r\nContent-Disposition: form-data; name=\""
  6717. << paramName
  6718. << "\"; filename=\""
  6719. << f.getFileName()
  6720. << "\"\r\n";
  6721. const String mimeType (url.getMimeTypesOfUploadFiles()
  6722. .getValue (paramName, String::empty));
  6723. if (mimeType.isNotEmpty())
  6724. s << "Content-Type: " << mimeType << "\r\n";
  6725. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  6726. appendUTF8ToPostData (s);
  6727. f.loadFileAsData (postData);
  6728. s = "\r\n--" + boundary;
  6729. appendUTF8ToPostData (s);
  6730. }
  6731. appendUTF8ToPostData ("--\r\n");
  6732. }
  6733. else
  6734. {
  6735. appendUTF8ToPostData (getMangledParameters (url.getParameters()));
  6736. appendUTF8ToPostData (url.getPostData());
  6737. // just a short text attachment, so use simple url encoding..
  6738. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6739. + String (postData.getSize())
  6740. + "\r\n";
  6741. }
  6742. }
  6743. void appendUTF8ToPostData (const String& text) throw()
  6744. {
  6745. postData.append (text.toUTF8(),
  6746. (int) strlen (text.toUTF8()));
  6747. }
  6748. WebInputStream (const WebInputStream&);
  6749. const WebInputStream& operator= (const WebInputStream&);
  6750. };
  6751. InputStream* URL::createInputStream (const bool usePostCommand,
  6752. OpenStreamProgressCallback* const progressCallback,
  6753. void* const progressCallbackContext,
  6754. const String& extraHeaders,
  6755. const int timeOutMs) const
  6756. {
  6757. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  6758. progressCallback, progressCallbackContext,
  6759. extraHeaders,
  6760. timeOutMs);
  6761. if (wi->isError())
  6762. {
  6763. delete wi;
  6764. wi = 0;
  6765. }
  6766. return wi;
  6767. }
  6768. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6769. const bool usePostCommand) const
  6770. {
  6771. InputStream* const in = createInputStream (usePostCommand);
  6772. if (in != 0)
  6773. {
  6774. in->readIntoMemoryBlock (destData, -1);
  6775. delete in;
  6776. return true;
  6777. }
  6778. return false;
  6779. }
  6780. const String URL::readEntireTextStream (const bool usePostCommand) const
  6781. {
  6782. String result;
  6783. InputStream* const in = createInputStream (usePostCommand);
  6784. if (in != 0)
  6785. {
  6786. result = in->readEntireStreamAsString();
  6787. delete in;
  6788. }
  6789. return result;
  6790. }
  6791. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6792. {
  6793. XmlDocument doc (readEntireTextStream (usePostCommand));
  6794. return doc.getDocumentElement();
  6795. }
  6796. const URL URL::withParameter (const String& parameterName,
  6797. const String& parameterValue) const
  6798. {
  6799. URL u (*this);
  6800. u.parameters.set (parameterName, parameterValue);
  6801. return u;
  6802. }
  6803. const URL URL::withFileToUpload (const String& parameterName,
  6804. const File& fileToUpload,
  6805. const String& mimeType) const
  6806. {
  6807. URL u (*this);
  6808. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6809. u.mimeTypes.set (parameterName, mimeType);
  6810. return u;
  6811. }
  6812. const URL URL::withPOSTData (const String& postData_) const
  6813. {
  6814. URL u (*this);
  6815. u.postData = postData_;
  6816. return u;
  6817. }
  6818. const StringPairArray& URL::getParameters() const throw()
  6819. {
  6820. return parameters;
  6821. }
  6822. const StringPairArray& URL::getFilesToUpload() const throw()
  6823. {
  6824. return filesToUpload;
  6825. }
  6826. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  6827. {
  6828. return mimeTypes;
  6829. }
  6830. const String URL::removeEscapeChars (const String& s)
  6831. {
  6832. const int len = s.length();
  6833. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  6834. uint8* r = resultUTF8;
  6835. for (int i = 0; i < len; ++i)
  6836. {
  6837. char c = (char) s[i];
  6838. if (c == 0)
  6839. break;
  6840. if (c == '+')
  6841. {
  6842. c = ' ';
  6843. }
  6844. else if (c == '%')
  6845. {
  6846. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  6847. i += 2;
  6848. }
  6849. *r++ = c;
  6850. }
  6851. const String stringResult (String::fromUTF8 (resultUTF8));
  6852. juce_free (resultUTF8);
  6853. return stringResult;
  6854. }
  6855. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6856. {
  6857. String result;
  6858. result.preallocateStorage (s.length() + 8);
  6859. const char* utf8 = s.toUTF8();
  6860. const char* legalChars = isParameter ? "_-.*!'()"
  6861. : "_-$.*!'(),";
  6862. while (*utf8 != 0)
  6863. {
  6864. const char c = *utf8++;
  6865. if (CharacterFunctions::isLetterOrDigit (c)
  6866. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6867. {
  6868. result << c;
  6869. }
  6870. else
  6871. {
  6872. const int v = (int) (uint8) c;
  6873. if (v < 0x10)
  6874. result << T("%0");
  6875. else
  6876. result << T('%');
  6877. result << String::toHexString (v);
  6878. }
  6879. }
  6880. return result;
  6881. }
  6882. extern bool juce_launchFile (const String& fileName,
  6883. const String& parameters) throw();
  6884. bool URL::launchInDefaultBrowser() const
  6885. {
  6886. String u (toString (true));
  6887. if (u.contains (T("@")) && ! u.contains (T(":")))
  6888. u = "mailto:" + u;
  6889. return juce_launchFile (u, String::empty);
  6890. }
  6891. END_JUCE_NAMESPACE
  6892. /********* End of inlined file: juce_URL.cpp *********/
  6893. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  6894. BEGIN_JUCE_NAMESPACE
  6895. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6896. const int bufferSize_,
  6897. const bool deleteSourceWhenDestroyed_) throw()
  6898. : source (source_),
  6899. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  6900. bufferSize (jmax (256, bufferSize_)),
  6901. position (source_->getPosition()),
  6902. lastReadPos (0),
  6903. bufferOverlap (128)
  6904. {
  6905. const int sourceSize = (int) source_->getTotalLength();
  6906. if (sourceSize >= 0)
  6907. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6908. bufferStart = position;
  6909. buffer = (char*) juce_malloc (bufferSize);
  6910. }
  6911. BufferedInputStream::~BufferedInputStream() throw()
  6912. {
  6913. if (deleteSourceWhenDestroyed)
  6914. delete source;
  6915. juce_free (buffer);
  6916. }
  6917. int64 BufferedInputStream::getTotalLength()
  6918. {
  6919. return source->getTotalLength();
  6920. }
  6921. int64 BufferedInputStream::getPosition()
  6922. {
  6923. return position;
  6924. }
  6925. bool BufferedInputStream::setPosition (int64 newPosition)
  6926. {
  6927. position = jmax ((int64) 0, newPosition);
  6928. return true;
  6929. }
  6930. bool BufferedInputStream::isExhausted()
  6931. {
  6932. return (position >= lastReadPos)
  6933. && source->isExhausted();
  6934. }
  6935. void BufferedInputStream::ensureBuffered()
  6936. {
  6937. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6938. if (position < bufferStart || position >= bufferEndOverlap)
  6939. {
  6940. int bytesRead;
  6941. if (position < lastReadPos
  6942. && position >= bufferEndOverlap
  6943. && position >= bufferStart)
  6944. {
  6945. const int bytesToKeep = (int) (lastReadPos - position);
  6946. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  6947. bufferStart = position;
  6948. bytesRead = source->read (buffer + bytesToKeep,
  6949. bufferSize - bytesToKeep);
  6950. lastReadPos += bytesRead;
  6951. bytesRead += bytesToKeep;
  6952. }
  6953. else
  6954. {
  6955. bufferStart = position;
  6956. source->setPosition (bufferStart);
  6957. bytesRead = source->read (buffer, bufferSize);
  6958. lastReadPos = bufferStart + bytesRead;
  6959. }
  6960. while (bytesRead < bufferSize)
  6961. buffer [bytesRead++] = 0;
  6962. }
  6963. }
  6964. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6965. {
  6966. if (position >= bufferStart
  6967. && position + maxBytesToRead <= lastReadPos)
  6968. {
  6969. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  6970. position += maxBytesToRead;
  6971. return maxBytesToRead;
  6972. }
  6973. else
  6974. {
  6975. if (position < bufferStart || position >= lastReadPos)
  6976. ensureBuffered();
  6977. int bytesRead = 0;
  6978. while (maxBytesToRead > 0)
  6979. {
  6980. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6981. if (bytesAvailable > 0)
  6982. {
  6983. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  6984. maxBytesToRead -= bytesAvailable;
  6985. bytesRead += bytesAvailable;
  6986. position += bytesAvailable;
  6987. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  6988. }
  6989. const int64 oldLastReadPos = lastReadPos;
  6990. ensureBuffered();
  6991. if (oldLastReadPos == lastReadPos)
  6992. break; // if ensureBuffered() failed to read any more data, bail out
  6993. if (isExhausted())
  6994. break;
  6995. }
  6996. return bytesRead;
  6997. }
  6998. }
  6999. const String BufferedInputStream::readString()
  7000. {
  7001. if (position >= bufferStart
  7002. && position < lastReadPos)
  7003. {
  7004. const int maxChars = (int) (lastReadPos - position);
  7005. const char* const src = buffer + (position - bufferStart);
  7006. for (int i = 0; i < maxChars; ++i)
  7007. {
  7008. if (src[i] == 0)
  7009. {
  7010. position += i + 1;
  7011. return String::fromUTF8 ((const uint8*) src, i);
  7012. }
  7013. }
  7014. }
  7015. return InputStream::readString();
  7016. }
  7017. END_JUCE_NAMESPACE
  7018. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  7019. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  7020. BEGIN_JUCE_NAMESPACE
  7021. FileInputSource::FileInputSource (const File& file_) throw()
  7022. : file (file_)
  7023. {
  7024. }
  7025. FileInputSource::~FileInputSource()
  7026. {
  7027. }
  7028. InputStream* FileInputSource::createInputStream()
  7029. {
  7030. return file.createInputStream();
  7031. }
  7032. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7033. {
  7034. return file.getSiblingFile (relatedItemPath).createInputStream();
  7035. }
  7036. int64 FileInputSource::hashCode() const
  7037. {
  7038. return file.hashCode();
  7039. }
  7040. END_JUCE_NAMESPACE
  7041. /********* End of inlined file: juce_FileInputSource.cpp *********/
  7042. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  7043. BEGIN_JUCE_NAMESPACE
  7044. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7045. const int sourceDataSize,
  7046. const bool keepInternalCopy) throw()
  7047. : data ((const char*) sourceData),
  7048. dataSize (sourceDataSize),
  7049. position (0)
  7050. {
  7051. if (keepInternalCopy)
  7052. {
  7053. internalCopy.append (data, sourceDataSize);
  7054. data = (const char*) internalCopy.getData();
  7055. }
  7056. }
  7057. MemoryInputStream::~MemoryInputStream() throw()
  7058. {
  7059. }
  7060. int64 MemoryInputStream::getTotalLength()
  7061. {
  7062. return dataSize;
  7063. }
  7064. int MemoryInputStream::read (void* buffer, int howMany)
  7065. {
  7066. const int num = jmin (howMany, dataSize - position);
  7067. memcpy (buffer, data + position, num);
  7068. position += num;
  7069. return num;
  7070. }
  7071. bool MemoryInputStream::isExhausted()
  7072. {
  7073. return (position >= dataSize);
  7074. }
  7075. bool MemoryInputStream::setPosition (int64 pos)
  7076. {
  7077. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7078. return true;
  7079. }
  7080. int64 MemoryInputStream::getPosition()
  7081. {
  7082. return position;
  7083. }
  7084. END_JUCE_NAMESPACE
  7085. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  7086. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  7087. BEGIN_JUCE_NAMESPACE
  7088. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  7089. const int blockSizeToIncreaseBy,
  7090. MemoryBlock* const memoryBlockToWriteTo) throw()
  7091. : data (memoryBlockToWriteTo),
  7092. position (0),
  7093. size (0),
  7094. blockSize (jmax (16, blockSizeToIncreaseBy)),
  7095. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  7096. {
  7097. if (memoryBlockToWriteTo == 0)
  7098. data = new MemoryBlock (initialSize);
  7099. else
  7100. memoryBlockToWriteTo->setSize (initialSize, false);
  7101. }
  7102. MemoryOutputStream::~MemoryOutputStream() throw()
  7103. {
  7104. if (ownsMemoryBlock)
  7105. delete data;
  7106. else
  7107. flush();
  7108. }
  7109. void MemoryOutputStream::flush()
  7110. {
  7111. if (! ownsMemoryBlock)
  7112. data->setSize (size, false);
  7113. }
  7114. void MemoryOutputStream::reset() throw()
  7115. {
  7116. position = 0;
  7117. size = 0;
  7118. }
  7119. bool MemoryOutputStream::write (const void* buffer, int howMany)
  7120. {
  7121. if (howMany > 0)
  7122. {
  7123. int storageNeeded = position + howMany;
  7124. if (storageNeeded >= data->getSize())
  7125. {
  7126. // if we need more space, increase the block by at least 10%..
  7127. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7128. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7129. data->ensureSize (storageNeeded);
  7130. }
  7131. data->copyFrom (buffer, position, howMany);
  7132. position += howMany;
  7133. size = jmax (size, position);
  7134. }
  7135. return true;
  7136. }
  7137. const char* MemoryOutputStream::getData() throw()
  7138. {
  7139. if (data->getSize() > size)
  7140. ((char*) data->getData()) [size] = 0;
  7141. return (const char*) data->getData();
  7142. }
  7143. int MemoryOutputStream::getDataSize() const throw()
  7144. {
  7145. return size;
  7146. }
  7147. int64 MemoryOutputStream::getPosition()
  7148. {
  7149. return position;
  7150. }
  7151. bool MemoryOutputStream::setPosition (int64 newPosition)
  7152. {
  7153. if (newPosition <= size)
  7154. {
  7155. // ok to seek backwards
  7156. position = jlimit (0, size, (int) newPosition);
  7157. return true;
  7158. }
  7159. else
  7160. {
  7161. // trying to make it bigger isn't a good thing to do..
  7162. return false;
  7163. }
  7164. }
  7165. END_JUCE_NAMESPACE
  7166. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  7167. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  7168. BEGIN_JUCE_NAMESPACE
  7169. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7170. const int64 startPositionInSourceStream_,
  7171. const int64 lengthOfSourceStream_,
  7172. const bool deleteSourceWhenDestroyed_) throw()
  7173. : source (sourceStream),
  7174. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  7175. startPositionInSourceStream (startPositionInSourceStream_),
  7176. lengthOfSourceStream (lengthOfSourceStream_)
  7177. {
  7178. setPosition (0);
  7179. }
  7180. SubregionStream::~SubregionStream() throw()
  7181. {
  7182. if (deleteSourceWhenDestroyed)
  7183. delete source;
  7184. }
  7185. int64 SubregionStream::getTotalLength()
  7186. {
  7187. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7188. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7189. : srcLen;
  7190. }
  7191. int64 SubregionStream::getPosition()
  7192. {
  7193. return source->getPosition() - startPositionInSourceStream;
  7194. }
  7195. bool SubregionStream::setPosition (int64 newPosition)
  7196. {
  7197. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7198. }
  7199. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7200. {
  7201. if (lengthOfSourceStream < 0)
  7202. {
  7203. return source->read (destBuffer, maxBytesToRead);
  7204. }
  7205. else
  7206. {
  7207. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7208. if (maxBytesToRead <= 0)
  7209. return 0;
  7210. return source->read (destBuffer, maxBytesToRead);
  7211. }
  7212. }
  7213. bool SubregionStream::isExhausted()
  7214. {
  7215. if (lengthOfSourceStream >= 0)
  7216. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7217. else
  7218. return source->isExhausted();
  7219. }
  7220. END_JUCE_NAMESPACE
  7221. /********* End of inlined file: juce_SubregionStream.cpp *********/
  7222. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  7223. BEGIN_JUCE_NAMESPACE
  7224. PerformanceCounter::PerformanceCounter (const String& name_,
  7225. int runsPerPrintout,
  7226. const File& loggingFile)
  7227. : name (name_),
  7228. numRuns (0),
  7229. runsPerPrint (runsPerPrintout),
  7230. totalTime (0),
  7231. outputFile (loggingFile)
  7232. {
  7233. if (outputFile != File::nonexistent)
  7234. {
  7235. String s ("**** Counter for \"");
  7236. s << name_ << "\" started at: "
  7237. << Time::getCurrentTime().toString (true, true)
  7238. << "\r\n";
  7239. outputFile.appendText (s, false, false);
  7240. }
  7241. }
  7242. PerformanceCounter::~PerformanceCounter()
  7243. {
  7244. printStatistics();
  7245. }
  7246. void PerformanceCounter::start()
  7247. {
  7248. started = Time::getHighResolutionTicks();
  7249. }
  7250. void PerformanceCounter::stop()
  7251. {
  7252. const int64 now = Time::getHighResolutionTicks();
  7253. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7254. if (++numRuns == runsPerPrint)
  7255. printStatistics();
  7256. }
  7257. void PerformanceCounter::printStatistics()
  7258. {
  7259. if (numRuns > 0)
  7260. {
  7261. String s ("Performance count for \"");
  7262. s << name << "\" - average over " << numRuns << " run(s) = ";
  7263. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7264. if (micros > 10000)
  7265. s << (micros/1000) << " millisecs";
  7266. else
  7267. s << micros << " microsecs";
  7268. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7269. Logger::outputDebugString (s);
  7270. s << "\r\n";
  7271. if (outputFile != File::nonexistent)
  7272. outputFile.appendText (s, false, false);
  7273. numRuns = 0;
  7274. totalTime = 0;
  7275. }
  7276. }
  7277. END_JUCE_NAMESPACE
  7278. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  7279. /********* Start of inlined file: juce_Uuid.cpp *********/
  7280. BEGIN_JUCE_NAMESPACE
  7281. Uuid::Uuid()
  7282. {
  7283. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7284. // to make it very very unlikely that two UUIDs will ever be the same..
  7285. static int64 macAddresses[2];
  7286. static bool hasCheckedMacAddresses = false;
  7287. if (! hasCheckedMacAddresses)
  7288. {
  7289. hasCheckedMacAddresses = true;
  7290. SystemStats::getMACAddresses (macAddresses, 2);
  7291. }
  7292. value.asInt64[0] = macAddresses[0];
  7293. value.asInt64[1] = macAddresses[1];
  7294. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7295. // whose seed will carry over between calls to this method.
  7296. Random r (macAddresses[0] ^ macAddresses[1]
  7297. ^ Random::getSystemRandom().nextInt64());
  7298. for (int i = 4; --i >= 0;)
  7299. {
  7300. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7301. value.asInt[i] ^= r.nextInt();
  7302. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7303. }
  7304. }
  7305. Uuid::~Uuid() throw()
  7306. {
  7307. }
  7308. Uuid::Uuid (const Uuid& other)
  7309. : value (other.value)
  7310. {
  7311. }
  7312. Uuid& Uuid::operator= (const Uuid& other)
  7313. {
  7314. if (this != &other)
  7315. value = other.value;
  7316. return *this;
  7317. }
  7318. bool Uuid::operator== (const Uuid& other) const
  7319. {
  7320. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  7321. }
  7322. bool Uuid::operator!= (const Uuid& other) const
  7323. {
  7324. return ! operator== (other);
  7325. }
  7326. bool Uuid::isNull() const throw()
  7327. {
  7328. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7329. }
  7330. const String Uuid::toString() const
  7331. {
  7332. return String::toHexString (value.asBytes, 16, 0);
  7333. }
  7334. Uuid::Uuid (const String& uuidString)
  7335. {
  7336. operator= (uuidString);
  7337. }
  7338. Uuid& Uuid::operator= (const String& uuidString)
  7339. {
  7340. int destIndex = 0;
  7341. int i = 0;
  7342. for (;;)
  7343. {
  7344. int byte = 0;
  7345. for (int loop = 2; --loop >= 0;)
  7346. {
  7347. byte <<= 4;
  7348. for (;;)
  7349. {
  7350. const tchar c = uuidString [i++];
  7351. if (c >= T('0') && c <= T('9'))
  7352. {
  7353. byte |= c - T('0');
  7354. break;
  7355. }
  7356. else if (c >= T('a') && c <= T('z'))
  7357. {
  7358. byte |= c - (T('a') - 10);
  7359. break;
  7360. }
  7361. else if (c >= T('A') && c <= T('Z'))
  7362. {
  7363. byte |= c - (T('A') - 10);
  7364. break;
  7365. }
  7366. else if (c == 0)
  7367. {
  7368. while (destIndex < 16)
  7369. value.asBytes [destIndex++] = 0;
  7370. return *this;
  7371. }
  7372. }
  7373. }
  7374. value.asBytes [destIndex++] = (uint8) byte;
  7375. }
  7376. }
  7377. Uuid::Uuid (const uint8* const rawData)
  7378. {
  7379. operator= (rawData);
  7380. }
  7381. Uuid& Uuid::operator= (const uint8* const rawData)
  7382. {
  7383. if (rawData != 0)
  7384. memcpy (value.asBytes, rawData, 16);
  7385. else
  7386. zeromem (value.asBytes, 16);
  7387. return *this;
  7388. }
  7389. END_JUCE_NAMESPACE
  7390. /********* End of inlined file: juce_Uuid.cpp *********/
  7391. /********* Start of inlined file: juce_ZipFile.cpp *********/
  7392. BEGIN_JUCE_NAMESPACE
  7393. struct ZipEntryInfo
  7394. {
  7395. ZipFile::ZipEntry entry;
  7396. int streamOffset;
  7397. int compressedSize;
  7398. bool compressed;
  7399. };
  7400. class ZipInputStream : public InputStream
  7401. {
  7402. public:
  7403. ZipInputStream (ZipFile& file_,
  7404. ZipEntryInfo& zei) throw()
  7405. : file (file_),
  7406. zipEntryInfo (zei),
  7407. pos (0),
  7408. headerSize (0),
  7409. inputStream (0)
  7410. {
  7411. inputStream = file_.inputStream;
  7412. if (file_.inputSource != 0)
  7413. {
  7414. inputStream = file.inputSource->createInputStream();
  7415. }
  7416. else
  7417. {
  7418. #ifdef JUCE_DEBUG
  7419. file_.numOpenStreams++;
  7420. #endif
  7421. }
  7422. char buffer [30];
  7423. if (inputStream != 0
  7424. && inputStream->setPosition (zei.streamOffset)
  7425. && inputStream->read (buffer, 30) == 30
  7426. && littleEndianInt (buffer) == 0x04034b50)
  7427. {
  7428. headerSize = 30 + littleEndianShort (buffer + 26)
  7429. + littleEndianShort (buffer + 28);
  7430. }
  7431. }
  7432. ~ZipInputStream() throw()
  7433. {
  7434. #ifdef JUCE_DEBUG
  7435. if (inputStream != 0 && inputStream == file.inputStream)
  7436. file.numOpenStreams--;
  7437. #endif
  7438. if (inputStream != file.inputStream)
  7439. delete inputStream;
  7440. }
  7441. int64 getTotalLength() throw()
  7442. {
  7443. return zipEntryInfo.compressedSize;
  7444. }
  7445. int read (void* buffer, int howMany) throw()
  7446. {
  7447. if (headerSize <= 0)
  7448. return 0;
  7449. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7450. if (inputStream == 0)
  7451. return 0;
  7452. int num;
  7453. if (inputStream == file.inputStream)
  7454. {
  7455. const ScopedLock sl (file.lock);
  7456. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7457. num = inputStream->read (buffer, howMany);
  7458. }
  7459. else
  7460. {
  7461. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7462. num = inputStream->read (buffer, howMany);
  7463. }
  7464. pos += num;
  7465. return num;
  7466. }
  7467. bool isExhausted() throw()
  7468. {
  7469. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7470. }
  7471. int64 getPosition() throw()
  7472. {
  7473. return pos;
  7474. }
  7475. bool setPosition (int64 newPos) throw()
  7476. {
  7477. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7478. return true;
  7479. }
  7480. private:
  7481. ZipFile& file;
  7482. ZipEntryInfo zipEntryInfo;
  7483. int64 pos;
  7484. int headerSize;
  7485. InputStream* inputStream;
  7486. ZipInputStream (const ZipInputStream&);
  7487. const ZipInputStream& operator= (const ZipInputStream&);
  7488. };
  7489. ZipFile::ZipFile (InputStream* const source_,
  7490. const bool deleteStreamWhenDestroyed_) throw()
  7491. : inputStream (source_),
  7492. inputSource (0),
  7493. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  7494. #ifdef JUCE_DEBUG
  7495. , numOpenStreams (0)
  7496. #endif
  7497. {
  7498. init();
  7499. }
  7500. ZipFile::ZipFile (const File& file)
  7501. : inputStream (0),
  7502. deleteStreamWhenDestroyed (false)
  7503. #ifdef JUCE_DEBUG
  7504. , numOpenStreams (0)
  7505. #endif
  7506. {
  7507. inputSource = new FileInputSource (file);
  7508. init();
  7509. }
  7510. ZipFile::ZipFile (InputSource* const inputSource_)
  7511. : inputStream (0),
  7512. inputSource (inputSource_),
  7513. deleteStreamWhenDestroyed (false)
  7514. #ifdef JUCE_DEBUG
  7515. , numOpenStreams (0)
  7516. #endif
  7517. {
  7518. init();
  7519. }
  7520. ZipFile::~ZipFile() throw()
  7521. {
  7522. for (int i = entries.size(); --i >= 0;)
  7523. {
  7524. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  7525. delete zei;
  7526. }
  7527. if (deleteStreamWhenDestroyed)
  7528. delete inputStream;
  7529. delete inputSource;
  7530. #ifdef JUCE_DEBUG
  7531. // If you hit this assertion, it means you've created a stream to read
  7532. // one of the items in the zipfile, but you've forgotten to delete that
  7533. // stream object before deleting the file.. Streams can't be kept open
  7534. // after the file is deleted because they need to share the input
  7535. // stream that the file uses to read itself.
  7536. jassert (numOpenStreams == 0);
  7537. #endif
  7538. }
  7539. int ZipFile::getNumEntries() const throw()
  7540. {
  7541. return entries.size();
  7542. }
  7543. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7544. {
  7545. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  7546. return (zei != 0) ? &(zei->entry)
  7547. : 0;
  7548. }
  7549. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7550. {
  7551. for (int i = 0; i < entries.size(); ++i)
  7552. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  7553. return i;
  7554. return -1;
  7555. }
  7556. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7557. {
  7558. return getEntry (getIndexOfFileName (fileName));
  7559. }
  7560. InputStream* ZipFile::createStreamForEntry (const int index)
  7561. {
  7562. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  7563. InputStream* stream = 0;
  7564. if (zei != 0)
  7565. {
  7566. stream = new ZipInputStream (*this, *zei);
  7567. if (zei->compressed)
  7568. {
  7569. stream = new GZIPDecompressorInputStream (stream, true, true,
  7570. zei->entry.uncompressedSize);
  7571. // (much faster to unzip in big blocks using a buffer..)
  7572. stream = new BufferedInputStream (stream, 32768, true);
  7573. }
  7574. }
  7575. return stream;
  7576. }
  7577. class ZipFilenameComparator
  7578. {
  7579. public:
  7580. static int compareElements (const void* const first, const void* const second) throw()
  7581. {
  7582. return ((const ZipEntryInfo*) first)->entry.filename
  7583. .compare (((const ZipEntryInfo*) second)->entry.filename);
  7584. }
  7585. };
  7586. void ZipFile::sortEntriesByFilename()
  7587. {
  7588. ZipFilenameComparator sorter;
  7589. entries.sort (sorter);
  7590. }
  7591. void ZipFile::init()
  7592. {
  7593. InputStream* in = inputStream;
  7594. bool deleteInput = false;
  7595. if (inputSource != 0)
  7596. {
  7597. deleteInput = true;
  7598. in = inputSource->createInputStream();
  7599. }
  7600. if (in != 0)
  7601. {
  7602. numEntries = 0;
  7603. int pos = findEndOfZipEntryTable (in);
  7604. if (pos >= 0 && pos < in->getTotalLength())
  7605. {
  7606. const int size = (int) (in->getTotalLength() - pos);
  7607. in->setPosition (pos);
  7608. MemoryBlock headerData;
  7609. if (in->readIntoMemoryBlock (headerData, size) == size)
  7610. {
  7611. pos = 0;
  7612. for (int i = 0; i < numEntries; ++i)
  7613. {
  7614. if (pos + 46 > size)
  7615. break;
  7616. const char* const buffer = ((const char*) headerData.getData()) + pos;
  7617. const int fileNameLen = littleEndianShort (buffer + 28);
  7618. if (pos + 46 + fileNameLen > size)
  7619. break;
  7620. ZipEntryInfo* const zei = new ZipEntryInfo();
  7621. zei->entry.filename = String (buffer + 46, fileNameLen);
  7622. const int time = littleEndianShort (buffer + 12);
  7623. const int date = littleEndianShort (buffer + 14);
  7624. const int year = 1980 + (date >> 9);
  7625. const int month = ((date >> 5) & 15) - 1;
  7626. const int day = date & 31;
  7627. const int hours = time >> 11;
  7628. const int minutes = (time >> 5) & 63;
  7629. const int seconds = (time & 31) << 1;
  7630. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7631. zei->compressed = littleEndianShort (buffer + 10) != 0;
  7632. zei->compressedSize = littleEndianInt (buffer + 20);
  7633. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  7634. zei->streamOffset = littleEndianInt (buffer + 42);
  7635. entries.add (zei);
  7636. pos += 46 + fileNameLen
  7637. + littleEndianShort (buffer + 30)
  7638. + littleEndianShort (buffer + 32);
  7639. }
  7640. }
  7641. }
  7642. if (deleteInput)
  7643. delete in;
  7644. }
  7645. }
  7646. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  7647. {
  7648. BufferedInputStream in (input, 8192, false);
  7649. in.setPosition (in.getTotalLength());
  7650. int64 pos = in.getPosition();
  7651. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7652. char buffer [32];
  7653. zeromem (buffer, sizeof (buffer));
  7654. while (pos > lowestPos)
  7655. {
  7656. in.setPosition (pos - 22);
  7657. pos = in.getPosition();
  7658. memcpy (buffer + 22, buffer, 4);
  7659. if (in.read (buffer, 22) != 22)
  7660. return 0;
  7661. for (int i = 0; i < 22; ++i)
  7662. {
  7663. if (littleEndianInt (buffer + i) == 0x06054b50)
  7664. {
  7665. in.setPosition (pos + i);
  7666. in.read (buffer, 22);
  7667. numEntries = littleEndianShort (buffer + 10);
  7668. return littleEndianInt (buffer + 16);
  7669. }
  7670. }
  7671. }
  7672. return 0;
  7673. }
  7674. void ZipFile::uncompressTo (const File& targetDirectory,
  7675. const bool shouldOverwriteFiles)
  7676. {
  7677. for (int i = 0; i < entries.size(); ++i)
  7678. {
  7679. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  7680. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  7681. if (zei.entry.filename.endsWithChar (T('/')))
  7682. {
  7683. targetFile.createDirectory(); // (entry is a directory, not a file)
  7684. }
  7685. else
  7686. {
  7687. InputStream* const in = createStreamForEntry (i);
  7688. if (in != 0)
  7689. {
  7690. if (shouldOverwriteFiles)
  7691. targetFile.deleteFile();
  7692. if ((! targetFile.exists())
  7693. && targetFile.getParentDirectory().createDirectory())
  7694. {
  7695. FileOutputStream* const out = targetFile.createOutputStream();
  7696. if (out != 0)
  7697. {
  7698. out->writeFromInputStream (*in, -1);
  7699. delete out;
  7700. targetFile.setCreationTime (zei.entry.fileTime);
  7701. targetFile.setLastModificationTime (zei.entry.fileTime);
  7702. targetFile.setLastAccessTime (zei.entry.fileTime);
  7703. }
  7704. }
  7705. delete in;
  7706. }
  7707. }
  7708. }
  7709. }
  7710. END_JUCE_NAMESPACE
  7711. /********* End of inlined file: juce_ZipFile.cpp *********/
  7712. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  7713. #ifdef _MSC_VER
  7714. #pragma warning (disable: 4514 4996)
  7715. #pragma warning (push)
  7716. #endif
  7717. #include <cwctype>
  7718. #include <cctype>
  7719. #include <ctime>
  7720. #ifdef _MSC_VER
  7721. #pragma warning (pop)
  7722. #endif
  7723. BEGIN_JUCE_NAMESPACE
  7724. int CharacterFunctions::length (const char* const s) throw()
  7725. {
  7726. return (int) strlen (s);
  7727. }
  7728. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7729. {
  7730. return (int) wcslen (s);
  7731. }
  7732. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7733. {
  7734. strncpy (dest, src, maxChars);
  7735. }
  7736. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7737. {
  7738. wcsncpy (dest, src, maxChars);
  7739. }
  7740. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7741. {
  7742. mbstowcs (dest, src, maxChars);
  7743. }
  7744. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7745. {
  7746. wcstombs (dest, src, maxChars);
  7747. }
  7748. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7749. {
  7750. return (int) wcstombs (0, src, 0);
  7751. }
  7752. void CharacterFunctions::append (char* dest, const char* src) throw()
  7753. {
  7754. strcat (dest, src);
  7755. }
  7756. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7757. {
  7758. wcscat (dest, src);
  7759. }
  7760. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7761. {
  7762. return strcmp (s1, s2);
  7763. }
  7764. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7765. {
  7766. jassert (s1 != 0 && s2 != 0);
  7767. return wcscmp (s1, s2);
  7768. }
  7769. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7770. {
  7771. jassert (s1 != 0 && s2 != 0);
  7772. return strncmp (s1, s2, maxChars);
  7773. }
  7774. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7775. {
  7776. jassert (s1 != 0 && s2 != 0);
  7777. return wcsncmp (s1, s2, maxChars);
  7778. }
  7779. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7780. {
  7781. jassert (s1 != 0 && s2 != 0);
  7782. #if JUCE_WIN32
  7783. return stricmp (s1, s2);
  7784. #else
  7785. return strcasecmp (s1, s2);
  7786. #endif
  7787. }
  7788. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7789. {
  7790. jassert (s1 != 0 && s2 != 0);
  7791. #if JUCE_WIN32
  7792. return _wcsicmp (s1, s2);
  7793. #else
  7794. for (;;)
  7795. {
  7796. if (*s1 != *s2)
  7797. {
  7798. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7799. if (diff != 0)
  7800. return diff < 0 ? -1 : 1;
  7801. }
  7802. else if (*s1 == 0)
  7803. break;
  7804. ++s1;
  7805. ++s2;
  7806. }
  7807. return 0;
  7808. #endif
  7809. }
  7810. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7811. {
  7812. jassert (s1 != 0 && s2 != 0);
  7813. #if JUCE_WIN32
  7814. return strnicmp (s1, s2, maxChars);
  7815. #else
  7816. return strncasecmp (s1, s2, maxChars);
  7817. #endif
  7818. }
  7819. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7820. {
  7821. jassert (s1 != 0 && s2 != 0);
  7822. #if JUCE_WIN32
  7823. return _wcsnicmp (s1, s2, maxChars);
  7824. #else
  7825. while (--maxChars >= 0)
  7826. {
  7827. if (*s1 != *s2)
  7828. {
  7829. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7830. if (diff != 0)
  7831. return diff < 0 ? -1 : 1;
  7832. }
  7833. else if (*s1 == 0)
  7834. break;
  7835. ++s1;
  7836. ++s2;
  7837. }
  7838. return 0;
  7839. #endif
  7840. }
  7841. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7842. {
  7843. return strstr (haystack, needle);
  7844. }
  7845. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7846. {
  7847. return wcsstr (haystack, needle);
  7848. }
  7849. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7850. {
  7851. if (haystack != 0)
  7852. {
  7853. int i = 0;
  7854. if (ignoreCase)
  7855. {
  7856. const char n1 = toLowerCase (needle);
  7857. const char n2 = toUpperCase (needle);
  7858. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7859. {
  7860. while (haystack[i] != 0)
  7861. {
  7862. if (haystack[i] == n1 || haystack[i] == n2)
  7863. return i;
  7864. ++i;
  7865. }
  7866. return -1;
  7867. }
  7868. jassert (n1 == needle);
  7869. }
  7870. while (haystack[i] != 0)
  7871. {
  7872. if (haystack[i] == needle)
  7873. return i;
  7874. ++i;
  7875. }
  7876. }
  7877. return -1;
  7878. }
  7879. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7880. {
  7881. if (haystack != 0)
  7882. {
  7883. int i = 0;
  7884. if (ignoreCase)
  7885. {
  7886. const juce_wchar n1 = toLowerCase (needle);
  7887. const juce_wchar n2 = toUpperCase (needle);
  7888. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7889. {
  7890. while (haystack[i] != 0)
  7891. {
  7892. if (haystack[i] == n1 || haystack[i] == n2)
  7893. return i;
  7894. ++i;
  7895. }
  7896. return -1;
  7897. }
  7898. jassert (n1 == needle);
  7899. }
  7900. while (haystack[i] != 0)
  7901. {
  7902. if (haystack[i] == needle)
  7903. return i;
  7904. ++i;
  7905. }
  7906. }
  7907. return -1;
  7908. }
  7909. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7910. {
  7911. jassert (haystack != 0);
  7912. int i = 0;
  7913. while (haystack[i] != 0)
  7914. {
  7915. if (haystack[i] == needle)
  7916. return i;
  7917. ++i;
  7918. }
  7919. return -1;
  7920. }
  7921. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7922. {
  7923. jassert (haystack != 0);
  7924. int i = 0;
  7925. while (haystack[i] != 0)
  7926. {
  7927. if (haystack[i] == needle)
  7928. return i;
  7929. ++i;
  7930. }
  7931. return -1;
  7932. }
  7933. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7934. {
  7935. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7936. }
  7937. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7938. {
  7939. if (allowedChars == 0)
  7940. return 0;
  7941. int i = 0;
  7942. for (;;)
  7943. {
  7944. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7945. break;
  7946. ++i;
  7947. }
  7948. return i;
  7949. }
  7950. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7951. {
  7952. return (int) strftime (dest, maxChars, format, tm);
  7953. }
  7954. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7955. {
  7956. return (int) wcsftime (dest, maxChars, format, tm);
  7957. }
  7958. int CharacterFunctions::getIntValue (const char* const s) throw()
  7959. {
  7960. return atoi (s);
  7961. }
  7962. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7963. {
  7964. #if JUCE_WIN32
  7965. return _wtoi (s);
  7966. #else
  7967. int v = 0;
  7968. while (isWhitespace (*s))
  7969. ++s;
  7970. const bool isNeg = *s == T('-');
  7971. if (isNeg)
  7972. ++s;
  7973. for (;;)
  7974. {
  7975. const wchar_t c = *s++;
  7976. if (c >= T('0') && c <= T('9'))
  7977. v = v * 10 + (int) (c - T('0'));
  7978. else
  7979. break;
  7980. }
  7981. return isNeg ? -v : v;
  7982. #endif
  7983. }
  7984. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7985. {
  7986. #if JUCE_LINUX
  7987. return atoll (s);
  7988. #elif defined (JUCE_WIN32)
  7989. return _atoi64 (s);
  7990. #else
  7991. int64 v = 0;
  7992. while (isWhitespace (*s))
  7993. ++s;
  7994. const bool isNeg = *s == T('-');
  7995. if (isNeg)
  7996. ++s;
  7997. for (;;)
  7998. {
  7999. const char c = *s++;
  8000. if (c >= '0' && c <= '9')
  8001. v = v * 10 + (int64) (c - '0');
  8002. else
  8003. break;
  8004. }
  8005. return isNeg ? -v : v;
  8006. #endif
  8007. }
  8008. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8009. {
  8010. #if JUCE_WIN32
  8011. return _wtoi64 (s);
  8012. #else
  8013. int64 v = 0;
  8014. while (isWhitespace (*s))
  8015. ++s;
  8016. const bool isNeg = *s == T('-');
  8017. if (isNeg)
  8018. ++s;
  8019. for (;;)
  8020. {
  8021. const juce_wchar c = *s++;
  8022. if (c >= T('0') && c <= T('9'))
  8023. v = v * 10 + (int64) (c - T('0'));
  8024. else
  8025. break;
  8026. }
  8027. return isNeg ? -v : v;
  8028. #endif
  8029. }
  8030. static double juce_mulexp10 (const double value, int exponent) throw()
  8031. {
  8032. if (exponent == 0)
  8033. return value;
  8034. if (value == 0)
  8035. return 0;
  8036. const bool negative = (exponent < 0);
  8037. if (negative)
  8038. exponent = -exponent;
  8039. double result = 1.0, power = 10.0;
  8040. for (int bit = 1; exponent != 0; bit <<= 1)
  8041. {
  8042. if ((exponent & bit) != 0)
  8043. {
  8044. exponent ^= bit;
  8045. result *= power;
  8046. if (exponent == 0)
  8047. break;
  8048. }
  8049. power *= power;
  8050. }
  8051. return negative ? (value / result) : (value * result);
  8052. }
  8053. template <class CharType>
  8054. double juce_atof (const CharType* const original) throw()
  8055. {
  8056. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8057. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8058. int exponent = 0, decPointIndex = 0, digit = 0;
  8059. int lastDigit = 0, numSignificantDigits = 0;
  8060. bool isNegative = false, digitsFound = false;
  8061. const int maxSignificantDigits = 15 + 2;
  8062. const CharType* s = original;
  8063. while (CharacterFunctions::isWhitespace (*s))
  8064. ++s;
  8065. switch (*s)
  8066. {
  8067. case '-': isNegative = true; // fall-through..
  8068. case '+': ++s;
  8069. }
  8070. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8071. return atof (String (original)); // Let the c library deal with NAN and INF
  8072. for (;;)
  8073. {
  8074. if (CharacterFunctions::isDigit (*s))
  8075. {
  8076. lastDigit = digit;
  8077. digit = *s++ - '0';
  8078. digitsFound = true;
  8079. if (decPointIndex != 0)
  8080. exponentAdjustment[1]++;
  8081. if (numSignificantDigits == 0 && digit == 0)
  8082. continue;
  8083. if (++numSignificantDigits > maxSignificantDigits)
  8084. {
  8085. if (digit > 5)
  8086. ++accumulator [decPointIndex];
  8087. else if (digit == 5 && (lastDigit & 1) != 0)
  8088. ++accumulator [decPointIndex];
  8089. if (decPointIndex > 0)
  8090. exponentAdjustment[1]--;
  8091. else
  8092. exponentAdjustment[0]++;
  8093. while (CharacterFunctions::isDigit (*s))
  8094. {
  8095. ++s;
  8096. if (decPointIndex == 0)
  8097. exponentAdjustment[0]++;
  8098. }
  8099. }
  8100. else
  8101. {
  8102. const double maxAccumulatorValue = (double) ((UINT_MAX - 9) / 10);
  8103. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8104. {
  8105. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8106. + accumulator [decPointIndex];
  8107. accumulator [decPointIndex] = 0;
  8108. exponentAccumulator [decPointIndex] = 0;
  8109. }
  8110. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8111. exponentAccumulator [decPointIndex]++;
  8112. }
  8113. }
  8114. else if (decPointIndex == 0 && *s == '.')
  8115. {
  8116. ++s;
  8117. decPointIndex = 1;
  8118. if (numSignificantDigits > maxSignificantDigits)
  8119. {
  8120. while (CharacterFunctions::isDigit (*s))
  8121. ++s;
  8122. break;
  8123. }
  8124. }
  8125. else
  8126. {
  8127. break;
  8128. }
  8129. }
  8130. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8131. if (decPointIndex != 0)
  8132. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8133. if ((*s == 'e' || *s == 'E') && digitsFound)
  8134. {
  8135. bool negativeExponent = false;
  8136. switch (*++s)
  8137. {
  8138. case '-': negativeExponent = true; // fall-through..
  8139. case '+': ++s;
  8140. }
  8141. while (CharacterFunctions::isDigit (*s))
  8142. exponent = (exponent * 10) + (*s++ - '0');
  8143. if (negativeExponent)
  8144. exponent = -exponent;
  8145. }
  8146. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8147. if (decPointIndex != 0)
  8148. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8149. return isNegative ? -r : r;
  8150. }
  8151. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8152. {
  8153. return juce_atof <char> (s);
  8154. }
  8155. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8156. {
  8157. return juce_atof <juce_wchar> (s);
  8158. }
  8159. char CharacterFunctions::toUpperCase (const char character) throw()
  8160. {
  8161. return (char) toupper (character);
  8162. }
  8163. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8164. {
  8165. return towupper (character);
  8166. }
  8167. void CharacterFunctions::toUpperCase (char* s) throw()
  8168. {
  8169. #if JUCE_WIN32
  8170. strupr (s);
  8171. #else
  8172. while (*s != 0)
  8173. {
  8174. *s = toUpperCase (*s);
  8175. ++s;
  8176. }
  8177. #endif
  8178. }
  8179. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8180. {
  8181. #if JUCE_WIN32
  8182. _wcsupr (s);
  8183. #else
  8184. while (*s != 0)
  8185. {
  8186. *s = toUpperCase (*s);
  8187. ++s;
  8188. }
  8189. #endif
  8190. }
  8191. bool CharacterFunctions::isUpperCase (const char character) throw()
  8192. {
  8193. return isupper (character) != 0;
  8194. }
  8195. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8196. {
  8197. #if JUCE_WIN32
  8198. return iswupper (character) != 0;
  8199. #else
  8200. return toLowerCase (character) != character;
  8201. #endif
  8202. }
  8203. char CharacterFunctions::toLowerCase (const char character) throw()
  8204. {
  8205. return (char) tolower (character);
  8206. }
  8207. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8208. {
  8209. return towlower (character);
  8210. }
  8211. void CharacterFunctions::toLowerCase (char* s) throw()
  8212. {
  8213. #if JUCE_WIN32
  8214. strlwr (s);
  8215. #else
  8216. while (*s != 0)
  8217. {
  8218. *s = toLowerCase (*s);
  8219. ++s;
  8220. }
  8221. #endif
  8222. }
  8223. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8224. {
  8225. #if JUCE_WIN32
  8226. _wcslwr (s);
  8227. #else
  8228. while (*s != 0)
  8229. {
  8230. *s = toLowerCase (*s);
  8231. ++s;
  8232. }
  8233. #endif
  8234. }
  8235. bool CharacterFunctions::isLowerCase (const char character) throw()
  8236. {
  8237. return islower (character) != 0;
  8238. }
  8239. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8240. {
  8241. #if JUCE_WIN32
  8242. return iswlower (character) != 0;
  8243. #else
  8244. return toUpperCase (character) != character;
  8245. #endif
  8246. }
  8247. bool CharacterFunctions::isWhitespace (const char character) throw()
  8248. {
  8249. return character == T(' ') || (character <= 13 && character >= 9);
  8250. }
  8251. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8252. {
  8253. return iswspace (character) != 0;
  8254. }
  8255. bool CharacterFunctions::isDigit (const char character) throw()
  8256. {
  8257. return (character >= '0' && character <= '9');
  8258. }
  8259. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8260. {
  8261. return iswdigit (character) != 0;
  8262. }
  8263. bool CharacterFunctions::isLetter (const char character) throw()
  8264. {
  8265. return (character >= 'a' && character <= 'z')
  8266. || (character >= 'A' && character <= 'Z');
  8267. }
  8268. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8269. {
  8270. return iswalpha (character) != 0;
  8271. }
  8272. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8273. {
  8274. return (character >= 'a' && character <= 'z')
  8275. || (character >= 'A' && character <= 'Z')
  8276. || (character >= '0' && character <= '9');
  8277. }
  8278. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8279. {
  8280. return iswalnum (character) != 0;
  8281. }
  8282. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  8283. {
  8284. if (digit >= T('0') && digit <= T('9'))
  8285. return digit - T('0');
  8286. else if (digit >= T('a') && digit <= T('f'))
  8287. return digit - (T('a') - 10);
  8288. else if (digit >= T('A') && digit <= T('F'))
  8289. return digit - (T('A') - 10);
  8290. return -1;
  8291. }
  8292. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  8293. {
  8294. va_list list;
  8295. va_start (list, format);
  8296. return vprintf (dest, maxLength, format, list);
  8297. }
  8298. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  8299. {
  8300. va_list list;
  8301. va_start (list, format);
  8302. return vprintf (dest, maxLength, format, list);
  8303. }
  8304. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  8305. {
  8306. #if JUCE_WIN32
  8307. return (int) _vsnprintf (dest, maxLength, format, args);
  8308. #else
  8309. return (int) vsnprintf (dest, maxLength, format, args);
  8310. #endif
  8311. }
  8312. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  8313. {
  8314. #if MACOS_10_3_OR_EARLIER
  8315. const String formatTemp (format);
  8316. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  8317. String temp ((char*) dest);
  8318. temp.copyToBuffer (dest, num);
  8319. dest [num] = 0;
  8320. return (int) num;
  8321. #elif defined (JUCE_WIN32)
  8322. return (int) _vsnwprintf (dest, maxLength, format, args);
  8323. #else
  8324. return (int) vswprintf (dest, maxLength, format, args);
  8325. #endif
  8326. }
  8327. END_JUCE_NAMESPACE
  8328. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  8329. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  8330. BEGIN_JUCE_NAMESPACE
  8331. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  8332. {
  8333. loadFromText (fileContents);
  8334. }
  8335. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  8336. {
  8337. loadFromText (fileToLoad.loadFileAsString());
  8338. }
  8339. LocalisedStrings::~LocalisedStrings() throw()
  8340. {
  8341. }
  8342. const String LocalisedStrings::translate (const String& text) const throw()
  8343. {
  8344. return translations.getValue (text, text);
  8345. }
  8346. static int findCloseQuote (const String& text, int startPos) throw()
  8347. {
  8348. tchar lastChar = 0;
  8349. for (;;)
  8350. {
  8351. const tchar c = text [startPos];
  8352. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  8353. break;
  8354. lastChar = c;
  8355. ++startPos;
  8356. }
  8357. return startPos;
  8358. }
  8359. static const String unescapeString (const String& s) throw()
  8360. {
  8361. return s.replace (T("\\\""), T("\""))
  8362. .replace (T("\\\'"), T("\'"))
  8363. .replace (T("\\t"), T("\t"))
  8364. .replace (T("\\r"), T("\r"))
  8365. .replace (T("\\n"), T("\n"));
  8366. }
  8367. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  8368. {
  8369. StringArray lines;
  8370. lines.addLines (fileContents);
  8371. for (int i = 0; i < lines.size(); ++i)
  8372. {
  8373. String line (lines[i].trim());
  8374. if (line.startsWithChar (T('"')))
  8375. {
  8376. int closeQuote = findCloseQuote (line, 1);
  8377. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8378. if (originalText.isNotEmpty())
  8379. {
  8380. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8381. closeQuote = findCloseQuote (line, openingQuote + 1);
  8382. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8383. if (newText.isNotEmpty())
  8384. translations.set (originalText, newText);
  8385. }
  8386. }
  8387. else if (line.startsWithIgnoreCase (T("language:")))
  8388. {
  8389. languageName = line.substring (9).trim();
  8390. }
  8391. else if (line.startsWithIgnoreCase (T("countries:")))
  8392. {
  8393. countryCodes.addTokens (line.substring (10).trim(), true);
  8394. countryCodes.trim();
  8395. countryCodes.removeEmptyStrings();
  8396. }
  8397. }
  8398. }
  8399. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase) throw()
  8400. {
  8401. translations.setIgnoresCase (shouldIgnoreCase);
  8402. }
  8403. static CriticalSection currentMappingsLock;
  8404. static LocalisedStrings* currentMappings = 0;
  8405. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  8406. {
  8407. const ScopedLock sl (currentMappingsLock);
  8408. delete currentMappings;
  8409. currentMappings = newTranslations;
  8410. }
  8411. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  8412. {
  8413. return currentMappings;
  8414. }
  8415. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  8416. {
  8417. const ScopedLock sl (currentMappingsLock);
  8418. if (currentMappings != 0)
  8419. return currentMappings->translate (text);
  8420. return text;
  8421. }
  8422. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  8423. {
  8424. return translateWithCurrentMappings (String (text));
  8425. }
  8426. END_JUCE_NAMESPACE
  8427. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  8428. /********* Start of inlined file: juce_String.cpp *********/
  8429. #ifdef _MSC_VER
  8430. #pragma warning (disable: 4514)
  8431. #pragma warning (push)
  8432. #endif
  8433. #include <locale>
  8434. #if JUCE_MSVC
  8435. #include <float.h>
  8436. #endif
  8437. BEGIN_JUCE_NAMESPACE
  8438. #ifdef _MSC_VER
  8439. #pragma warning (pop)
  8440. #endif
  8441. static const char* const emptyCharString = "\0\0\0\0JUCE";
  8442. static const int safeEmptyStringRefCount = 0x3fffffff;
  8443. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  8444. static tchar decimalPoint = T('.');
  8445. void juce_initialiseStrings()
  8446. {
  8447. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  8448. }
  8449. void String::deleteInternal() throw()
  8450. {
  8451. if (atomicDecrementAndReturn (text->refCount) == 0)
  8452. juce_free (text);
  8453. }
  8454. void String::createInternal (const int numChars) throw()
  8455. {
  8456. jassert (numChars > 0);
  8457. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8458. + numChars * sizeof (tchar));
  8459. text->refCount = 1;
  8460. text->allocatedNumChars = numChars;
  8461. text->text[0] = 0;
  8462. }
  8463. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  8464. {
  8465. jassert (*(textEnd - 1) == 0); // must have a null terminator
  8466. const int numChars = (int) (textEnd - t);
  8467. createInternal (numChars - 1);
  8468. memcpy (text->text, t, numChars * sizeof (tchar));
  8469. }
  8470. void String::appendInternal (const tchar* const newText,
  8471. const int numExtraChars) throw()
  8472. {
  8473. if (numExtraChars > 0)
  8474. {
  8475. const int oldLen = CharacterFunctions::length (text->text);
  8476. const int newTotalLen = oldLen + numExtraChars;
  8477. if (text->refCount > 1)
  8478. {
  8479. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  8480. InternalRefCountedStringHolder* const newTextHolder
  8481. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8482. + newTotalLen * sizeof (tchar));
  8483. newTextHolder->refCount = 1;
  8484. newTextHolder->allocatedNumChars = newTotalLen;
  8485. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  8486. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8487. InternalRefCountedStringHolder* const old = text;
  8488. text = newTextHolder;
  8489. if (atomicDecrementAndReturn (old->refCount) == 0)
  8490. juce_free (old);
  8491. }
  8492. else
  8493. {
  8494. // no other strings using it, so just expand it if needed..
  8495. if (newTotalLen > text->allocatedNumChars)
  8496. {
  8497. text = (InternalRefCountedStringHolder*)
  8498. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8499. + newTotalLen * sizeof (tchar));
  8500. text->allocatedNumChars = newTotalLen;
  8501. }
  8502. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8503. }
  8504. text->text [newTotalLen] = 0;
  8505. }
  8506. }
  8507. void String::dupeInternalIfMultiplyReferenced() throw()
  8508. {
  8509. if (text->refCount > 1)
  8510. {
  8511. InternalRefCountedStringHolder* const old = text;
  8512. const int len = old->allocatedNumChars;
  8513. InternalRefCountedStringHolder* const newTextHolder
  8514. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8515. + len * sizeof (tchar));
  8516. newTextHolder->refCount = 1;
  8517. newTextHolder->allocatedNumChars = len;
  8518. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  8519. text = newTextHolder;
  8520. if (atomicDecrementAndReturn (old->refCount) == 0)
  8521. juce_free (old);
  8522. }
  8523. }
  8524. const String String::empty;
  8525. String::String() throw()
  8526. : text (&emptyString)
  8527. {
  8528. }
  8529. String::String (const String& other) throw()
  8530. : text (other.text)
  8531. {
  8532. atomicIncrement (text->refCount);
  8533. }
  8534. String::String (const int numChars,
  8535. const int /*dummyVariable*/) throw()
  8536. {
  8537. createInternal (numChars);
  8538. }
  8539. String::String (const char* const t) throw()
  8540. {
  8541. if (t != 0 && *t != 0)
  8542. {
  8543. const int len = CharacterFunctions::length (t);
  8544. createInternal (len);
  8545. #if JUCE_STRINGS_ARE_UNICODE
  8546. CharacterFunctions::copy (text->text, t, len + 1);
  8547. #else
  8548. memcpy (text->text, t, len + 1);
  8549. #endif
  8550. }
  8551. else
  8552. {
  8553. text = &emptyString;
  8554. emptyString.refCount = safeEmptyStringRefCount;
  8555. }
  8556. }
  8557. String::String (const juce_wchar* const t) throw()
  8558. {
  8559. if (t != 0 && *t != 0)
  8560. {
  8561. #if JUCE_STRINGS_ARE_UNICODE
  8562. const int len = CharacterFunctions::length (t);
  8563. createInternal (len);
  8564. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  8565. #else
  8566. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  8567. createInternal (len);
  8568. CharacterFunctions::copy (text->text, t, len + 1);
  8569. #endif
  8570. }
  8571. else
  8572. {
  8573. text = &emptyString;
  8574. emptyString.refCount = safeEmptyStringRefCount;
  8575. }
  8576. }
  8577. String::String (const char* const t,
  8578. const int maxChars) throw()
  8579. {
  8580. int i;
  8581. for (i = 0; i < maxChars; ++i)
  8582. if (t[i] == 0)
  8583. break;
  8584. if (i > 0)
  8585. {
  8586. createInternal (i);
  8587. #if JUCE_STRINGS_ARE_UNICODE
  8588. CharacterFunctions::copy (text->text, t, i);
  8589. #else
  8590. memcpy (text->text, t, i);
  8591. #endif
  8592. text->text [i] = 0;
  8593. }
  8594. else
  8595. {
  8596. text = &emptyString;
  8597. emptyString.refCount = safeEmptyStringRefCount;
  8598. }
  8599. }
  8600. String::String (const juce_wchar* const t,
  8601. const int maxChars) throw()
  8602. {
  8603. int i;
  8604. for (i = 0; i < maxChars; ++i)
  8605. if (t[i] == 0)
  8606. break;
  8607. if (i > 0)
  8608. {
  8609. createInternal (i);
  8610. #if JUCE_STRINGS_ARE_UNICODE
  8611. memcpy (text->text, t, i * sizeof (tchar));
  8612. #else
  8613. CharacterFunctions::copy (text->text, t, i);
  8614. #endif
  8615. text->text [i] = 0;
  8616. }
  8617. else
  8618. {
  8619. text = &emptyString;
  8620. emptyString.refCount = safeEmptyStringRefCount;
  8621. }
  8622. }
  8623. const String String::charToString (const tchar character) throw()
  8624. {
  8625. tchar temp[2];
  8626. temp[0] = character;
  8627. temp[1] = 0;
  8628. return String (temp);
  8629. }
  8630. // pass in a pointer to the END of a buffer..
  8631. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  8632. {
  8633. *--t = 0;
  8634. int64 v = (n >= 0) ? n : -n;
  8635. do
  8636. {
  8637. *--t = (tchar) (T('0') + (int) (v % 10));
  8638. v /= 10;
  8639. } while (v > 0);
  8640. if (n < 0)
  8641. *--t = T('-');
  8642. return t;
  8643. }
  8644. static tchar* intToCharString (tchar* t, const int n) throw()
  8645. {
  8646. if (n == (int) 0x80000000) // (would cause an overflow)
  8647. return int64ToCharString (t, n);
  8648. *--t = 0;
  8649. int v = abs (n);
  8650. do
  8651. {
  8652. *--t = (tchar) (T('0') + (v % 10));
  8653. v /= 10;
  8654. } while (v > 0);
  8655. if (n < 0)
  8656. *--t = T('-');
  8657. return t;
  8658. }
  8659. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  8660. {
  8661. *--t = 0;
  8662. do
  8663. {
  8664. *--t = (tchar) (T('0') + (v % 10));
  8665. v /= 10;
  8666. } while (v > 0);
  8667. return t;
  8668. }
  8669. String::String (const int number) throw()
  8670. {
  8671. tchar buffer [16];
  8672. tchar* const end = buffer + 16;
  8673. createInternal (intToCharString (end, number), end);
  8674. }
  8675. String::String (const unsigned int number) throw()
  8676. {
  8677. tchar buffer [16];
  8678. tchar* const end = buffer + 16;
  8679. createInternal (uintToCharString (end, number), end);
  8680. }
  8681. String::String (const short number) throw()
  8682. {
  8683. tchar buffer [16];
  8684. tchar* const end = buffer + 16;
  8685. createInternal (intToCharString (end, (int) number), end);
  8686. }
  8687. String::String (const unsigned short number) throw()
  8688. {
  8689. tchar buffer [16];
  8690. tchar* const end = buffer + 16;
  8691. createInternal (uintToCharString (end, (unsigned int) number), end);
  8692. }
  8693. String::String (const int64 number) throw()
  8694. {
  8695. tchar buffer [32];
  8696. tchar* const end = buffer + 32;
  8697. createInternal (int64ToCharString (end, number), end);
  8698. }
  8699. String::String (const uint64 number) throw()
  8700. {
  8701. tchar buffer [32];
  8702. tchar* const end = buffer + 32;
  8703. tchar* t = end;
  8704. *--t = 0;
  8705. int64 v = number;
  8706. do
  8707. {
  8708. *--t = (tchar) (T('0') + (int) (v % 10));
  8709. v /= 10;
  8710. } while (v > 0);
  8711. createInternal (t, end);
  8712. }
  8713. // a double-to-string routine that actually uses the number of dec. places you asked for
  8714. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  8715. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  8716. {
  8717. const int bufSize = 80;
  8718. tchar buffer [bufSize];
  8719. int len;
  8720. tchar* t;
  8721. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8722. {
  8723. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  8724. t = buffer + bufSize;
  8725. *--t = (tchar) 0;
  8726. while (numDecPlaces >= 0 || v > 0)
  8727. {
  8728. if (numDecPlaces == 0)
  8729. *--t = decimalPoint;
  8730. *--t = (tchar) (T('0') + (v % 10));
  8731. v /= 10;
  8732. --numDecPlaces;
  8733. }
  8734. if (n < 0)
  8735. *--t = T('-');
  8736. len = (int) ((buffer + bufSize) - t);
  8737. }
  8738. else
  8739. {
  8740. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  8741. t = buffer;
  8742. }
  8743. if (len > 1)
  8744. {
  8745. jassert (len < numElementsInArray (buffer));
  8746. createInternal (len - 1);
  8747. memcpy (text->text, t, len * sizeof (tchar));
  8748. }
  8749. else
  8750. {
  8751. jassert (*t == 0);
  8752. text = &emptyString;
  8753. emptyString.refCount = safeEmptyStringRefCount;
  8754. }
  8755. }
  8756. String::String (const float number,
  8757. const int numberOfDecimalPlaces) throw()
  8758. {
  8759. doubleToStringWithDecPlaces ((double) number,
  8760. numberOfDecimalPlaces);
  8761. }
  8762. String::String (const double number,
  8763. const int numberOfDecimalPlaces) throw()
  8764. {
  8765. doubleToStringWithDecPlaces (number,
  8766. numberOfDecimalPlaces);
  8767. }
  8768. String::~String() throw()
  8769. {
  8770. emptyString.refCount = safeEmptyStringRefCount;
  8771. if (atomicDecrementAndReturn (text->refCount) == 0)
  8772. juce_free (text);
  8773. }
  8774. void String::preallocateStorage (const int numChars) throw()
  8775. {
  8776. if (numChars > text->allocatedNumChars)
  8777. {
  8778. dupeInternalIfMultiplyReferenced();
  8779. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8780. + numChars * sizeof (tchar));
  8781. text->allocatedNumChars = numChars;
  8782. }
  8783. }
  8784. #if JUCE_STRINGS_ARE_UNICODE
  8785. String::operator const char*() const throw()
  8786. {
  8787. if (isEmpty())
  8788. {
  8789. return (const char*) emptyCharString;
  8790. }
  8791. else
  8792. {
  8793. String* const mutableThis = const_cast <String*> (this);
  8794. mutableThis->dupeInternalIfMultiplyReferenced();
  8795. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  8796. mutableThis->text = (InternalRefCountedStringHolder*)
  8797. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8798. + (len * sizeof (juce_wchar) + len));
  8799. char* otherCopy = (char*) (text->text + len);
  8800. --len;
  8801. CharacterFunctions::copy (otherCopy, text->text, len);
  8802. otherCopy [len] = 0;
  8803. return otherCopy;
  8804. }
  8805. }
  8806. #else
  8807. String::operator const juce_wchar*() const throw()
  8808. {
  8809. if (isEmpty())
  8810. {
  8811. return (const juce_wchar*) emptyCharString;
  8812. }
  8813. else
  8814. {
  8815. String* const mutableThis = const_cast <String*> (this);
  8816. mutableThis->dupeInternalIfMultiplyReferenced();
  8817. int len = CharacterFunctions::length (text->text) + 1;
  8818. mutableThis->text = (InternalRefCountedStringHolder*)
  8819. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8820. + (len * sizeof (juce_wchar) + len));
  8821. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  8822. --len;
  8823. CharacterFunctions::copy (otherCopy, text->text, len);
  8824. otherCopy [len] = 0;
  8825. return otherCopy;
  8826. }
  8827. }
  8828. #endif
  8829. void String::copyToBuffer (char* const destBuffer,
  8830. const int bufferSizeBytes) const throw()
  8831. {
  8832. #if JUCE_STRINGS_ARE_UNICODE
  8833. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  8834. CharacterFunctions::copy (destBuffer, text->text, len);
  8835. #else
  8836. const int len = jmin (bufferSizeBytes, length());
  8837. memcpy (destBuffer, text->text, len * sizeof (tchar));
  8838. #endif
  8839. destBuffer [len] = 0;
  8840. }
  8841. void String::copyToBuffer (juce_wchar* const destBuffer,
  8842. const int maxCharsToCopy) const throw()
  8843. {
  8844. const int len = jmin (maxCharsToCopy, length());
  8845. #if JUCE_STRINGS_ARE_UNICODE
  8846. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  8847. #else
  8848. CharacterFunctions::copy (destBuffer, text->text, len);
  8849. #endif
  8850. destBuffer [len] = 0;
  8851. }
  8852. int String::length() const throw()
  8853. {
  8854. return CharacterFunctions::length (text->text);
  8855. }
  8856. int String::hashCode() const throw()
  8857. {
  8858. const tchar* t = text->text;
  8859. int result = 0;
  8860. while (*t != (tchar) 0)
  8861. result = 31 * result + *t++;
  8862. return result;
  8863. }
  8864. int64 String::hashCode64() const throw()
  8865. {
  8866. const tchar* t = text->text;
  8867. int64 result = 0;
  8868. while (*t != (tchar) 0)
  8869. result = 101 * result + *t++;
  8870. return result;
  8871. }
  8872. const String& String::operator= (const tchar* const otherText) throw()
  8873. {
  8874. if (otherText != 0 && *otherText != 0)
  8875. {
  8876. const int otherLen = CharacterFunctions::length (otherText);
  8877. if (otherLen > 0)
  8878. {
  8879. // avoid resizing the memory block if the string is
  8880. // shrinking..
  8881. if (text->refCount > 1
  8882. || otherLen > text->allocatedNumChars
  8883. || otherLen <= (text->allocatedNumChars >> 1))
  8884. {
  8885. deleteInternal();
  8886. createInternal (otherLen);
  8887. }
  8888. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  8889. return *this;
  8890. }
  8891. }
  8892. deleteInternal();
  8893. text = &emptyString;
  8894. emptyString.refCount = safeEmptyStringRefCount;
  8895. return *this;
  8896. }
  8897. const String& String::operator= (const String& other) throw()
  8898. {
  8899. if (this != &other)
  8900. {
  8901. atomicIncrement (other.text->refCount);
  8902. if (atomicDecrementAndReturn (text->refCount) == 0)
  8903. juce_free (text);
  8904. text = other.text;
  8905. }
  8906. return *this;
  8907. }
  8908. bool String::operator== (const String& other) const throw()
  8909. {
  8910. return text == other.text
  8911. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  8912. }
  8913. bool String::operator== (const tchar* const t) const throw()
  8914. {
  8915. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  8916. : isEmpty();
  8917. }
  8918. bool String::equalsIgnoreCase (const tchar* t) const throw()
  8919. {
  8920. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  8921. : isEmpty();
  8922. }
  8923. bool String::equalsIgnoreCase (const String& other) const throw()
  8924. {
  8925. return text == other.text
  8926. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  8927. }
  8928. bool String::operator!= (const String& other) const throw()
  8929. {
  8930. return text != other.text
  8931. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  8932. }
  8933. bool String::operator!= (const tchar* const t) const throw()
  8934. {
  8935. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  8936. : isNotEmpty();
  8937. }
  8938. bool String::operator> (const String& other) const throw()
  8939. {
  8940. return compare (other) > 0;
  8941. }
  8942. bool String::operator< (const tchar* const other) const throw()
  8943. {
  8944. return compare (other) < 0;
  8945. }
  8946. bool String::operator>= (const String& other) const throw()
  8947. {
  8948. return compare (other) >= 0;
  8949. }
  8950. bool String::operator<= (const tchar* const other) const throw()
  8951. {
  8952. return compare (other) <= 0;
  8953. }
  8954. int String::compare (const tchar* const other) const throw()
  8955. {
  8956. return other != 0 ? CharacterFunctions::compare (text->text, other)
  8957. : isEmpty();
  8958. }
  8959. int String::compareIgnoreCase (const tchar* const other) const throw()
  8960. {
  8961. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  8962. : isEmpty();
  8963. }
  8964. int String::compareLexicographically (const tchar* other) const throw()
  8965. {
  8966. if (other == 0)
  8967. return isEmpty();
  8968. const tchar* s1 = text->text;
  8969. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8970. ++s1;
  8971. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  8972. ++other;
  8973. return CharacterFunctions::compareIgnoreCase (s1, other);
  8974. }
  8975. const String String::operator+ (const String& other) const throw()
  8976. {
  8977. if (*(other.text->text) == 0)
  8978. return *this;
  8979. if (isEmpty())
  8980. return other;
  8981. const int len = CharacterFunctions::length (text->text);
  8982. const int otherLen = CharacterFunctions::length (other.text->text);
  8983. String result (len + otherLen, (int) 0);
  8984. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8985. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  8986. result.text->text [len + otherLen] = 0;
  8987. return result;
  8988. }
  8989. const String String::operator+ (const tchar* const textToAppend) const throw()
  8990. {
  8991. if (textToAppend == 0 || *textToAppend == 0)
  8992. return *this;
  8993. const int len = CharacterFunctions::length (text->text);
  8994. const int otherLen = CharacterFunctions::length (textToAppend);
  8995. String result (len + otherLen, (int) 0);
  8996. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8997. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  8998. result.text->text [len + otherLen] = 0;
  8999. return result;
  9000. }
  9001. const String String::operator+ (const tchar characterToAppend) const throw()
  9002. {
  9003. if (characterToAppend == 0)
  9004. return *this;
  9005. const int len = CharacterFunctions::length (text->text);
  9006. String result ((int) (len + 1), (int) 0);
  9007. memcpy (result.text->text, text->text, len * sizeof (tchar));
  9008. result.text->text[len] = characterToAppend;
  9009. result.text->text[len + 1] = 0;
  9010. return result;
  9011. }
  9012. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  9013. const String& string2) throw()
  9014. {
  9015. String s (string1);
  9016. s += string2;
  9017. return s;
  9018. }
  9019. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  9020. const String& string2) throw()
  9021. {
  9022. String s (string1);
  9023. s += string2;
  9024. return s;
  9025. }
  9026. const String& String::operator+= (const tchar* const t) throw()
  9027. {
  9028. if (t != 0)
  9029. appendInternal (t, CharacterFunctions::length (t));
  9030. return *this;
  9031. }
  9032. const String& String::operator+= (const String& other) throw()
  9033. {
  9034. if (isEmpty())
  9035. operator= (other);
  9036. else
  9037. appendInternal (other.text->text,
  9038. CharacterFunctions::length (other.text->text));
  9039. return *this;
  9040. }
  9041. const String& String::operator+= (const char ch) throw()
  9042. {
  9043. char asString[2];
  9044. asString[0] = ch;
  9045. asString[1] = 0;
  9046. #if JUCE_STRINGS_ARE_UNICODE
  9047. operator+= (String (asString));
  9048. #else
  9049. appendInternal (asString, 1);
  9050. #endif
  9051. return *this;
  9052. }
  9053. const String& String::operator+= (const juce_wchar ch) throw()
  9054. {
  9055. juce_wchar asString[2];
  9056. asString[0] = ch;
  9057. asString[1] = 0;
  9058. #if JUCE_STRINGS_ARE_UNICODE
  9059. appendInternal (asString, 1);
  9060. #else
  9061. operator+= (String (asString));
  9062. #endif
  9063. return *this;
  9064. }
  9065. void String::append (const tchar* const other,
  9066. const int howMany) throw()
  9067. {
  9068. if (howMany > 0)
  9069. {
  9070. int i;
  9071. for (i = 0; i < howMany; ++i)
  9072. if (other[i] == 0)
  9073. break;
  9074. appendInternal (other, i);
  9075. }
  9076. }
  9077. String& String::operator<< (const int number) throw()
  9078. {
  9079. tchar buffer [64];
  9080. tchar* const end = buffer + 64;
  9081. const tchar* const t = intToCharString (end, number);
  9082. appendInternal (t, (int) (end - t) - 1);
  9083. return *this;
  9084. }
  9085. String& String::operator<< (const unsigned int number) throw()
  9086. {
  9087. tchar buffer [64];
  9088. tchar* const end = buffer + 64;
  9089. const tchar* const t = uintToCharString (end, number);
  9090. appendInternal (t, (int) (end - t) - 1);
  9091. return *this;
  9092. }
  9093. String& String::operator<< (const short number) throw()
  9094. {
  9095. tchar buffer [64];
  9096. tchar* const end = buffer + 64;
  9097. const tchar* const t = intToCharString (end, (int) number);
  9098. appendInternal (t, (int) (end - t) - 1);
  9099. return *this;
  9100. }
  9101. String& String::operator<< (const double number) throw()
  9102. {
  9103. operator+= (String (number));
  9104. return *this;
  9105. }
  9106. String& String::operator<< (const float number) throw()
  9107. {
  9108. operator+= (String (number));
  9109. return *this;
  9110. }
  9111. String& String::operator<< (const char character) throw()
  9112. {
  9113. operator+= (character);
  9114. return *this;
  9115. }
  9116. String& String::operator<< (const juce_wchar character) throw()
  9117. {
  9118. operator+= (character);
  9119. return *this;
  9120. }
  9121. String& String::operator<< (const char* const t) throw()
  9122. {
  9123. #if JUCE_STRINGS_ARE_UNICODE
  9124. operator+= (String (t));
  9125. #else
  9126. operator+= (t);
  9127. #endif
  9128. return *this;
  9129. }
  9130. String& String::operator<< (const juce_wchar* const t) throw()
  9131. {
  9132. #if JUCE_STRINGS_ARE_UNICODE
  9133. operator+= (t);
  9134. #else
  9135. operator+= (String (t));
  9136. #endif
  9137. return *this;
  9138. }
  9139. String& String::operator<< (const String& t) throw()
  9140. {
  9141. operator+= (t);
  9142. return *this;
  9143. }
  9144. int String::indexOfChar (const tchar character) const throw()
  9145. {
  9146. const tchar* t = text->text;
  9147. for (;;)
  9148. {
  9149. if (*t == character)
  9150. return (int) (t - text->text);
  9151. if (*t++ == 0)
  9152. return -1;
  9153. }
  9154. }
  9155. int String::lastIndexOfChar (const tchar character) const throw()
  9156. {
  9157. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9158. if (text->text[i] == character)
  9159. return i;
  9160. return -1;
  9161. }
  9162. int String::indexOf (const tchar* const t) const throw()
  9163. {
  9164. const tchar* const r = CharacterFunctions::find (text->text, t);
  9165. return (r == 0) ? -1
  9166. : (int) (r - text->text);
  9167. }
  9168. int String::indexOfChar (const int startIndex,
  9169. const tchar character) const throw()
  9170. {
  9171. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  9172. return -1;
  9173. const tchar* t = text->text + jmax (0, startIndex);
  9174. for (;;)
  9175. {
  9176. if (*t == character)
  9177. return (int) (t - text->text);
  9178. if (*t++ == 0)
  9179. return -1;
  9180. }
  9181. }
  9182. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  9183. const int startIndex,
  9184. const bool ignoreCase) const throw()
  9185. {
  9186. if (charactersToLookFor == 0
  9187. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  9188. return -1;
  9189. const tchar* t = text->text + jmax (0, startIndex);
  9190. while (*t != 0)
  9191. {
  9192. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  9193. return (int) (t - text->text);
  9194. ++t;
  9195. }
  9196. return -1;
  9197. }
  9198. int String::indexOf (const int startIndex,
  9199. const tchar* const other) const throw()
  9200. {
  9201. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  9202. return -1;
  9203. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  9204. other);
  9205. return (found == 0) ? -1
  9206. : (int) (found - text->text);
  9207. }
  9208. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  9209. {
  9210. if (other != 0 && *other != 0)
  9211. {
  9212. const int len = CharacterFunctions::length (other);
  9213. const int end = CharacterFunctions::length (text->text) - len;
  9214. for (int i = 0; i <= end; ++i)
  9215. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9216. return i;
  9217. }
  9218. return -1;
  9219. }
  9220. int String::indexOfIgnoreCase (const int startIndex,
  9221. const tchar* const other) const throw()
  9222. {
  9223. if (other != 0 && *other != 0)
  9224. {
  9225. const int len = CharacterFunctions::length (other);
  9226. const int end = length() - len;
  9227. for (int i = jmax (0, startIndex); i <= end; ++i)
  9228. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9229. return i;
  9230. }
  9231. return -1;
  9232. }
  9233. int String::lastIndexOf (const tchar* const other) const throw()
  9234. {
  9235. if (other != 0 && *other != 0)
  9236. {
  9237. const int len = CharacterFunctions::length (other);
  9238. int i = length() - len;
  9239. if (i >= 0)
  9240. {
  9241. const tchar* n = text->text + i;
  9242. while (i >= 0)
  9243. {
  9244. if (CharacterFunctions::compare (n--, other, len) == 0)
  9245. return i;
  9246. --i;
  9247. }
  9248. }
  9249. }
  9250. return -1;
  9251. }
  9252. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  9253. {
  9254. if (other != 0 && *other != 0)
  9255. {
  9256. const int len = CharacterFunctions::length (other);
  9257. int i = length() - len;
  9258. if (i >= 0)
  9259. {
  9260. const tchar* n = text->text + i;
  9261. while (i >= 0)
  9262. {
  9263. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  9264. return i;
  9265. --i;
  9266. }
  9267. }
  9268. }
  9269. return -1;
  9270. }
  9271. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  9272. const bool ignoreCase) const throw()
  9273. {
  9274. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9275. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  9276. return i;
  9277. return -1;
  9278. }
  9279. bool String::contains (const tchar* const other) const throw()
  9280. {
  9281. return indexOf (other) >= 0;
  9282. }
  9283. bool String::containsChar (const tchar character) const throw()
  9284. {
  9285. return indexOfChar (character) >= 0;
  9286. }
  9287. bool String::containsIgnoreCase (const tchar* const t) const throw()
  9288. {
  9289. return indexOfIgnoreCase (t) >= 0;
  9290. }
  9291. int String::indexOfWholeWord (const tchar* const word) const throw()
  9292. {
  9293. if (word != 0 && *word != 0)
  9294. {
  9295. const int wordLen = CharacterFunctions::length (word);
  9296. const int end = length() - wordLen;
  9297. const tchar* t = text->text;
  9298. for (int i = 0; i <= end; ++i)
  9299. {
  9300. if (CharacterFunctions::compare (t, word, wordLen) == 0
  9301. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9302. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9303. {
  9304. return i;
  9305. }
  9306. ++t;
  9307. }
  9308. }
  9309. return -1;
  9310. }
  9311. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  9312. {
  9313. if (word != 0 && *word != 0)
  9314. {
  9315. const int wordLen = CharacterFunctions::length (word);
  9316. const int end = length() - wordLen;
  9317. const tchar* t = text->text;
  9318. for (int i = 0; i <= end; ++i)
  9319. {
  9320. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  9321. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9322. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9323. {
  9324. return i;
  9325. }
  9326. ++t;
  9327. }
  9328. }
  9329. return -1;
  9330. }
  9331. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  9332. {
  9333. return indexOfWholeWord (wordToLookFor) >= 0;
  9334. }
  9335. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  9336. {
  9337. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9338. }
  9339. static int indexOfMatch (const tchar* const wildcard,
  9340. const tchar* const test,
  9341. const bool ignoreCase) throw()
  9342. {
  9343. int start = 0;
  9344. while (test [start] != 0)
  9345. {
  9346. int i = 0;
  9347. for (;;)
  9348. {
  9349. const tchar wc = wildcard [i];
  9350. const tchar c = test [i + start];
  9351. if (wc == c
  9352. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9353. || (wc == T('?') && c != 0))
  9354. {
  9355. if (wc == 0)
  9356. return start;
  9357. ++i;
  9358. }
  9359. else
  9360. {
  9361. if (wc == T('*') && (wildcard [i + 1] == 0
  9362. || indexOfMatch (wildcard + i + 1,
  9363. test + start + i,
  9364. ignoreCase) >= 0))
  9365. {
  9366. return start;
  9367. }
  9368. break;
  9369. }
  9370. }
  9371. ++start;
  9372. }
  9373. return -1;
  9374. }
  9375. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  9376. {
  9377. int i = 0;
  9378. for (;;)
  9379. {
  9380. const tchar wc = wildcard [i];
  9381. const tchar c = text->text [i];
  9382. if (wc == c
  9383. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9384. || (wc == T('?') && c != 0))
  9385. {
  9386. if (wc == 0)
  9387. return true;
  9388. ++i;
  9389. }
  9390. else
  9391. {
  9392. return wc == T('*') && (wildcard [i + 1] == 0
  9393. || indexOfMatch (wildcard + i + 1,
  9394. text->text + i,
  9395. ignoreCase) >= 0);
  9396. }
  9397. }
  9398. }
  9399. void String::printf (const tchar* const pf, ...) throw()
  9400. {
  9401. va_list list;
  9402. va_start (list, pf);
  9403. vprintf (pf, list);
  9404. }
  9405. const String String::formatted (const tchar* const pf, ...) throw()
  9406. {
  9407. va_list list;
  9408. va_start (list, pf);
  9409. String result;
  9410. result.vprintf (pf, list);
  9411. return result;
  9412. }
  9413. void String::vprintf (const tchar* const pf, va_list& args) throw()
  9414. {
  9415. tchar stackBuf [256];
  9416. unsigned int bufSize = 256;
  9417. tchar* buf = stackBuf;
  9418. deleteInternal();
  9419. do
  9420. {
  9421. #if JUCE_LINUX && JUCE_64BIT
  9422. va_list tempArgs;
  9423. va_copy (tempArgs, args);
  9424. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  9425. va_end (tempArgs);
  9426. #else
  9427. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  9428. #endif
  9429. if (num > 0)
  9430. {
  9431. createInternal (num);
  9432. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  9433. break;
  9434. }
  9435. else if (num == 0)
  9436. {
  9437. text = &emptyString;
  9438. emptyString.refCount = safeEmptyStringRefCount;
  9439. break;
  9440. }
  9441. if (buf != stackBuf)
  9442. juce_free (buf);
  9443. bufSize += 256;
  9444. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  9445. }
  9446. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  9447. // returns -1 because of an error rather than because it needs more space.
  9448. if (buf != stackBuf)
  9449. juce_free (buf);
  9450. }
  9451. const String String::repeatedString (const tchar* const stringToRepeat,
  9452. int numberOfTimesToRepeat) throw()
  9453. {
  9454. const int len = CharacterFunctions::length (stringToRepeat);
  9455. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  9456. tchar* n = result.text->text;
  9457. n[0] = 0;
  9458. while (--numberOfTimesToRepeat >= 0)
  9459. {
  9460. CharacterFunctions::append (n, stringToRepeat);
  9461. n += len;
  9462. }
  9463. return result;
  9464. }
  9465. const String String::replaceSection (int index,
  9466. int numCharsToReplace,
  9467. const tchar* const stringToInsert) const throw()
  9468. {
  9469. if (index < 0)
  9470. {
  9471. // a negative index to replace from?
  9472. jassertfalse
  9473. index = 0;
  9474. }
  9475. if (numCharsToReplace < 0)
  9476. {
  9477. // replacing a negative number of characters?
  9478. numCharsToReplace = 0;
  9479. jassertfalse;
  9480. }
  9481. const int len = length();
  9482. if (index + numCharsToReplace > len)
  9483. {
  9484. if (index > len)
  9485. {
  9486. // replacing beyond the end of the string?
  9487. index = len;
  9488. jassertfalse
  9489. }
  9490. numCharsToReplace = len - index;
  9491. }
  9492. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  9493. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9494. if (newTotalLen <= 0)
  9495. return String::empty;
  9496. String result (newTotalLen, (int) 0);
  9497. memcpy (result.text->text,
  9498. text->text,
  9499. index * sizeof (tchar));
  9500. if (newStringLen > 0)
  9501. memcpy (result.text->text + index,
  9502. stringToInsert,
  9503. newStringLen * sizeof (tchar));
  9504. const int endStringLen = newTotalLen - (index + newStringLen);
  9505. if (endStringLen > 0)
  9506. memcpy (result.text->text + (index + newStringLen),
  9507. text->text + (index + numCharsToReplace),
  9508. endStringLen * sizeof (tchar));
  9509. result.text->text [newTotalLen] = 0;
  9510. return result;
  9511. }
  9512. const String String::replace (const tchar* const stringToReplace,
  9513. const tchar* const stringToInsert,
  9514. const bool ignoreCase) const throw()
  9515. {
  9516. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  9517. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  9518. int i = 0;
  9519. String result (*this);
  9520. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9521. : result.indexOf (i, stringToReplace))) >= 0)
  9522. {
  9523. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9524. i += stringToInsertLen;
  9525. }
  9526. return result;
  9527. }
  9528. const String String::replaceCharacter (const tchar charToReplace,
  9529. const tchar charToInsert) const throw()
  9530. {
  9531. const int index = indexOfChar (charToReplace);
  9532. if (index < 0)
  9533. return *this;
  9534. String result (*this);
  9535. result.dupeInternalIfMultiplyReferenced();
  9536. tchar* t = result.text->text + index;
  9537. while (*t != 0)
  9538. {
  9539. if (*t == charToReplace)
  9540. *t = charToInsert;
  9541. ++t;
  9542. }
  9543. return result;
  9544. }
  9545. const String String::replaceCharacters (const String& charactersToReplace,
  9546. const tchar* const charactersToInsertInstead) const throw()
  9547. {
  9548. String result (*this);
  9549. result.dupeInternalIfMultiplyReferenced();
  9550. tchar* t = result.text->text;
  9551. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  9552. // the two strings passed in are supposed to be the same length!
  9553. jassert (len2 == charactersToReplace.length());
  9554. while (*t != 0)
  9555. {
  9556. const int index = charactersToReplace.indexOfChar (*t);
  9557. if (((unsigned int) index) < (unsigned int) len2)
  9558. *t = charactersToInsertInstead [index];
  9559. ++t;
  9560. }
  9561. return result;
  9562. }
  9563. bool String::startsWith (const tchar* const other) const throw()
  9564. {
  9565. return other != 0
  9566. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  9567. }
  9568. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  9569. {
  9570. return other != 0
  9571. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  9572. }
  9573. bool String::startsWithChar (const tchar character) const throw()
  9574. {
  9575. jassert (character != 0); // strings can't contain a null character!
  9576. return text->text[0] == character;
  9577. }
  9578. bool String::endsWithChar (const tchar character) const throw()
  9579. {
  9580. jassert (character != 0); // strings can't contain a null character!
  9581. return text->text[0] != 0
  9582. && text->text [length() - 1] == character;
  9583. }
  9584. bool String::endsWith (const tchar* const other) const throw()
  9585. {
  9586. if (other == 0)
  9587. return false;
  9588. const int thisLen = length();
  9589. const int otherLen = CharacterFunctions::length (other);
  9590. return thisLen >= otherLen
  9591. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  9592. }
  9593. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  9594. {
  9595. if (other == 0)
  9596. return false;
  9597. const int thisLen = length();
  9598. const int otherLen = CharacterFunctions::length (other);
  9599. return thisLen >= otherLen
  9600. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  9601. }
  9602. const String String::toUpperCase() const throw()
  9603. {
  9604. String result (*this);
  9605. result.dupeInternalIfMultiplyReferenced();
  9606. CharacterFunctions::toUpperCase (result.text->text);
  9607. return result;
  9608. }
  9609. const String String::toLowerCase() const throw()
  9610. {
  9611. String result (*this);
  9612. result.dupeInternalIfMultiplyReferenced();
  9613. CharacterFunctions::toLowerCase (result.text->text);
  9614. return result;
  9615. }
  9616. tchar& String::operator[] (const int index) throw()
  9617. {
  9618. jassert (((unsigned int) index) <= (unsigned int) length());
  9619. dupeInternalIfMultiplyReferenced();
  9620. return text->text [index];
  9621. }
  9622. tchar String::getLastCharacter() const throw()
  9623. {
  9624. return (isEmpty()) ? ((tchar) 0)
  9625. : text->text [CharacterFunctions::length (text->text) - 1];
  9626. }
  9627. const String String::substring (int start, int end) const throw()
  9628. {
  9629. if (start < 0)
  9630. start = 0;
  9631. else if (end <= start)
  9632. return empty;
  9633. int len = 0;
  9634. const tchar* const t = text->text;
  9635. while (len <= end && t [len] != 0)
  9636. ++len;
  9637. if (end >= len)
  9638. {
  9639. if (start == 0)
  9640. return *this;
  9641. end = len;
  9642. }
  9643. return String (text->text + start,
  9644. end - start);
  9645. }
  9646. const String String::substring (const int start) const throw()
  9647. {
  9648. if (start <= 0)
  9649. return *this;
  9650. const int len = CharacterFunctions::length (text->text);
  9651. if (start >= len)
  9652. return empty;
  9653. else
  9654. return String (text->text + start,
  9655. len - start);
  9656. }
  9657. const String String::dropLastCharacters (const int numberToDrop) const throw()
  9658. {
  9659. return String (text->text,
  9660. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  9661. }
  9662. const String String::getLastCharacters (const int numCharacters) const throw()
  9663. {
  9664. return String (text->text + jmax (0, CharacterFunctions::length (text->text) - jmax (0, numCharacters)));
  9665. }
  9666. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  9667. const bool includeSubString,
  9668. const bool ignoreCase) const throw()
  9669. {
  9670. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9671. : indexOf (sub);
  9672. if (i < 0)
  9673. return empty;
  9674. else
  9675. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9676. }
  9677. const String String::fromLastOccurrenceOf (const tchar* const sub,
  9678. const bool includeSubString,
  9679. const bool ignoreCase) const throw()
  9680. {
  9681. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9682. : lastIndexOf (sub);
  9683. if (i < 0)
  9684. return *this;
  9685. else
  9686. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9687. }
  9688. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  9689. const bool includeSubString,
  9690. const bool ignoreCase) const throw()
  9691. {
  9692. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9693. : indexOf (sub);
  9694. if (i < 0)
  9695. return *this;
  9696. else
  9697. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9698. }
  9699. const String String::upToLastOccurrenceOf (const tchar* const sub,
  9700. const bool includeSubString,
  9701. const bool ignoreCase) const throw()
  9702. {
  9703. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9704. : lastIndexOf (sub);
  9705. if (i < 0)
  9706. return *this;
  9707. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9708. }
  9709. bool String::isQuotedString() const throw()
  9710. {
  9711. const String trimmed (trimStart());
  9712. return trimmed[0] == T('"')
  9713. || trimmed[0] == T('\'');
  9714. }
  9715. const String String::unquoted() const throw()
  9716. {
  9717. String s (*this);
  9718. if (s[0] == T('"') || s[0] == T('\''))
  9719. s = s.substring (1);
  9720. const int lastCharIndex = s.length() - 1;
  9721. if (lastCharIndex >= 0
  9722. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  9723. s [lastCharIndex] = 0;
  9724. return s;
  9725. }
  9726. const String String::quoted (const tchar quoteCharacter) const throw()
  9727. {
  9728. if (isEmpty())
  9729. return charToString (quoteCharacter) + quoteCharacter;
  9730. String t (*this);
  9731. if (! t.startsWithChar (quoteCharacter))
  9732. t = charToString (quoteCharacter) + t;
  9733. if (! t.endsWithChar (quoteCharacter))
  9734. t += quoteCharacter;
  9735. return t;
  9736. }
  9737. const String String::trim() const throw()
  9738. {
  9739. if (isEmpty())
  9740. return empty;
  9741. int start = 0;
  9742. while (CharacterFunctions::isWhitespace (text->text [start]))
  9743. ++start;
  9744. const int len = CharacterFunctions::length (text->text);
  9745. int end = len - 1;
  9746. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  9747. --end;
  9748. ++end;
  9749. if (end <= start)
  9750. return empty;
  9751. else if (start > 0 || end < len)
  9752. return String (text->text + start, end - start);
  9753. else
  9754. return *this;
  9755. }
  9756. const String String::trimStart() const throw()
  9757. {
  9758. if (isEmpty())
  9759. return empty;
  9760. const tchar* t = text->text;
  9761. while (CharacterFunctions::isWhitespace (*t))
  9762. ++t;
  9763. if (t == text->text)
  9764. return *this;
  9765. else
  9766. return String (t);
  9767. }
  9768. const String String::trimEnd() const throw()
  9769. {
  9770. if (isEmpty())
  9771. return empty;
  9772. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  9773. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  9774. --endT;
  9775. return String (text->text, (int) (++endT - text->text));
  9776. }
  9777. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  9778. {
  9779. jassert (charactersToRetain != 0);
  9780. if (isEmpty())
  9781. return empty;
  9782. String result (text->allocatedNumChars, (int) 0);
  9783. tchar* dst = result.text->text;
  9784. const tchar* src = text->text;
  9785. while (*src != 0)
  9786. {
  9787. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  9788. *dst++ = *src;
  9789. ++src;
  9790. }
  9791. *dst = 0;
  9792. return result;
  9793. }
  9794. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  9795. {
  9796. jassert (charactersToRemove != 0);
  9797. if (isEmpty())
  9798. return empty;
  9799. String result (text->allocatedNumChars, (int) 0);
  9800. tchar* dst = result.text->text;
  9801. const tchar* src = text->text;
  9802. while (*src != 0)
  9803. {
  9804. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  9805. *dst++ = *src;
  9806. ++src;
  9807. }
  9808. *dst = 0;
  9809. return result;
  9810. }
  9811. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  9812. {
  9813. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  9814. }
  9815. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  9816. {
  9817. jassert (charactersToStopAt != 0);
  9818. const tchar* const t = text->text;
  9819. int i = 0;
  9820. while (t[i] != 0)
  9821. {
  9822. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  9823. return String (text->text, i);
  9824. ++i;
  9825. }
  9826. return empty;
  9827. }
  9828. bool String::containsOnly (const tchar* const chars) const throw()
  9829. {
  9830. jassert (chars != 0);
  9831. const tchar* t = text->text;
  9832. while (*t != 0)
  9833. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  9834. return false;
  9835. return true;
  9836. }
  9837. bool String::containsAnyOf (const tchar* const chars) const throw()
  9838. {
  9839. jassert (chars != 0);
  9840. const tchar* t = text->text;
  9841. while (*t != 0)
  9842. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  9843. return true;
  9844. return false;
  9845. }
  9846. bool String::containsNonWhitespaceChars() const throw()
  9847. {
  9848. const tchar* t = text->text;
  9849. while (*t != 0)
  9850. if (! CharacterFunctions::isWhitespace (*t++))
  9851. return true;
  9852. return false;
  9853. }
  9854. int String::getIntValue() const throw()
  9855. {
  9856. return CharacterFunctions::getIntValue (text->text);
  9857. }
  9858. int String::getTrailingIntValue() const throw()
  9859. {
  9860. int n = 0;
  9861. int mult = 1;
  9862. const tchar* t = text->text + length();
  9863. while (--t >= text->text)
  9864. {
  9865. const tchar c = *t;
  9866. if (! CharacterFunctions::isDigit (c))
  9867. {
  9868. if (c == T('-'))
  9869. n = -n;
  9870. break;
  9871. }
  9872. n += mult * (c - T('0'));
  9873. mult *= 10;
  9874. }
  9875. return n;
  9876. }
  9877. int64 String::getLargeIntValue() const throw()
  9878. {
  9879. return CharacterFunctions::getInt64Value (text->text);
  9880. }
  9881. float String::getFloatValue() const throw()
  9882. {
  9883. return (float) CharacterFunctions::getDoubleValue (text->text);
  9884. }
  9885. double String::getDoubleValue() const throw()
  9886. {
  9887. return CharacterFunctions::getDoubleValue (text->text);
  9888. }
  9889. static const tchar* const hexDigits = T("0123456789abcdef");
  9890. const String String::toHexString (const int number) throw()
  9891. {
  9892. tchar buffer[32];
  9893. tchar* const end = buffer + 32;
  9894. tchar* t = end;
  9895. *--t = 0;
  9896. unsigned int v = (unsigned int) number;
  9897. do
  9898. {
  9899. *--t = hexDigits [v & 15];
  9900. v >>= 4;
  9901. } while (v != 0);
  9902. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9903. }
  9904. const String String::toHexString (const int64 number) throw()
  9905. {
  9906. tchar buffer[32];
  9907. tchar* const end = buffer + 32;
  9908. tchar* t = end;
  9909. *--t = 0;
  9910. uint64 v = (uint64) number;
  9911. do
  9912. {
  9913. *--t = hexDigits [(int) (v & 15)];
  9914. v >>= 4;
  9915. } while (v != 0);
  9916. return String (t, (int) (((char*) end) - (char*) t));
  9917. }
  9918. const String String::toHexString (const short number) throw()
  9919. {
  9920. return toHexString ((int) (unsigned short) number);
  9921. }
  9922. const String String::toHexString (const unsigned char* data,
  9923. const int size,
  9924. const int groupSize) throw()
  9925. {
  9926. if (size <= 0)
  9927. return empty;
  9928. int numChars = (size * 2) + 2;
  9929. if (groupSize > 0)
  9930. numChars += size / groupSize;
  9931. String s (numChars, (int) 0);
  9932. tchar* d = s.text->text;
  9933. for (int i = 0; i < size; ++i)
  9934. {
  9935. *d++ = hexDigits [(*data) >> 4];
  9936. *d++ = hexDigits [(*data) & 0xf];
  9937. ++data;
  9938. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9939. *d++ = T(' ');
  9940. }
  9941. *d = 0;
  9942. return s;
  9943. }
  9944. int String::getHexValue32() const throw()
  9945. {
  9946. int result = 0;
  9947. const tchar* c = text->text;
  9948. for (;;)
  9949. {
  9950. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9951. if (hexValue >= 0)
  9952. result = (result << 4) | hexValue;
  9953. else if (*c == 0)
  9954. break;
  9955. ++c;
  9956. }
  9957. return result;
  9958. }
  9959. int64 String::getHexValue64() const throw()
  9960. {
  9961. int64 result = 0;
  9962. const tchar* c = text->text;
  9963. for (;;)
  9964. {
  9965. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9966. if (hexValue >= 0)
  9967. result = (result << 4) | hexValue;
  9968. else if (*c == 0)
  9969. break;
  9970. ++c;
  9971. }
  9972. return result;
  9973. }
  9974. const String String::createStringFromData (const void* const data_,
  9975. const int size) throw()
  9976. {
  9977. const char* const data = (const char*) data_;
  9978. if (size <= 0 || data == 0)
  9979. {
  9980. return empty;
  9981. }
  9982. else if (size < 2)
  9983. {
  9984. return charToString (data[0]);
  9985. }
  9986. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9987. || (data[0] == (char)-1 && data[1] == (char)-2))
  9988. {
  9989. // assume it's 16-bit unicode
  9990. const bool bigEndian = (data[0] == (char)-2);
  9991. const int numChars = size / 2 - 1;
  9992. String result;
  9993. result.preallocateStorage (numChars + 2);
  9994. const uint16* const src = (const uint16*) (data + 2);
  9995. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  9996. if (bigEndian)
  9997. {
  9998. for (int i = 0; i < numChars; ++i)
  9999. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  10000. }
  10001. else
  10002. {
  10003. for (int i = 0; i < numChars; ++i)
  10004. dst[i] = (tchar) swapIfBigEndian (src[i]);
  10005. }
  10006. dst [numChars] = 0;
  10007. return result;
  10008. }
  10009. else
  10010. {
  10011. return String::fromUTF8 ((const uint8*) data, size);
  10012. }
  10013. }
  10014. const char* String::toUTF8() const throw()
  10015. {
  10016. if (isEmpty())
  10017. {
  10018. return (const char*) emptyCharString;
  10019. }
  10020. else
  10021. {
  10022. String* const mutableThis = const_cast <String*> (this);
  10023. mutableThis->dupeInternalIfMultiplyReferenced();
  10024. const int currentLen = CharacterFunctions::length (text->text) + 1;
  10025. const int utf8BytesNeeded = copyToUTF8 (0);
  10026. mutableThis->text = (InternalRefCountedStringHolder*)
  10027. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  10028. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  10029. char* const otherCopy = (char*) (text->text + currentLen);
  10030. copyToUTF8 ((uint8*) otherCopy);
  10031. return otherCopy;
  10032. }
  10033. }
  10034. int String::copyToUTF8 (uint8* const buffer, const int maxBufferSizeBytes) const throw()
  10035. {
  10036. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10037. #if JUCE_STRINGS_ARE_UNICODE
  10038. int num = 0, index = 0;
  10039. for (;;)
  10040. {
  10041. const uint32 c = (uint32) text->text [index++];
  10042. if (c >= 0x80)
  10043. {
  10044. int numExtraBytes = 1;
  10045. if (c >= 0x800)
  10046. {
  10047. ++numExtraBytes;
  10048. if (c >= 0x10000)
  10049. {
  10050. ++numExtraBytes;
  10051. if (c >= 0x200000)
  10052. {
  10053. ++numExtraBytes;
  10054. if (c >= 0x4000000)
  10055. ++numExtraBytes;
  10056. }
  10057. }
  10058. }
  10059. if (buffer != 0)
  10060. {
  10061. if (num + numExtraBytes >= maxBufferSizeBytes)
  10062. {
  10063. buffer [num++] = 0;
  10064. break;
  10065. }
  10066. else
  10067. {
  10068. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10069. while (--numExtraBytes >= 0)
  10070. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10071. }
  10072. }
  10073. else
  10074. {
  10075. num += numExtraBytes + 1;
  10076. }
  10077. }
  10078. else
  10079. {
  10080. if (buffer != 0)
  10081. {
  10082. if (num + 1 >= maxBufferSizeBytes)
  10083. {
  10084. buffer [num++] = 0;
  10085. break;
  10086. }
  10087. buffer [num] = (uint8) c;
  10088. }
  10089. ++num;
  10090. }
  10091. if (c == 0)
  10092. break;
  10093. }
  10094. return num;
  10095. #else
  10096. const int numBytes = jmin (maxBufferSizeBytes, length() + 1);
  10097. if (buffer != 0)
  10098. copyToBuffer ((char*) buffer, maxBufferSizeBytes);
  10099. return numBytes;
  10100. #endif
  10101. }
  10102. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  10103. {
  10104. if (buffer == 0)
  10105. return empty;
  10106. if (bufferSizeBytes < 0)
  10107. bufferSizeBytes = INT_MAX;
  10108. int numBytes;
  10109. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  10110. if (buffer [numBytes] == 0)
  10111. break;
  10112. String result (numBytes + 1, 0);
  10113. tchar* dest = result.text->text;
  10114. int i = 0;
  10115. while (i < numBytes)
  10116. {
  10117. const uint8 c = buffer [i++];
  10118. if ((c & 0x80) != 0)
  10119. {
  10120. int mask = 0x7f;
  10121. int bit = 0x40;
  10122. int numExtraValues = 0;
  10123. while (bit != 0 && (c & bit) != 0)
  10124. {
  10125. bit >>= 1;
  10126. mask >>= 1;
  10127. ++numExtraValues;
  10128. }
  10129. int n = (c & mask);
  10130. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  10131. {
  10132. const uint8 c = buffer[i];
  10133. if ((c & 0xc0) != 0x80)
  10134. break;
  10135. n <<= 6;
  10136. n |= (c & 0x3f);
  10137. ++i;
  10138. }
  10139. *dest++ = (tchar) n;
  10140. }
  10141. else
  10142. {
  10143. *dest++ = (tchar) c;
  10144. }
  10145. }
  10146. *dest = 0;
  10147. return result;
  10148. }
  10149. END_JUCE_NAMESPACE
  10150. /********* End of inlined file: juce_String.cpp *********/
  10151. /********* Start of inlined file: juce_StringArray.cpp *********/
  10152. BEGIN_JUCE_NAMESPACE
  10153. StringArray::StringArray() throw()
  10154. {
  10155. }
  10156. StringArray::StringArray (const StringArray& other) throw()
  10157. {
  10158. addArray (other);
  10159. }
  10160. StringArray::StringArray (const juce_wchar** const strings,
  10161. const int numberOfStrings) throw()
  10162. {
  10163. for (int i = 0; i < numberOfStrings; ++i)
  10164. add (strings [i]);
  10165. }
  10166. StringArray::StringArray (const char** const strings,
  10167. const int numberOfStrings) throw()
  10168. {
  10169. for (int i = 0; i < numberOfStrings; ++i)
  10170. add (strings [i]);
  10171. }
  10172. StringArray::StringArray (const juce_wchar** const strings) throw()
  10173. {
  10174. int i = 0;
  10175. while (strings[i] != 0)
  10176. add (strings [i++]);
  10177. }
  10178. StringArray::StringArray (const char** const strings) throw()
  10179. {
  10180. int i = 0;
  10181. while (strings[i] != 0)
  10182. add (strings [i++]);
  10183. }
  10184. const StringArray& StringArray::operator= (const StringArray& other) throw()
  10185. {
  10186. if (this != &other)
  10187. {
  10188. clear();
  10189. addArray (other);
  10190. }
  10191. return *this;
  10192. }
  10193. StringArray::~StringArray() throw()
  10194. {
  10195. clear();
  10196. }
  10197. bool StringArray::operator== (const StringArray& other) const throw()
  10198. {
  10199. if (other.size() != size())
  10200. return false;
  10201. for (int i = size(); --i >= 0;)
  10202. {
  10203. if (*(String*) other.strings.getUnchecked(i)
  10204. != *(String*) strings.getUnchecked(i))
  10205. {
  10206. return false;
  10207. }
  10208. }
  10209. return true;
  10210. }
  10211. bool StringArray::operator!= (const StringArray& other) const throw()
  10212. {
  10213. return ! operator== (other);
  10214. }
  10215. void StringArray::clear() throw()
  10216. {
  10217. for (int i = size(); --i >= 0;)
  10218. {
  10219. String* const s = (String*) strings.getUnchecked(i);
  10220. delete s;
  10221. }
  10222. strings.clear();
  10223. }
  10224. const String& StringArray::operator[] (const int index) const throw()
  10225. {
  10226. if (((unsigned int) index) < (unsigned int) strings.size())
  10227. return *(const String*) (strings.getUnchecked (index));
  10228. return String::empty;
  10229. }
  10230. void StringArray::add (const String& newString) throw()
  10231. {
  10232. strings.add (new String (newString));
  10233. }
  10234. void StringArray::insert (const int index,
  10235. const String& newString) throw()
  10236. {
  10237. strings.insert (index, new String (newString));
  10238. }
  10239. void StringArray::addIfNotAlreadyThere (const String& newString,
  10240. const bool ignoreCase) throw()
  10241. {
  10242. if (! contains (newString, ignoreCase))
  10243. add (newString);
  10244. }
  10245. void StringArray::addArray (const StringArray& otherArray,
  10246. int startIndex,
  10247. int numElementsToAdd) throw()
  10248. {
  10249. if (startIndex < 0)
  10250. {
  10251. jassertfalse
  10252. startIndex = 0;
  10253. }
  10254. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10255. numElementsToAdd = otherArray.size() - startIndex;
  10256. while (--numElementsToAdd >= 0)
  10257. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  10258. }
  10259. void StringArray::set (const int index,
  10260. const String& newString) throw()
  10261. {
  10262. String* const s = (String*) strings [index];
  10263. if (s != 0)
  10264. {
  10265. *s = newString;
  10266. }
  10267. else if (index >= 0)
  10268. {
  10269. add (newString);
  10270. }
  10271. }
  10272. bool StringArray::contains (const String& stringToLookFor,
  10273. const bool ignoreCase) const throw()
  10274. {
  10275. if (ignoreCase)
  10276. {
  10277. for (int i = size(); --i >= 0;)
  10278. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  10279. return true;
  10280. }
  10281. else
  10282. {
  10283. for (int i = size(); --i >= 0;)
  10284. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  10285. return true;
  10286. }
  10287. return false;
  10288. }
  10289. int StringArray::indexOf (const String& stringToLookFor,
  10290. const bool ignoreCase,
  10291. int i) const throw()
  10292. {
  10293. if (i < 0)
  10294. i = 0;
  10295. const int numElements = size();
  10296. if (ignoreCase)
  10297. {
  10298. while (i < numElements)
  10299. {
  10300. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10301. return i;
  10302. ++i;
  10303. }
  10304. }
  10305. else
  10306. {
  10307. while (i < numElements)
  10308. {
  10309. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  10310. return i;
  10311. ++i;
  10312. }
  10313. }
  10314. return -1;
  10315. }
  10316. void StringArray::remove (const int index) throw()
  10317. {
  10318. String* const s = (String*) strings [index];
  10319. if (s != 0)
  10320. {
  10321. strings.remove (index);
  10322. delete s;
  10323. }
  10324. }
  10325. void StringArray::removeString (const String& stringToRemove,
  10326. const bool ignoreCase) throw()
  10327. {
  10328. if (ignoreCase)
  10329. {
  10330. for (int i = size(); --i >= 0;)
  10331. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10332. remove (i);
  10333. }
  10334. else
  10335. {
  10336. for (int i = size(); --i >= 0;)
  10337. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  10338. remove (i);
  10339. }
  10340. }
  10341. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  10342. {
  10343. if (removeWhitespaceStrings)
  10344. {
  10345. for (int i = size(); --i >= 0;)
  10346. if (! ((const String*) strings.getUnchecked(i))->containsNonWhitespaceChars())
  10347. remove (i);
  10348. }
  10349. else
  10350. {
  10351. for (int i = size(); --i >= 0;)
  10352. if (((const String*) strings.getUnchecked(i))->isEmpty())
  10353. remove (i);
  10354. }
  10355. }
  10356. void StringArray::trim() throw()
  10357. {
  10358. for (int i = size(); --i >= 0;)
  10359. {
  10360. String& s = *(String*) strings.getUnchecked(i);
  10361. s = s.trim();
  10362. }
  10363. }
  10364. class InternalStringArrayComparator
  10365. {
  10366. public:
  10367. static int compareElements (void* const first, void* const second) throw()
  10368. {
  10369. return ((const String*) first)->compare (*(const String*) second);
  10370. }
  10371. };
  10372. class InsensitiveInternalStringArrayComparator
  10373. {
  10374. public:
  10375. static int compareElements (void* const first, void* const second) throw()
  10376. {
  10377. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  10378. }
  10379. };
  10380. void StringArray::sort (const bool ignoreCase) throw()
  10381. {
  10382. if (ignoreCase)
  10383. {
  10384. InsensitiveInternalStringArrayComparator comp;
  10385. strings.sort (comp);
  10386. }
  10387. else
  10388. {
  10389. InternalStringArrayComparator comp;
  10390. strings.sort (comp);
  10391. }
  10392. }
  10393. void StringArray::move (const int currentIndex, int newIndex) throw()
  10394. {
  10395. strings.move (currentIndex, newIndex);
  10396. }
  10397. const String StringArray::joinIntoString (const String& separator,
  10398. int start,
  10399. int numberToJoin) const throw()
  10400. {
  10401. const int last = (numberToJoin < 0) ? size()
  10402. : jmin (size(), start + numberToJoin);
  10403. if (start < 0)
  10404. start = 0;
  10405. if (start >= last)
  10406. return String::empty;
  10407. if (start == last - 1)
  10408. return *(const String*) strings.getUnchecked (start);
  10409. const int separatorLen = separator.length();
  10410. int charsNeeded = separatorLen * (last - start - 1);
  10411. for (int i = start; i < last; ++i)
  10412. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  10413. String result;
  10414. result.preallocateStorage (charsNeeded);
  10415. tchar* dest = (tchar*) (const tchar*) result;
  10416. while (start < last)
  10417. {
  10418. const String& s = *(const String*) strings.getUnchecked (start);
  10419. const int len = s.length();
  10420. if (len > 0)
  10421. {
  10422. s.copyToBuffer (dest, len);
  10423. dest += len;
  10424. }
  10425. if (++start < last && separatorLen > 0)
  10426. {
  10427. separator.copyToBuffer (dest, separatorLen);
  10428. dest += separatorLen;
  10429. }
  10430. }
  10431. *dest = 0;
  10432. return result;
  10433. }
  10434. int StringArray::addTokens (const tchar* const text,
  10435. const bool preserveQuotedStrings) throw()
  10436. {
  10437. return addTokens (text,
  10438. T(" \n\r\t"),
  10439. preserveQuotedStrings ? T("\"") : 0);
  10440. }
  10441. int StringArray::addTokens (const tchar* const text,
  10442. const tchar* breakCharacters,
  10443. const tchar* quoteCharacters) throw()
  10444. {
  10445. int num = 0;
  10446. if (text != 0 && *text != 0)
  10447. {
  10448. if (breakCharacters == 0)
  10449. breakCharacters = T("");
  10450. if (quoteCharacters == 0)
  10451. quoteCharacters = T("");
  10452. bool insideQuotes = false;
  10453. tchar currentQuoteChar = 0;
  10454. int i = 0;
  10455. int tokenStart = 0;
  10456. for (;;)
  10457. {
  10458. const tchar c = text[i];
  10459. bool isBreak = (c == 0);
  10460. if (! (insideQuotes || isBreak))
  10461. {
  10462. const tchar* b = breakCharacters;
  10463. while (*b != 0)
  10464. {
  10465. if (*b++ == c)
  10466. {
  10467. isBreak = true;
  10468. break;
  10469. }
  10470. }
  10471. }
  10472. if (! isBreak)
  10473. {
  10474. bool isQuote = false;
  10475. const tchar* q = quoteCharacters;
  10476. while (*q != 0)
  10477. {
  10478. if (*q++ == c)
  10479. {
  10480. isQuote = true;
  10481. break;
  10482. }
  10483. }
  10484. if (isQuote)
  10485. {
  10486. if (insideQuotes)
  10487. {
  10488. // only break out of quotes-mode if we find a matching quote to the
  10489. // one that we opened with..
  10490. if (currentQuoteChar == c)
  10491. insideQuotes = false;
  10492. }
  10493. else
  10494. {
  10495. insideQuotes = true;
  10496. currentQuoteChar = c;
  10497. }
  10498. }
  10499. }
  10500. else
  10501. {
  10502. add (String (text + tokenStart, i - tokenStart));
  10503. ++num;
  10504. tokenStart = i + 1;
  10505. }
  10506. if (c == 0)
  10507. break;
  10508. ++i;
  10509. }
  10510. }
  10511. return num;
  10512. }
  10513. int StringArray::addLines (const tchar* text) throw()
  10514. {
  10515. int numLines = 0;
  10516. if (text != 0)
  10517. {
  10518. while (*text != 0)
  10519. {
  10520. const tchar* const startOfLine = text;
  10521. while (*text != 0)
  10522. {
  10523. if (*text == T('\r'))
  10524. {
  10525. ++text;
  10526. if (*text == T('\n'))
  10527. ++text;
  10528. break;
  10529. }
  10530. if (*text == T('\n'))
  10531. {
  10532. ++text;
  10533. break;
  10534. }
  10535. ++text;
  10536. }
  10537. const tchar* endOfLine = text;
  10538. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10539. --endOfLine;
  10540. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10541. --endOfLine;
  10542. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10543. ++numLines;
  10544. }
  10545. }
  10546. return numLines;
  10547. }
  10548. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  10549. {
  10550. for (int i = 0; i < size() - 1; ++i)
  10551. {
  10552. const String& s = *(String*) strings.getUnchecked(i);
  10553. int nextIndex = i + 1;
  10554. for (;;)
  10555. {
  10556. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10557. if (nextIndex < 0)
  10558. break;
  10559. remove (nextIndex);
  10560. }
  10561. }
  10562. }
  10563. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10564. const bool appendNumberToFirstInstance,
  10565. const tchar* const preNumberString,
  10566. const tchar* const postNumberString) throw()
  10567. {
  10568. for (int i = 0; i < size() - 1; ++i)
  10569. {
  10570. String& s = *(String*) strings.getUnchecked(i);
  10571. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10572. if (nextIndex >= 0)
  10573. {
  10574. const String original (s);
  10575. int number = 0;
  10576. if (appendNumberToFirstInstance)
  10577. s = original + preNumberString + String (++number) + postNumberString;
  10578. else
  10579. ++number;
  10580. while (nextIndex >= 0)
  10581. {
  10582. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10583. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10584. }
  10585. }
  10586. }
  10587. }
  10588. void StringArray::minimiseStorageOverheads() throw()
  10589. {
  10590. strings.minimiseStorageOverheads();
  10591. }
  10592. END_JUCE_NAMESPACE
  10593. /********* End of inlined file: juce_StringArray.cpp *********/
  10594. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  10595. BEGIN_JUCE_NAMESPACE
  10596. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  10597. : ignoreCase (ignoreCase_)
  10598. {
  10599. }
  10600. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  10601. : keys (other.keys),
  10602. values (other.values),
  10603. ignoreCase (other.ignoreCase)
  10604. {
  10605. }
  10606. StringPairArray::~StringPairArray() throw()
  10607. {
  10608. }
  10609. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  10610. {
  10611. keys = other.keys;
  10612. values = other.values;
  10613. return *this;
  10614. }
  10615. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  10616. {
  10617. for (int i = keys.size(); --i >= 0;)
  10618. if (other [keys[i]] != values[i])
  10619. return false;
  10620. return true;
  10621. }
  10622. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  10623. {
  10624. return ! operator== (other);
  10625. }
  10626. const String& StringPairArray::operator[] (const String& key) const throw()
  10627. {
  10628. return values [keys.indexOf (key, ignoreCase)];
  10629. }
  10630. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10631. {
  10632. const int i = keys.indexOf (key, ignoreCase);
  10633. if (i >= 0)
  10634. return values[i];
  10635. return defaultReturnValue;
  10636. }
  10637. void StringPairArray::set (const String& key,
  10638. const String& value) throw()
  10639. {
  10640. const int i = keys.indexOf (key, ignoreCase);
  10641. if (i >= 0)
  10642. {
  10643. values.set (i, value);
  10644. }
  10645. else
  10646. {
  10647. keys.add (key);
  10648. values.add (value);
  10649. }
  10650. }
  10651. void StringPairArray::addArray (const StringPairArray& other)
  10652. {
  10653. for (int i = 0; i < other.size(); ++i)
  10654. set (other.keys[i], other.values[i]);
  10655. }
  10656. void StringPairArray::clear() throw()
  10657. {
  10658. keys.clear();
  10659. values.clear();
  10660. }
  10661. void StringPairArray::remove (const String& key) throw()
  10662. {
  10663. remove (keys.indexOf (key, ignoreCase));
  10664. }
  10665. void StringPairArray::remove (const int index) throw()
  10666. {
  10667. keys.remove (index);
  10668. values.remove (index);
  10669. }
  10670. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase) throw()
  10671. {
  10672. ignoreCase = shouldIgnoreCase;
  10673. }
  10674. const String StringPairArray::getDescription() const
  10675. {
  10676. String s;
  10677. for (int i = 0; i < keys.size(); ++i)
  10678. {
  10679. s << keys[i] << T(" = ") << values[i];
  10680. if (i < keys.size())
  10681. s << T(", ");
  10682. }
  10683. return s;
  10684. }
  10685. void StringPairArray::minimiseStorageOverheads() throw()
  10686. {
  10687. keys.minimiseStorageOverheads();
  10688. values.minimiseStorageOverheads();
  10689. }
  10690. END_JUCE_NAMESPACE
  10691. /********* End of inlined file: juce_StringPairArray.cpp *********/
  10692. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  10693. BEGIN_JUCE_NAMESPACE
  10694. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  10695. {
  10696. return CharacterFunctions::isLetterOrDigit (c)
  10697. || c == T('_')
  10698. || c == T('-')
  10699. || c == T(':')
  10700. || c == T('.');
  10701. }
  10702. #define isXmlIdentifierChar(c) \
  10703. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  10704. XmlDocument::XmlDocument (const String& documentText) throw()
  10705. : originalText (documentText),
  10706. ignoreEmptyTextElements (true),
  10707. inputSource (0)
  10708. {
  10709. }
  10710. XmlDocument::XmlDocument (const File& file)
  10711. {
  10712. inputSource = new FileInputSource (file);
  10713. }
  10714. XmlDocument::~XmlDocument() throw()
  10715. {
  10716. delete inputSource;
  10717. }
  10718. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10719. {
  10720. if (inputSource != newSource)
  10721. {
  10722. delete inputSource;
  10723. inputSource = newSource;
  10724. }
  10725. }
  10726. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10727. {
  10728. ignoreEmptyTextElements = shouldBeIgnored;
  10729. }
  10730. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10731. {
  10732. String textToParse (originalText);
  10733. if (textToParse.isEmpty() && inputSource != 0)
  10734. {
  10735. InputStream* const in = inputSource->createInputStream();
  10736. if (in != 0)
  10737. {
  10738. MemoryBlock data;
  10739. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10740. delete in;
  10741. if (data.getSize() >= 2
  10742. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10743. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10744. {
  10745. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  10746. }
  10747. else
  10748. {
  10749. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  10750. }
  10751. if (! onlyReadOuterDocumentElement)
  10752. originalText = textToParse;
  10753. }
  10754. }
  10755. input = textToParse;
  10756. lastError = String::empty;
  10757. errorOccurred = false;
  10758. outOfData = false;
  10759. needToLoadDTD = true;
  10760. for (int i = 0; i < 128; ++i)
  10761. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  10762. if (textToParse.isEmpty())
  10763. {
  10764. lastError = "not enough input";
  10765. }
  10766. else
  10767. {
  10768. skipHeader();
  10769. if (input != 0)
  10770. {
  10771. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  10772. if (errorOccurred)
  10773. delete result;
  10774. else
  10775. return result;
  10776. }
  10777. else
  10778. {
  10779. lastError = "incorrect xml header";
  10780. }
  10781. }
  10782. return 0;
  10783. }
  10784. const String& XmlDocument::getLastParseError() const throw()
  10785. {
  10786. return lastError;
  10787. }
  10788. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  10789. {
  10790. lastError = desc;
  10791. errorOccurred = ! carryOn;
  10792. }
  10793. const String XmlDocument::getFileContents (const String& filename) const
  10794. {
  10795. String result;
  10796. if (inputSource != 0)
  10797. {
  10798. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  10799. if (in != 0)
  10800. {
  10801. result = in->readEntireStreamAsString();
  10802. delete in;
  10803. }
  10804. }
  10805. return result;
  10806. }
  10807. tchar XmlDocument::readNextChar() throw()
  10808. {
  10809. if (*input != 0)
  10810. {
  10811. return *input++;
  10812. }
  10813. else
  10814. {
  10815. outOfData = true;
  10816. return 0;
  10817. }
  10818. }
  10819. int XmlDocument::findNextTokenLength() throw()
  10820. {
  10821. int len = 0;
  10822. tchar c = *input;
  10823. while (isXmlIdentifierChar (c))
  10824. c = input [++len];
  10825. return len;
  10826. }
  10827. void XmlDocument::skipHeader() throw()
  10828. {
  10829. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10830. if (found != 0)
  10831. {
  10832. input = found;
  10833. input = CharacterFunctions::find (input, T("?>"));
  10834. if (input == 0)
  10835. return;
  10836. input += 2;
  10837. }
  10838. skipNextWhiteSpace();
  10839. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10840. if (docType == 0)
  10841. return;
  10842. input = docType + 9;
  10843. int n = 1;
  10844. while (n > 0)
  10845. {
  10846. const tchar c = readNextChar();
  10847. if (outOfData)
  10848. return;
  10849. if (c == T('<'))
  10850. ++n;
  10851. else if (c == T('>'))
  10852. --n;
  10853. }
  10854. docType += 9;
  10855. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10856. }
  10857. void XmlDocument::skipNextWhiteSpace() throw()
  10858. {
  10859. for (;;)
  10860. {
  10861. tchar c = *input;
  10862. while (CharacterFunctions::isWhitespace (c))
  10863. c = *++input;
  10864. if (c == 0)
  10865. {
  10866. outOfData = true;
  10867. break;
  10868. }
  10869. else if (c == T('<'))
  10870. {
  10871. if (input[1] == T('!')
  10872. && input[2] == T('-')
  10873. && input[3] == T('-'))
  10874. {
  10875. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10876. if (closeComment == 0)
  10877. {
  10878. outOfData = true;
  10879. break;
  10880. }
  10881. input = closeComment + 3;
  10882. continue;
  10883. }
  10884. else if (input[1] == T('?'))
  10885. {
  10886. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10887. if (closeBracket == 0)
  10888. {
  10889. outOfData = true;
  10890. break;
  10891. }
  10892. input = closeBracket + 2;
  10893. continue;
  10894. }
  10895. }
  10896. break;
  10897. }
  10898. }
  10899. void XmlDocument::readQuotedString (String& result) throw()
  10900. {
  10901. const tchar quote = readNextChar();
  10902. while (! outOfData)
  10903. {
  10904. const tchar character = readNextChar();
  10905. if (character == quote)
  10906. break;
  10907. if (character == T('&'))
  10908. {
  10909. --input;
  10910. readEntity (result);
  10911. }
  10912. else
  10913. {
  10914. --input;
  10915. const tchar* const start = input;
  10916. for (;;)
  10917. {
  10918. const tchar character = *input;
  10919. if (character == quote)
  10920. {
  10921. result.append (start, (int) (input - start));
  10922. ++input;
  10923. return;
  10924. }
  10925. else if (character == T('&'))
  10926. {
  10927. result.append (start, (int) (input - start));
  10928. break;
  10929. }
  10930. else if (character == 0)
  10931. {
  10932. outOfData = true;
  10933. setLastError ("unmatched quotes", false);
  10934. break;
  10935. }
  10936. ++input;
  10937. }
  10938. }
  10939. }
  10940. }
  10941. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  10942. {
  10943. XmlElement* node = 0;
  10944. skipNextWhiteSpace();
  10945. if (outOfData)
  10946. return 0;
  10947. input = CharacterFunctions::find (input, T("<"));
  10948. if (input != 0)
  10949. {
  10950. ++input;
  10951. int tagLen = findNextTokenLength();
  10952. if (tagLen == 0)
  10953. {
  10954. // no tag name - but allow for a gap after the '<' before giving an error
  10955. skipNextWhiteSpace();
  10956. tagLen = findNextTokenLength();
  10957. if (tagLen == 0)
  10958. {
  10959. setLastError ("tag name missing", false);
  10960. return node;
  10961. }
  10962. }
  10963. node = new XmlElement (input, tagLen);
  10964. input += tagLen;
  10965. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10966. // look for attributes
  10967. for (;;)
  10968. {
  10969. skipNextWhiteSpace();
  10970. const tchar c = *input;
  10971. // empty tag..
  10972. if (c == T('/') && input[1] == T('>'))
  10973. {
  10974. input += 2;
  10975. break;
  10976. }
  10977. // parse the guts of the element..
  10978. if (c == T('>'))
  10979. {
  10980. ++input;
  10981. skipNextWhiteSpace();
  10982. if (alsoParseSubElements)
  10983. readChildElements (node);
  10984. break;
  10985. }
  10986. // get an attribute..
  10987. if (isXmlIdentifierChar (c))
  10988. {
  10989. const int attNameLen = findNextTokenLength();
  10990. if (attNameLen > 0)
  10991. {
  10992. const tchar* attNameStart = input;
  10993. input += attNameLen;
  10994. skipNextWhiteSpace();
  10995. if (readNextChar() == T('='))
  10996. {
  10997. skipNextWhiteSpace();
  10998. const tchar c = *input;
  10999. if (c == T('"') || c == T('\''))
  11000. {
  11001. XmlElement::XmlAttributeNode* const newAtt
  11002. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  11003. String::empty);
  11004. readQuotedString (newAtt->value);
  11005. if (lastAttribute == 0)
  11006. node->attributes = newAtt;
  11007. else
  11008. lastAttribute->next = newAtt;
  11009. lastAttribute = newAtt;
  11010. continue;
  11011. }
  11012. }
  11013. }
  11014. }
  11015. else
  11016. {
  11017. if (! outOfData)
  11018. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11019. }
  11020. break;
  11021. }
  11022. }
  11023. return node;
  11024. }
  11025. void XmlDocument::readChildElements (XmlElement* parent) throw()
  11026. {
  11027. XmlElement* lastChildNode = 0;
  11028. for (;;)
  11029. {
  11030. skipNextWhiteSpace();
  11031. if (outOfData)
  11032. {
  11033. setLastError ("unmatched tags", false);
  11034. break;
  11035. }
  11036. if (*input == T('<'))
  11037. {
  11038. if (input[1] == T('/'))
  11039. {
  11040. // our close tag..
  11041. input = CharacterFunctions::find (input, T(">"));
  11042. ++input;
  11043. break;
  11044. }
  11045. else if (input[1] == T('!')
  11046. && input[2] == T('[')
  11047. && input[3] == T('C')
  11048. && input[4] == T('D')
  11049. && input[5] == T('A')
  11050. && input[6] == T('T')
  11051. && input[7] == T('A')
  11052. && input[8] == T('['))
  11053. {
  11054. input += 9;
  11055. const tchar* const inputStart = input;
  11056. int len = 0;
  11057. for (;;)
  11058. {
  11059. if (*input == 0)
  11060. {
  11061. setLastError ("unterminated CDATA section", false);
  11062. outOfData = true;
  11063. break;
  11064. }
  11065. else if (input[0] == T(']')
  11066. && input[1] == T(']')
  11067. && input[2] == T('>'))
  11068. {
  11069. input += 3;
  11070. break;
  11071. }
  11072. ++input;
  11073. ++len;
  11074. }
  11075. XmlElement* const e = new XmlElement ((int) 0);
  11076. e->setText (String (inputStart, len));
  11077. if (lastChildNode != 0)
  11078. lastChildNode->nextElement = e;
  11079. else
  11080. parent->addChildElement (e);
  11081. lastChildNode = e;
  11082. }
  11083. else
  11084. {
  11085. // this is some other element, so parse and add it..
  11086. XmlElement* const n = readNextElement (true);
  11087. if (n != 0)
  11088. {
  11089. if (lastChildNode == 0)
  11090. parent->addChildElement (n);
  11091. else
  11092. lastChildNode->nextElement = n;
  11093. lastChildNode = n;
  11094. }
  11095. else
  11096. {
  11097. return;
  11098. }
  11099. }
  11100. }
  11101. else
  11102. {
  11103. // read character block..
  11104. XmlElement* const e = new XmlElement ((int)0);
  11105. if (lastChildNode != 0)
  11106. lastChildNode->nextElement = e;
  11107. else
  11108. parent->addChildElement (e);
  11109. lastChildNode = e;
  11110. String textElementContent;
  11111. for (;;)
  11112. {
  11113. const tchar c = *input;
  11114. if (c == T('<'))
  11115. break;
  11116. if (c == 0)
  11117. {
  11118. setLastError ("unmatched tags", false);
  11119. outOfData = true;
  11120. return;
  11121. }
  11122. if (c == T('&'))
  11123. {
  11124. String entity;
  11125. readEntity (entity);
  11126. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  11127. {
  11128. const tchar* const oldInput = input;
  11129. const bool oldOutOfData = outOfData;
  11130. input = (const tchar*) entity;
  11131. outOfData = false;
  11132. for (;;)
  11133. {
  11134. XmlElement* const n = readNextElement (true);
  11135. if (n == 0)
  11136. break;
  11137. if (lastChildNode == 0)
  11138. parent->addChildElement (n);
  11139. else
  11140. lastChildNode->nextElement = n;
  11141. lastChildNode = n;
  11142. }
  11143. input = oldInput;
  11144. outOfData = oldOutOfData;
  11145. }
  11146. else
  11147. {
  11148. textElementContent += entity;
  11149. }
  11150. }
  11151. else
  11152. {
  11153. const tchar* start = input;
  11154. int len = 0;
  11155. for (;;)
  11156. {
  11157. const tchar c = *input;
  11158. if (c == T('<') || c == T('&'))
  11159. {
  11160. break;
  11161. }
  11162. else if (c == 0)
  11163. {
  11164. setLastError ("unmatched tags", false);
  11165. outOfData = true;
  11166. return;
  11167. }
  11168. ++input;
  11169. ++len;
  11170. }
  11171. textElementContent.append (start, len);
  11172. }
  11173. }
  11174. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11175. : textElementContent.isNotEmpty())
  11176. e->setText (textElementContent);
  11177. }
  11178. }
  11179. }
  11180. void XmlDocument::readEntity (String& result) throw()
  11181. {
  11182. // skip over the ampersand
  11183. ++input;
  11184. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  11185. {
  11186. input += 4;
  11187. result += T("&");
  11188. }
  11189. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  11190. {
  11191. input += 5;
  11192. result += T("\"");
  11193. }
  11194. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  11195. {
  11196. input += 5;
  11197. result += T("\'");
  11198. }
  11199. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  11200. {
  11201. input += 3;
  11202. result += T("<");
  11203. }
  11204. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  11205. {
  11206. input += 3;
  11207. result += T(">");
  11208. }
  11209. else if (*input == T('#'))
  11210. {
  11211. int charCode = 0;
  11212. ++input;
  11213. if (*input == T('x') || *input == T('X'))
  11214. {
  11215. ++input;
  11216. int numChars = 0;
  11217. while (input[0] != T(';'))
  11218. {
  11219. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11220. if (hexValue < 0 || ++numChars > 8)
  11221. {
  11222. setLastError ("illegal escape sequence", true);
  11223. break;
  11224. }
  11225. charCode = (charCode << 4) | hexValue;
  11226. ++input;
  11227. }
  11228. ++input;
  11229. }
  11230. else if (input[0] >= T('0') && input[0] <= T('9'))
  11231. {
  11232. int numChars = 0;
  11233. while (input[0] != T(';'))
  11234. {
  11235. if (++numChars > 12)
  11236. {
  11237. setLastError ("illegal escape sequence", true);
  11238. break;
  11239. }
  11240. charCode = charCode * 10 + (input[0] - T('0'));
  11241. ++input;
  11242. }
  11243. ++input;
  11244. }
  11245. else
  11246. {
  11247. setLastError ("illegal escape sequence", true);
  11248. result += T("&");
  11249. return;
  11250. }
  11251. result << (tchar) charCode;
  11252. }
  11253. else
  11254. {
  11255. const tchar* const entityNameStart = input;
  11256. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  11257. if (closingSemiColon == 0)
  11258. {
  11259. outOfData = true;
  11260. result += T("&");
  11261. }
  11262. else
  11263. {
  11264. input = closingSemiColon + 1;
  11265. result += expandExternalEntity (String (entityNameStart,
  11266. (int) (closingSemiColon - entityNameStart)));
  11267. }
  11268. }
  11269. }
  11270. const String XmlDocument::expandEntity (const String& ent)
  11271. {
  11272. if (ent.equalsIgnoreCase (T("amp")))
  11273. {
  11274. return T("&");
  11275. }
  11276. else if (ent.equalsIgnoreCase (T("quot")))
  11277. {
  11278. return T("\"");
  11279. }
  11280. else if (ent.equalsIgnoreCase (T("apos")))
  11281. {
  11282. return T("\'");
  11283. }
  11284. else if (ent.equalsIgnoreCase (T("lt")))
  11285. {
  11286. return T("<");
  11287. }
  11288. else if (ent.equalsIgnoreCase (T("gt")))
  11289. {
  11290. return T(">");
  11291. }
  11292. else if (ent[0] == T('#'))
  11293. {
  11294. if (ent[1] == T('x') || ent[1] == T('X'))
  11295. {
  11296. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  11297. }
  11298. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  11299. {
  11300. return String::charToString ((tchar) ent.substring (1).getIntValue());
  11301. }
  11302. setLastError ("illegal escape sequence", false);
  11303. return T("&");
  11304. }
  11305. else
  11306. {
  11307. return expandExternalEntity (ent);
  11308. }
  11309. }
  11310. const String XmlDocument::expandExternalEntity (const String& entity)
  11311. {
  11312. if (needToLoadDTD)
  11313. {
  11314. if (dtdText.isNotEmpty())
  11315. {
  11316. while (dtdText.endsWithChar (T('>')))
  11317. dtdText = dtdText.dropLastCharacters (1);
  11318. tokenisedDTD.addTokens (dtdText, true);
  11319. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  11320. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11321. {
  11322. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11323. tokenisedDTD.clear();
  11324. tokenisedDTD.addTokens (getFileContents (fn), true);
  11325. }
  11326. else
  11327. {
  11328. tokenisedDTD.clear();
  11329. const int openBracket = dtdText.indexOfChar (T('['));
  11330. if (openBracket > 0)
  11331. {
  11332. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  11333. if (closeBracket > openBracket)
  11334. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11335. closeBracket), true);
  11336. }
  11337. }
  11338. for (int i = tokenisedDTD.size(); --i >= 0;)
  11339. {
  11340. if (tokenisedDTD[i].startsWithChar (T('%'))
  11341. && tokenisedDTD[i].endsWithChar (T(';')))
  11342. {
  11343. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11344. StringArray newToks;
  11345. newToks.addTokens (parsed, true);
  11346. tokenisedDTD.remove (i);
  11347. for (int j = newToks.size(); --j >= 0;)
  11348. tokenisedDTD.insert (i, newToks[j]);
  11349. }
  11350. }
  11351. }
  11352. needToLoadDTD = false;
  11353. }
  11354. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11355. {
  11356. if (tokenisedDTD[i] == entity)
  11357. {
  11358. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  11359. {
  11360. String ent (tokenisedDTD [i + 1]);
  11361. while (ent.endsWithChar (T('>')))
  11362. ent = ent.dropLastCharacters (1);
  11363. ent = ent.trim().unquoted();
  11364. // check for sub-entities..
  11365. int ampersand = ent.indexOfChar (T('&'));
  11366. while (ampersand >= 0)
  11367. {
  11368. const int semiColon = ent.indexOf (i + 1, T(";"));
  11369. if (semiColon < 0)
  11370. {
  11371. setLastError ("entity without terminating semi-colon", false);
  11372. break;
  11373. }
  11374. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11375. ent = ent.substring (0, ampersand)
  11376. + resolved
  11377. + ent.substring (semiColon + 1);
  11378. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  11379. }
  11380. return ent;
  11381. }
  11382. }
  11383. }
  11384. setLastError ("unknown entity", true);
  11385. return entity;
  11386. }
  11387. const String XmlDocument::getParameterEntity (const String& entity)
  11388. {
  11389. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11390. {
  11391. if (tokenisedDTD[i] == entity)
  11392. {
  11393. if (tokenisedDTD [i - 1] == T("%")
  11394. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  11395. {
  11396. String ent (tokenisedDTD [i + 1]);
  11397. while (ent.endsWithChar (T('>')))
  11398. ent = ent.dropLastCharacters (1);
  11399. if (ent.equalsIgnoreCase (T("system")))
  11400. {
  11401. String filename (tokenisedDTD [i + 2]);
  11402. while (filename.endsWithChar (T('>')))
  11403. filename = filename.dropLastCharacters (1);
  11404. return getFileContents (filename);
  11405. }
  11406. else
  11407. {
  11408. return ent.trim().unquoted();
  11409. }
  11410. }
  11411. }
  11412. }
  11413. return entity;
  11414. }
  11415. END_JUCE_NAMESPACE
  11416. /********* End of inlined file: juce_XmlDocument.cpp *********/
  11417. /********* Start of inlined file: juce_XmlElement.cpp *********/
  11418. BEGIN_JUCE_NAMESPACE
  11419. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11420. : name (other.name),
  11421. value (other.value),
  11422. next (0)
  11423. {
  11424. }
  11425. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  11426. const String& value_) throw()
  11427. : name (name_),
  11428. value (value_),
  11429. next (0)
  11430. {
  11431. }
  11432. XmlElement::XmlElement (const String& tagName_) throw()
  11433. : tagName (tagName_),
  11434. firstChildElement (0),
  11435. nextElement (0),
  11436. attributes (0)
  11437. {
  11438. // the tag name mustn't be empty, or it'll look like a text element!
  11439. jassert (tagName_.containsNonWhitespaceChars())
  11440. }
  11441. XmlElement::XmlElement (int /*dummy*/) throw()
  11442. : firstChildElement (0),
  11443. nextElement (0),
  11444. attributes (0)
  11445. {
  11446. }
  11447. XmlElement::XmlElement (const tchar* const tagName_,
  11448. const int nameLen) throw()
  11449. : tagName (tagName_, nameLen),
  11450. firstChildElement (0),
  11451. nextElement (0),
  11452. attributes (0)
  11453. {
  11454. }
  11455. XmlElement::XmlElement (const XmlElement& other) throw()
  11456. : tagName (other.tagName),
  11457. firstChildElement (0),
  11458. nextElement (0),
  11459. attributes (0)
  11460. {
  11461. copyChildrenAndAttributesFrom (other);
  11462. }
  11463. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11464. {
  11465. if (this != &other)
  11466. {
  11467. removeAllAttributes();
  11468. deleteAllChildElements();
  11469. tagName = other.tagName;
  11470. copyChildrenAndAttributesFrom (other);
  11471. }
  11472. return *this;
  11473. }
  11474. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11475. {
  11476. XmlElement* child = other.firstChildElement;
  11477. XmlElement* lastChild = 0;
  11478. while (child != 0)
  11479. {
  11480. XmlElement* const copiedChild = new XmlElement (*child);
  11481. if (lastChild != 0)
  11482. lastChild->nextElement = copiedChild;
  11483. else
  11484. firstChildElement = copiedChild;
  11485. lastChild = copiedChild;
  11486. child = child->nextElement;
  11487. }
  11488. const XmlAttributeNode* att = other.attributes;
  11489. XmlAttributeNode* lastAtt = 0;
  11490. while (att != 0)
  11491. {
  11492. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11493. if (lastAtt != 0)
  11494. lastAtt->next = newAtt;
  11495. else
  11496. attributes = newAtt;
  11497. lastAtt = newAtt;
  11498. att = att->next;
  11499. }
  11500. }
  11501. XmlElement::~XmlElement() throw()
  11502. {
  11503. XmlElement* child = firstChildElement;
  11504. while (child != 0)
  11505. {
  11506. XmlElement* const nextChild = child->nextElement;
  11507. delete child;
  11508. child = nextChild;
  11509. }
  11510. XmlAttributeNode* att = attributes;
  11511. while (att != 0)
  11512. {
  11513. XmlAttributeNode* const nextAtt = att->next;
  11514. delete att;
  11515. att = nextAtt;
  11516. }
  11517. }
  11518. static bool isLegalXmlChar (const juce_wchar character)
  11519. {
  11520. if ((character >= 'a' && character <= 'z')
  11521. || (character >= 'A' && character <= 'Z')
  11522. || (character >= '0' && character <= '9'))
  11523. return true;
  11524. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11525. do
  11526. {
  11527. if (((juce_wchar) (uint8) *t) == character)
  11528. return true;
  11529. }
  11530. while (*++t != 0);
  11531. return false;
  11532. }
  11533. static void escapeIllegalXmlChars (OutputStream& outputStream,
  11534. const String& text,
  11535. const bool changeNewLines) throw()
  11536. {
  11537. const juce_wchar* t = (const juce_wchar*) text;
  11538. for (;;)
  11539. {
  11540. const juce_wchar character = *t++;
  11541. if (character == 0)
  11542. {
  11543. break;
  11544. }
  11545. else if (isLegalXmlChar (character))
  11546. {
  11547. outputStream.writeByte ((char) character);
  11548. }
  11549. else
  11550. {
  11551. switch (character)
  11552. {
  11553. case '&':
  11554. outputStream.write ("&amp;", 5);
  11555. break;
  11556. case '"':
  11557. outputStream.write ("&quot;", 6);
  11558. break;
  11559. case '>':
  11560. outputStream.write ("&gt;", 4);
  11561. break;
  11562. case '<':
  11563. outputStream.write ("&lt;", 4);
  11564. break;
  11565. case '\n':
  11566. if (changeNewLines)
  11567. outputStream.write ("&#10;", 5);
  11568. else
  11569. outputStream.writeByte ((char) character);
  11570. break;
  11571. case '\r':
  11572. if (changeNewLines)
  11573. outputStream.write ("&#13;", 5);
  11574. else
  11575. outputStream.writeByte ((char) character);
  11576. break;
  11577. default:
  11578. {
  11579. String encoded (T("&#"));
  11580. encoded << String ((int) (unsigned int) character).trim()
  11581. << T(';');
  11582. outputStream.write ((const char*) encoded, encoded.length());
  11583. }
  11584. }
  11585. }
  11586. }
  11587. }
  11588. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  11589. {
  11590. if (numSpaces > 0)
  11591. {
  11592. const char* const blanks = " ";
  11593. const int blankSize = (int) sizeof (blanks) - 1;
  11594. while (numSpaces > blankSize)
  11595. {
  11596. out.write (blanks, blankSize);
  11597. numSpaces -= blankSize;
  11598. }
  11599. out.write (blanks, numSpaces);
  11600. }
  11601. }
  11602. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11603. const int indentationLevel,
  11604. const int lineWrapLength) const throw()
  11605. {
  11606. writeSpaces (outputStream, indentationLevel);
  11607. if (! isTextElement())
  11608. {
  11609. outputStream.writeByte ('<');
  11610. const int nameLen = tagName.length();
  11611. outputStream.write ((const char*) tagName, nameLen);
  11612. const int attIndent = indentationLevel + nameLen + 1;
  11613. int lineLen = 0;
  11614. const XmlAttributeNode* att = attributes;
  11615. while (att != 0)
  11616. {
  11617. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11618. {
  11619. outputStream.write ("\r\n", 2);
  11620. writeSpaces (outputStream, attIndent);
  11621. lineLen = 0;
  11622. }
  11623. const int attNameLen = att->name.length();
  11624. outputStream.writeByte (' ');
  11625. outputStream.write ((const char*) (att->name), attNameLen);
  11626. outputStream.write ("=\"", 2);
  11627. escapeIllegalXmlChars (outputStream, att->value, true);
  11628. outputStream.writeByte ('"');
  11629. lineLen += 4 + attNameLen + att->value.length();
  11630. att = att->next;
  11631. }
  11632. if (firstChildElement != 0)
  11633. {
  11634. XmlElement* child = firstChildElement;
  11635. if (child->nextElement == 0 && child->isTextElement())
  11636. {
  11637. outputStream.writeByte ('>');
  11638. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11639. }
  11640. else
  11641. {
  11642. if (indentationLevel >= 0)
  11643. outputStream.write (">\r\n", 3);
  11644. else
  11645. outputStream.writeByte ('>');
  11646. bool lastWasTextNode = false;
  11647. while (child != 0)
  11648. {
  11649. if (child->isTextElement())
  11650. {
  11651. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11652. writeSpaces (outputStream, indentationLevel + 2);
  11653. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11654. lastWasTextNode = true;
  11655. }
  11656. else
  11657. {
  11658. if (indentationLevel >= 0)
  11659. {
  11660. if (lastWasTextNode)
  11661. outputStream.write ("\r\n", 2);
  11662. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11663. }
  11664. else
  11665. {
  11666. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11667. }
  11668. lastWasTextNode = false;
  11669. }
  11670. child = child->nextElement;
  11671. }
  11672. if (indentationLevel >= 0)
  11673. {
  11674. if (lastWasTextNode)
  11675. outputStream.write ("\r\n", 2);
  11676. writeSpaces (outputStream, indentationLevel);
  11677. }
  11678. }
  11679. outputStream.write ("</", 2);
  11680. outputStream.write ((const char*) tagName, nameLen);
  11681. if (indentationLevel >= 0)
  11682. outputStream.write (">\r\n", 3);
  11683. else
  11684. outputStream.writeByte ('>');
  11685. }
  11686. else
  11687. {
  11688. if (indentationLevel >= 0)
  11689. outputStream.write ("/>\r\n", 4);
  11690. else
  11691. outputStream.write ("/>", 2);
  11692. }
  11693. }
  11694. else
  11695. {
  11696. if (indentationLevel >= 0)
  11697. writeSpaces (outputStream, indentationLevel + 2);
  11698. escapeIllegalXmlChars (outputStream, getText(), false);
  11699. }
  11700. }
  11701. const String XmlElement::createDocument (const String& dtd,
  11702. const bool allOnOneLine,
  11703. const bool includeXmlHeader,
  11704. const tchar* const encoding,
  11705. const int lineWrapLength) const throw()
  11706. {
  11707. String doc;
  11708. doc.preallocateStorage (1024);
  11709. if (includeXmlHeader)
  11710. {
  11711. doc << "<?xml version=\"1.0\" encoding=\""
  11712. << encoding;
  11713. if (allOnOneLine)
  11714. doc += "\"?> ";
  11715. else
  11716. doc += "\"?>\n\n";
  11717. }
  11718. if (dtd.isNotEmpty())
  11719. {
  11720. if (allOnOneLine)
  11721. doc << dtd << " ";
  11722. else
  11723. doc << dtd << "\r\n";
  11724. }
  11725. MemoryOutputStream mem (2048, 4096);
  11726. writeElementAsText (mem, allOnOneLine ? -1 : 0, lineWrapLength);
  11727. return doc + String (mem.getData(),
  11728. mem.getDataSize());
  11729. }
  11730. bool XmlElement::writeToFile (const File& f,
  11731. const String& dtd,
  11732. const tchar* const encoding,
  11733. const int lineWrapLength) const throw()
  11734. {
  11735. if (f.hasWriteAccess())
  11736. {
  11737. const File tempFile (f.getNonexistentSibling());
  11738. FileOutputStream* const out = tempFile.createOutputStream();
  11739. if (out != 0)
  11740. {
  11741. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  11742. << dtd << "\r\n";
  11743. writeElementAsText (*out, 0, lineWrapLength);
  11744. delete out;
  11745. if (tempFile.moveFileTo (f))
  11746. return true;
  11747. tempFile.deleteFile();
  11748. }
  11749. }
  11750. return false;
  11751. }
  11752. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  11753. {
  11754. #ifdef JUCE_DEBUG
  11755. // if debugging, check that the case is actually the same, because
  11756. // valid xml is case-sensitive, and although this lets it pass, it's
  11757. // better not to..
  11758. if (tagName.equalsIgnoreCase (tagNameWanted))
  11759. {
  11760. jassert (tagName == tagNameWanted);
  11761. return true;
  11762. }
  11763. else
  11764. {
  11765. return false;
  11766. }
  11767. #else
  11768. return tagName.equalsIgnoreCase (tagNameWanted);
  11769. #endif
  11770. }
  11771. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  11772. {
  11773. XmlElement* e = nextElement;
  11774. while (e != 0 && ! e->hasTagName (requiredTagName))
  11775. e = e->nextElement;
  11776. return e;
  11777. }
  11778. int XmlElement::getNumAttributes() const throw()
  11779. {
  11780. const XmlAttributeNode* att = attributes;
  11781. int count = 0;
  11782. while (att != 0)
  11783. {
  11784. att = att->next;
  11785. ++count;
  11786. }
  11787. return count;
  11788. }
  11789. const String& XmlElement::getAttributeName (const int index) const throw()
  11790. {
  11791. const XmlAttributeNode* att = attributes;
  11792. int count = 0;
  11793. while (att != 0)
  11794. {
  11795. if (count == index)
  11796. return att->name;
  11797. att = att->next;
  11798. ++count;
  11799. }
  11800. return String::empty;
  11801. }
  11802. const String& XmlElement::getAttributeValue (const int index) const throw()
  11803. {
  11804. const XmlAttributeNode* att = attributes;
  11805. int count = 0;
  11806. while (att != 0)
  11807. {
  11808. if (count == index)
  11809. return att->value;
  11810. att = att->next;
  11811. ++count;
  11812. }
  11813. return String::empty;
  11814. }
  11815. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  11816. {
  11817. const XmlAttributeNode* att = attributes;
  11818. while (att != 0)
  11819. {
  11820. if (att->name.equalsIgnoreCase (attributeName))
  11821. return true;
  11822. att = att->next;
  11823. }
  11824. return false;
  11825. }
  11826. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  11827. const tchar* const defaultReturnValue) const throw()
  11828. {
  11829. const XmlAttributeNode* att = attributes;
  11830. while (att != 0)
  11831. {
  11832. if (att->name.equalsIgnoreCase (attributeName))
  11833. return att->value;
  11834. att = att->next;
  11835. }
  11836. return defaultReturnValue;
  11837. }
  11838. int XmlElement::getIntAttribute (const tchar* const attributeName,
  11839. const int defaultReturnValue) const throw()
  11840. {
  11841. const XmlAttributeNode* att = attributes;
  11842. while (att != 0)
  11843. {
  11844. if (att->name.equalsIgnoreCase (attributeName))
  11845. return att->value.getIntValue();
  11846. att = att->next;
  11847. }
  11848. return defaultReturnValue;
  11849. }
  11850. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  11851. const double defaultReturnValue) const throw()
  11852. {
  11853. const XmlAttributeNode* att = attributes;
  11854. while (att != 0)
  11855. {
  11856. if (att->name.equalsIgnoreCase (attributeName))
  11857. return att->value.getDoubleValue();
  11858. att = att->next;
  11859. }
  11860. return defaultReturnValue;
  11861. }
  11862. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  11863. const bool defaultReturnValue) const throw()
  11864. {
  11865. const XmlAttributeNode* att = attributes;
  11866. while (att != 0)
  11867. {
  11868. if (att->name.equalsIgnoreCase (attributeName))
  11869. {
  11870. tchar firstChar = att->value[0];
  11871. if (CharacterFunctions::isWhitespace (firstChar))
  11872. firstChar = att->value.trimStart() [0];
  11873. return firstChar == T('1')
  11874. || firstChar == T('t')
  11875. || firstChar == T('y')
  11876. || firstChar == T('T')
  11877. || firstChar == T('Y');
  11878. }
  11879. att = att->next;
  11880. }
  11881. return defaultReturnValue;
  11882. }
  11883. bool XmlElement::compareAttribute (const tchar* const attributeName,
  11884. const tchar* const stringToCompareAgainst,
  11885. const bool ignoreCase) const throw()
  11886. {
  11887. const XmlAttributeNode* att = attributes;
  11888. while (att != 0)
  11889. {
  11890. if (att->name.equalsIgnoreCase (attributeName))
  11891. {
  11892. if (ignoreCase)
  11893. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11894. else
  11895. return att->value == stringToCompareAgainst;
  11896. }
  11897. att = att->next;
  11898. }
  11899. return false;
  11900. }
  11901. void XmlElement::setAttribute (const tchar* const attributeName,
  11902. const String& value) throw()
  11903. {
  11904. #ifdef JUCE_DEBUG
  11905. // check the identifier being passed in is legal..
  11906. const tchar* t = attributeName;
  11907. while (*t != 0)
  11908. {
  11909. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11910. || *t == T('_')
  11911. || *t == T('-')
  11912. || *t == T(':'));
  11913. ++t;
  11914. }
  11915. #endif
  11916. if (attributes == 0)
  11917. {
  11918. attributes = new XmlAttributeNode (attributeName, value);
  11919. }
  11920. else
  11921. {
  11922. XmlAttributeNode* att = attributes;
  11923. for (;;)
  11924. {
  11925. if (att->name.equalsIgnoreCase (attributeName))
  11926. {
  11927. att->value = value;
  11928. break;
  11929. }
  11930. else if (att->next == 0)
  11931. {
  11932. att->next = new XmlAttributeNode (attributeName, value);
  11933. break;
  11934. }
  11935. att = att->next;
  11936. }
  11937. }
  11938. }
  11939. void XmlElement::setAttribute (const tchar* const attributeName,
  11940. const tchar* const text) throw()
  11941. {
  11942. setAttribute (attributeName, String (text));
  11943. }
  11944. void XmlElement::setAttribute (const tchar* const attributeName,
  11945. const int number) throw()
  11946. {
  11947. setAttribute (attributeName, String (number));
  11948. }
  11949. void XmlElement::setAttribute (const tchar* const attributeName,
  11950. const double number) throw()
  11951. {
  11952. tchar buffer [40];
  11953. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  11954. setAttribute (attributeName, buffer);
  11955. }
  11956. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  11957. {
  11958. XmlAttributeNode* att = attributes;
  11959. XmlAttributeNode* lastAtt = 0;
  11960. while (att != 0)
  11961. {
  11962. if (att->name.equalsIgnoreCase (attributeName))
  11963. {
  11964. if (lastAtt == 0)
  11965. attributes = att->next;
  11966. else
  11967. lastAtt->next = att->next;
  11968. delete att;
  11969. break;
  11970. }
  11971. lastAtt = att;
  11972. att = att->next;
  11973. }
  11974. }
  11975. void XmlElement::removeAllAttributes() throw()
  11976. {
  11977. while (attributes != 0)
  11978. {
  11979. XmlAttributeNode* const nextAtt = attributes->next;
  11980. delete attributes;
  11981. attributes = nextAtt;
  11982. }
  11983. }
  11984. int XmlElement::getNumChildElements() const throw()
  11985. {
  11986. int count = 0;
  11987. const XmlElement* child = firstChildElement;
  11988. while (child != 0)
  11989. {
  11990. ++count;
  11991. child = child->nextElement;
  11992. }
  11993. return count;
  11994. }
  11995. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11996. {
  11997. int count = 0;
  11998. XmlElement* child = firstChildElement;
  11999. while (child != 0 && count < index)
  12000. {
  12001. child = child->nextElement;
  12002. ++count;
  12003. }
  12004. return child;
  12005. }
  12006. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  12007. {
  12008. XmlElement* child = firstChildElement;
  12009. while (child != 0)
  12010. {
  12011. if (child->hasTagName (childName))
  12012. break;
  12013. child = child->nextElement;
  12014. }
  12015. return child;
  12016. }
  12017. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12018. {
  12019. if (newNode != 0)
  12020. {
  12021. if (firstChildElement == 0)
  12022. {
  12023. firstChildElement = newNode;
  12024. }
  12025. else
  12026. {
  12027. XmlElement* child = firstChildElement;
  12028. while (child->nextElement != 0)
  12029. child = child->nextElement;
  12030. child->nextElement = newNode;
  12031. // if this is non-zero, then something's probably
  12032. // gone wrong..
  12033. jassert (newNode->nextElement == 0);
  12034. }
  12035. }
  12036. }
  12037. void XmlElement::insertChildElement (XmlElement* const newNode,
  12038. int indexToInsertAt) throw()
  12039. {
  12040. if (newNode != 0)
  12041. {
  12042. removeChildElement (newNode, false);
  12043. if (indexToInsertAt == 0)
  12044. {
  12045. newNode->nextElement = firstChildElement;
  12046. firstChildElement = newNode;
  12047. }
  12048. else
  12049. {
  12050. if (firstChildElement == 0)
  12051. {
  12052. firstChildElement = newNode;
  12053. }
  12054. else
  12055. {
  12056. if (indexToInsertAt < 0)
  12057. indexToInsertAt = INT_MAX;
  12058. XmlElement* child = firstChildElement;
  12059. while (child->nextElement != 0 && --indexToInsertAt > 0)
  12060. child = child->nextElement;
  12061. newNode->nextElement = child->nextElement;
  12062. child->nextElement = newNode;
  12063. }
  12064. }
  12065. }
  12066. }
  12067. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12068. XmlElement* const newNode) throw()
  12069. {
  12070. if (newNode != 0)
  12071. {
  12072. XmlElement* child = firstChildElement;
  12073. XmlElement* previousNode = 0;
  12074. while (child != 0)
  12075. {
  12076. if (child == currentChildElement)
  12077. {
  12078. if (child != newNode)
  12079. {
  12080. if (previousNode == 0)
  12081. firstChildElement = newNode;
  12082. else
  12083. previousNode->nextElement = newNode;
  12084. newNode->nextElement = child->nextElement;
  12085. delete child;
  12086. }
  12087. return true;
  12088. }
  12089. previousNode = child;
  12090. child = child->nextElement;
  12091. }
  12092. }
  12093. return false;
  12094. }
  12095. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12096. const bool shouldDeleteTheChild) throw()
  12097. {
  12098. if (childToRemove != 0)
  12099. {
  12100. if (firstChildElement == childToRemove)
  12101. {
  12102. firstChildElement = childToRemove->nextElement;
  12103. childToRemove->nextElement = 0;
  12104. }
  12105. else
  12106. {
  12107. XmlElement* child = firstChildElement;
  12108. XmlElement* last = 0;
  12109. while (child != 0)
  12110. {
  12111. if (child == childToRemove)
  12112. {
  12113. if (last == 0)
  12114. firstChildElement = child->nextElement;
  12115. else
  12116. last->nextElement = child->nextElement;
  12117. childToRemove->nextElement = 0;
  12118. break;
  12119. }
  12120. last = child;
  12121. child = child->nextElement;
  12122. }
  12123. }
  12124. if (shouldDeleteTheChild)
  12125. delete childToRemove;
  12126. }
  12127. }
  12128. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12129. const bool ignoreOrderOfAttributes) const throw()
  12130. {
  12131. if (this != other)
  12132. {
  12133. if (other == 0 || tagName != other->tagName)
  12134. {
  12135. return false;
  12136. }
  12137. if (ignoreOrderOfAttributes)
  12138. {
  12139. int totalAtts = 0;
  12140. const XmlAttributeNode* att = attributes;
  12141. while (att != 0)
  12142. {
  12143. if (! other->compareAttribute (att->name, att->value))
  12144. return false;
  12145. att = att->next;
  12146. ++totalAtts;
  12147. }
  12148. if (totalAtts != other->getNumAttributes())
  12149. return false;
  12150. }
  12151. else
  12152. {
  12153. const XmlAttributeNode* thisAtt = attributes;
  12154. const XmlAttributeNode* otherAtt = other->attributes;
  12155. for (;;)
  12156. {
  12157. if (thisAtt == 0 || otherAtt == 0)
  12158. {
  12159. if (thisAtt == otherAtt) // both 0, so it's a match
  12160. break;
  12161. return false;
  12162. }
  12163. if (thisAtt->name != otherAtt->name
  12164. || thisAtt->value != otherAtt->value)
  12165. {
  12166. return false;
  12167. }
  12168. thisAtt = thisAtt->next;
  12169. otherAtt = otherAtt->next;
  12170. }
  12171. }
  12172. const XmlElement* thisChild = firstChildElement;
  12173. const XmlElement* otherChild = other->firstChildElement;
  12174. for (;;)
  12175. {
  12176. if (thisChild == 0 || otherChild == 0)
  12177. {
  12178. if (thisChild == otherChild) // both 0, so it's a match
  12179. break;
  12180. return false;
  12181. }
  12182. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12183. return false;
  12184. thisChild = thisChild->nextElement;
  12185. otherChild = otherChild->nextElement;
  12186. }
  12187. }
  12188. return true;
  12189. }
  12190. void XmlElement::deleteAllChildElements() throw()
  12191. {
  12192. while (firstChildElement != 0)
  12193. {
  12194. XmlElement* const nextChild = firstChildElement->nextElement;
  12195. delete firstChildElement;
  12196. firstChildElement = nextChild;
  12197. }
  12198. }
  12199. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  12200. {
  12201. XmlElement* child = firstChildElement;
  12202. while (child != 0)
  12203. {
  12204. if (child->hasTagName (name))
  12205. {
  12206. XmlElement* const nextChild = child->nextElement;
  12207. removeChildElement (child, true);
  12208. child = nextChild;
  12209. }
  12210. else
  12211. {
  12212. child = child->nextElement;
  12213. }
  12214. }
  12215. }
  12216. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12217. {
  12218. const XmlElement* child = firstChildElement;
  12219. while (child != 0)
  12220. {
  12221. if (child == possibleChild)
  12222. return true;
  12223. child = child->nextElement;
  12224. }
  12225. return false;
  12226. }
  12227. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12228. {
  12229. if (this == elementToLookFor || elementToLookFor == 0)
  12230. return 0;
  12231. XmlElement* child = firstChildElement;
  12232. while (child != 0)
  12233. {
  12234. if (elementToLookFor == child)
  12235. return this;
  12236. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12237. if (found != 0)
  12238. return found;
  12239. child = child->nextElement;
  12240. }
  12241. return 0;
  12242. }
  12243. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  12244. {
  12245. XmlElement** const elems = new XmlElement* [num];
  12246. XmlElement* e = firstChildElement;
  12247. int i = 0;
  12248. while (e != 0)
  12249. {
  12250. elems [i++] = e;
  12251. e = e->nextElement;
  12252. }
  12253. return elems;
  12254. }
  12255. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12256. {
  12257. XmlElement* e = firstChildElement = elems[0];
  12258. for (int i = 1; i < num; ++i)
  12259. {
  12260. e->nextElement = elems[i];
  12261. e = e->nextElement;
  12262. }
  12263. e->nextElement = 0;
  12264. }
  12265. bool XmlElement::isTextElement() const throw()
  12266. {
  12267. return tagName.isEmpty();
  12268. }
  12269. static const tchar* const juce_xmltextContentAttributeName = T("text");
  12270. const String XmlElement::getText() const throw()
  12271. {
  12272. jassert (isTextElement()); // you're trying to get the text from an element that
  12273. // isn't actually a text element.. If this contains text sub-nodes, you
  12274. // can use getAllSubText instead to
  12275. return getStringAttribute (juce_xmltextContentAttributeName);
  12276. }
  12277. void XmlElement::setText (const String& newText) throw()
  12278. {
  12279. if (isTextElement())
  12280. {
  12281. setAttribute (juce_xmltextContentAttributeName, newText);
  12282. }
  12283. else
  12284. {
  12285. jassertfalse // you can only change the text in a text element, not a normal one.
  12286. }
  12287. }
  12288. const String XmlElement::getAllSubText() const throw()
  12289. {
  12290. String result;
  12291. const XmlElement* child = firstChildElement;
  12292. while (child != 0)
  12293. {
  12294. if (child->isTextElement())
  12295. result += child->getText();
  12296. child = child->nextElement;
  12297. }
  12298. return result;
  12299. }
  12300. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  12301. const String& defaultReturnValue) const throw()
  12302. {
  12303. const XmlElement* const child = getChildByName (childTagName);
  12304. if (child != 0)
  12305. return child->getAllSubText();
  12306. return defaultReturnValue;
  12307. }
  12308. XmlElement* XmlElement::createTextElement (const String& text) throw()
  12309. {
  12310. XmlElement* const e = new XmlElement ((int) 0);
  12311. e->setAttribute (juce_xmltextContentAttributeName, text);
  12312. return e;
  12313. }
  12314. void XmlElement::addTextElement (const String& text) throw()
  12315. {
  12316. addChildElement (createTextElement (text));
  12317. }
  12318. void XmlElement::deleteAllTextElements() throw()
  12319. {
  12320. XmlElement* child = firstChildElement;
  12321. while (child != 0)
  12322. {
  12323. XmlElement* const next = child->nextElement;
  12324. if (child->isTextElement())
  12325. removeChildElement (child, true);
  12326. child = next;
  12327. }
  12328. }
  12329. END_JUCE_NAMESPACE
  12330. /********* End of inlined file: juce_XmlElement.cpp *********/
  12331. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  12332. BEGIN_JUCE_NAMESPACE
  12333. // (implemented in the platform-specific code files)
  12334. END_JUCE_NAMESPACE
  12335. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  12336. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  12337. BEGIN_JUCE_NAMESPACE
  12338. ReadWriteLock::ReadWriteLock() throw()
  12339. : numWaitingWriters (0),
  12340. numWriters (0),
  12341. writerThreadId (0)
  12342. {
  12343. }
  12344. ReadWriteLock::~ReadWriteLock() throw()
  12345. {
  12346. jassert (readerThreads.size() == 0);
  12347. jassert (numWriters == 0);
  12348. }
  12349. void ReadWriteLock::enterRead() const throw()
  12350. {
  12351. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12352. const ScopedLock sl (accessLock);
  12353. for (;;)
  12354. {
  12355. jassert (readerThreads.size() % 2 == 0);
  12356. int i;
  12357. for (i = 0; i < readerThreads.size(); i += 2)
  12358. if (readerThreads.getUnchecked(i) == threadId)
  12359. break;
  12360. if (i < readerThreads.size()
  12361. || numWriters + numWaitingWriters == 0
  12362. || (threadId == writerThreadId && numWriters > 0))
  12363. {
  12364. if (i < readerThreads.size())
  12365. {
  12366. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12367. }
  12368. else
  12369. {
  12370. readerThreads.add (threadId);
  12371. readerThreads.add ((Thread::ThreadID) 1);
  12372. }
  12373. return;
  12374. }
  12375. const ScopedUnlock ul (accessLock);
  12376. waitEvent.wait (100);
  12377. }
  12378. }
  12379. void ReadWriteLock::exitRead() const throw()
  12380. {
  12381. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12382. const ScopedLock sl (accessLock);
  12383. for (int i = 0; i < readerThreads.size(); i += 2)
  12384. {
  12385. if (readerThreads.getUnchecked(i) == threadId)
  12386. {
  12387. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12388. if (newCount == 0)
  12389. {
  12390. readerThreads.removeRange (i, 2);
  12391. waitEvent.signal();
  12392. }
  12393. else
  12394. {
  12395. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12396. }
  12397. return;
  12398. }
  12399. }
  12400. jassertfalse // unlocking a lock that wasn't locked..
  12401. }
  12402. void ReadWriteLock::enterWrite() const throw()
  12403. {
  12404. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12405. const ScopedLock sl (accessLock);
  12406. for (;;)
  12407. {
  12408. if (readerThreads.size() + numWriters == 0
  12409. || threadId == writerThreadId
  12410. || (readerThreads.size() == 2
  12411. && readerThreads.getUnchecked(0) == threadId))
  12412. {
  12413. writerThreadId = threadId;
  12414. ++numWriters;
  12415. break;
  12416. }
  12417. ++numWaitingWriters;
  12418. accessLock.exit();
  12419. waitEvent.wait (100);
  12420. accessLock.enter();
  12421. --numWaitingWriters;
  12422. }
  12423. }
  12424. bool ReadWriteLock::tryEnterWrite() const throw()
  12425. {
  12426. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12427. const ScopedLock sl (accessLock);
  12428. if (readerThreads.size() + numWriters == 0
  12429. || threadId == writerThreadId
  12430. || (readerThreads.size() == 2
  12431. && readerThreads.getUnchecked(0) == threadId))
  12432. {
  12433. writerThreadId = threadId;
  12434. ++numWriters;
  12435. return true;
  12436. }
  12437. return false;
  12438. }
  12439. void ReadWriteLock::exitWrite() const throw()
  12440. {
  12441. const ScopedLock sl (accessLock);
  12442. // check this thread actually had the lock..
  12443. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12444. if (--numWriters == 0)
  12445. {
  12446. writerThreadId = 0;
  12447. waitEvent.signal();
  12448. }
  12449. }
  12450. END_JUCE_NAMESPACE
  12451. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  12452. /********* Start of inlined file: juce_Thread.cpp *********/
  12453. BEGIN_JUCE_NAMESPACE
  12454. // these functions are implemented in the platform-specific code.
  12455. void* juce_createThread (void* userData) throw();
  12456. void juce_killThread (void* handle) throw();
  12457. bool juce_setThreadPriority (void* handle, int priority) throw();
  12458. void juce_setCurrentThreadName (const String& name) throw();
  12459. #if JUCE_WIN32
  12460. void juce_CloseThreadHandle (void* handle) throw();
  12461. #endif
  12462. static VoidArray runningThreads (4);
  12463. static CriticalSection runningThreadsLock;
  12464. void Thread::threadEntryPoint (Thread* const thread) throw()
  12465. {
  12466. {
  12467. const ScopedLock sl (runningThreadsLock);
  12468. runningThreads.add (thread);
  12469. }
  12470. JUCE_TRY
  12471. {
  12472. thread->threadId_ = Thread::getCurrentThreadId();
  12473. if (thread->threadName_.isNotEmpty())
  12474. juce_setCurrentThreadName (thread->threadName_);
  12475. if (thread->startSuspensionEvent_.wait (10000))
  12476. {
  12477. if (thread->affinityMask_ != 0)
  12478. setCurrentThreadAffinityMask (thread->affinityMask_);
  12479. thread->run();
  12480. }
  12481. }
  12482. JUCE_CATCH_ALL_ASSERT
  12483. {
  12484. const ScopedLock sl (runningThreadsLock);
  12485. jassert (runningThreads.contains (thread));
  12486. runningThreads.removeValue (thread);
  12487. }
  12488. #if JUCE_WIN32
  12489. juce_CloseThreadHandle (thread->threadHandle_);
  12490. #endif
  12491. thread->threadHandle_ = 0;
  12492. thread->threadId_ = 0;
  12493. }
  12494. // used to wrap the incoming call from the platform-specific code
  12495. void JUCE_API juce_threadEntryPoint (void* userData)
  12496. {
  12497. Thread::threadEntryPoint ((Thread*) userData);
  12498. }
  12499. Thread::Thread (const String& threadName)
  12500. : threadName_ (threadName),
  12501. threadHandle_ (0),
  12502. threadPriority_ (5),
  12503. threadId_ (0),
  12504. affinityMask_ (0),
  12505. threadShouldExit_ (false)
  12506. {
  12507. }
  12508. Thread::~Thread()
  12509. {
  12510. stopThread (100);
  12511. }
  12512. void Thread::startThread() throw()
  12513. {
  12514. const ScopedLock sl (startStopLock);
  12515. threadShouldExit_ = false;
  12516. if (threadHandle_ == 0)
  12517. {
  12518. threadHandle_ = juce_createThread ((void*) this);
  12519. juce_setThreadPriority (threadHandle_, threadPriority_);
  12520. startSuspensionEvent_.signal();
  12521. }
  12522. }
  12523. void Thread::startThread (const int priority) throw()
  12524. {
  12525. const ScopedLock sl (startStopLock);
  12526. if (threadHandle_ == 0)
  12527. {
  12528. threadPriority_ = priority;
  12529. startThread();
  12530. }
  12531. else
  12532. {
  12533. setPriority (priority);
  12534. }
  12535. }
  12536. bool Thread::isThreadRunning() const throw()
  12537. {
  12538. return threadHandle_ != 0;
  12539. }
  12540. void Thread::signalThreadShouldExit() throw()
  12541. {
  12542. threadShouldExit_ = true;
  12543. }
  12544. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  12545. {
  12546. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12547. jassert (getThreadId() != getCurrentThreadId());
  12548. const int sleepMsPerIteration = 5;
  12549. int count = timeOutMilliseconds / sleepMsPerIteration;
  12550. while (isThreadRunning())
  12551. {
  12552. if (timeOutMilliseconds > 0 && --count < 0)
  12553. return false;
  12554. sleep (sleepMsPerIteration);
  12555. }
  12556. return true;
  12557. }
  12558. void Thread::stopThread (const int timeOutMilliseconds) throw()
  12559. {
  12560. // agh! You can't stop the thread that's calling this method! How on earth
  12561. // would that work??
  12562. jassert (getCurrentThreadId() != getThreadId());
  12563. const ScopedLock sl (startStopLock);
  12564. if (isThreadRunning())
  12565. {
  12566. signalThreadShouldExit();
  12567. notify();
  12568. if (timeOutMilliseconds != 0)
  12569. waitForThreadToExit (timeOutMilliseconds);
  12570. if (isThreadRunning())
  12571. {
  12572. // very bad karma if this point is reached, as
  12573. // there are bound to be locks and events left in
  12574. // silly states when a thread is killed by force..
  12575. jassertfalse
  12576. Logger::writeToLog ("!! killing thread by force !!");
  12577. juce_killThread (threadHandle_);
  12578. threadHandle_ = 0;
  12579. threadId_ = 0;
  12580. const ScopedLock sl (runningThreadsLock);
  12581. runningThreads.removeValue (this);
  12582. }
  12583. }
  12584. }
  12585. bool Thread::setPriority (const int priority) throw()
  12586. {
  12587. const ScopedLock sl (startStopLock);
  12588. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12589. if (worked)
  12590. threadPriority_ = priority;
  12591. return worked;
  12592. }
  12593. bool Thread::setCurrentThreadPriority (const int priority) throw()
  12594. {
  12595. return juce_setThreadPriority (0, priority);
  12596. }
  12597. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  12598. {
  12599. affinityMask_ = affinityMask;
  12600. }
  12601. Thread::ThreadID Thread::getThreadId() const throw()
  12602. {
  12603. return threadId_;
  12604. }
  12605. bool Thread::wait (const int timeOutMilliseconds) const throw()
  12606. {
  12607. return defaultEvent_.wait (timeOutMilliseconds);
  12608. }
  12609. void Thread::notify() const throw()
  12610. {
  12611. defaultEvent_.signal();
  12612. }
  12613. int Thread::getNumRunningThreads() throw()
  12614. {
  12615. return runningThreads.size();
  12616. }
  12617. Thread* Thread::getCurrentThread() throw()
  12618. {
  12619. const ThreadID thisId = getCurrentThreadId();
  12620. const ScopedLock sl (runningThreadsLock);
  12621. for (int i = runningThreads.size(); --i >= 0;)
  12622. {
  12623. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  12624. if (t->threadId_ == thisId)
  12625. return t;
  12626. }
  12627. return 0;
  12628. }
  12629. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  12630. {
  12631. {
  12632. const ScopedLock sl (runningThreadsLock);
  12633. for (int i = runningThreads.size(); --i >= 0;)
  12634. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  12635. }
  12636. for (;;)
  12637. {
  12638. runningThreadsLock.enter();
  12639. Thread* const t = (Thread*) runningThreads[0];
  12640. runningThreadsLock.exit();
  12641. if (t == 0)
  12642. break;
  12643. t->stopThread (timeOutMilliseconds);
  12644. }
  12645. }
  12646. END_JUCE_NAMESPACE
  12647. /********* End of inlined file: juce_Thread.cpp *********/
  12648. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  12649. BEGIN_JUCE_NAMESPACE
  12650. ThreadPoolJob::ThreadPoolJob (const String& name)
  12651. : jobName (name),
  12652. pool (0),
  12653. shouldStop (false),
  12654. isActive (false),
  12655. shouldBeDeleted (false)
  12656. {
  12657. }
  12658. ThreadPoolJob::~ThreadPoolJob()
  12659. {
  12660. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12661. // to remove it first!
  12662. jassert (pool == 0 || ! pool->contains (this));
  12663. }
  12664. const String ThreadPoolJob::getJobName() const throw()
  12665. {
  12666. return jobName;
  12667. }
  12668. void ThreadPoolJob::setJobName (const String& newName) throw()
  12669. {
  12670. jobName = newName;
  12671. }
  12672. void ThreadPoolJob::signalJobShouldExit() throw()
  12673. {
  12674. shouldStop = true;
  12675. }
  12676. class ThreadPoolThread : public Thread
  12677. {
  12678. ThreadPool& pool;
  12679. bool volatile busy;
  12680. ThreadPoolThread (const ThreadPoolThread&);
  12681. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  12682. public:
  12683. ThreadPoolThread (ThreadPool& pool_)
  12684. : Thread (T("Pool")),
  12685. pool (pool_),
  12686. busy (false)
  12687. {
  12688. }
  12689. ~ThreadPoolThread()
  12690. {
  12691. }
  12692. void run()
  12693. {
  12694. while (! threadShouldExit())
  12695. {
  12696. if (! pool.runNextJob())
  12697. wait (500);
  12698. }
  12699. }
  12700. };
  12701. ThreadPool::ThreadPool (const int numThreads_,
  12702. const bool startThreadsOnlyWhenNeeded,
  12703. const int stopThreadsWhenNotUsedTimeoutMs)
  12704. : numThreads (jmax (1, numThreads_)),
  12705. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12706. priority (5)
  12707. {
  12708. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  12709. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  12710. for (int i = numThreads; --i >= 0;)
  12711. threads[i] = new ThreadPoolThread (*this);
  12712. if (! startThreadsOnlyWhenNeeded)
  12713. for (int i = numThreads; --i >= 0;)
  12714. threads[i]->startThread (priority);
  12715. }
  12716. ThreadPool::~ThreadPool()
  12717. {
  12718. removeAllJobs (true, 4000);
  12719. int i;
  12720. for (i = numThreads; --i >= 0;)
  12721. threads[i]->signalThreadShouldExit();
  12722. for (i = numThreads; --i >= 0;)
  12723. {
  12724. threads[i]->stopThread (500);
  12725. delete threads[i];
  12726. }
  12727. juce_free (threads);
  12728. }
  12729. void ThreadPool::addJob (ThreadPoolJob* const job)
  12730. {
  12731. jassert (job->pool == 0);
  12732. if (job->pool == 0)
  12733. {
  12734. job->pool = this;
  12735. job->shouldStop = false;
  12736. job->isActive = false;
  12737. lock.enter();
  12738. jobs.add (job);
  12739. int numRunning = 0;
  12740. int i;
  12741. for (i = numThreads; --i >= 0;)
  12742. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  12743. ++numRunning;
  12744. if (numRunning < numThreads)
  12745. {
  12746. bool startedOne = false;
  12747. int n = 1000;
  12748. while (--n >= 0 && ! startedOne)
  12749. {
  12750. for (int i = numThreads; --i >= 0;)
  12751. {
  12752. if (! threads[i]->isThreadRunning())
  12753. {
  12754. threads[i]->startThread (priority);
  12755. startedOne = true;
  12756. break;
  12757. }
  12758. }
  12759. if (! startedOne)
  12760. Thread::sleep (2);
  12761. }
  12762. }
  12763. lock.exit();
  12764. for (i = numThreads; --i >= 0;)
  12765. threads[i]->notify();
  12766. }
  12767. }
  12768. int ThreadPool::getNumJobs() const throw()
  12769. {
  12770. return jobs.size();
  12771. }
  12772. ThreadPoolJob* ThreadPool::getJob (const int index) const throw()
  12773. {
  12774. const ScopedLock sl (lock);
  12775. return (ThreadPoolJob*) jobs [index];
  12776. }
  12777. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  12778. {
  12779. const ScopedLock sl (lock);
  12780. return jobs.contains ((void*) job);
  12781. }
  12782. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12783. {
  12784. const ScopedLock sl (lock);
  12785. return jobs.contains ((void*) job) && job->isActive;
  12786. }
  12787. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12788. const int timeOutMs) const
  12789. {
  12790. if (job != 0)
  12791. {
  12792. const uint32 start = Time::getMillisecondCounter();
  12793. while (contains (job))
  12794. {
  12795. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12796. return false;
  12797. jobFinishedSignal.wait (2);
  12798. }
  12799. }
  12800. return true;
  12801. }
  12802. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12803. const bool interruptIfRunning,
  12804. const int timeOutMs)
  12805. {
  12806. if (job != 0)
  12807. {
  12808. lock.enter();
  12809. if (jobs.contains (job))
  12810. {
  12811. if (job->isActive)
  12812. {
  12813. if (interruptIfRunning)
  12814. job->signalJobShouldExit();
  12815. lock.exit();
  12816. return waitForJobToFinish (job, timeOutMs);
  12817. }
  12818. else
  12819. {
  12820. jobs.removeValue (job);
  12821. }
  12822. }
  12823. lock.exit();
  12824. }
  12825. return true;
  12826. }
  12827. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12828. const int timeOutMs,
  12829. const bool deleteInactiveJobs)
  12830. {
  12831. lock.enter();
  12832. for (int i = jobs.size(); --i >= 0;)
  12833. {
  12834. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  12835. if (job->isActive)
  12836. {
  12837. if (interruptRunningJobs)
  12838. job->signalJobShouldExit();
  12839. }
  12840. else
  12841. {
  12842. jobs.remove (i);
  12843. if (deleteInactiveJobs)
  12844. delete job;
  12845. }
  12846. }
  12847. lock.exit();
  12848. const uint32 start = Time::getMillisecondCounter();
  12849. while (jobs.size() > 0)
  12850. {
  12851. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12852. return false;
  12853. jobFinishedSignal.wait (2);
  12854. }
  12855. return true;
  12856. }
  12857. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const throw()
  12858. {
  12859. StringArray s;
  12860. const ScopedLock sl (lock);
  12861. for (int i = 0; i < jobs.size(); ++i)
  12862. {
  12863. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  12864. if (job->isActive || ! onlyReturnActiveJobs)
  12865. s.add (job->getJobName());
  12866. }
  12867. return s;
  12868. }
  12869. bool ThreadPool::setThreadPriorities (const int newPriority)
  12870. {
  12871. bool ok = true;
  12872. if (priority != newPriority)
  12873. {
  12874. priority = newPriority;
  12875. for (int i = numThreads; --i >= 0;)
  12876. if (! threads[i]->setPriority (newPriority))
  12877. ok = false;
  12878. }
  12879. return ok;
  12880. }
  12881. bool ThreadPool::runNextJob()
  12882. {
  12883. lock.enter();
  12884. ThreadPoolJob* job = 0;
  12885. for (int i = 0; i < jobs.size(); ++i)
  12886. {
  12887. job = (ThreadPoolJob*) jobs [i];
  12888. if (job != 0 && ! (job->isActive || job->shouldStop))
  12889. break;
  12890. job = 0;
  12891. }
  12892. if (job != 0)
  12893. {
  12894. job->isActive = true;
  12895. lock.exit();
  12896. JUCE_TRY
  12897. {
  12898. ThreadPoolJob::JobStatus result = job->runJob();
  12899. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12900. const ScopedLock sl (lock);
  12901. if (jobs.contains (job))
  12902. {
  12903. job->isActive = false;
  12904. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12905. {
  12906. job->pool = 0;
  12907. job->shouldStop = true;
  12908. jobs.removeValue (job);
  12909. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12910. delete job;
  12911. jobFinishedSignal.signal();
  12912. }
  12913. else
  12914. {
  12915. // move the job to the end of the queue if it wants another go
  12916. jobs.move (jobs.indexOf (job), -1);
  12917. }
  12918. }
  12919. }
  12920. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12921. catch (...)
  12922. {
  12923. lock.enter();
  12924. jobs.removeValue (job);
  12925. lock.exit();
  12926. }
  12927. #endif
  12928. }
  12929. else
  12930. {
  12931. lock.exit();
  12932. if (threadStopTimeout > 0
  12933. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12934. {
  12935. const ScopedLock sl (lock);
  12936. if (jobs.size() == 0)
  12937. for (int i = numThreads; --i >= 0;)
  12938. threads[i]->signalThreadShouldExit();
  12939. }
  12940. else
  12941. {
  12942. return false;
  12943. }
  12944. }
  12945. return true;
  12946. }
  12947. END_JUCE_NAMESPACE
  12948. /********* End of inlined file: juce_ThreadPool.cpp *********/
  12949. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  12950. BEGIN_JUCE_NAMESPACE
  12951. TimeSliceThread::TimeSliceThread (const String& threadName)
  12952. : Thread (threadName),
  12953. index (0),
  12954. clientBeingCalled (0),
  12955. clientsChanged (false)
  12956. {
  12957. }
  12958. TimeSliceThread::~TimeSliceThread()
  12959. {
  12960. stopThread (2000);
  12961. }
  12962. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12963. {
  12964. const ScopedLock sl (listLock);
  12965. clients.addIfNotAlreadyThere (client);
  12966. clientsChanged = true;
  12967. notify();
  12968. }
  12969. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12970. {
  12971. const ScopedLock sl1 (listLock);
  12972. clientsChanged = true;
  12973. // if there's a chance we're in the middle of calling this client, we need to
  12974. // also lock the outer lock..
  12975. if (clientBeingCalled == client)
  12976. {
  12977. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12978. const ScopedLock sl1 (callbackLock);
  12979. const ScopedLock sl2 (listLock);
  12980. clients.removeValue (client);
  12981. }
  12982. else
  12983. {
  12984. clients.removeValue (client);
  12985. }
  12986. }
  12987. int TimeSliceThread::getNumClients() const throw()
  12988. {
  12989. return clients.size();
  12990. }
  12991. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  12992. {
  12993. const ScopedLock sl (listLock);
  12994. return clients [index];
  12995. }
  12996. void TimeSliceThread::run()
  12997. {
  12998. int numCallsSinceBusy = 0;
  12999. while (! threadShouldExit())
  13000. {
  13001. int timeToWait = 500;
  13002. {
  13003. const ScopedLock sl (callbackLock);
  13004. {
  13005. const ScopedLock sl (listLock);
  13006. if (clients.size() > 0)
  13007. {
  13008. index = (index + 1) % clients.size();
  13009. clientBeingCalled = clients [index];
  13010. }
  13011. else
  13012. {
  13013. index = 0;
  13014. clientBeingCalled = 0;
  13015. }
  13016. if (clientsChanged)
  13017. {
  13018. clientsChanged = false;
  13019. numCallsSinceBusy = 0;
  13020. }
  13021. }
  13022. if (clientBeingCalled != 0)
  13023. {
  13024. if (clientBeingCalled->useTimeSlice())
  13025. numCallsSinceBusy = 0;
  13026. else
  13027. ++numCallsSinceBusy;
  13028. if (numCallsSinceBusy >= clients.size())
  13029. timeToWait = 500;
  13030. else if (index == 0)
  13031. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13032. else
  13033. timeToWait = 0;
  13034. }
  13035. }
  13036. if (timeToWait > 0)
  13037. wait (timeToWait);
  13038. }
  13039. }
  13040. END_JUCE_NAMESPACE
  13041. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  13042. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  13043. /********* Start of inlined file: juce_Application.cpp *********/
  13044. #if JUCE_MSVC
  13045. #pragma warning (push)
  13046. #pragma warning (disable: 4245 4514 4100)
  13047. #include <crtdbg.h>
  13048. #pragma warning (pop)
  13049. #endif
  13050. BEGIN_JUCE_NAMESPACE
  13051. void juce_setCurrentThreadName (const String& name) throw();
  13052. static JUCEApplication* appInstance = 0;
  13053. JUCEApplication::JUCEApplication()
  13054. : appReturnValue (0),
  13055. stillInitialising (true),
  13056. appLock (0)
  13057. {
  13058. }
  13059. JUCEApplication::~JUCEApplication()
  13060. {
  13061. if (appLock != 0)
  13062. {
  13063. appLock->exit();
  13064. delete appLock;
  13065. }
  13066. }
  13067. JUCEApplication* JUCEApplication::getInstance() throw()
  13068. {
  13069. return appInstance;
  13070. }
  13071. bool JUCEApplication::isInitialising() const throw()
  13072. {
  13073. return stillInitialising;
  13074. }
  13075. const String JUCEApplication::getApplicationVersion()
  13076. {
  13077. return String::empty;
  13078. }
  13079. bool JUCEApplication::moreThanOneInstanceAllowed()
  13080. {
  13081. return true;
  13082. }
  13083. void JUCEApplication::anotherInstanceStarted (const String&)
  13084. {
  13085. }
  13086. void JUCEApplication::systemRequestedQuit()
  13087. {
  13088. quit();
  13089. }
  13090. void JUCEApplication::quit()
  13091. {
  13092. MessageManager::getInstance()->stopDispatchLoop();
  13093. }
  13094. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13095. {
  13096. appReturnValue = newReturnValue;
  13097. }
  13098. void JUCEApplication::unhandledException (const std::exception*,
  13099. const String&,
  13100. const int)
  13101. {
  13102. jassertfalse
  13103. }
  13104. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13105. const char* const sourceFile,
  13106. const int lineNumber)
  13107. {
  13108. if (appInstance != 0)
  13109. appInstance->unhandledException (e, sourceFile, lineNumber);
  13110. }
  13111. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13112. {
  13113. return 0;
  13114. }
  13115. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13116. {
  13117. commands.add (StandardApplicationCommandIDs::quit);
  13118. }
  13119. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13120. {
  13121. if (commandID == StandardApplicationCommandIDs::quit)
  13122. {
  13123. result.setInfo ("Quit",
  13124. "Quits the application",
  13125. "Application",
  13126. 0);
  13127. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  13128. }
  13129. }
  13130. bool JUCEApplication::perform (const InvocationInfo& info)
  13131. {
  13132. if (info.commandID == StandardApplicationCommandIDs::quit)
  13133. {
  13134. systemRequestedQuit();
  13135. return true;
  13136. }
  13137. return false;
  13138. }
  13139. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13140. {
  13141. if (! app->initialiseApp (commandLine))
  13142. return 0;
  13143. // now loop until a quit message is received..
  13144. JUCE_TRY
  13145. {
  13146. MessageManager::getInstance()->runDispatchLoop();
  13147. }
  13148. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13149. catch (const std::exception& e)
  13150. {
  13151. app->unhandledException (&e, __FILE__, __LINE__);
  13152. }
  13153. catch (...)
  13154. {
  13155. app->unhandledException (0, __FILE__, __LINE__);
  13156. }
  13157. #endif
  13158. return shutdownAppAndClearUp();
  13159. }
  13160. bool JUCEApplication::initialiseApp (String& commandLine)
  13161. {
  13162. jassert (appInstance == 0);
  13163. appInstance = this;
  13164. commandLineParameters = commandLine.trim();
  13165. commandLine = String::empty;
  13166. initialiseJuce_GUI();
  13167. jassert (appLock == 0); // initialiseApp must only be called once!
  13168. if (! moreThanOneInstanceAllowed())
  13169. {
  13170. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13171. if (! appLock->enter(0))
  13172. {
  13173. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13174. delete appInstance;
  13175. appInstance = 0;
  13176. DBG ("Another instance is running - quitting...");
  13177. return false;
  13178. }
  13179. }
  13180. // let the app do its setting-up..
  13181. initialise (commandLineParameters);
  13182. // register for broadcast new app messages
  13183. MessageManager::getInstance()->registerBroadcastListener (this);
  13184. stillInitialising = false;
  13185. return true;
  13186. }
  13187. int JUCEApplication::shutdownAppAndClearUp()
  13188. {
  13189. jassert (appInstance != 0);
  13190. JUCEApplication* const app = appInstance;
  13191. int returnValue = 0;
  13192. MessageManager::getInstance()->deregisterBroadcastListener (app);
  13193. static bool reentrancyCheck = false;
  13194. if (! reentrancyCheck)
  13195. {
  13196. reentrancyCheck = true;
  13197. JUCE_TRY
  13198. {
  13199. // give the app a chance to clean up..
  13200. app->shutdown();
  13201. }
  13202. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13203. catch (const std::exception& e)
  13204. {
  13205. app->unhandledException (&e, __FILE__, __LINE__);
  13206. }
  13207. catch (...)
  13208. {
  13209. app->unhandledException (0, __FILE__, __LINE__);
  13210. }
  13211. #endif
  13212. JUCE_TRY
  13213. {
  13214. shutdownJuce_GUI();
  13215. returnValue = app->getApplicationReturnValue();
  13216. appInstance = 0;
  13217. delete app;
  13218. }
  13219. JUCE_CATCH_ALL_ASSERT
  13220. reentrancyCheck = false;
  13221. }
  13222. return returnValue;
  13223. }
  13224. #if JUCE_IPHONE
  13225. extern int juce_IPhoneMain (int argc, char* argv[], JUCEApplication* app);
  13226. #endif
  13227. int JUCEApplication::main (int argc, char* argv[],
  13228. JUCEApplication* const newApp)
  13229. {
  13230. #if JUCE_IPHONE
  13231. const ScopedAutoReleasePool pool;
  13232. return juce_IPhoneMain (argc, argv, newApp);
  13233. #else
  13234. #if JUCE_MAC
  13235. const ScopedAutoReleasePool pool;
  13236. #endif
  13237. String cmd;
  13238. for (int i = 1; i < argc; ++i)
  13239. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  13240. return JUCEApplication::main (cmd, newApp);
  13241. #endif
  13242. }
  13243. void JUCEApplication::actionListenerCallback (const String& message)
  13244. {
  13245. if (message.startsWith (getApplicationName() + "/"))
  13246. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13247. }
  13248. static bool juceInitialisedGUI = false;
  13249. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13250. {
  13251. if (! juceInitialisedGUI)
  13252. {
  13253. #if JUCE_MAC || JUCE_IPHONE
  13254. const ScopedAutoReleasePool pool;
  13255. #endif
  13256. juceInitialisedGUI = true;
  13257. initialiseJuce_NonGUI();
  13258. MessageManager::getInstance();
  13259. LookAndFeel::setDefaultLookAndFeel (0);
  13260. juce_setCurrentThreadName ("Juce Message Thread");
  13261. #if JUCE_WINDOWS && JUCE_DEBUG
  13262. // This section is just for catching people who mess up their project settings and
  13263. // turn RTTI off..
  13264. try
  13265. {
  13266. TextButton tb (String::empty);
  13267. Component* c = &tb;
  13268. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13269. c = dynamic_cast <Button*> (c);
  13270. }
  13271. catch (...)
  13272. {
  13273. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13274. // got as far as this catch statement, then why haven't you got exception catching
  13275. // turned on in the debugger???
  13276. jassertfalse
  13277. }
  13278. #endif
  13279. }
  13280. }
  13281. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13282. {
  13283. if (juceInitialisedGUI)
  13284. {
  13285. #if JUCE_MAC
  13286. const ScopedAutoReleasePool pool;
  13287. #endif
  13288. {
  13289. DeletedAtShutdown::deleteAll();
  13290. LookAndFeel::clearDefaultLookAndFeel();
  13291. }
  13292. delete MessageManager::getInstance();
  13293. shutdownJuce_NonGUI();
  13294. juceInitialisedGUI = false;
  13295. }
  13296. }
  13297. END_JUCE_NAMESPACE
  13298. /********* End of inlined file: juce_Application.cpp *********/
  13299. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13300. BEGIN_JUCE_NAMESPACE
  13301. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13302. : commandID (commandID_),
  13303. flags (0)
  13304. {
  13305. }
  13306. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13307. const String& description_,
  13308. const String& categoryName_,
  13309. const int flags_) throw()
  13310. {
  13311. shortName = shortName_;
  13312. description = description_;
  13313. categoryName = categoryName_;
  13314. flags = flags_;
  13315. }
  13316. void ApplicationCommandInfo::setActive (const bool b) throw()
  13317. {
  13318. if (b)
  13319. flags &= ~isDisabled;
  13320. else
  13321. flags |= isDisabled;
  13322. }
  13323. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13324. {
  13325. if (b)
  13326. flags |= isTicked;
  13327. else
  13328. flags &= ~isTicked;
  13329. }
  13330. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13331. {
  13332. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13333. }
  13334. END_JUCE_NAMESPACE
  13335. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13336. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  13337. BEGIN_JUCE_NAMESPACE
  13338. ApplicationCommandManager::ApplicationCommandManager()
  13339. : listeners (8),
  13340. firstTarget (0)
  13341. {
  13342. keyMappings = new KeyPressMappingSet (this);
  13343. Desktop::getInstance().addFocusChangeListener (this);
  13344. }
  13345. ApplicationCommandManager::~ApplicationCommandManager()
  13346. {
  13347. Desktop::getInstance().removeFocusChangeListener (this);
  13348. deleteAndZero (keyMappings);
  13349. }
  13350. void ApplicationCommandManager::clearCommands()
  13351. {
  13352. commands.clear();
  13353. keyMappings->clearAllKeyPresses();
  13354. triggerAsyncUpdate();
  13355. }
  13356. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13357. {
  13358. // zero isn't a valid command ID!
  13359. jassert (newCommand.commandID != 0);
  13360. // the name isn't optional!
  13361. jassert (newCommand.shortName.isNotEmpty());
  13362. if (getCommandForID (newCommand.commandID) == 0)
  13363. {
  13364. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13365. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13366. commands.add (newInfo);
  13367. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13368. triggerAsyncUpdate();
  13369. }
  13370. else
  13371. {
  13372. // trying to re-register the same command with different parameters?
  13373. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13374. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13375. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13376. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13377. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13378. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13379. }
  13380. }
  13381. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13382. {
  13383. if (target != 0)
  13384. {
  13385. Array <CommandID> commandIDs;
  13386. target->getAllCommands (commandIDs);
  13387. for (int i = 0; i < commandIDs.size(); ++i)
  13388. {
  13389. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13390. target->getCommandInfo (info.commandID, info);
  13391. registerCommand (info);
  13392. }
  13393. }
  13394. }
  13395. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13396. {
  13397. for (int i = commands.size(); --i >= 0;)
  13398. {
  13399. if (commands.getUnchecked (i)->commandID == commandID)
  13400. {
  13401. commands.remove (i);
  13402. triggerAsyncUpdate();
  13403. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13404. for (int j = keys.size(); --j >= 0;)
  13405. keyMappings->removeKeyPress (keys.getReference (j));
  13406. }
  13407. }
  13408. }
  13409. void ApplicationCommandManager::commandStatusChanged()
  13410. {
  13411. triggerAsyncUpdate();
  13412. }
  13413. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13414. {
  13415. for (int i = commands.size(); --i >= 0;)
  13416. if (commands.getUnchecked(i)->commandID == commandID)
  13417. return commands.getUnchecked(i);
  13418. return 0;
  13419. }
  13420. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13421. {
  13422. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13423. return (ci != 0) ? ci->shortName : String::empty;
  13424. }
  13425. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13426. {
  13427. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13428. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13429. : String::empty;
  13430. }
  13431. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13432. {
  13433. StringArray s;
  13434. for (int i = 0; i < commands.size(); ++i)
  13435. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13436. return s;
  13437. }
  13438. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13439. {
  13440. Array <CommandID> results (4);
  13441. for (int i = 0; i < commands.size(); ++i)
  13442. if (commands.getUnchecked(i)->categoryName == categoryName)
  13443. results.add (commands.getUnchecked(i)->commandID);
  13444. return results;
  13445. }
  13446. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13447. {
  13448. ApplicationCommandTarget::InvocationInfo info (commandID);
  13449. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13450. return invoke (info, asynchronously);
  13451. }
  13452. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13453. {
  13454. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13455. // manager first..
  13456. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13457. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13458. if (target == 0)
  13459. return false;
  13460. ApplicationCommandInfo commandInfo (0);
  13461. target->getCommandInfo (info_.commandID, commandInfo);
  13462. ApplicationCommandTarget::InvocationInfo info (info_);
  13463. info.commandFlags = commandInfo.flags;
  13464. sendListenerInvokeCallback (info);
  13465. const bool ok = target->invoke (info, asynchronously);
  13466. commandStatusChanged();
  13467. return ok;
  13468. }
  13469. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13470. {
  13471. return firstTarget != 0 ? firstTarget
  13472. : findDefaultComponentTarget();
  13473. }
  13474. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13475. {
  13476. firstTarget = newTarget;
  13477. }
  13478. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13479. ApplicationCommandInfo& upToDateInfo)
  13480. {
  13481. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13482. if (target == 0)
  13483. target = JUCEApplication::getInstance();
  13484. if (target != 0)
  13485. target = target->getTargetForCommand (commandID);
  13486. if (target != 0)
  13487. target->getCommandInfo (commandID, upToDateInfo);
  13488. return target;
  13489. }
  13490. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13491. {
  13492. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13493. if (target == 0 && c != 0)
  13494. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13495. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13496. return target;
  13497. }
  13498. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13499. {
  13500. Component* c = Component::getCurrentlyFocusedComponent();
  13501. if (c == 0)
  13502. {
  13503. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13504. if (activeWindow != 0)
  13505. {
  13506. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13507. if (c == 0)
  13508. c = activeWindow;
  13509. }
  13510. }
  13511. if (c == 0 && Process::isForegroundProcess())
  13512. {
  13513. // getting a bit desperate now - try all desktop comps..
  13514. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13515. {
  13516. ApplicationCommandTarget* const target
  13517. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13518. ->getPeer()->getLastFocusedSubcomponent());
  13519. if (target != 0)
  13520. return target;
  13521. }
  13522. }
  13523. if (c != 0)
  13524. {
  13525. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  13526. // if we're focused on a ResizableWindow, chances are that it's the content
  13527. // component that really should get the event. And if not, the event will
  13528. // still be passed up to the top level window anyway, so let's send it to the
  13529. // content comp.
  13530. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  13531. c = resizableWindow->getContentComponent();
  13532. ApplicationCommandTarget* const target = findTargetForComponent (c);
  13533. if (target != 0)
  13534. return target;
  13535. }
  13536. return JUCEApplication::getInstance();
  13537. }
  13538. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  13539. {
  13540. jassert (listener != 0);
  13541. if (listener != 0)
  13542. listeners.add (listener);
  13543. }
  13544. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  13545. {
  13546. listeners.removeValue (listener);
  13547. }
  13548. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  13549. {
  13550. for (int i = listeners.size(); --i >= 0;)
  13551. {
  13552. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  13553. i = jmin (i, listeners.size());
  13554. }
  13555. }
  13556. void ApplicationCommandManager::handleAsyncUpdate()
  13557. {
  13558. for (int i = listeners.size(); --i >= 0;)
  13559. {
  13560. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  13561. i = jmin (i, listeners.size());
  13562. }
  13563. }
  13564. void ApplicationCommandManager::globalFocusChanged (Component*)
  13565. {
  13566. commandStatusChanged();
  13567. }
  13568. END_JUCE_NAMESPACE
  13569. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  13570. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13571. BEGIN_JUCE_NAMESPACE
  13572. ApplicationCommandTarget::ApplicationCommandTarget()
  13573. : messageInvoker (0)
  13574. {
  13575. }
  13576. ApplicationCommandTarget::~ApplicationCommandTarget()
  13577. {
  13578. deleteAndZero (messageInvoker);
  13579. }
  13580. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  13581. {
  13582. if (isCommandActive (info.commandID))
  13583. {
  13584. if (async)
  13585. {
  13586. if (messageInvoker == 0)
  13587. messageInvoker = new CommandTargetMessageInvoker (this);
  13588. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  13589. return true;
  13590. }
  13591. else
  13592. {
  13593. const bool success = perform (info);
  13594. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  13595. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  13596. // returns the command's info.
  13597. return success;
  13598. }
  13599. }
  13600. return false;
  13601. }
  13602. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  13603. {
  13604. Component* c = dynamic_cast <Component*> (this);
  13605. if (c != 0)
  13606. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13607. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13608. return 0;
  13609. }
  13610. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  13611. {
  13612. ApplicationCommandTarget* target = this;
  13613. int depth = 0;
  13614. while (target != 0)
  13615. {
  13616. Array <CommandID> commandIDs;
  13617. target->getAllCommands (commandIDs);
  13618. if (commandIDs.contains (commandID))
  13619. return target;
  13620. target = target->getNextCommandTarget();
  13621. ++depth;
  13622. jassert (depth < 100); // could be a recursive command chain??
  13623. jassert (target != this); // definitely a recursive command chain!
  13624. if (depth > 100 || target == this)
  13625. break;
  13626. }
  13627. if (target == 0)
  13628. {
  13629. target = JUCEApplication::getInstance();
  13630. if (target != 0)
  13631. {
  13632. Array <CommandID> commandIDs;
  13633. target->getAllCommands (commandIDs);
  13634. if (commandIDs.contains (commandID))
  13635. return target;
  13636. }
  13637. }
  13638. return 0;
  13639. }
  13640. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  13641. {
  13642. ApplicationCommandInfo info (commandID);
  13643. info.flags = ApplicationCommandInfo::isDisabled;
  13644. getCommandInfo (commandID, info);
  13645. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  13646. }
  13647. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  13648. {
  13649. ApplicationCommandTarget* target = this;
  13650. int depth = 0;
  13651. while (target != 0)
  13652. {
  13653. if (target->tryToInvoke (info, async))
  13654. return true;
  13655. target = target->getNextCommandTarget();
  13656. ++depth;
  13657. jassert (depth < 100); // could be a recursive command chain??
  13658. jassert (target != this); // definitely a recursive command chain!
  13659. if (depth > 100 || target == this)
  13660. break;
  13661. }
  13662. if (target == 0)
  13663. {
  13664. target = JUCEApplication::getInstance();
  13665. if (target != 0)
  13666. return target->tryToInvoke (info, async);
  13667. }
  13668. return false;
  13669. }
  13670. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13671. {
  13672. ApplicationCommandTarget::InvocationInfo info (commandID);
  13673. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13674. return invoke (info, asynchronously);
  13675. }
  13676. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  13677. : commandID (commandID_),
  13678. commandFlags (0),
  13679. invocationMethod (direct),
  13680. originatingComponent (0),
  13681. isKeyDown (false),
  13682. millisecsSinceKeyPressed (0)
  13683. {
  13684. }
  13685. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  13686. : owner (owner_)
  13687. {
  13688. }
  13689. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  13690. {
  13691. }
  13692. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  13693. {
  13694. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  13695. owner->tryToInvoke (*info, false);
  13696. delete info;
  13697. }
  13698. END_JUCE_NAMESPACE
  13699. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13700. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  13701. BEGIN_JUCE_NAMESPACE
  13702. juce_ImplementSingleton (ApplicationProperties)
  13703. ApplicationProperties::ApplicationProperties() throw()
  13704. : userProps (0),
  13705. commonProps (0),
  13706. msBeforeSaving (3000),
  13707. options (PropertiesFile::storeAsBinary),
  13708. commonSettingsAreReadOnly (0)
  13709. {
  13710. }
  13711. ApplicationProperties::~ApplicationProperties()
  13712. {
  13713. closeFiles();
  13714. clearSingletonInstance();
  13715. }
  13716. void ApplicationProperties::setStorageParameters (const String& applicationName,
  13717. const String& fileNameSuffix,
  13718. const String& folderName_,
  13719. const int millisecondsBeforeSaving,
  13720. const int propertiesFileOptions) throw()
  13721. {
  13722. appName = applicationName;
  13723. fileSuffix = fileNameSuffix;
  13724. folderName = folderName_;
  13725. msBeforeSaving = millisecondsBeforeSaving;
  13726. options = propertiesFileOptions;
  13727. }
  13728. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  13729. const bool testCommonSettings,
  13730. const bool showWarningDialogOnFailure)
  13731. {
  13732. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  13733. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  13734. if (! (userOk && commonOk))
  13735. {
  13736. if (showWarningDialogOnFailure)
  13737. {
  13738. String filenames;
  13739. if (userProps != 0 && ! userOk)
  13740. filenames << '\n' << userProps->getFile().getFullPathName();
  13741. if (commonProps != 0 && ! commonOk)
  13742. filenames << '\n' << commonProps->getFile().getFullPathName();
  13743. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13744. appName + TRANS(" - Unable to save settings"),
  13745. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  13746. + appName + TRANS(" needs to be able to write to the following files:\n")
  13747. + filenames
  13748. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  13749. }
  13750. return false;
  13751. }
  13752. return true;
  13753. }
  13754. void ApplicationProperties::openFiles() throw()
  13755. {
  13756. // You need to call setStorageParameters() before trying to get hold of the
  13757. // properties!
  13758. jassert (appName.isNotEmpty());
  13759. if (appName.isNotEmpty())
  13760. {
  13761. if (userProps == 0)
  13762. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13763. false, msBeforeSaving, options);
  13764. if (commonProps == 0)
  13765. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13766. true, msBeforeSaving, options);
  13767. userProps->setFallbackPropertySet (commonProps);
  13768. }
  13769. }
  13770. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  13771. {
  13772. if (userProps == 0)
  13773. openFiles();
  13774. return userProps;
  13775. }
  13776. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  13777. {
  13778. if (commonProps == 0)
  13779. openFiles();
  13780. if (returnUserPropsIfReadOnly)
  13781. {
  13782. if (commonSettingsAreReadOnly == 0)
  13783. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  13784. if (commonSettingsAreReadOnly > 0)
  13785. return userProps;
  13786. }
  13787. return commonProps;
  13788. }
  13789. bool ApplicationProperties::saveIfNeeded()
  13790. {
  13791. return (userProps == 0 || userProps->saveIfNeeded())
  13792. && (commonProps == 0 || commonProps->saveIfNeeded());
  13793. }
  13794. void ApplicationProperties::closeFiles()
  13795. {
  13796. deleteAndZero (userProps);
  13797. deleteAndZero (commonProps);
  13798. }
  13799. END_JUCE_NAMESPACE
  13800. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  13801. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  13802. BEGIN_JUCE_NAMESPACE
  13803. static VoidArray objectsToDelete (16);
  13804. static CriticalSection lock;
  13805. DeletedAtShutdown::DeletedAtShutdown() throw()
  13806. {
  13807. const ScopedLock sl (lock);
  13808. objectsToDelete.add (this);
  13809. }
  13810. DeletedAtShutdown::~DeletedAtShutdown()
  13811. {
  13812. const ScopedLock sl (lock);
  13813. objectsToDelete.removeValue (this);
  13814. }
  13815. void DeletedAtShutdown::deleteAll()
  13816. {
  13817. // make a local copy of the array, so it can't get into a loop if something
  13818. // creates another DeletedAtShutdown object during its destructor.
  13819. lock.enter();
  13820. const VoidArray localCopy (objectsToDelete);
  13821. lock.exit();
  13822. for (int i = localCopy.size(); --i >= 0;)
  13823. {
  13824. JUCE_TRY
  13825. {
  13826. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  13827. // double-check that it's not already been deleted during another object's destructor.
  13828. lock.enter();
  13829. const bool okToDelete = objectsToDelete.contains (deletee);
  13830. lock.exit();
  13831. if (okToDelete)
  13832. delete deletee;
  13833. }
  13834. JUCE_CATCH_EXCEPTION
  13835. }
  13836. // if no objects got re-created during shutdown, this should have been emptied by their
  13837. // destructors
  13838. jassert (objectsToDelete.size() == 0);
  13839. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  13840. }
  13841. END_JUCE_NAMESPACE
  13842. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  13843. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  13844. BEGIN_JUCE_NAMESPACE
  13845. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  13846. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  13847. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  13848. static const tchar* const propertyTagName = T("VALUE");
  13849. PropertiesFile::PropertiesFile (const File& f,
  13850. const int millisecondsBeforeSaving,
  13851. const int options_) throw()
  13852. : PropertySet (ignoreCaseOfKeyNames),
  13853. file (f),
  13854. timerInterval (millisecondsBeforeSaving),
  13855. options (options_),
  13856. needsWriting (false)
  13857. {
  13858. // You need to correctly specify just one storage format for the file
  13859. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  13860. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  13861. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  13862. InputStream* fileStream = f.createInputStream();
  13863. if (fileStream != 0)
  13864. {
  13865. int magicNumber = fileStream->readInt();
  13866. if (magicNumber == propFileMagicNumberCompressed)
  13867. {
  13868. fileStream = new SubregionStream (fileStream, 4, -1, true);
  13869. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  13870. magicNumber = propFileMagicNumber;
  13871. }
  13872. if (magicNumber == propFileMagicNumber)
  13873. {
  13874. BufferedInputStream in (fileStream, 2048, true);
  13875. int numValues = in.readInt();
  13876. while (--numValues >= 0 && ! in.isExhausted())
  13877. {
  13878. const String key (in.readString());
  13879. const String value (in.readString());
  13880. jassert (key.isNotEmpty());
  13881. if (key.isNotEmpty())
  13882. getAllProperties().set (key, value);
  13883. }
  13884. }
  13885. else
  13886. {
  13887. // Not a binary props file - let's see if it's XML..
  13888. delete fileStream;
  13889. XmlDocument parser (f);
  13890. XmlElement* doc = parser.getDocumentElement (true);
  13891. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  13892. {
  13893. delete doc;
  13894. doc = parser.getDocumentElement();
  13895. if (doc != 0)
  13896. {
  13897. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  13898. {
  13899. const String name (e->getStringAttribute (T("name")));
  13900. if (name.isNotEmpty())
  13901. {
  13902. getAllProperties().set (name,
  13903. e->getFirstChildElement() != 0
  13904. ? e->getFirstChildElement()->createDocument (String::empty, true)
  13905. : e->getStringAttribute (T("val")));
  13906. }
  13907. }
  13908. }
  13909. else
  13910. {
  13911. // must be a pretty broken XML file we're trying to parse here!
  13912. jassertfalse
  13913. }
  13914. delete doc;
  13915. }
  13916. }
  13917. }
  13918. }
  13919. PropertiesFile::~PropertiesFile()
  13920. {
  13921. saveIfNeeded();
  13922. }
  13923. bool PropertiesFile::saveIfNeeded()
  13924. {
  13925. const ScopedLock sl (getLock());
  13926. return (! needsWriting) || save();
  13927. }
  13928. bool PropertiesFile::needsToBeSaved() const throw()
  13929. {
  13930. const ScopedLock sl (getLock());
  13931. return needsWriting;
  13932. }
  13933. bool PropertiesFile::save()
  13934. {
  13935. const ScopedLock sl (getLock());
  13936. stopTimer();
  13937. if (file == File::nonexistent
  13938. || file.isDirectory()
  13939. || ! file.getParentDirectory().createDirectory())
  13940. return false;
  13941. if ((options & storeAsXML) != 0)
  13942. {
  13943. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  13944. for (int i = 0; i < getAllProperties().size(); ++i)
  13945. {
  13946. XmlElement* const e = new XmlElement (propertyTagName);
  13947. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  13948. // if the value seems to contain xml, store it as such..
  13949. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  13950. XmlElement* const childElement = xmlContent.getDocumentElement();
  13951. if (childElement != 0)
  13952. e->addChildElement (childElement);
  13953. else
  13954. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  13955. doc->addChildElement (e);
  13956. }
  13957. const bool ok = doc->writeToFile (file, String::empty);
  13958. delete doc;
  13959. return ok;
  13960. }
  13961. else
  13962. {
  13963. const File tempFile (file.getNonexistentSibling (false));
  13964. OutputStream* out = tempFile.createOutputStream();
  13965. if (out != 0)
  13966. {
  13967. if ((options & storeAsCompressedBinary) != 0)
  13968. {
  13969. out->writeInt (propFileMagicNumberCompressed);
  13970. out->flush();
  13971. out = new GZIPCompressorOutputStream (out, 9, true);
  13972. }
  13973. else
  13974. {
  13975. // have you set up the storage option flags correctly?
  13976. jassert ((options & storeAsBinary) != 0);
  13977. out->writeInt (propFileMagicNumber);
  13978. }
  13979. const int numProperties = getAllProperties().size();
  13980. out->writeInt (numProperties);
  13981. for (int i = 0; i < numProperties; ++i)
  13982. {
  13983. out->writeString (getAllProperties().getAllKeys() [i]);
  13984. out->writeString (getAllProperties().getAllValues() [i]);
  13985. }
  13986. out->flush();
  13987. delete out;
  13988. if (tempFile.moveFileTo (file))
  13989. {
  13990. needsWriting = false;
  13991. return true;
  13992. }
  13993. tempFile.deleteFile();
  13994. }
  13995. }
  13996. return false;
  13997. }
  13998. void PropertiesFile::timerCallback()
  13999. {
  14000. saveIfNeeded();
  14001. }
  14002. void PropertiesFile::propertyChanged()
  14003. {
  14004. sendChangeMessage (this);
  14005. needsWriting = true;
  14006. if (timerInterval > 0)
  14007. startTimer (timerInterval);
  14008. else if (timerInterval == 0)
  14009. saveIfNeeded();
  14010. }
  14011. const File PropertiesFile::getFile() const throw()
  14012. {
  14013. return file;
  14014. }
  14015. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14016. const String& fileNameSuffix,
  14017. const String& folderName,
  14018. const bool commonToAllUsers)
  14019. {
  14020. // mustn't have illegal characters in this name..
  14021. jassert (applicationName == File::createLegalFileName (applicationName));
  14022. #if JUCE_MAC || JUCE_IPHONE
  14023. File dir (commonToAllUsers ? "/Library/Preferences"
  14024. : "~/Library/Preferences");
  14025. if (folderName.isNotEmpty())
  14026. dir = dir.getChildFile (folderName);
  14027. #endif
  14028. #ifdef JUCE_LINUX
  14029. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  14030. + (folderName.isNotEmpty() ? folderName
  14031. : (T(".") + applicationName)));
  14032. #endif
  14033. #if JUCE_WIN32
  14034. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14035. : File::userApplicationDataDirectory));
  14036. if (dir == File::nonexistent)
  14037. return File::nonexistent;
  14038. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14039. : applicationName);
  14040. #endif
  14041. return dir.getChildFile (applicationName)
  14042. .withFileExtension (fileNameSuffix);
  14043. }
  14044. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14045. const String& fileNameSuffix,
  14046. const String& folderName,
  14047. const bool commonToAllUsers,
  14048. const int millisecondsBeforeSaving,
  14049. const int propertiesFileOptions)
  14050. {
  14051. const File file (getDefaultAppSettingsFile (applicationName,
  14052. fileNameSuffix,
  14053. folderName,
  14054. commonToAllUsers));
  14055. jassert (file != File::nonexistent);
  14056. if (file == File::nonexistent)
  14057. return 0;
  14058. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  14059. }
  14060. END_JUCE_NAMESPACE
  14061. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  14062. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  14063. BEGIN_JUCE_NAMESPACE
  14064. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14065. const String& fileWildcard_,
  14066. const String& openFileDialogTitle_,
  14067. const String& saveFileDialogTitle_)
  14068. : changedSinceSave (false),
  14069. fileExtension (fileExtension_),
  14070. fileWildcard (fileWildcard_),
  14071. openFileDialogTitle (openFileDialogTitle_),
  14072. saveFileDialogTitle (saveFileDialogTitle_)
  14073. {
  14074. }
  14075. FileBasedDocument::~FileBasedDocument()
  14076. {
  14077. }
  14078. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14079. {
  14080. changedSinceSave = hasChanged;
  14081. }
  14082. void FileBasedDocument::changed()
  14083. {
  14084. changedSinceSave = true;
  14085. sendChangeMessage (this);
  14086. }
  14087. void FileBasedDocument::setFile (const File& newFile)
  14088. {
  14089. if (documentFile != newFile)
  14090. {
  14091. documentFile = newFile;
  14092. changedSinceSave = true;
  14093. }
  14094. }
  14095. bool FileBasedDocument::loadFrom (const File& newFile,
  14096. const bool showMessageOnFailure)
  14097. {
  14098. MouseCursor::showWaitCursor();
  14099. const File oldFile (documentFile);
  14100. documentFile = newFile;
  14101. String error;
  14102. if (newFile.existsAsFile())
  14103. {
  14104. error = loadDocument (newFile);
  14105. if (error.isEmpty())
  14106. {
  14107. setChangedFlag (false);
  14108. MouseCursor::hideWaitCursor();
  14109. setLastDocumentOpened (newFile);
  14110. return true;
  14111. }
  14112. }
  14113. else
  14114. {
  14115. error = "The file doesn't exist";
  14116. }
  14117. documentFile = oldFile;
  14118. MouseCursor::hideWaitCursor();
  14119. if (showMessageOnFailure)
  14120. {
  14121. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14122. TRANS("Failed to open file..."),
  14123. TRANS("There was an error while trying to load the file:\n\n")
  14124. + newFile.getFullPathName()
  14125. + T("\n\n")
  14126. + error);
  14127. }
  14128. return false;
  14129. }
  14130. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14131. {
  14132. FileChooser fc (openFileDialogTitle,
  14133. getLastDocumentOpened(),
  14134. fileWildcard);
  14135. if (fc.browseForFileToOpen())
  14136. return loadFrom (fc.getResult(), showMessageOnFailure);
  14137. return false;
  14138. }
  14139. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14140. const bool showMessageOnFailure)
  14141. {
  14142. return saveAs (documentFile,
  14143. false,
  14144. askUserForFileIfNotSpecified,
  14145. showMessageOnFailure);
  14146. }
  14147. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14148. const bool warnAboutOverwritingExistingFiles,
  14149. const bool askUserForFileIfNotSpecified,
  14150. const bool showMessageOnFailure)
  14151. {
  14152. if (newFile == File::nonexistent)
  14153. {
  14154. if (askUserForFileIfNotSpecified)
  14155. {
  14156. return saveAsInteractive (true);
  14157. }
  14158. else
  14159. {
  14160. // can't save to an unspecified file
  14161. jassertfalse
  14162. return failedToWriteToFile;
  14163. }
  14164. }
  14165. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14166. {
  14167. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14168. TRANS("File already exists"),
  14169. TRANS("There's already a file called:\n\n")
  14170. + newFile.getFullPathName()
  14171. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14172. TRANS("overwrite"),
  14173. TRANS("cancel")))
  14174. {
  14175. return userCancelledSave;
  14176. }
  14177. }
  14178. MouseCursor::showWaitCursor();
  14179. const File oldFile (documentFile);
  14180. documentFile = newFile;
  14181. String error (saveDocument (newFile));
  14182. if (error.isEmpty())
  14183. {
  14184. setChangedFlag (false);
  14185. MouseCursor::hideWaitCursor();
  14186. return savedOk;
  14187. }
  14188. documentFile = oldFile;
  14189. MouseCursor::hideWaitCursor();
  14190. if (showMessageOnFailure)
  14191. {
  14192. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14193. TRANS("Error writing to file..."),
  14194. TRANS("An error occurred while trying to save \"")
  14195. + getDocumentTitle()
  14196. + TRANS("\" to the file:\n\n")
  14197. + newFile.getFullPathName()
  14198. + T("\n\n")
  14199. + error);
  14200. }
  14201. return failedToWriteToFile;
  14202. }
  14203. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14204. {
  14205. if (! hasChangedSinceSaved())
  14206. return savedOk;
  14207. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14208. TRANS("Closing document..."),
  14209. TRANS("Do you want to save the changes to \"")
  14210. + getDocumentTitle() + T("\"?"),
  14211. TRANS("save"),
  14212. TRANS("discard changes"),
  14213. TRANS("cancel"));
  14214. if (r == 1)
  14215. {
  14216. // save changes
  14217. return save (true, true);
  14218. }
  14219. else if (r == 2)
  14220. {
  14221. // discard changes
  14222. return savedOk;
  14223. }
  14224. return userCancelledSave;
  14225. }
  14226. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14227. {
  14228. File f;
  14229. if (documentFile.existsAsFile())
  14230. f = documentFile;
  14231. else
  14232. f = getLastDocumentOpened();
  14233. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14234. if (legalFilename.isEmpty())
  14235. legalFilename = "unnamed";
  14236. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14237. f = f.getSiblingFile (legalFilename);
  14238. else
  14239. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14240. f = f.withFileExtension (fileExtension)
  14241. .getNonexistentSibling (true);
  14242. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14243. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14244. {
  14245. setLastDocumentOpened (fc.getResult());
  14246. File chosen (fc.getResult());
  14247. if (chosen.getFileExtension().isEmpty())
  14248. {
  14249. chosen = chosen.withFileExtension (fileExtension);
  14250. if (chosen.exists())
  14251. {
  14252. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14253. TRANS("File already exists"),
  14254. TRANS("There's already a file called:\n\n")
  14255. + chosen.getFullPathName()
  14256. + T("\n\nAre you sure you want to overwrite it?"),
  14257. TRANS("overwrite"),
  14258. TRANS("cancel")))
  14259. {
  14260. return userCancelledSave;
  14261. }
  14262. }
  14263. }
  14264. return saveAs (chosen, false, false, true);
  14265. }
  14266. return userCancelledSave;
  14267. }
  14268. END_JUCE_NAMESPACE
  14269. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  14270. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14271. BEGIN_JUCE_NAMESPACE
  14272. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14273. : maxNumberOfItems (10)
  14274. {
  14275. }
  14276. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14277. {
  14278. }
  14279. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14280. {
  14281. maxNumberOfItems = jmax (1, newMaxNumber);
  14282. while (getNumFiles() > maxNumberOfItems)
  14283. files.remove (getNumFiles() - 1);
  14284. }
  14285. int RecentlyOpenedFilesList::getNumFiles() const
  14286. {
  14287. return files.size();
  14288. }
  14289. const File RecentlyOpenedFilesList::getFile (const int index) const
  14290. {
  14291. return File (files [index]);
  14292. }
  14293. void RecentlyOpenedFilesList::clear()
  14294. {
  14295. files.clear();
  14296. }
  14297. void RecentlyOpenedFilesList::addFile (const File& file)
  14298. {
  14299. const String path (file.getFullPathName());
  14300. files.removeString (path, true);
  14301. files.insert (0, path);
  14302. setMaxNumberOfItems (maxNumberOfItems);
  14303. }
  14304. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14305. {
  14306. for (int i = getNumFiles(); --i >= 0;)
  14307. if (! getFile(i).exists())
  14308. files.remove (i);
  14309. }
  14310. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14311. const int baseItemId,
  14312. const bool showFullPaths,
  14313. const bool dontAddNonExistentFiles,
  14314. const File** filesToAvoid)
  14315. {
  14316. int num = 0;
  14317. for (int i = 0; i < getNumFiles(); ++i)
  14318. {
  14319. const File f (getFile(i));
  14320. if ((! dontAddNonExistentFiles) || f.exists())
  14321. {
  14322. bool needsAvoiding = false;
  14323. if (filesToAvoid != 0)
  14324. {
  14325. const File** files = filesToAvoid;
  14326. while (*files != 0)
  14327. {
  14328. if (f == **files)
  14329. {
  14330. needsAvoiding = true;
  14331. break;
  14332. }
  14333. ++files;
  14334. }
  14335. }
  14336. if (! needsAvoiding)
  14337. {
  14338. menuToAddTo.addItem (baseItemId + i,
  14339. showFullPaths ? f.getFullPathName()
  14340. : f.getFileName());
  14341. ++num;
  14342. }
  14343. }
  14344. }
  14345. return num;
  14346. }
  14347. const String RecentlyOpenedFilesList::toString() const
  14348. {
  14349. return files.joinIntoString (T("\n"));
  14350. }
  14351. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14352. {
  14353. clear();
  14354. files.addLines (stringifiedVersion);
  14355. setMaxNumberOfItems (maxNumberOfItems);
  14356. }
  14357. END_JUCE_NAMESPACE
  14358. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14359. /********* Start of inlined file: juce_UndoManager.cpp *********/
  14360. BEGIN_JUCE_NAMESPACE
  14361. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14362. const int minimumTransactions)
  14363. : totalUnitsStored (0),
  14364. nextIndex (0),
  14365. newTransaction (true),
  14366. reentrancyCheck (false)
  14367. {
  14368. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14369. minimumTransactions);
  14370. }
  14371. UndoManager::~UndoManager()
  14372. {
  14373. clearUndoHistory();
  14374. }
  14375. void UndoManager::clearUndoHistory()
  14376. {
  14377. transactions.clear();
  14378. transactionNames.clear();
  14379. totalUnitsStored = 0;
  14380. nextIndex = 0;
  14381. sendChangeMessage (this);
  14382. }
  14383. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14384. {
  14385. return totalUnitsStored;
  14386. }
  14387. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14388. const int minimumTransactions)
  14389. {
  14390. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14391. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14392. }
  14393. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14394. {
  14395. if (command != 0)
  14396. {
  14397. if (actionName.isNotEmpty())
  14398. currentTransactionName = actionName;
  14399. if (reentrancyCheck)
  14400. {
  14401. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14402. // undo() methods, or else these actions won't actually get done.
  14403. return false;
  14404. }
  14405. else
  14406. {
  14407. bool success = false;
  14408. JUCE_TRY
  14409. {
  14410. success = command->perform();
  14411. }
  14412. JUCE_CATCH_EXCEPTION
  14413. jassert (success);
  14414. if (success)
  14415. {
  14416. if (nextIndex > 0 && ! newTransaction)
  14417. {
  14418. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14419. jassert (commandSet != 0);
  14420. if (commandSet == 0)
  14421. return false;
  14422. commandSet->add (command);
  14423. }
  14424. else
  14425. {
  14426. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14427. commandSet->add (command);
  14428. transactions.insert (nextIndex, commandSet);
  14429. transactionNames.insert (nextIndex, currentTransactionName);
  14430. ++nextIndex;
  14431. }
  14432. totalUnitsStored += command->getSizeInUnits();
  14433. newTransaction = false;
  14434. }
  14435. while (nextIndex < transactions.size())
  14436. {
  14437. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14438. for (int i = lastSet->size(); --i >= 0;)
  14439. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14440. transactions.removeLast();
  14441. transactionNames.remove (transactionNames.size() - 1);
  14442. }
  14443. while (nextIndex > 0
  14444. && totalUnitsStored > maxNumUnitsToKeep
  14445. && transactions.size() > minimumTransactionsToKeep)
  14446. {
  14447. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14448. for (int i = firstSet->size(); --i >= 0;)
  14449. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14450. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14451. transactions.remove (0);
  14452. transactionNames.remove (0);
  14453. --nextIndex;
  14454. }
  14455. sendChangeMessage (this);
  14456. return success;
  14457. }
  14458. }
  14459. return false;
  14460. }
  14461. void UndoManager::beginNewTransaction (const String& actionName)
  14462. {
  14463. newTransaction = true;
  14464. currentTransactionName = actionName;
  14465. }
  14466. void UndoManager::setCurrentTransactionName (const String& newName)
  14467. {
  14468. currentTransactionName = newName;
  14469. }
  14470. bool UndoManager::canUndo() const
  14471. {
  14472. return nextIndex > 0;
  14473. }
  14474. bool UndoManager::canRedo() const
  14475. {
  14476. return nextIndex < transactions.size();
  14477. }
  14478. const String UndoManager::getUndoDescription() const
  14479. {
  14480. return transactionNames [nextIndex - 1];
  14481. }
  14482. const String UndoManager::getRedoDescription() const
  14483. {
  14484. return transactionNames [nextIndex];
  14485. }
  14486. bool UndoManager::undo()
  14487. {
  14488. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14489. if (commandSet == 0)
  14490. return false;
  14491. reentrancyCheck = true;
  14492. bool failed = false;
  14493. for (int i = commandSet->size(); --i >= 0;)
  14494. {
  14495. if (! commandSet->getUnchecked(i)->undo())
  14496. {
  14497. jassertfalse
  14498. failed = true;
  14499. break;
  14500. }
  14501. }
  14502. reentrancyCheck = false;
  14503. if (failed)
  14504. {
  14505. clearUndoHistory();
  14506. }
  14507. else
  14508. {
  14509. --nextIndex;
  14510. }
  14511. beginNewTransaction();
  14512. sendChangeMessage (this);
  14513. return true;
  14514. }
  14515. bool UndoManager::redo()
  14516. {
  14517. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  14518. if (commandSet == 0)
  14519. return false;
  14520. reentrancyCheck = true;
  14521. bool failed = false;
  14522. for (int i = 0; i < commandSet->size(); ++i)
  14523. {
  14524. if (! commandSet->getUnchecked(i)->perform())
  14525. {
  14526. jassertfalse
  14527. failed = true;
  14528. break;
  14529. }
  14530. }
  14531. reentrancyCheck = false;
  14532. if (failed)
  14533. {
  14534. clearUndoHistory();
  14535. }
  14536. else
  14537. {
  14538. ++nextIndex;
  14539. }
  14540. beginNewTransaction();
  14541. sendChangeMessage (this);
  14542. return true;
  14543. }
  14544. bool UndoManager::undoCurrentTransactionOnly()
  14545. {
  14546. return newTransaction ? false
  14547. : undo();
  14548. }
  14549. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  14550. {
  14551. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14552. if (commandSet != 0 && ! newTransaction)
  14553. {
  14554. for (int i = 0; i < commandSet->size(); ++i)
  14555. actionsFound.add (commandSet->getUnchecked(i));
  14556. }
  14557. }
  14558. END_JUCE_NAMESPACE
  14559. /********* End of inlined file: juce_UndoManager.cpp *********/
  14560. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  14561. BEGIN_JUCE_NAMESPACE
  14562. #undef chunkName
  14563. #define chunkName(a) (int)littleEndianInt(a)
  14564. #define aiffFormatName TRANS("AIFF file")
  14565. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  14566. class AiffAudioFormatReader : public AudioFormatReader
  14567. {
  14568. public:
  14569. int bytesPerFrame;
  14570. int64 dataChunkStart;
  14571. bool littleEndian;
  14572. AiffAudioFormatReader (InputStream* in)
  14573. : AudioFormatReader (in, aiffFormatName)
  14574. {
  14575. if (input->readInt() == chunkName ("FORM"))
  14576. {
  14577. const int len = input->readIntBigEndian();
  14578. const int64 end = input->getPosition() + len;
  14579. const int nextType = input->readInt();
  14580. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  14581. {
  14582. bool hasGotVer = false;
  14583. bool hasGotData = false;
  14584. bool hasGotType = false;
  14585. while (input->getPosition() < end)
  14586. {
  14587. const int type = input->readInt();
  14588. const uint32 length = (uint32) input->readIntBigEndian();
  14589. const int64 chunkEnd = input->getPosition() + length;
  14590. if (type == chunkName ("FVER"))
  14591. {
  14592. hasGotVer = true;
  14593. const int ver = input->readIntBigEndian();
  14594. if (ver != 0 && ver != (int)0xa2805140)
  14595. break;
  14596. }
  14597. else if (type == chunkName ("COMM"))
  14598. {
  14599. hasGotType = true;
  14600. numChannels = (unsigned int)input->readShortBigEndian();
  14601. lengthInSamples = input->readIntBigEndian();
  14602. bitsPerSample = input->readShortBigEndian();
  14603. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  14604. unsigned char sampleRateBytes[10];
  14605. input->read (sampleRateBytes, 10);
  14606. const int byte0 = sampleRateBytes[0];
  14607. if ((byte0 & 0x80) != 0
  14608. || byte0 <= 0x3F || byte0 > 0x40
  14609. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  14610. break;
  14611. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  14612. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  14613. sampleRate = (int)sampRate;
  14614. if (length <= 18)
  14615. {
  14616. // some types don't have a chunk large enough to include a compression
  14617. // type, so assume it's just big-endian pcm
  14618. littleEndian = false;
  14619. }
  14620. else
  14621. {
  14622. const int compType = input->readInt();
  14623. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  14624. {
  14625. littleEndian = false;
  14626. }
  14627. else if (compType == chunkName ("sowt"))
  14628. {
  14629. littleEndian = true;
  14630. }
  14631. else
  14632. {
  14633. sampleRate = 0;
  14634. break;
  14635. }
  14636. }
  14637. }
  14638. else if (type == chunkName ("SSND"))
  14639. {
  14640. hasGotData = true;
  14641. const int offset = input->readIntBigEndian();
  14642. dataChunkStart = input->getPosition() + 4 + offset;
  14643. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  14644. }
  14645. else if ((hasGotVer && hasGotData && hasGotType)
  14646. || chunkEnd < input->getPosition()
  14647. || input->isExhausted())
  14648. {
  14649. break;
  14650. }
  14651. input->setPosition (chunkEnd);
  14652. }
  14653. }
  14654. }
  14655. }
  14656. ~AiffAudioFormatReader()
  14657. {
  14658. }
  14659. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  14660. int64 startSampleInFile, int numSamples)
  14661. {
  14662. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  14663. if (samplesAvailable < numSamples)
  14664. {
  14665. for (int i = numDestChannels; --i >= 0;)
  14666. if (destSamples[i] != 0)
  14667. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  14668. numSamples = (int) samplesAvailable;
  14669. }
  14670. if (numSamples <= 0)
  14671. return true;
  14672. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  14673. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  14674. char tempBuffer [tempBufSize];
  14675. while (numSamples > 0)
  14676. {
  14677. int* left = destSamples[0];
  14678. if (left != 0)
  14679. left += startOffsetInDestBuffer;
  14680. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  14681. if (right != 0)
  14682. right += startOffsetInDestBuffer;
  14683. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  14684. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  14685. if (bytesRead < numThisTime * bytesPerFrame)
  14686. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  14687. if (bitsPerSample == 16)
  14688. {
  14689. if (littleEndian)
  14690. {
  14691. const short* src = (const short*) tempBuffer;
  14692. if (numChannels > 1)
  14693. {
  14694. if (left == 0)
  14695. {
  14696. for (int i = numThisTime; --i >= 0;)
  14697. {
  14698. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14699. ++src;
  14700. }
  14701. }
  14702. else if (right == 0)
  14703. {
  14704. for (int i = numThisTime; --i >= 0;)
  14705. {
  14706. ++src;
  14707. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14708. }
  14709. }
  14710. else
  14711. {
  14712. for (int i = numThisTime; --i >= 0;)
  14713. {
  14714. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14715. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14716. }
  14717. }
  14718. }
  14719. else
  14720. {
  14721. for (int i = numThisTime; --i >= 0;)
  14722. {
  14723. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14724. }
  14725. }
  14726. }
  14727. else
  14728. {
  14729. const char* src = (const char*) tempBuffer;
  14730. if (numChannels > 1)
  14731. {
  14732. if (left == 0)
  14733. {
  14734. for (int i = numThisTime; --i >= 0;)
  14735. {
  14736. *right++ = bigEndianShort (src) << 16;
  14737. src += 4;
  14738. }
  14739. }
  14740. else if (right == 0)
  14741. {
  14742. for (int i = numThisTime; --i >= 0;)
  14743. {
  14744. src += 2;
  14745. *left++ = bigEndianShort (src) << 16;
  14746. src += 2;
  14747. }
  14748. }
  14749. else
  14750. {
  14751. for (int i = numThisTime; --i >= 0;)
  14752. {
  14753. *left++ = bigEndianShort (src) << 16;
  14754. src += 2;
  14755. *right++ = bigEndianShort (src) << 16;
  14756. src += 2;
  14757. }
  14758. }
  14759. }
  14760. else
  14761. {
  14762. for (int i = numThisTime; --i >= 0;)
  14763. {
  14764. *left++ = bigEndianShort (src) << 16;
  14765. src += 2;
  14766. }
  14767. }
  14768. }
  14769. }
  14770. else if (bitsPerSample == 24)
  14771. {
  14772. const char* src = (const char*)tempBuffer;
  14773. if (littleEndian)
  14774. {
  14775. if (numChannels > 1)
  14776. {
  14777. if (left == 0)
  14778. {
  14779. for (int i = numThisTime; --i >= 0;)
  14780. {
  14781. *right++ = littleEndian24Bit (src) << 8;
  14782. src += 6;
  14783. }
  14784. }
  14785. else if (right == 0)
  14786. {
  14787. for (int i = numThisTime; --i >= 0;)
  14788. {
  14789. src += 3;
  14790. *left++ = littleEndian24Bit (src) << 8;
  14791. src += 3;
  14792. }
  14793. }
  14794. else
  14795. {
  14796. for (int i = numThisTime; --i >= 0;)
  14797. {
  14798. *left++ = littleEndian24Bit (src) << 8;
  14799. src += 3;
  14800. *right++ = littleEndian24Bit (src) << 8;
  14801. src += 3;
  14802. }
  14803. }
  14804. }
  14805. else
  14806. {
  14807. for (int i = numThisTime; --i >= 0;)
  14808. {
  14809. *left++ = littleEndian24Bit (src) << 8;
  14810. src += 3;
  14811. }
  14812. }
  14813. }
  14814. else
  14815. {
  14816. if (numChannels > 1)
  14817. {
  14818. if (left == 0)
  14819. {
  14820. for (int i = numThisTime; --i >= 0;)
  14821. {
  14822. *right++ = bigEndian24Bit (src) << 8;
  14823. src += 6;
  14824. }
  14825. }
  14826. else if (right == 0)
  14827. {
  14828. for (int i = numThisTime; --i >= 0;)
  14829. {
  14830. src += 3;
  14831. *left++ = bigEndian24Bit (src) << 8;
  14832. src += 3;
  14833. }
  14834. }
  14835. else
  14836. {
  14837. for (int i = numThisTime; --i >= 0;)
  14838. {
  14839. *left++ = bigEndian24Bit (src) << 8;
  14840. src += 3;
  14841. *right++ = bigEndian24Bit (src) << 8;
  14842. src += 3;
  14843. }
  14844. }
  14845. }
  14846. else
  14847. {
  14848. for (int i = numThisTime; --i >= 0;)
  14849. {
  14850. *left++ = bigEndian24Bit (src) << 8;
  14851. src += 3;
  14852. }
  14853. }
  14854. }
  14855. }
  14856. else if (bitsPerSample == 32)
  14857. {
  14858. const unsigned int* src = (const unsigned int*) tempBuffer;
  14859. unsigned int* l = (unsigned int*) left;
  14860. unsigned int* r = (unsigned int*) right;
  14861. if (littleEndian)
  14862. {
  14863. if (numChannels > 1)
  14864. {
  14865. if (l == 0)
  14866. {
  14867. for (int i = numThisTime; --i >= 0;)
  14868. {
  14869. ++src;
  14870. *r++ = swapIfBigEndian (*src++);
  14871. }
  14872. }
  14873. else if (r == 0)
  14874. {
  14875. for (int i = numThisTime; --i >= 0;)
  14876. {
  14877. *l++ = swapIfBigEndian (*src++);
  14878. ++src;
  14879. }
  14880. }
  14881. else
  14882. {
  14883. for (int i = numThisTime; --i >= 0;)
  14884. {
  14885. *l++ = swapIfBigEndian (*src++);
  14886. *r++ = swapIfBigEndian (*src++);
  14887. }
  14888. }
  14889. }
  14890. else
  14891. {
  14892. for (int i = numThisTime; --i >= 0;)
  14893. {
  14894. *l++ = swapIfBigEndian (*src++);
  14895. }
  14896. }
  14897. }
  14898. else
  14899. {
  14900. if (numChannels > 1)
  14901. {
  14902. if (l == 0)
  14903. {
  14904. for (int i = numThisTime; --i >= 0;)
  14905. {
  14906. ++src;
  14907. *r++ = swapIfLittleEndian (*src++);
  14908. }
  14909. }
  14910. else if (r == 0)
  14911. {
  14912. for (int i = numThisTime; --i >= 0;)
  14913. {
  14914. *l++ = swapIfLittleEndian (*src++);
  14915. ++src;
  14916. }
  14917. }
  14918. else
  14919. {
  14920. for (int i = numThisTime; --i >= 0;)
  14921. {
  14922. *l++ = swapIfLittleEndian (*src++);
  14923. *r++ = swapIfLittleEndian (*src++);
  14924. }
  14925. }
  14926. }
  14927. else
  14928. {
  14929. for (int i = numThisTime; --i >= 0;)
  14930. {
  14931. *l++ = swapIfLittleEndian (*src++);
  14932. }
  14933. }
  14934. }
  14935. left = (int*) l;
  14936. right = (int*) r;
  14937. }
  14938. else if (bitsPerSample == 8)
  14939. {
  14940. const char* src = (const char*) tempBuffer;
  14941. if (numChannels > 1)
  14942. {
  14943. if (left == 0)
  14944. {
  14945. for (int i = numThisTime; --i >= 0;)
  14946. {
  14947. *right++ = ((int) *src++) << 24;
  14948. ++src;
  14949. }
  14950. }
  14951. else if (right == 0)
  14952. {
  14953. for (int i = numThisTime; --i >= 0;)
  14954. {
  14955. ++src;
  14956. *left++ = ((int) *src++) << 24;
  14957. }
  14958. }
  14959. else
  14960. {
  14961. for (int i = numThisTime; --i >= 0;)
  14962. {
  14963. *left++ = ((int) *src++) << 24;
  14964. *right++ = ((int) *src++) << 24;
  14965. }
  14966. }
  14967. }
  14968. else
  14969. {
  14970. for (int i = numThisTime; --i >= 0;)
  14971. {
  14972. *left++ = ((int) *src++) << 24;
  14973. }
  14974. }
  14975. }
  14976. startOffsetInDestBuffer += numThisTime;
  14977. numSamples -= numThisTime;
  14978. }
  14979. if (numSamples > 0)
  14980. {
  14981. for (int i = numDestChannels; --i >= 0;)
  14982. if (destSamples[i] != 0)
  14983. zeromem (destSamples[i] + startOffsetInDestBuffer,
  14984. sizeof (int) * numSamples);
  14985. }
  14986. return true;
  14987. }
  14988. juce_UseDebuggingNewOperator
  14989. private:
  14990. AiffAudioFormatReader (const AiffAudioFormatReader&);
  14991. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  14992. };
  14993. class AiffAudioFormatWriter : public AudioFormatWriter
  14994. {
  14995. MemoryBlock tempBlock;
  14996. uint32 lengthInSamples, bytesWritten;
  14997. int64 headerPosition;
  14998. bool writeFailed;
  14999. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15000. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15001. void writeHeader()
  15002. {
  15003. const bool couldSeekOk = output->setPosition (headerPosition);
  15004. (void) couldSeekOk;
  15005. // if this fails, you've given it an output stream that can't seek! It needs
  15006. // to be able to seek back to write the header
  15007. jassert (couldSeekOk);
  15008. const int headerLen = 54;
  15009. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15010. audioBytes += (audioBytes & 1);
  15011. output->writeInt (chunkName ("FORM"));
  15012. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15013. output->writeInt (chunkName ("AIFF"));
  15014. output->writeInt (chunkName ("COMM"));
  15015. output->writeIntBigEndian (18);
  15016. output->writeShortBigEndian ((short) numChannels);
  15017. output->writeIntBigEndian (lengthInSamples);
  15018. output->writeShortBigEndian ((short) bitsPerSample);
  15019. uint8 sampleRateBytes[10];
  15020. zeromem (sampleRateBytes, 10);
  15021. if (sampleRate <= 1)
  15022. {
  15023. sampleRateBytes[0] = 0x3f;
  15024. sampleRateBytes[1] = 0xff;
  15025. sampleRateBytes[2] = 0x80;
  15026. }
  15027. else
  15028. {
  15029. int mask = 0x40000000;
  15030. sampleRateBytes[0] = 0x40;
  15031. if (sampleRate >= mask)
  15032. {
  15033. jassertfalse
  15034. sampleRateBytes[1] = 0x1d;
  15035. }
  15036. else
  15037. {
  15038. int n = (int) sampleRate;
  15039. int i;
  15040. for (i = 0; i <= 32 ; ++i)
  15041. {
  15042. if ((n & mask) != 0)
  15043. break;
  15044. mask >>= 1;
  15045. }
  15046. n = n << (i + 1);
  15047. sampleRateBytes[1] = (uint8) (29 - i);
  15048. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15049. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15050. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15051. sampleRateBytes[5] = (uint8) (n & 0xff);
  15052. }
  15053. }
  15054. output->write (sampleRateBytes, 10);
  15055. output->writeInt (chunkName ("SSND"));
  15056. output->writeIntBigEndian (audioBytes + 8);
  15057. output->writeInt (0);
  15058. output->writeInt (0);
  15059. jassert (output->getPosition() == headerLen);
  15060. }
  15061. public:
  15062. AiffAudioFormatWriter (OutputStream* out,
  15063. const double sampleRate_,
  15064. const unsigned int chans,
  15065. const int bits)
  15066. : AudioFormatWriter (out,
  15067. aiffFormatName,
  15068. sampleRate_,
  15069. chans,
  15070. bits),
  15071. lengthInSamples (0),
  15072. bytesWritten (0),
  15073. writeFailed (false)
  15074. {
  15075. headerPosition = out->getPosition();
  15076. writeHeader();
  15077. }
  15078. ~AiffAudioFormatWriter()
  15079. {
  15080. if ((bytesWritten & 1) != 0)
  15081. output->writeByte (0);
  15082. writeHeader();
  15083. }
  15084. bool write (const int** data, int numSamples)
  15085. {
  15086. if (writeFailed)
  15087. return false;
  15088. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15089. tempBlock.ensureSize (bytes, false);
  15090. char* buffer = (char*) tempBlock.getData();
  15091. const int* left = data[0];
  15092. const int* right = data[1];
  15093. if (right == 0)
  15094. right = left;
  15095. if (bitsPerSample == 16)
  15096. {
  15097. short* b = (short*) buffer;
  15098. if (numChannels > 1)
  15099. {
  15100. for (int i = numSamples; --i >= 0;)
  15101. {
  15102. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  15103. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  15104. }
  15105. }
  15106. else
  15107. {
  15108. for (int i = numSamples; --i >= 0;)
  15109. {
  15110. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  15111. }
  15112. }
  15113. }
  15114. else if (bitsPerSample == 24)
  15115. {
  15116. char* b = (char*) buffer;
  15117. if (numChannels > 1)
  15118. {
  15119. for (int i = numSamples; --i >= 0;)
  15120. {
  15121. bigEndian24BitToChars (*left++ >> 8, b);
  15122. b += 3;
  15123. bigEndian24BitToChars (*right++ >> 8, b);
  15124. b += 3;
  15125. }
  15126. }
  15127. else
  15128. {
  15129. for (int i = numSamples; --i >= 0;)
  15130. {
  15131. bigEndian24BitToChars (*left++ >> 8, b);
  15132. b += 3;
  15133. }
  15134. }
  15135. }
  15136. else if (bitsPerSample == 32)
  15137. {
  15138. unsigned int* b = (unsigned int*) buffer;
  15139. if (numChannels > 1)
  15140. {
  15141. for (int i = numSamples; --i >= 0;)
  15142. {
  15143. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  15144. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  15145. }
  15146. }
  15147. else
  15148. {
  15149. for (int i = numSamples; --i >= 0;)
  15150. {
  15151. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  15152. }
  15153. }
  15154. }
  15155. else if (bitsPerSample == 8)
  15156. {
  15157. char* b = (char*)buffer;
  15158. if (numChannels > 1)
  15159. {
  15160. for (int i = numSamples; --i >= 0;)
  15161. {
  15162. *b++ = (char) (*left++ >> 24);
  15163. *b++ = (char) (*right++ >> 24);
  15164. }
  15165. }
  15166. else
  15167. {
  15168. for (int i = numSamples; --i >= 0;)
  15169. {
  15170. *b++ = (char) (*left++ >> 24);
  15171. }
  15172. }
  15173. }
  15174. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15175. || ! output->write (buffer, bytes))
  15176. {
  15177. // failed to write to disk, so let's try writing the header.
  15178. // If it's just run out of disk space, then if it does manage
  15179. // to write the header, we'll still have a useable file..
  15180. writeHeader();
  15181. writeFailed = true;
  15182. return false;
  15183. }
  15184. else
  15185. {
  15186. bytesWritten += bytes;
  15187. lengthInSamples += numSamples;
  15188. return true;
  15189. }
  15190. }
  15191. juce_UseDebuggingNewOperator
  15192. };
  15193. AiffAudioFormat::AiffAudioFormat()
  15194. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  15195. {
  15196. }
  15197. AiffAudioFormat::~AiffAudioFormat()
  15198. {
  15199. }
  15200. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15201. {
  15202. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15203. return Array <int> (rates);
  15204. }
  15205. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15206. {
  15207. const int depths[] = { 8, 16, 24, 0 };
  15208. return Array <int> (depths);
  15209. }
  15210. bool AiffAudioFormat::canDoStereo()
  15211. {
  15212. return true;
  15213. }
  15214. bool AiffAudioFormat::canDoMono()
  15215. {
  15216. return true;
  15217. }
  15218. #if JUCE_MAC
  15219. bool AiffAudioFormat::canHandleFile (const File& f)
  15220. {
  15221. if (AudioFormat::canHandleFile (f))
  15222. return true;
  15223. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15224. return type == 'AIFF' || type == 'AIFC'
  15225. || type == 'aiff' || type == 'aifc';
  15226. }
  15227. #endif
  15228. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15229. const bool deleteStreamIfOpeningFails)
  15230. {
  15231. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  15232. if (w->sampleRate == 0)
  15233. {
  15234. if (! deleteStreamIfOpeningFails)
  15235. w->input = 0;
  15236. deleteAndZero (w);
  15237. }
  15238. return w;
  15239. }
  15240. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15241. double sampleRate,
  15242. unsigned int chans,
  15243. int bitsPerSample,
  15244. const StringPairArray& /*metadataValues*/,
  15245. int /*qualityOptionIndex*/)
  15246. {
  15247. if (getPossibleBitDepths().contains (bitsPerSample))
  15248. {
  15249. return new AiffAudioFormatWriter (out,
  15250. sampleRate,
  15251. chans,
  15252. bitsPerSample);
  15253. }
  15254. return 0;
  15255. }
  15256. END_JUCE_NAMESPACE
  15257. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  15258. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  15259. BEGIN_JUCE_NAMESPACE
  15260. #if JUCE_MAC
  15261. // Mac version doesn't need any native code because it's all done with files..
  15262. // Windows + Linux versions are in the platform-dependent code sections.
  15263. static void findCDs (OwnedArray<File>& cds)
  15264. {
  15265. File volumes ("/Volumes");
  15266. volumes.findChildFiles (cds, File::findDirectories, false);
  15267. for (int i = cds.size(); --i >= 0;)
  15268. if (! cds[i]->getChildFile (".TOC.plist").exists())
  15269. cds.remove (i);
  15270. }
  15271. const StringArray AudioCDReader::getAvailableCDNames()
  15272. {
  15273. OwnedArray<File> cds;
  15274. findCDs (cds);
  15275. StringArray names;
  15276. for (int i = 0; i < cds.size(); ++i)
  15277. names.add (cds[i]->getFileName());
  15278. return names;
  15279. }
  15280. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15281. {
  15282. OwnedArray<File> cds;
  15283. findCDs (cds);
  15284. if (cds[index] != 0)
  15285. return new AudioCDReader (*cds[index]);
  15286. else
  15287. return 0;
  15288. }
  15289. AudioCDReader::AudioCDReader (const File& volume)
  15290. : AudioFormatReader (0, "CD Audio"),
  15291. volumeDir (volume),
  15292. currentReaderTrack (-1),
  15293. reader (0)
  15294. {
  15295. sampleRate = 44100.0;
  15296. bitsPerSample = 16;
  15297. numChannels = 2;
  15298. usesFloatingPointData = false;
  15299. refreshTrackLengths();
  15300. }
  15301. AudioCDReader::~AudioCDReader()
  15302. {
  15303. if (reader != 0)
  15304. delete reader;
  15305. }
  15306. static int getTrackNumber (const File& file)
  15307. {
  15308. return file.getFileName()
  15309. .initialSectionContainingOnly (T("0123456789"))
  15310. .getIntValue();
  15311. }
  15312. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  15313. {
  15314. const int firstTrack = getTrackNumber (*first);
  15315. const int secondTrack = getTrackNumber (*second);
  15316. jassert (firstTrack > 0 && secondTrack > 0);
  15317. return firstTrack - secondTrack;
  15318. }
  15319. void AudioCDReader::refreshTrackLengths()
  15320. {
  15321. tracks.clear();
  15322. trackStartSamples.clear();
  15323. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  15324. tracks.sort (*this);
  15325. AiffAudioFormat format;
  15326. int sample = 0;
  15327. for (int i = 0; i < tracks.size(); ++i)
  15328. {
  15329. trackStartSamples.add (sample);
  15330. FileInputStream* const in = tracks[i]->createInputStream();
  15331. if (in != 0)
  15332. {
  15333. AudioFormatReader* const r = format.createReaderFor (in, true);
  15334. if (r != 0)
  15335. {
  15336. sample += r->lengthInSamples;
  15337. delete r;
  15338. }
  15339. }
  15340. }
  15341. trackStartSamples.add (sample);
  15342. lengthInSamples = sample;
  15343. }
  15344. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15345. int64 startSampleInFile, int numSamples)
  15346. {
  15347. while (numSamples > 0)
  15348. {
  15349. int track = -1;
  15350. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15351. {
  15352. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15353. {
  15354. track = i;
  15355. break;
  15356. }
  15357. }
  15358. if (track < 0)
  15359. return false;
  15360. if (track != currentReaderTrack)
  15361. {
  15362. deleteAndZero (reader);
  15363. if (tracks [track] != 0)
  15364. {
  15365. FileInputStream* const in = tracks [track]->createInputStream();
  15366. if (in != 0)
  15367. {
  15368. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15369. AiffAudioFormat format;
  15370. reader = format.createReaderFor (bin, true);
  15371. if (reader == 0)
  15372. currentReaderTrack = -1;
  15373. else
  15374. currentReaderTrack = track;
  15375. }
  15376. }
  15377. }
  15378. if (reader == 0)
  15379. return false;
  15380. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15381. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15382. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15383. numSamples -= numAvailable;
  15384. startSampleInFile += numAvailable;
  15385. }
  15386. return true;
  15387. }
  15388. bool AudioCDReader::isCDStillPresent() const
  15389. {
  15390. return volumeDir.exists();
  15391. }
  15392. int AudioCDReader::getNumTracks() const
  15393. {
  15394. return tracks.size();
  15395. }
  15396. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15397. {
  15398. return trackStartSamples [trackNum];
  15399. }
  15400. bool AudioCDReader::isTrackAudio (int trackNum) const
  15401. {
  15402. return tracks [trackNum] != 0;
  15403. }
  15404. void AudioCDReader::enableIndexScanning (bool b)
  15405. {
  15406. // any way to do this on a Mac??
  15407. }
  15408. int AudioCDReader::getLastIndex() const
  15409. {
  15410. return 0;
  15411. }
  15412. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15413. {
  15414. return Array <int>();
  15415. }
  15416. int AudioCDReader::getCDDBId()
  15417. {
  15418. return 0; //xxx
  15419. }
  15420. #endif
  15421. END_JUCE_NAMESPACE
  15422. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  15423. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  15424. BEGIN_JUCE_NAMESPACE
  15425. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15426. const String& formatName_)
  15427. : sampleRate (0),
  15428. bitsPerSample (0),
  15429. lengthInSamples (0),
  15430. numChannels (0),
  15431. usesFloatingPointData (false),
  15432. input (in),
  15433. formatName (formatName_)
  15434. {
  15435. }
  15436. AudioFormatReader::~AudioFormatReader()
  15437. {
  15438. delete input;
  15439. }
  15440. bool AudioFormatReader::read (int** destSamples,
  15441. int numDestChannels,
  15442. int64 startSampleInSource,
  15443. int numSamplesToRead,
  15444. const bool fillLeftoverChannelsWithCopies)
  15445. {
  15446. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15447. int startOffsetInDestBuffer = 0;
  15448. if (startSampleInSource < 0)
  15449. {
  15450. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15451. for (int i = numDestChannels; --i >= 0;)
  15452. if (destSamples[i] != 0)
  15453. zeromem (destSamples[i], sizeof (int) * silence);
  15454. startOffsetInDestBuffer += silence;
  15455. numSamplesToRead -= silence;
  15456. startSampleInSource = 0;
  15457. }
  15458. if (numSamplesToRead <= 0)
  15459. return true;
  15460. if (! readSamples (destSamples, jmin (numChannels, numDestChannels), startOffsetInDestBuffer,
  15461. startSampleInSource, numSamplesToRead))
  15462. return false;
  15463. if (numDestChannels > (int) numChannels)
  15464. {
  15465. if (fillLeftoverChannelsWithCopies)
  15466. {
  15467. int* lastFullChannel = destSamples[0];
  15468. for (int i = numDestChannels; --i > 0;)
  15469. {
  15470. if (destSamples[i] != 0)
  15471. {
  15472. lastFullChannel = destSamples[i];
  15473. break;
  15474. }
  15475. }
  15476. if (lastFullChannel != 0)
  15477. for (int i = numChannels; i < numDestChannels; ++i)
  15478. if (destSamples[i] != 0)
  15479. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15480. }
  15481. else
  15482. {
  15483. for (int i = numChannels; i < numDestChannels; ++i)
  15484. if (destSamples[i] != 0)
  15485. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15486. }
  15487. }
  15488. return true;
  15489. }
  15490. static void findMaxMin (const float* src, const int num,
  15491. float& maxVal, float& minVal)
  15492. {
  15493. float mn = src[0];
  15494. float mx = mn;
  15495. for (int i = 1; i < num; ++i)
  15496. {
  15497. const float s = src[i];
  15498. if (s > mx)
  15499. mx = s;
  15500. if (s < mn)
  15501. mn = s;
  15502. }
  15503. maxVal = mx;
  15504. minVal = mn;
  15505. }
  15506. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15507. int64 numSamples,
  15508. float& lowestLeft, float& highestLeft,
  15509. float& lowestRight, float& highestRight)
  15510. {
  15511. if (numSamples <= 0)
  15512. {
  15513. lowestLeft = 0;
  15514. lowestRight = 0;
  15515. highestLeft = 0;
  15516. highestRight = 0;
  15517. return;
  15518. }
  15519. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  15520. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15521. int* tempBuffer[3];
  15522. tempBuffer[0] = (int*) tempSpace.getData();
  15523. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15524. tempBuffer[2] = 0;
  15525. if (usesFloatingPointData)
  15526. {
  15527. float lmin = 1.0e6;
  15528. float lmax = -lmin;
  15529. float rmin = lmin;
  15530. float rmax = lmax;
  15531. while (numSamples > 0)
  15532. {
  15533. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15534. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15535. numSamples -= numToDo;
  15536. startSampleInFile += numToDo;
  15537. float bufmin, bufmax;
  15538. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  15539. lmin = jmin (lmin, bufmin);
  15540. lmax = jmax (lmax, bufmax);
  15541. if (numChannels > 1)
  15542. {
  15543. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  15544. rmin = jmin (rmin, bufmin);
  15545. rmax = jmax (rmax, bufmax);
  15546. }
  15547. }
  15548. if (numChannels <= 1)
  15549. {
  15550. rmax = lmax;
  15551. rmin = lmin;
  15552. }
  15553. lowestLeft = lmin;
  15554. highestLeft = lmax;
  15555. lowestRight = rmin;
  15556. highestRight = rmax;
  15557. }
  15558. else
  15559. {
  15560. int lmax = INT_MIN;
  15561. int lmin = INT_MAX;
  15562. int rmax = INT_MIN;
  15563. int rmin = INT_MAX;
  15564. while (numSamples > 0)
  15565. {
  15566. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15567. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15568. numSamples -= numToDo;
  15569. startSampleInFile += numToDo;
  15570. for (int j = numChannels; --j >= 0;)
  15571. {
  15572. int bufMax = INT_MIN;
  15573. int bufMin = INT_MAX;
  15574. const int* const b = tempBuffer[j];
  15575. for (int i = 0; i < numToDo; ++i)
  15576. {
  15577. const int samp = b[i];
  15578. if (samp < bufMin)
  15579. bufMin = samp;
  15580. if (samp > bufMax)
  15581. bufMax = samp;
  15582. }
  15583. if (j == 0)
  15584. {
  15585. lmax = jmax (lmax, bufMax);
  15586. lmin = jmin (lmin, bufMin);
  15587. }
  15588. else
  15589. {
  15590. rmax = jmax (rmax, bufMax);
  15591. rmin = jmin (rmin, bufMin);
  15592. }
  15593. }
  15594. }
  15595. if (numChannels <= 1)
  15596. {
  15597. rmax = lmax;
  15598. rmin = lmin;
  15599. }
  15600. lowestLeft = lmin / (float)INT_MAX;
  15601. highestLeft = lmax / (float)INT_MAX;
  15602. lowestRight = rmin / (float)INT_MAX;
  15603. highestRight = rmax / (float)INT_MAX;
  15604. }
  15605. }
  15606. int64 AudioFormatReader::searchForLevel (int64 startSample,
  15607. int64 numSamplesToSearch,
  15608. const double magnitudeRangeMinimum,
  15609. const double magnitudeRangeMaximum,
  15610. const int minimumConsecutiveSamples)
  15611. {
  15612. if (numSamplesToSearch == 0)
  15613. return -1;
  15614. const int bufferSize = 4096;
  15615. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15616. int* tempBuffer[3];
  15617. tempBuffer[0] = (int*) tempSpace.getData();
  15618. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15619. tempBuffer[2] = 0;
  15620. int consecutive = 0;
  15621. int64 firstMatchPos = -1;
  15622. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  15623. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  15624. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  15625. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  15626. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  15627. while (numSamplesToSearch != 0)
  15628. {
  15629. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  15630. int64 bufferStart = startSample;
  15631. if (numSamplesToSearch < 0)
  15632. bufferStart -= numThisTime;
  15633. if (bufferStart >= (int) lengthInSamples)
  15634. break;
  15635. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  15636. int num = numThisTime;
  15637. while (--num >= 0)
  15638. {
  15639. if (numSamplesToSearch < 0)
  15640. --startSample;
  15641. bool matches = false;
  15642. const int index = (int) (startSample - bufferStart);
  15643. if (usesFloatingPointData)
  15644. {
  15645. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  15646. if (sample1 >= magnitudeRangeMinimum
  15647. && sample1 <= magnitudeRangeMaximum)
  15648. {
  15649. matches = true;
  15650. }
  15651. else if (numChannels > 1)
  15652. {
  15653. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  15654. matches = (sample2 >= magnitudeRangeMinimum
  15655. && sample2 <= magnitudeRangeMaximum);
  15656. }
  15657. }
  15658. else
  15659. {
  15660. const int sample1 = abs (tempBuffer[0] [index]);
  15661. if (sample1 >= intMagnitudeRangeMinimum
  15662. && sample1 <= intMagnitudeRangeMaximum)
  15663. {
  15664. matches = true;
  15665. }
  15666. else if (numChannels > 1)
  15667. {
  15668. const int sample2 = abs (tempBuffer[1][index]);
  15669. matches = (sample2 >= intMagnitudeRangeMinimum
  15670. && sample2 <= intMagnitudeRangeMaximum);
  15671. }
  15672. }
  15673. if (matches)
  15674. {
  15675. if (firstMatchPos < 0)
  15676. firstMatchPos = startSample;
  15677. if (++consecutive >= minimumConsecutiveSamples)
  15678. {
  15679. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  15680. return -1;
  15681. return firstMatchPos;
  15682. }
  15683. }
  15684. else
  15685. {
  15686. consecutive = 0;
  15687. firstMatchPos = -1;
  15688. }
  15689. if (numSamplesToSearch > 0)
  15690. ++startSample;
  15691. }
  15692. if (numSamplesToSearch > 0)
  15693. numSamplesToSearch -= numThisTime;
  15694. else
  15695. numSamplesToSearch += numThisTime;
  15696. }
  15697. return -1;
  15698. }
  15699. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  15700. const String& formatName_,
  15701. const double rate,
  15702. const unsigned int numChannels_,
  15703. const unsigned int bitsPerSample_)
  15704. : sampleRate (rate),
  15705. numChannels (numChannels_),
  15706. bitsPerSample (bitsPerSample_),
  15707. usesFloatingPointData (false),
  15708. output (out),
  15709. formatName (formatName_)
  15710. {
  15711. }
  15712. AudioFormatWriter::~AudioFormatWriter()
  15713. {
  15714. delete output;
  15715. }
  15716. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  15717. int64 startSample,
  15718. int64 numSamplesToRead)
  15719. {
  15720. const int bufferSize = 16384;
  15721. const int maxChans = 128;
  15722. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  15723. int* buffers [maxChans];
  15724. for (int i = maxChans; --i >= 0;)
  15725. buffers[i] = 0;
  15726. if (numSamplesToRead < 0)
  15727. numSamplesToRead = reader.lengthInSamples;
  15728. while (numSamplesToRead > 0)
  15729. {
  15730. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  15731. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  15732. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15733. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  15734. return false;
  15735. if (reader.usesFloatingPointData != isFloatingPoint())
  15736. {
  15737. int** bufferChan = buffers;
  15738. while (*bufferChan != 0)
  15739. {
  15740. int* b = *bufferChan++;
  15741. if (isFloatingPoint())
  15742. {
  15743. // int -> float
  15744. const double factor = 1.0 / INT_MAX;
  15745. for (int i = 0; i < numToDo; ++i)
  15746. ((float*)b)[i] = (float) (factor * b[i]);
  15747. }
  15748. else
  15749. {
  15750. // float -> int
  15751. for (int i = 0; i < numToDo; ++i)
  15752. {
  15753. const double samp = *(const float*) b;
  15754. if (samp <= -1.0)
  15755. *b++ = INT_MIN;
  15756. else if (samp >= 1.0)
  15757. *b++ = INT_MAX;
  15758. else
  15759. *b++ = roundDoubleToInt (INT_MAX * samp);
  15760. }
  15761. }
  15762. }
  15763. }
  15764. if (! write ((const int**) buffers, numToDo))
  15765. return false;
  15766. numSamplesToRead -= numToDo;
  15767. startSample += numToDo;
  15768. }
  15769. return true;
  15770. }
  15771. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  15772. int numSamplesToRead,
  15773. const int samplesPerBlock)
  15774. {
  15775. const int maxChans = 128;
  15776. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  15777. int* buffers [maxChans];
  15778. while (numSamplesToRead > 0)
  15779. {
  15780. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  15781. AudioSourceChannelInfo info;
  15782. info.buffer = &tempBuffer;
  15783. info.startSample = 0;
  15784. info.numSamples = numToDo;
  15785. info.clearActiveBufferRegion();
  15786. source.getNextAudioBlock (info);
  15787. int i;
  15788. for (i = maxChans; --i >= 0;)
  15789. buffers[i] = 0;
  15790. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  15791. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15792. if (! isFloatingPoint())
  15793. {
  15794. int** bufferChan = buffers;
  15795. while (*bufferChan != 0)
  15796. {
  15797. int* b = *bufferChan++;
  15798. // float -> int
  15799. for (int j = numToDo; --j >= 0;)
  15800. {
  15801. const double samp = *(const float*) b;
  15802. if (samp <= -1.0)
  15803. *b++ = INT_MIN;
  15804. else if (samp >= 1.0)
  15805. *b++ = INT_MAX;
  15806. else
  15807. *b++ = roundDoubleToInt (INT_MAX * samp);
  15808. }
  15809. }
  15810. }
  15811. if (! write ((const int**) buffers, numToDo))
  15812. return false;
  15813. numSamplesToRead -= numToDo;
  15814. }
  15815. return true;
  15816. }
  15817. AudioFormat::AudioFormat (const String& name,
  15818. const tchar** const extensions)
  15819. : formatName (name),
  15820. fileExtensions (extensions)
  15821. {
  15822. }
  15823. AudioFormat::~AudioFormat()
  15824. {
  15825. }
  15826. const String& AudioFormat::getFormatName() const
  15827. {
  15828. return formatName;
  15829. }
  15830. const StringArray& AudioFormat::getFileExtensions() const
  15831. {
  15832. return fileExtensions;
  15833. }
  15834. bool AudioFormat::canHandleFile (const File& f)
  15835. {
  15836. for (int i = 0; i < fileExtensions.size(); ++i)
  15837. if (f.hasFileExtension (fileExtensions[i]))
  15838. return true;
  15839. return false;
  15840. }
  15841. bool AudioFormat::isCompressed()
  15842. {
  15843. return false;
  15844. }
  15845. const StringArray AudioFormat::getQualityOptions()
  15846. {
  15847. return StringArray();
  15848. }
  15849. END_JUCE_NAMESPACE
  15850. /********* End of inlined file: juce_AudioFormat.cpp *********/
  15851. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  15852. BEGIN_JUCE_NAMESPACE
  15853. AudioFormatManager::AudioFormatManager()
  15854. : knownFormats (4),
  15855. defaultFormatIndex (0)
  15856. {
  15857. }
  15858. AudioFormatManager::~AudioFormatManager()
  15859. {
  15860. clearFormats();
  15861. clearSingletonInstance();
  15862. }
  15863. juce_ImplementSingleton (AudioFormatManager);
  15864. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  15865. const bool makeThisTheDefaultFormat)
  15866. {
  15867. jassert (newFormat != 0);
  15868. if (newFormat != 0)
  15869. {
  15870. #ifdef JUCE_DEBUG
  15871. for (int i = getNumKnownFormats(); --i >= 0;)
  15872. {
  15873. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  15874. {
  15875. jassertfalse // trying to add the same format twice!
  15876. }
  15877. }
  15878. #endif
  15879. if (makeThisTheDefaultFormat)
  15880. defaultFormatIndex = knownFormats.size();
  15881. knownFormats.add (newFormat);
  15882. }
  15883. }
  15884. void AudioFormatManager::registerBasicFormats()
  15885. {
  15886. #if JUCE_MAC
  15887. registerFormat (new AiffAudioFormat(), true);
  15888. registerFormat (new WavAudioFormat(), false);
  15889. #else
  15890. registerFormat (new WavAudioFormat(), true);
  15891. registerFormat (new AiffAudioFormat(), false);
  15892. #endif
  15893. #if JUCE_USE_FLAC
  15894. registerFormat (new FlacAudioFormat(), false);
  15895. #endif
  15896. #if JUCE_USE_OGGVORBIS
  15897. registerFormat (new OggVorbisAudioFormat(), false);
  15898. #endif
  15899. }
  15900. void AudioFormatManager::clearFormats()
  15901. {
  15902. for (int i = getNumKnownFormats(); --i >= 0;)
  15903. {
  15904. AudioFormat* const af = getKnownFormat(i);
  15905. delete af;
  15906. }
  15907. knownFormats.clear();
  15908. defaultFormatIndex = 0;
  15909. }
  15910. int AudioFormatManager::getNumKnownFormats() const
  15911. {
  15912. return knownFormats.size();
  15913. }
  15914. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  15915. {
  15916. return (AudioFormat*) knownFormats [index];
  15917. }
  15918. AudioFormat* AudioFormatManager::getDefaultFormat() const
  15919. {
  15920. return getKnownFormat (defaultFormatIndex);
  15921. }
  15922. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  15923. {
  15924. String e (fileExtension);
  15925. if (! e.startsWithChar (T('.')))
  15926. e = T(".") + e;
  15927. for (int i = 0; i < getNumKnownFormats(); ++i)
  15928. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  15929. return getKnownFormat(i);
  15930. return 0;
  15931. }
  15932. const String AudioFormatManager::getWildcardForAllFormats() const
  15933. {
  15934. StringArray allExtensions;
  15935. int i;
  15936. for (i = 0; i < getNumKnownFormats(); ++i)
  15937. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  15938. allExtensions.trim();
  15939. allExtensions.removeEmptyStrings();
  15940. String s;
  15941. for (i = 0; i < allExtensions.size(); ++i)
  15942. {
  15943. s << T('*');
  15944. if (! allExtensions[i].startsWithChar (T('.')))
  15945. s << T('.');
  15946. s << allExtensions[i];
  15947. if (i < allExtensions.size() - 1)
  15948. s << T(';');
  15949. }
  15950. return s;
  15951. }
  15952. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  15953. {
  15954. // you need to actually register some formats before the manager can
  15955. // use them to open a file!
  15956. jassert (knownFormats.size() > 0);
  15957. for (int i = 0; i < getNumKnownFormats(); ++i)
  15958. {
  15959. AudioFormat* const af = getKnownFormat(i);
  15960. if (af->canHandleFile (file))
  15961. {
  15962. InputStream* const in = file.createInputStream();
  15963. if (in != 0)
  15964. {
  15965. AudioFormatReader* const r = af->createReaderFor (in, true);
  15966. if (r != 0)
  15967. return r;
  15968. }
  15969. }
  15970. }
  15971. return 0;
  15972. }
  15973. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  15974. {
  15975. // you need to actually register some formats before the manager can
  15976. // use them to open a file!
  15977. jassert (knownFormats.size() > 0);
  15978. if (in != 0)
  15979. {
  15980. const int64 originalStreamPos = in->getPosition();
  15981. for (int i = 0; i < getNumKnownFormats(); ++i)
  15982. {
  15983. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  15984. if (r != 0)
  15985. return r;
  15986. in->setPosition (originalStreamPos);
  15987. // the stream that is passed-in must be capable of being repositioned so
  15988. // that all the formats can have a go at opening it.
  15989. jassert (in->getPosition() == originalStreamPos);
  15990. }
  15991. delete in;
  15992. }
  15993. return 0;
  15994. }
  15995. END_JUCE_NAMESPACE
  15996. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  15997. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  15998. BEGIN_JUCE_NAMESPACE
  15999. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16000. const int64 startSample_,
  16001. const int64 length_,
  16002. const bool deleteSourceWhenDeleted_)
  16003. : AudioFormatReader (0, source_->getFormatName()),
  16004. source (source_),
  16005. startSample (startSample_),
  16006. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16007. {
  16008. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16009. sampleRate = source->sampleRate;
  16010. bitsPerSample = source->bitsPerSample;
  16011. lengthInSamples = length;
  16012. numChannels = source->numChannels;
  16013. usesFloatingPointData = source->usesFloatingPointData;
  16014. }
  16015. AudioSubsectionReader::~AudioSubsectionReader()
  16016. {
  16017. if (deleteSourceWhenDeleted)
  16018. delete source;
  16019. }
  16020. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16021. int64 startSampleInFile, int numSamples)
  16022. {
  16023. if (startSampleInFile + numSamples > length)
  16024. {
  16025. for (int i = numDestChannels; --i >= 0;)
  16026. if (destSamples[i] != 0)
  16027. zeromem (destSamples[i], sizeof (int) * numSamples);
  16028. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16029. if (numSamples <= 0)
  16030. return true;
  16031. }
  16032. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16033. startSampleInFile + startSample, numSamples);
  16034. }
  16035. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16036. int64 numSamples,
  16037. float& lowestLeft,
  16038. float& highestLeft,
  16039. float& lowestRight,
  16040. float& highestRight)
  16041. {
  16042. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16043. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16044. source->readMaxLevels (startSampleInFile + startSample,
  16045. numSamples,
  16046. lowestLeft,
  16047. highestLeft,
  16048. lowestRight,
  16049. highestRight);
  16050. }
  16051. END_JUCE_NAMESPACE
  16052. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  16053. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  16054. BEGIN_JUCE_NAMESPACE
  16055. const int timeBeforeDeletingReader = 2000;
  16056. struct AudioThumbnailDataFormat
  16057. {
  16058. char thumbnailMagic[4];
  16059. int samplesPerThumbSample;
  16060. int64 totalSamples; // source samples
  16061. int64 numFinishedSamples; // source samples
  16062. int numThumbnailSamples;
  16063. int numChannels;
  16064. int sampleRate;
  16065. char future[16];
  16066. char data[1];
  16067. };
  16068. #if JUCE_BIG_ENDIAN
  16069. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  16070. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  16071. #endif
  16072. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  16073. {
  16074. (void) d;
  16075. #if JUCE_BIG_ENDIAN
  16076. swap (d->samplesPerThumbSample);
  16077. swap (d->totalSamples);
  16078. swap (d->numFinishedSamples);
  16079. swap (d->numThumbnailSamples);
  16080. swap (d->numChannels);
  16081. swap (d->sampleRate);
  16082. #endif
  16083. }
  16084. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16085. AudioFormatManager& formatManagerToUse_,
  16086. AudioThumbnailCache& cacheToUse)
  16087. : formatManagerToUse (formatManagerToUse_),
  16088. cache (cacheToUse),
  16089. source (0),
  16090. reader (0),
  16091. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16092. {
  16093. clear();
  16094. }
  16095. AudioThumbnail::~AudioThumbnail()
  16096. {
  16097. cache.removeThumbnail (this);
  16098. const ScopedLock sl (readerLock);
  16099. deleteAndZero (reader);
  16100. delete source;
  16101. }
  16102. void AudioThumbnail::setSource (InputSource* const newSource)
  16103. {
  16104. cache.removeThumbnail (this);
  16105. timerCallback(); // stops the timer and deletes the reader
  16106. delete source;
  16107. source = newSource;
  16108. clear();
  16109. if (newSource != 0
  16110. && ! (cache.loadThumb (*this, newSource->hashCode())
  16111. && isFullyLoaded()))
  16112. {
  16113. {
  16114. const ScopedLock sl (readerLock);
  16115. reader = createReader();
  16116. }
  16117. if (reader != 0)
  16118. {
  16119. initialiseFromAudioFile (*reader);
  16120. cache.addThumbnail (this);
  16121. }
  16122. }
  16123. sendChangeMessage (this);
  16124. }
  16125. bool AudioThumbnail::useTimeSlice()
  16126. {
  16127. const ScopedLock sl (readerLock);
  16128. if (isFullyLoaded())
  16129. {
  16130. if (reader != 0)
  16131. startTimer (timeBeforeDeletingReader);
  16132. cache.removeThumbnail (this);
  16133. return false;
  16134. }
  16135. if (reader == 0)
  16136. reader = createReader();
  16137. if (reader != 0)
  16138. {
  16139. readNextBlockFromAudioFile (*reader);
  16140. stopTimer();
  16141. sendChangeMessage (this);
  16142. const bool justFinished = isFullyLoaded();
  16143. if (justFinished)
  16144. cache.storeThumb (*this, source->hashCode());
  16145. return ! justFinished;
  16146. }
  16147. return false;
  16148. }
  16149. AudioFormatReader* AudioThumbnail::createReader() const
  16150. {
  16151. if (source != 0)
  16152. {
  16153. InputStream* const audioFileStream = source->createInputStream();
  16154. if (audioFileStream != 0)
  16155. return formatManagerToUse.createReaderFor (audioFileStream);
  16156. }
  16157. return 0;
  16158. }
  16159. void AudioThumbnail::timerCallback()
  16160. {
  16161. stopTimer();
  16162. const ScopedLock sl (readerLock);
  16163. deleteAndZero (reader);
  16164. }
  16165. void AudioThumbnail::clear()
  16166. {
  16167. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16168. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16169. d->thumbnailMagic[0] = 'j';
  16170. d->thumbnailMagic[1] = 'a';
  16171. d->thumbnailMagic[2] = 't';
  16172. d->thumbnailMagic[3] = 'm';
  16173. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16174. d->totalSamples = 0;
  16175. d->numFinishedSamples = 0;
  16176. d->numThumbnailSamples = 0;
  16177. d->numChannels = 0;
  16178. d->sampleRate = 0;
  16179. numSamplesCached = 0;
  16180. cacheNeedsRefilling = true;
  16181. }
  16182. void AudioThumbnail::loadFrom (InputStream& input)
  16183. {
  16184. data.setSize (0);
  16185. input.readIntoMemoryBlock (data);
  16186. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16187. swapEndiannessIfNeeded (d);
  16188. if (! (d->thumbnailMagic[0] == 'j'
  16189. && d->thumbnailMagic[1] == 'a'
  16190. && d->thumbnailMagic[2] == 't'
  16191. && d->thumbnailMagic[3] == 'm'))
  16192. {
  16193. clear();
  16194. }
  16195. numSamplesCached = 0;
  16196. cacheNeedsRefilling = true;
  16197. }
  16198. void AudioThumbnail::saveTo (OutputStream& output) const
  16199. {
  16200. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16201. swapEndiannessIfNeeded (d);
  16202. output.write (data.getData(), data.getSize());
  16203. swapEndiannessIfNeeded (d);
  16204. }
  16205. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  16206. {
  16207. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16208. d->totalSamples = reader.lengthInSamples;
  16209. d->numChannels = jmin (2, reader.numChannels);
  16210. d->numFinishedSamples = 0;
  16211. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  16212. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16213. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16214. d = (AudioThumbnailDataFormat*) data.getData();
  16215. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16216. return d->totalSamples > 0;
  16217. }
  16218. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  16219. {
  16220. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16221. if (d->numFinishedSamples < d->totalSamples)
  16222. {
  16223. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16224. generateSection (reader,
  16225. d->numFinishedSamples,
  16226. numToDo);
  16227. d->numFinishedSamples += numToDo;
  16228. }
  16229. cacheNeedsRefilling = true;
  16230. return (d->numFinishedSamples < d->totalSamples);
  16231. }
  16232. int AudioThumbnail::getNumChannels() const throw()
  16233. {
  16234. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16235. jassert (d != 0);
  16236. return d->numChannels;
  16237. }
  16238. double AudioThumbnail::getTotalLength() const throw()
  16239. {
  16240. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16241. jassert (d != 0);
  16242. if (d->sampleRate > 0)
  16243. return d->totalSamples / (double)d->sampleRate;
  16244. else
  16245. return 0.0;
  16246. }
  16247. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  16248. int64 startSample,
  16249. int numSamples)
  16250. {
  16251. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16252. jassert (d != 0);
  16253. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16254. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16255. char* l = getChannelData (0);
  16256. char* r = getChannelData (1);
  16257. for (int i = firstDataPos; i < lastDataPos; ++i)
  16258. {
  16259. const int sourceStart = i * d->samplesPerThumbSample;
  16260. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16261. float lowestLeft, highestLeft, lowestRight, highestRight;
  16262. reader.readMaxLevels (sourceStart,
  16263. sourceEnd - sourceStart,
  16264. lowestLeft,
  16265. highestLeft,
  16266. lowestRight,
  16267. highestRight);
  16268. int n = i * 2;
  16269. if (r != 0)
  16270. {
  16271. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16272. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16273. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16274. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16275. }
  16276. else
  16277. {
  16278. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16279. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16280. }
  16281. }
  16282. }
  16283. char* AudioThumbnail::getChannelData (int channel) const
  16284. {
  16285. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16286. jassert (d != 0);
  16287. if (channel >= 0 && channel < d->numChannels)
  16288. return d->data + (channel * 2 * d->numThumbnailSamples);
  16289. return 0;
  16290. }
  16291. bool AudioThumbnail::isFullyLoaded() const throw()
  16292. {
  16293. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16294. jassert (d != 0);
  16295. return d->numFinishedSamples >= d->totalSamples;
  16296. }
  16297. void AudioThumbnail::refillCache (const int numSamples,
  16298. double startTime,
  16299. const double timePerPixel)
  16300. {
  16301. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16302. jassert (d != 0);
  16303. if (numSamples <= 0
  16304. || timePerPixel <= 0.0
  16305. || d->sampleRate <= 0)
  16306. {
  16307. numSamplesCached = 0;
  16308. cacheNeedsRefilling = true;
  16309. return;
  16310. }
  16311. if (numSamples == numSamplesCached
  16312. && numChannelsCached == d->numChannels
  16313. && startTime == cachedStart
  16314. && timePerPixel == cachedTimePerPixel
  16315. && ! cacheNeedsRefilling)
  16316. {
  16317. return;
  16318. }
  16319. numSamplesCached = numSamples;
  16320. numChannelsCached = d->numChannels;
  16321. cachedStart = startTime;
  16322. cachedTimePerPixel = timePerPixel;
  16323. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16324. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16325. const ScopedLock sl (readerLock);
  16326. cacheNeedsRefilling = false;
  16327. if (needExtraDetail && reader == 0)
  16328. reader = createReader();
  16329. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16330. {
  16331. startTimer (timeBeforeDeletingReader);
  16332. char* cacheData = (char*) cachedLevels.getData();
  16333. int sample = roundDoubleToInt (startTime * d->sampleRate);
  16334. for (int i = numSamples; --i >= 0;)
  16335. {
  16336. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  16337. if (sample >= 0)
  16338. {
  16339. if (sample >= reader->lengthInSamples)
  16340. break;
  16341. float lmin, lmax, rmin, rmax;
  16342. reader->readMaxLevels (sample,
  16343. jmax (1, nextSample - sample),
  16344. lmin, lmax, rmin, rmax);
  16345. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16346. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16347. if (numChannelsCached > 1)
  16348. {
  16349. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16350. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16351. }
  16352. cacheData += 2 * numChannelsCached;
  16353. }
  16354. startTime += timePerPixel;
  16355. sample = nextSample;
  16356. }
  16357. }
  16358. else
  16359. {
  16360. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16361. {
  16362. char* const data = getChannelData (channelNum);
  16363. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  16364. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16365. startTime = cachedStart;
  16366. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  16367. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16368. for (int i = numSamples; --i >= 0;)
  16369. {
  16370. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16371. if (sample >= 0 && data != 0)
  16372. {
  16373. char mx = -128;
  16374. char mn = 127;
  16375. while (sample <= nextSample)
  16376. {
  16377. if (sample >= numFinished)
  16378. break;
  16379. const int n = sample << 1;
  16380. const char sampMin = data [n];
  16381. const char sampMax = data [n + 1];
  16382. if (sampMin < mn)
  16383. mn = sampMin;
  16384. if (sampMax > mx)
  16385. mx = sampMax;
  16386. ++sample;
  16387. }
  16388. if (mn <= mx)
  16389. {
  16390. cacheData[0] = mn;
  16391. cacheData[1] = mx;
  16392. }
  16393. else
  16394. {
  16395. cacheData[0] = 1;
  16396. cacheData[1] = 0;
  16397. }
  16398. }
  16399. else
  16400. {
  16401. cacheData[0] = 1;
  16402. cacheData[1] = 0;
  16403. }
  16404. cacheData += numChannelsCached * 2;
  16405. startTime += timePerPixel;
  16406. sample = nextSample;
  16407. }
  16408. }
  16409. }
  16410. }
  16411. void AudioThumbnail::drawChannel (Graphics& g,
  16412. int x, int y, int w, int h,
  16413. double startTime,
  16414. double endTime,
  16415. int channelNum,
  16416. const float verticalZoomFactor)
  16417. {
  16418. refillCache (w, startTime, (endTime - startTime) / w);
  16419. if (numSamplesCached >= w
  16420. && channelNum >= 0
  16421. && channelNum < numChannelsCached)
  16422. {
  16423. const float topY = (float) y;
  16424. const float bottomY = topY + h;
  16425. const float midY = topY + h * 0.5f;
  16426. const float vscale = verticalZoomFactor * h / 256.0f;
  16427. const Rectangle clip (g.getClipBounds());
  16428. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16429. w -= skipLeft;
  16430. x += skipLeft;
  16431. const char* cacheData = ((const char*) cachedLevels.getData())
  16432. + (channelNum << 1)
  16433. + skipLeft * (numChannelsCached << 1);
  16434. while (--w >= 0)
  16435. {
  16436. const char mn = cacheData[0];
  16437. const char mx = cacheData[1];
  16438. cacheData += numChannelsCached << 1;
  16439. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16440. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16441. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16442. ++x;
  16443. if (x >= clip.getRight())
  16444. break;
  16445. }
  16446. }
  16447. }
  16448. END_JUCE_NAMESPACE
  16449. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  16450. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  16451. BEGIN_JUCE_NAMESPACE
  16452. struct ThumbnailCacheEntry
  16453. {
  16454. int64 hash;
  16455. uint32 lastUsed;
  16456. MemoryBlock data;
  16457. juce_UseDebuggingNewOperator
  16458. };
  16459. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16460. : TimeSliceThread (T("thumb cache")),
  16461. maxNumThumbsToStore (maxNumThumbsToStore_)
  16462. {
  16463. startThread (2);
  16464. }
  16465. AudioThumbnailCache::~AudioThumbnailCache()
  16466. {
  16467. }
  16468. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16469. {
  16470. for (int i = thumbs.size(); --i >= 0;)
  16471. {
  16472. if (thumbs[i]->hash == hashCode)
  16473. {
  16474. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  16475. thumbs[i]->data.getSize(),
  16476. false);
  16477. thumb.loadFrom (in);
  16478. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16479. return true;
  16480. }
  16481. }
  16482. return false;
  16483. }
  16484. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16485. const int64 hashCode)
  16486. {
  16487. MemoryOutputStream out;
  16488. thumb.saveTo (out);
  16489. ThumbnailCacheEntry* te = 0;
  16490. for (int i = thumbs.size(); --i >= 0;)
  16491. {
  16492. if (thumbs[i]->hash == hashCode)
  16493. {
  16494. te = thumbs[i];
  16495. break;
  16496. }
  16497. }
  16498. if (te == 0)
  16499. {
  16500. te = new ThumbnailCacheEntry();
  16501. te->hash = hashCode;
  16502. if (thumbs.size() < maxNumThumbsToStore)
  16503. {
  16504. thumbs.add (te);
  16505. }
  16506. else
  16507. {
  16508. int oldest = 0;
  16509. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16510. int i;
  16511. for (i = thumbs.size(); --i >= 0;)
  16512. if (thumbs[i]->lastUsed < oldestTime)
  16513. oldest = i;
  16514. thumbs.set (i, te);
  16515. }
  16516. }
  16517. te->lastUsed = Time::getMillisecondCounter();
  16518. te->data.setSize (0);
  16519. te->data.append (out.getData(), out.getDataSize());
  16520. }
  16521. void AudioThumbnailCache::clear()
  16522. {
  16523. thumbs.clear();
  16524. }
  16525. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  16526. {
  16527. addTimeSliceClient (thumb);
  16528. }
  16529. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  16530. {
  16531. removeTimeSliceClient (thumb);
  16532. }
  16533. END_JUCE_NAMESPACE
  16534. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  16535. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16536. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  16537. #if ! JUCE_WINDOWS
  16538. #include <QuickTime/Movies.h>
  16539. #include <QuickTime/QTML.h>
  16540. #include <QuickTime/QuickTimeComponents.h>
  16541. #include <QuickTime/MediaHandlers.h>
  16542. #include <QuickTime/ImageCodec.h>
  16543. #else
  16544. #if JUCE_MSVC
  16545. #pragma warning (push)
  16546. #pragma warning (disable : 4100)
  16547. #endif
  16548. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  16549. add its header directory to your include path.
  16550. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  16551. flag in juce_Config.h
  16552. */
  16553. #include <Movies.h>
  16554. #include <QTML.h>
  16555. #include <QuickTimeComponents.h>
  16556. #include <MediaHandlers.h>
  16557. #include <ImageCodec.h>
  16558. #if JUCE_MSVC
  16559. #pragma warning (pop)
  16560. #endif
  16561. #endif
  16562. BEGIN_JUCE_NAMESPACE
  16563. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  16564. #define quickTimeFormatName TRANS("QuickTime file")
  16565. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  16566. class QTAudioReader : public AudioFormatReader
  16567. {
  16568. public:
  16569. QTAudioReader (InputStream* const input_, const int trackNum_)
  16570. : AudioFormatReader (input_, quickTimeFormatName),
  16571. ok (false),
  16572. movie (0),
  16573. trackNum (trackNum_),
  16574. extractor (0),
  16575. lastSampleRead (0),
  16576. lastThreadId (0),
  16577. dataHandle (0)
  16578. {
  16579. bufferList = (AudioBufferList*) juce_calloc (256);
  16580. #ifdef WIN32
  16581. if (InitializeQTML (0) != noErr)
  16582. return;
  16583. #endif
  16584. if (EnterMovies() != noErr)
  16585. return;
  16586. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  16587. if (! opened)
  16588. return;
  16589. {
  16590. const int numTracks = GetMovieTrackCount (movie);
  16591. int trackCount = 0;
  16592. for (int i = 1; i <= numTracks; ++i)
  16593. {
  16594. track = GetMovieIndTrack (movie, i);
  16595. media = GetTrackMedia (track);
  16596. OSType mediaType;
  16597. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  16598. if (mediaType == SoundMediaType
  16599. && trackCount++ == trackNum_)
  16600. {
  16601. ok = true;
  16602. break;
  16603. }
  16604. }
  16605. }
  16606. if (! ok)
  16607. return;
  16608. ok = false;
  16609. lengthInSamples = GetMediaDecodeDuration (media);
  16610. usesFloatingPointData = false;
  16611. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  16612. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  16613. / GetMediaTimeScale (media);
  16614. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  16615. unsigned long output_layout_size;
  16616. err = MovieAudioExtractionGetPropertyInfo (extractor,
  16617. kQTPropertyClass_MovieAudioExtraction_Audio,
  16618. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16619. 0, &output_layout_size, 0);
  16620. if (err != noErr)
  16621. return;
  16622. AudioChannelLayout* const qt_audio_channel_layout
  16623. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  16624. err = MovieAudioExtractionGetProperty (extractor,
  16625. kQTPropertyClass_MovieAudioExtraction_Audio,
  16626. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16627. output_layout_size, qt_audio_channel_layout, 0);
  16628. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  16629. err = MovieAudioExtractionSetProperty (extractor,
  16630. kQTPropertyClass_MovieAudioExtraction_Audio,
  16631. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16632. sizeof (qt_audio_channel_layout),
  16633. qt_audio_channel_layout);
  16634. juce_free (qt_audio_channel_layout);
  16635. err = MovieAudioExtractionGetProperty (extractor,
  16636. kQTPropertyClass_MovieAudioExtraction_Audio,
  16637. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16638. sizeof (inputStreamDesc),
  16639. &inputStreamDesc, 0);
  16640. if (err != noErr)
  16641. return;
  16642. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  16643. | kAudioFormatFlagIsPacked
  16644. | kAudioFormatFlagsNativeEndian;
  16645. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  16646. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  16647. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  16648. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  16649. err = MovieAudioExtractionSetProperty (extractor,
  16650. kQTPropertyClass_MovieAudioExtraction_Audio,
  16651. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16652. sizeof (inputStreamDesc),
  16653. &inputStreamDesc);
  16654. if (err != noErr)
  16655. return;
  16656. Boolean allChannelsDiscrete = false;
  16657. err = MovieAudioExtractionSetProperty (extractor,
  16658. kQTPropertyClass_MovieAudioExtraction_Movie,
  16659. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  16660. sizeof (allChannelsDiscrete),
  16661. &allChannelsDiscrete);
  16662. if (err != noErr)
  16663. return;
  16664. bufferList->mNumberBuffers = 1;
  16665. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  16666. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  16667. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  16668. sampleRate = inputStreamDesc.mSampleRate;
  16669. bitsPerSample = 16;
  16670. numChannels = inputStreamDesc.mChannelsPerFrame;
  16671. detachThread();
  16672. ok = true;
  16673. }
  16674. ~QTAudioReader()
  16675. {
  16676. if (dataHandle != 0)
  16677. DisposeHandle (dataHandle);
  16678. if (extractor != 0)
  16679. {
  16680. MovieAudioExtractionEnd (extractor);
  16681. extractor = 0;
  16682. }
  16683. checkThreadIsAttached();
  16684. DisposeMovie (movie);
  16685. juce_free (bufferList->mBuffers[0].mData);
  16686. juce_free (bufferList);
  16687. #if JUCE_MAC
  16688. ExitMoviesOnThread ();
  16689. #endif
  16690. }
  16691. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16692. int64 startSampleInFile, int numSamples)
  16693. {
  16694. checkThreadIsAttached();
  16695. while (numSamples > 0)
  16696. {
  16697. if (! loadFrame ((int) startSampleInFile))
  16698. return false;
  16699. const int numToDo = jmin (numSamples, samplesPerFrame);
  16700. for (int j = numDestChannels; --j >= 0;)
  16701. {
  16702. if (destSamples[j] != 0)
  16703. {
  16704. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  16705. for (int i = 0; i < numToDo; ++i)
  16706. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  16707. }
  16708. }
  16709. startOffsetInDestBuffer += numToDo;
  16710. startSampleInFile += numToDo;
  16711. numSamples -= numToDo;
  16712. }
  16713. detachThread();
  16714. return true;
  16715. }
  16716. bool loadFrame (const int sampleNum)
  16717. {
  16718. if (lastSampleRead != sampleNum)
  16719. {
  16720. TimeRecord time;
  16721. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  16722. time.base = 0;
  16723. time.value.hi = 0;
  16724. time.value.lo = (UInt32) sampleNum;
  16725. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  16726. kQTPropertyClass_MovieAudioExtraction_Movie,
  16727. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  16728. sizeof (time), &time);
  16729. if (err != noErr)
  16730. return false;
  16731. }
  16732. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  16733. UInt32 outFlags = 0;
  16734. UInt32 actualNumSamples = samplesPerFrame;
  16735. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  16736. bufferList, &outFlags);
  16737. lastSampleRead = sampleNum + samplesPerFrame;
  16738. return err == noErr;
  16739. }
  16740. juce_UseDebuggingNewOperator
  16741. bool ok;
  16742. private:
  16743. Movie movie;
  16744. Media media;
  16745. Track track;
  16746. const int trackNum;
  16747. double trackUnitsPerFrame;
  16748. int samplesPerFrame;
  16749. int lastSampleRead;
  16750. Thread::ThreadID lastThreadId;
  16751. MovieAudioExtractionRef extractor;
  16752. AudioStreamBasicDescription inputStreamDesc;
  16753. AudioBufferList* bufferList;
  16754. Handle dataHandle;
  16755. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  16756. {
  16757. input->setPosition (offset);
  16758. input->read (dataPtr, size);
  16759. return noErr;
  16760. }
  16761. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  16762. {
  16763. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  16764. }*/
  16765. void checkThreadIsAttached()
  16766. {
  16767. #if JUCE_MAC
  16768. if (Thread::getCurrentThreadId() != lastThreadId)
  16769. EnterMoviesOnThread (0);
  16770. AttachMovieToCurrentThread (movie);
  16771. #endif
  16772. }
  16773. void detachThread()
  16774. {
  16775. #if JUCE_MAC
  16776. DetachMovieFromCurrentThread (movie);
  16777. #endif
  16778. }
  16779. };
  16780. QuickTimeAudioFormat::QuickTimeAudioFormat()
  16781. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  16782. {
  16783. }
  16784. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  16785. {
  16786. }
  16787. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  16788. {
  16789. return Array<int>();
  16790. }
  16791. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  16792. {
  16793. return Array<int>();
  16794. }
  16795. bool QuickTimeAudioFormat::canDoStereo()
  16796. {
  16797. return true;
  16798. }
  16799. bool QuickTimeAudioFormat::canDoMono()
  16800. {
  16801. return true;
  16802. }
  16803. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  16804. const bool deleteStreamIfOpeningFails)
  16805. {
  16806. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  16807. if (! r->ok)
  16808. {
  16809. if (! deleteStreamIfOpeningFails)
  16810. r->input = 0;
  16811. deleteAndZero (r);
  16812. }
  16813. return r;
  16814. }
  16815. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  16816. double /*sampleRateToUse*/,
  16817. unsigned int /*numberOfChannels*/,
  16818. int /*bitsPerSample*/,
  16819. const StringPairArray& /*metadataValues*/,
  16820. int /*qualityOptionIndex*/)
  16821. {
  16822. jassertfalse // not yet implemented!
  16823. return 0;
  16824. }
  16825. END_JUCE_NAMESPACE
  16826. #endif
  16827. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16828. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  16829. BEGIN_JUCE_NAMESPACE
  16830. #define wavFormatName TRANS("WAV file")
  16831. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  16832. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  16833. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  16834. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  16835. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  16836. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  16837. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  16838. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  16839. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  16840. const String& originator,
  16841. const String& originatorRef,
  16842. const Time& date,
  16843. const int64 timeReferenceSamples,
  16844. const String& codingHistory)
  16845. {
  16846. StringPairArray m;
  16847. m.set (bwavDescription, description);
  16848. m.set (bwavOriginator, originator);
  16849. m.set (bwavOriginatorRef, originatorRef);
  16850. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  16851. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  16852. m.set (bwavTimeReference, String (timeReferenceSamples));
  16853. m.set (bwavCodingHistory, codingHistory);
  16854. return m;
  16855. }
  16856. #if JUCE_MSVC
  16857. #pragma pack (push, 1)
  16858. #define PACKED
  16859. #elif defined (JUCE_GCC)
  16860. #define PACKED __attribute__((packed))
  16861. #else
  16862. #define PACKED
  16863. #endif
  16864. struct BWAVChunk
  16865. {
  16866. uint8 description [256];
  16867. uint8 originator [32];
  16868. uint8 originatorRef [32];
  16869. uint8 originationDate [10];
  16870. uint8 originationTime [8];
  16871. uint32 timeRefLow;
  16872. uint32 timeRefHigh;
  16873. uint16 version;
  16874. uint8 umid[64];
  16875. uint8 reserved[190];
  16876. uint8 codingHistory[1];
  16877. void copyTo (StringPairArray& values) const
  16878. {
  16879. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  16880. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  16881. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  16882. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  16883. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  16884. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  16885. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  16886. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  16887. values.set (WavAudioFormat::bwavTimeReference, String (time));
  16888. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  16889. }
  16890. static MemoryBlock createFrom (const StringPairArray& values)
  16891. {
  16892. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (0) - 1;
  16893. MemoryBlock data ((sizeNeeded + 3) & ~3);
  16894. data.fillWith (0);
  16895. BWAVChunk* b = (BWAVChunk*) data.getData();
  16896. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  16897. // as they get called in the right order..
  16898. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  16899. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  16900. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  16901. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  16902. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  16903. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  16904. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  16905. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  16906. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory);
  16907. if (b->description[0] != 0
  16908. || b->originator[0] != 0
  16909. || b->originationDate[0] != 0
  16910. || b->originationTime[0] != 0
  16911. || b->codingHistory[0] != 0
  16912. || time != 0)
  16913. {
  16914. return data;
  16915. }
  16916. return MemoryBlock();
  16917. }
  16918. } PACKED;
  16919. struct SMPLChunk
  16920. {
  16921. struct SampleLoop
  16922. {
  16923. uint32 identifier;
  16924. uint32 type;
  16925. uint32 start;
  16926. uint32 end;
  16927. uint32 fraction;
  16928. uint32 playCount;
  16929. } PACKED;
  16930. uint32 manufacturer;
  16931. uint32 product;
  16932. uint32 samplePeriod;
  16933. uint32 midiUnityNote;
  16934. uint32 midiPitchFraction;
  16935. uint32 smpteFormat;
  16936. uint32 smpteOffset;
  16937. uint32 numSampleLoops;
  16938. uint32 samplerData;
  16939. SampleLoop loops[1];
  16940. void copyTo (StringPairArray& values, const int totalSize) const
  16941. {
  16942. values.set (T("Manufacturer"), String (swapIfBigEndian (manufacturer)));
  16943. values.set (T("Product"), String (swapIfBigEndian (product)));
  16944. values.set (T("SamplePeriod"), String (swapIfBigEndian (samplePeriod)));
  16945. values.set (T("MidiUnityNote"), String (swapIfBigEndian (midiUnityNote)));
  16946. values.set (T("MidiPitchFraction"), String (swapIfBigEndian (midiPitchFraction)));
  16947. values.set (T("SmpteFormat"), String (swapIfBigEndian (smpteFormat)));
  16948. values.set (T("SmpteOffset"), String (swapIfBigEndian (smpteOffset)));
  16949. values.set (T("NumSampleLoops"), String (swapIfBigEndian (numSampleLoops)));
  16950. values.set (T("SamplerData"), String (swapIfBigEndian (samplerData)));
  16951. for (uint32 i = 0; i < numSampleLoops; ++i)
  16952. {
  16953. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  16954. break;
  16955. values.set (String::formatted (T("Loop%dIdentifier"), i), String (swapIfBigEndian (loops[i].identifier)));
  16956. values.set (String::formatted (T("Loop%dType"), i), String (swapIfBigEndian (loops[i].type)));
  16957. values.set (String::formatted (T("Loop%dStart"), i), String (swapIfBigEndian (loops[i].start)));
  16958. values.set (String::formatted (T("Loop%dEnd"), i), String (swapIfBigEndian (loops[i].end)));
  16959. values.set (String::formatted (T("Loop%dFraction"), i), String (swapIfBigEndian (loops[i].fraction)));
  16960. values.set (String::formatted (T("Loop%dPlayCount"), i), String (swapIfBigEndian (loops[i].playCount)));
  16961. }
  16962. }
  16963. } PACKED;
  16964. #if JUCE_MSVC
  16965. #pragma pack (pop)
  16966. #endif
  16967. #undef PACKED
  16968. #undef chunkName
  16969. #define chunkName(a) ((int) littleEndianInt(a))
  16970. class WavAudioFormatReader : public AudioFormatReader
  16971. {
  16972. int bytesPerFrame;
  16973. int64 dataChunkStart, dataLength;
  16974. WavAudioFormatReader (const WavAudioFormatReader&);
  16975. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  16976. public:
  16977. int64 bwavChunkStart, bwavSize;
  16978. WavAudioFormatReader (InputStream* const in)
  16979. : AudioFormatReader (in, wavFormatName),
  16980. dataLength (0),
  16981. bwavChunkStart (0),
  16982. bwavSize (0)
  16983. {
  16984. if (input->readInt() == chunkName ("RIFF"))
  16985. {
  16986. const uint32 len = (uint32) input->readInt();
  16987. const int64 end = input->getPosition() + len;
  16988. bool hasGotType = false;
  16989. bool hasGotData = false;
  16990. if (input->readInt() == chunkName ("WAVE"))
  16991. {
  16992. while (input->getPosition() < end
  16993. && ! input->isExhausted())
  16994. {
  16995. const int chunkType = input->readInt();
  16996. uint32 length = (uint32) input->readInt();
  16997. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  16998. if (chunkType == chunkName ("fmt "))
  16999. {
  17000. // read the format chunk
  17001. const short format = input->readShort();
  17002. const short numChans = input->readShort();
  17003. sampleRate = input->readInt();
  17004. const int bytesPerSec = input->readInt();
  17005. numChannels = numChans;
  17006. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17007. bitsPerSample = 8 * bytesPerFrame / numChans;
  17008. if (format == 3)
  17009. usesFloatingPointData = true;
  17010. else if (format != 1)
  17011. bytesPerFrame = 0;
  17012. hasGotType = true;
  17013. }
  17014. else if (chunkType == chunkName ("data"))
  17015. {
  17016. // get the data chunk's position
  17017. dataLength = length;
  17018. dataChunkStart = input->getPosition();
  17019. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17020. hasGotData = true;
  17021. }
  17022. else if (chunkType == chunkName ("bext"))
  17023. {
  17024. bwavChunkStart = input->getPosition();
  17025. bwavSize = length;
  17026. // Broadcast-wav extension chunk..
  17027. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  17028. input->read (bwav, length);
  17029. bwav->copyTo (metadataValues);
  17030. juce_free (bwav);
  17031. }
  17032. else if (chunkType == chunkName ("smpl"))
  17033. {
  17034. SMPLChunk* const smpl = (SMPLChunk*) juce_calloc (jmax (length + 1, (int) sizeof (SMPLChunk)));
  17035. input->read (smpl, length);
  17036. smpl->copyTo (metadataValues, length);
  17037. juce_free (smpl);
  17038. }
  17039. else if (chunkEnd <= input->getPosition())
  17040. {
  17041. break;
  17042. }
  17043. input->setPosition (chunkEnd);
  17044. }
  17045. }
  17046. }
  17047. }
  17048. ~WavAudioFormatReader()
  17049. {
  17050. }
  17051. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17052. int64 startSampleInFile, int numSamples)
  17053. {
  17054. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17055. if (samplesAvailable < numSamples)
  17056. {
  17057. for (int i = numDestChannels; --i >= 0;)
  17058. if (destSamples[i] != 0)
  17059. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17060. numSamples = (int) samplesAvailable;
  17061. }
  17062. if (numSamples <= 0)
  17063. return true;
  17064. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17065. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17066. char tempBuffer [tempBufSize];
  17067. while (numSamples > 0)
  17068. {
  17069. int* left = destSamples[0];
  17070. if (left != 0)
  17071. left += startOffsetInDestBuffer;
  17072. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17073. if (right != 0)
  17074. right += startOffsetInDestBuffer;
  17075. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17076. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17077. if (bytesRead < numThisTime * bytesPerFrame)
  17078. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17079. if (bitsPerSample == 16)
  17080. {
  17081. const short* src = (const short*) tempBuffer;
  17082. if (numChannels > 1)
  17083. {
  17084. if (left == 0)
  17085. {
  17086. for (int i = numThisTime; --i >= 0;)
  17087. {
  17088. ++src;
  17089. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17090. }
  17091. }
  17092. else if (right == 0)
  17093. {
  17094. for (int i = numThisTime; --i >= 0;)
  17095. {
  17096. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17097. ++src;
  17098. }
  17099. }
  17100. else
  17101. {
  17102. for (int i = numThisTime; --i >= 0;)
  17103. {
  17104. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17105. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17106. }
  17107. }
  17108. }
  17109. else
  17110. {
  17111. for (int i = numThisTime; --i >= 0;)
  17112. {
  17113. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  17114. }
  17115. }
  17116. }
  17117. else if (bitsPerSample == 24)
  17118. {
  17119. const char* src = (const char*) tempBuffer;
  17120. if (numChannels > 1)
  17121. {
  17122. if (left == 0)
  17123. {
  17124. for (int i = numThisTime; --i >= 0;)
  17125. {
  17126. src += 3;
  17127. *right++ = littleEndian24Bit (src) << 8;
  17128. src += 3;
  17129. }
  17130. }
  17131. else if (right == 0)
  17132. {
  17133. for (int i = numThisTime; --i >= 0;)
  17134. {
  17135. *left++ = littleEndian24Bit (src) << 8;
  17136. src += 6;
  17137. }
  17138. }
  17139. else
  17140. {
  17141. for (int i = 0; i < numThisTime; ++i)
  17142. {
  17143. *left++ = littleEndian24Bit (src) << 8;
  17144. src += 3;
  17145. *right++ = littleEndian24Bit (src) << 8;
  17146. src += 3;
  17147. }
  17148. }
  17149. }
  17150. else
  17151. {
  17152. for (int i = 0; i < numThisTime; ++i)
  17153. {
  17154. *left++ = littleEndian24Bit (src) << 8;
  17155. src += 3;
  17156. }
  17157. }
  17158. }
  17159. else if (bitsPerSample == 32)
  17160. {
  17161. const unsigned int* src = (const unsigned int*) tempBuffer;
  17162. unsigned int* l = (unsigned int*) left;
  17163. unsigned int* r = (unsigned int*) right;
  17164. if (numChannels > 1)
  17165. {
  17166. if (l == 0)
  17167. {
  17168. for (int i = numThisTime; --i >= 0;)
  17169. {
  17170. ++src;
  17171. *r++ = swapIfBigEndian (*src++);
  17172. }
  17173. }
  17174. else if (r == 0)
  17175. {
  17176. for (int i = numThisTime; --i >= 0;)
  17177. {
  17178. *l++ = swapIfBigEndian (*src++);
  17179. ++src;
  17180. }
  17181. }
  17182. else
  17183. {
  17184. for (int i = numThisTime; --i >= 0;)
  17185. {
  17186. *l++ = swapIfBigEndian (*src++);
  17187. *r++ = swapIfBigEndian (*src++);
  17188. }
  17189. }
  17190. }
  17191. else
  17192. {
  17193. for (int i = numThisTime; --i >= 0;)
  17194. {
  17195. *l++ = swapIfBigEndian (*src++);
  17196. }
  17197. }
  17198. left = (int*)l;
  17199. right = (int*)r;
  17200. }
  17201. else if (bitsPerSample == 8)
  17202. {
  17203. const unsigned char* src = (const unsigned char*) tempBuffer;
  17204. if (numChannels > 1)
  17205. {
  17206. if (left == 0)
  17207. {
  17208. for (int i = numThisTime; --i >= 0;)
  17209. {
  17210. ++src;
  17211. *right++ = ((int) *src++ - 128) << 24;
  17212. }
  17213. }
  17214. else if (right == 0)
  17215. {
  17216. for (int i = numThisTime; --i >= 0;)
  17217. {
  17218. *left++ = ((int) *src++ - 128) << 24;
  17219. ++src;
  17220. }
  17221. }
  17222. else
  17223. {
  17224. for (int i = numThisTime; --i >= 0;)
  17225. {
  17226. *left++ = ((int) *src++ - 128) << 24;
  17227. *right++ = ((int) *src++ - 128) << 24;
  17228. }
  17229. }
  17230. }
  17231. else
  17232. {
  17233. for (int i = numThisTime; --i >= 0;)
  17234. {
  17235. *left++ = ((int)*src++ - 128) << 24;
  17236. }
  17237. }
  17238. }
  17239. startOffsetInDestBuffer += numThisTime;
  17240. numSamples -= numThisTime;
  17241. }
  17242. if (numSamples > 0)
  17243. {
  17244. for (int i = numDestChannels; --i >= 0;)
  17245. if (destSamples[i] != 0)
  17246. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17247. sizeof (int) * numSamples);
  17248. }
  17249. return true;
  17250. }
  17251. juce_UseDebuggingNewOperator
  17252. };
  17253. class WavAudioFormatWriter : public AudioFormatWriter
  17254. {
  17255. MemoryBlock tempBlock, bwavChunk;
  17256. uint32 lengthInSamples, bytesWritten;
  17257. int64 headerPosition;
  17258. bool writeFailed;
  17259. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17260. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17261. void writeHeader()
  17262. {
  17263. const bool seekedOk = output->setPosition (headerPosition);
  17264. (void) seekedOk;
  17265. // if this fails, you've given it an output stream that can't seek! It needs
  17266. // to be able to seek back to write the header
  17267. jassert (seekedOk);
  17268. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17269. output->writeInt (chunkName ("RIFF"));
  17270. output->writeInt (lengthInSamples * bytesPerFrame
  17271. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  17272. output->writeInt (chunkName ("WAVE"));
  17273. output->writeInt (chunkName ("fmt "));
  17274. output->writeInt (16);
  17275. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17276. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17277. output->writeShort ((short) numChannels);
  17278. output->writeInt ((int) sampleRate);
  17279. output->writeInt (bytesPerFrame * (int) sampleRate);
  17280. output->writeShort ((short) bytesPerFrame);
  17281. output->writeShort ((short) bitsPerSample);
  17282. if (bwavChunk.getSize() > 0)
  17283. {
  17284. output->writeInt (chunkName ("bext"));
  17285. output->writeInt (bwavChunk.getSize());
  17286. output->write (bwavChunk.getData(), bwavChunk.getSize());
  17287. }
  17288. output->writeInt (chunkName ("data"));
  17289. output->writeInt (lengthInSamples * bytesPerFrame);
  17290. usesFloatingPointData = (bitsPerSample == 32);
  17291. }
  17292. public:
  17293. WavAudioFormatWriter (OutputStream* const out,
  17294. const double sampleRate,
  17295. const unsigned int numChannels_,
  17296. const int bits,
  17297. const StringPairArray& metadataValues)
  17298. : AudioFormatWriter (out,
  17299. wavFormatName,
  17300. sampleRate,
  17301. numChannels_,
  17302. bits),
  17303. lengthInSamples (0),
  17304. bytesWritten (0),
  17305. writeFailed (false)
  17306. {
  17307. if (metadataValues.size() > 0)
  17308. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17309. headerPosition = out->getPosition();
  17310. writeHeader();
  17311. }
  17312. ~WavAudioFormatWriter()
  17313. {
  17314. writeHeader();
  17315. }
  17316. bool write (const int** data, int numSamples)
  17317. {
  17318. if (writeFailed)
  17319. return false;
  17320. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17321. tempBlock.ensureSize (bytes, false);
  17322. char* buffer = (char*) tempBlock.getData();
  17323. const int* left = data[0];
  17324. const int* right = data[1];
  17325. if (right == 0)
  17326. right = left;
  17327. if (bitsPerSample == 16)
  17328. {
  17329. short* b = (short*) buffer;
  17330. if (numChannels > 1)
  17331. {
  17332. for (int i = numSamples; --i >= 0;)
  17333. {
  17334. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17335. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17336. }
  17337. }
  17338. else
  17339. {
  17340. for (int i = numSamples; --i >= 0;)
  17341. {
  17342. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17343. }
  17344. }
  17345. }
  17346. else if (bitsPerSample == 24)
  17347. {
  17348. char* b = (char*) buffer;
  17349. if (numChannels > 1)
  17350. {
  17351. for (int i = numSamples; --i >= 0;)
  17352. {
  17353. littleEndian24BitToChars ((*left++) >> 8, b);
  17354. b += 3;
  17355. littleEndian24BitToChars ((*right++) >> 8, b);
  17356. b += 3;
  17357. }
  17358. }
  17359. else
  17360. {
  17361. for (int i = numSamples; --i >= 0;)
  17362. {
  17363. littleEndian24BitToChars ((*left++) >> 8, b);
  17364. b += 3;
  17365. }
  17366. }
  17367. }
  17368. else if (bitsPerSample == 32)
  17369. {
  17370. unsigned int* b = (unsigned int*) buffer;
  17371. if (numChannels > 1)
  17372. {
  17373. for (int i = numSamples; --i >= 0;)
  17374. {
  17375. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17376. *b++ = swapIfBigEndian ((unsigned int) *right++);
  17377. }
  17378. }
  17379. else
  17380. {
  17381. for (int i = numSamples; --i >= 0;)
  17382. {
  17383. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17384. }
  17385. }
  17386. }
  17387. else if (bitsPerSample == 8)
  17388. {
  17389. unsigned char* b = (unsigned char*) buffer;
  17390. if (numChannels > 1)
  17391. {
  17392. for (int i = numSamples; --i >= 0;)
  17393. {
  17394. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17395. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17396. }
  17397. }
  17398. else
  17399. {
  17400. for (int i = numSamples; --i >= 0;)
  17401. {
  17402. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17403. }
  17404. }
  17405. }
  17406. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17407. || ! output->write (buffer, bytes))
  17408. {
  17409. // failed to write to disk, so let's try writing the header.
  17410. // If it's just run out of disk space, then if it does manage
  17411. // to write the header, we'll still have a useable file..
  17412. writeHeader();
  17413. writeFailed = true;
  17414. return false;
  17415. }
  17416. else
  17417. {
  17418. bytesWritten += bytes;
  17419. lengthInSamples += numSamples;
  17420. return true;
  17421. }
  17422. }
  17423. juce_UseDebuggingNewOperator
  17424. };
  17425. WavAudioFormat::WavAudioFormat()
  17426. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  17427. {
  17428. }
  17429. WavAudioFormat::~WavAudioFormat()
  17430. {
  17431. }
  17432. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17433. {
  17434. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17435. return Array <int> (rates);
  17436. }
  17437. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17438. {
  17439. const int depths[] = { 8, 16, 24, 32, 0 };
  17440. return Array <int> (depths);
  17441. }
  17442. bool WavAudioFormat::canDoStereo()
  17443. {
  17444. return true;
  17445. }
  17446. bool WavAudioFormat::canDoMono()
  17447. {
  17448. return true;
  17449. }
  17450. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  17451. const bool deleteStreamIfOpeningFails)
  17452. {
  17453. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  17454. if (r->sampleRate == 0)
  17455. {
  17456. if (! deleteStreamIfOpeningFails)
  17457. r->input = 0;
  17458. deleteAndZero (r);
  17459. }
  17460. return r;
  17461. }
  17462. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  17463. double sampleRate,
  17464. unsigned int numChannels,
  17465. int bitsPerSample,
  17466. const StringPairArray& metadataValues,
  17467. int /*qualityOptionIndex*/)
  17468. {
  17469. if (getPossibleBitDepths().contains (bitsPerSample))
  17470. {
  17471. return new WavAudioFormatWriter (out,
  17472. sampleRate,
  17473. numChannels,
  17474. bitsPerSample,
  17475. metadataValues);
  17476. }
  17477. return 0;
  17478. }
  17479. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  17480. {
  17481. bool ok = false;
  17482. WavAudioFormat wav;
  17483. const File dest (file.getNonexistentSibling());
  17484. OutputStream* outStream = dest.createOutputStream();
  17485. if (outStream != 0)
  17486. {
  17487. AudioFormatReader* reader = wav.createReaderFor (file.createInputStream(), true);
  17488. if (reader != 0)
  17489. {
  17490. AudioFormatWriter* writer = wav.createWriterFor (outStream, reader->sampleRate,
  17491. reader->numChannels, reader->bitsPerSample,
  17492. metadata, 0);
  17493. if (writer != 0)
  17494. {
  17495. ok = writer->writeFromAudioReader (*reader, 0, -1);
  17496. outStream = 0;
  17497. delete writer;
  17498. }
  17499. delete reader;
  17500. }
  17501. delete outStream;
  17502. }
  17503. if (ok)
  17504. ok = dest.moveFileTo (file);
  17505. if (! ok)
  17506. dest.deleteFile();
  17507. return ok;
  17508. }
  17509. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  17510. {
  17511. WavAudioFormatReader* reader = (WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true);
  17512. if (reader != 0)
  17513. {
  17514. const int64 bwavPos = reader->bwavChunkStart;
  17515. const int64 bwavSize = reader->bwavSize;
  17516. delete reader;
  17517. if (bwavSize > 0)
  17518. {
  17519. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  17520. if (chunk.getSize() <= bwavSize)
  17521. {
  17522. // the new one will fit in the space available, so write it directly..
  17523. const int64 oldSize = wavFile.getSize();
  17524. FileOutputStream* out = wavFile.createOutputStream();
  17525. out->setPosition (bwavPos);
  17526. out->write (chunk.getData(), chunk.getSize());
  17527. out->setPosition (oldSize);
  17528. delete out;
  17529. jassert (wavFile.getSize() == oldSize);
  17530. return true;
  17531. }
  17532. }
  17533. }
  17534. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  17535. }
  17536. END_JUCE_NAMESPACE
  17537. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  17538. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17539. BEGIN_JUCE_NAMESPACE
  17540. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  17541. const bool deleteReaderWhenThisIsDeleted)
  17542. : reader (reader_),
  17543. deleteReader (deleteReaderWhenThisIsDeleted),
  17544. nextPlayPos (0),
  17545. looping (false)
  17546. {
  17547. jassert (reader != 0);
  17548. }
  17549. AudioFormatReaderSource::~AudioFormatReaderSource()
  17550. {
  17551. releaseResources();
  17552. if (deleteReader)
  17553. delete reader;
  17554. }
  17555. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  17556. {
  17557. nextPlayPos = newPosition;
  17558. }
  17559. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  17560. {
  17561. looping = shouldLoop;
  17562. }
  17563. int AudioFormatReaderSource::getNextReadPosition() const
  17564. {
  17565. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  17566. : nextPlayPos;
  17567. }
  17568. int AudioFormatReaderSource::getTotalLength() const
  17569. {
  17570. return (int) reader->lengthInSamples;
  17571. }
  17572. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  17573. double /*sampleRate*/)
  17574. {
  17575. }
  17576. void AudioFormatReaderSource::releaseResources()
  17577. {
  17578. }
  17579. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17580. {
  17581. if (info.numSamples > 0)
  17582. {
  17583. const int start = nextPlayPos;
  17584. if (looping)
  17585. {
  17586. const int newStart = start % (int) reader->lengthInSamples;
  17587. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  17588. if (newEnd > newStart)
  17589. {
  17590. info.buffer->readFromAudioReader (reader,
  17591. info.startSample,
  17592. newEnd - newStart,
  17593. newStart,
  17594. true, true);
  17595. }
  17596. else
  17597. {
  17598. const int endSamps = (int) reader->lengthInSamples - newStart;
  17599. info.buffer->readFromAudioReader (reader,
  17600. info.startSample,
  17601. endSamps,
  17602. newStart,
  17603. true, true);
  17604. info.buffer->readFromAudioReader (reader,
  17605. info.startSample + endSamps,
  17606. newEnd,
  17607. 0,
  17608. true, true);
  17609. }
  17610. nextPlayPos = newEnd;
  17611. }
  17612. else
  17613. {
  17614. info.buffer->readFromAudioReader (reader,
  17615. info.startSample,
  17616. info.numSamples,
  17617. start,
  17618. true, true);
  17619. nextPlayPos += info.numSamples;
  17620. }
  17621. }
  17622. }
  17623. END_JUCE_NAMESPACE
  17624. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17625. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  17626. BEGIN_JUCE_NAMESPACE
  17627. AudioSourcePlayer::AudioSourcePlayer()
  17628. : source (0),
  17629. sampleRate (0),
  17630. bufferSize (0),
  17631. tempBuffer (2, 8),
  17632. lastGain (1.0f),
  17633. gain (1.0f)
  17634. {
  17635. }
  17636. AudioSourcePlayer::~AudioSourcePlayer()
  17637. {
  17638. setSource (0);
  17639. }
  17640. void AudioSourcePlayer::setSource (AudioSource* newSource)
  17641. {
  17642. if (source != newSource)
  17643. {
  17644. AudioSource* const oldSource = source;
  17645. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  17646. newSource->prepareToPlay (bufferSize, sampleRate);
  17647. {
  17648. const ScopedLock sl (readLock);
  17649. source = newSource;
  17650. }
  17651. if (oldSource != 0)
  17652. oldSource->releaseResources();
  17653. }
  17654. }
  17655. void AudioSourcePlayer::setGain (const float newGain) throw()
  17656. {
  17657. gain = newGain;
  17658. }
  17659. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  17660. int totalNumInputChannels,
  17661. float** outputChannelData,
  17662. int totalNumOutputChannels,
  17663. int numSamples)
  17664. {
  17665. // these should have been prepared by audioDeviceAboutToStart()...
  17666. jassert (sampleRate > 0 && bufferSize > 0);
  17667. const ScopedLock sl (readLock);
  17668. if (source != 0)
  17669. {
  17670. AudioSourceChannelInfo info;
  17671. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  17672. // messy stuff needed to compact the channels down into an array
  17673. // of non-zero pointers..
  17674. for (i = 0; i < totalNumInputChannels; ++i)
  17675. {
  17676. if (inputChannelData[i] != 0)
  17677. {
  17678. inputChans [numInputs++] = inputChannelData[i];
  17679. if (numInputs >= numElementsInArray (inputChans))
  17680. break;
  17681. }
  17682. }
  17683. for (i = 0; i < totalNumOutputChannels; ++i)
  17684. {
  17685. if (outputChannelData[i] != 0)
  17686. {
  17687. outputChans [numOutputs++] = outputChannelData[i];
  17688. if (numOutputs >= numElementsInArray (outputChans))
  17689. break;
  17690. }
  17691. }
  17692. if (numInputs > numOutputs)
  17693. {
  17694. // if there aren't enough output channels for the number of
  17695. // inputs, we need to create some temporary extra ones (can't
  17696. // use the input data in case it gets written to)
  17697. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  17698. false, false, true);
  17699. for (i = 0; i < numOutputs; ++i)
  17700. {
  17701. channels[numActiveChans] = outputChans[i];
  17702. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17703. ++numActiveChans;
  17704. }
  17705. for (i = numOutputs; i < numInputs; ++i)
  17706. {
  17707. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  17708. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17709. ++numActiveChans;
  17710. }
  17711. }
  17712. else
  17713. {
  17714. for (i = 0; i < numInputs; ++i)
  17715. {
  17716. channels[numActiveChans] = outputChans[i];
  17717. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17718. ++numActiveChans;
  17719. }
  17720. for (i = numInputs; i < numOutputs; ++i)
  17721. {
  17722. channels[numActiveChans] = outputChans[i];
  17723. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  17724. ++numActiveChans;
  17725. }
  17726. }
  17727. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  17728. info.buffer = &buffer;
  17729. info.startSample = 0;
  17730. info.numSamples = numSamples;
  17731. source->getNextAudioBlock (info);
  17732. for (i = info.buffer->getNumChannels(); --i >= 0;)
  17733. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  17734. lastGain = gain;
  17735. }
  17736. else
  17737. {
  17738. for (int i = 0; i < totalNumOutputChannels; ++i)
  17739. if (outputChannelData[i] != 0)
  17740. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17741. }
  17742. }
  17743. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  17744. {
  17745. sampleRate = device->getCurrentSampleRate();
  17746. bufferSize = device->getCurrentBufferSizeSamples();
  17747. zeromem (channels, sizeof (channels));
  17748. if (source != 0)
  17749. source->prepareToPlay (bufferSize, sampleRate);
  17750. }
  17751. void AudioSourcePlayer::audioDeviceStopped()
  17752. {
  17753. if (source != 0)
  17754. source->releaseResources();
  17755. sampleRate = 0.0;
  17756. bufferSize = 0;
  17757. tempBuffer.setSize (2, 8);
  17758. }
  17759. END_JUCE_NAMESPACE
  17760. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  17761. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  17762. BEGIN_JUCE_NAMESPACE
  17763. AudioTransportSource::AudioTransportSource()
  17764. : source (0),
  17765. resamplerSource (0),
  17766. bufferingSource (0),
  17767. positionableSource (0),
  17768. masterSource (0),
  17769. gain (1.0f),
  17770. lastGain (1.0f),
  17771. playing (false),
  17772. stopped (true),
  17773. sampleRate (44100.0),
  17774. sourceSampleRate (0.0),
  17775. blockSize (128),
  17776. readAheadBufferSize (0),
  17777. isPrepared (false),
  17778. inputStreamEOF (false)
  17779. {
  17780. }
  17781. AudioTransportSource::~AudioTransportSource()
  17782. {
  17783. setSource (0);
  17784. releaseResources();
  17785. }
  17786. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  17787. int readAheadBufferSize_,
  17788. double sourceSampleRateToCorrectFor)
  17789. {
  17790. if (source == newSource)
  17791. {
  17792. if (source == 0)
  17793. return;
  17794. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  17795. }
  17796. readAheadBufferSize = readAheadBufferSize_;
  17797. sourceSampleRate = sourceSampleRateToCorrectFor;
  17798. ResamplingAudioSource* newResamplerSource = 0;
  17799. BufferingAudioSource* newBufferingSource = 0;
  17800. PositionableAudioSource* newPositionableSource = 0;
  17801. AudioSource* newMasterSource = 0;
  17802. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  17803. BufferingAudioSource* oldBufferingSource = bufferingSource;
  17804. AudioSource* oldMasterSource = masterSource;
  17805. if (newSource != 0)
  17806. {
  17807. newPositionableSource = newSource;
  17808. if (readAheadBufferSize_ > 0)
  17809. newPositionableSource = newBufferingSource
  17810. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  17811. newPositionableSource->setNextReadPosition (0);
  17812. if (sourceSampleRateToCorrectFor != 0)
  17813. newMasterSource = newResamplerSource
  17814. = new ResamplingAudioSource (newPositionableSource, false);
  17815. else
  17816. newMasterSource = newPositionableSource;
  17817. if (isPrepared)
  17818. {
  17819. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  17820. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17821. newMasterSource->prepareToPlay (blockSize, sampleRate);
  17822. }
  17823. }
  17824. {
  17825. const ScopedLock sl (callbackLock);
  17826. source = newSource;
  17827. resamplerSource = newResamplerSource;
  17828. bufferingSource = newBufferingSource;
  17829. masterSource = newMasterSource;
  17830. positionableSource = newPositionableSource;
  17831. playing = false;
  17832. }
  17833. if (oldMasterSource != 0)
  17834. oldMasterSource->releaseResources();
  17835. delete oldResamplerSource;
  17836. delete oldBufferingSource;
  17837. }
  17838. void AudioTransportSource::start()
  17839. {
  17840. if ((! playing) && masterSource != 0)
  17841. {
  17842. callbackLock.enter();
  17843. playing = true;
  17844. stopped = false;
  17845. inputStreamEOF = false;
  17846. callbackLock.exit();
  17847. sendChangeMessage (this);
  17848. }
  17849. }
  17850. void AudioTransportSource::stop()
  17851. {
  17852. if (playing)
  17853. {
  17854. callbackLock.enter();
  17855. playing = false;
  17856. callbackLock.exit();
  17857. int n = 500;
  17858. while (--n >= 0 && ! stopped)
  17859. Thread::sleep (2);
  17860. sendChangeMessage (this);
  17861. }
  17862. }
  17863. void AudioTransportSource::setPosition (double newPosition)
  17864. {
  17865. if (sampleRate > 0.0)
  17866. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  17867. }
  17868. double AudioTransportSource::getCurrentPosition() const
  17869. {
  17870. if (sampleRate > 0.0)
  17871. return getNextReadPosition() / sampleRate;
  17872. else
  17873. return 0.0;
  17874. }
  17875. void AudioTransportSource::setNextReadPosition (int newPosition)
  17876. {
  17877. if (positionableSource != 0)
  17878. {
  17879. if (sampleRate > 0 && sourceSampleRate > 0)
  17880. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  17881. positionableSource->setNextReadPosition (newPosition);
  17882. }
  17883. }
  17884. int AudioTransportSource::getNextReadPosition() const
  17885. {
  17886. if (positionableSource != 0)
  17887. {
  17888. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17889. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  17890. }
  17891. return 0;
  17892. }
  17893. int AudioTransportSource::getTotalLength() const
  17894. {
  17895. const ScopedLock sl (callbackLock);
  17896. if (positionableSource != 0)
  17897. {
  17898. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17899. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  17900. }
  17901. return 0;
  17902. }
  17903. bool AudioTransportSource::isLooping() const
  17904. {
  17905. const ScopedLock sl (callbackLock);
  17906. return positionableSource != 0
  17907. && positionableSource->isLooping();
  17908. }
  17909. void AudioTransportSource::setGain (const float newGain) throw()
  17910. {
  17911. gain = newGain;
  17912. }
  17913. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  17914. double sampleRate_)
  17915. {
  17916. const ScopedLock sl (callbackLock);
  17917. sampleRate = sampleRate_;
  17918. blockSize = samplesPerBlockExpected;
  17919. if (masterSource != 0)
  17920. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17921. if (resamplerSource != 0 && sourceSampleRate != 0)
  17922. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17923. isPrepared = true;
  17924. }
  17925. void AudioTransportSource::releaseResources()
  17926. {
  17927. const ScopedLock sl (callbackLock);
  17928. if (masterSource != 0)
  17929. masterSource->releaseResources();
  17930. isPrepared = false;
  17931. }
  17932. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17933. {
  17934. const ScopedLock sl (callbackLock);
  17935. inputStreamEOF = false;
  17936. if (masterSource != 0 && ! stopped)
  17937. {
  17938. masterSource->getNextAudioBlock (info);
  17939. if (! playing)
  17940. {
  17941. // just stopped playing, so fade out the last block..
  17942. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17943. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  17944. if (info.numSamples > 256)
  17945. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  17946. }
  17947. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  17948. && ! positionableSource->isLooping())
  17949. {
  17950. playing = false;
  17951. inputStreamEOF = true;
  17952. sendChangeMessage (this);
  17953. }
  17954. stopped = ! playing;
  17955. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17956. {
  17957. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  17958. lastGain, gain);
  17959. }
  17960. }
  17961. else
  17962. {
  17963. info.clearActiveBufferRegion();
  17964. stopped = true;
  17965. }
  17966. lastGain = gain;
  17967. }
  17968. END_JUCE_NAMESPACE
  17969. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  17970. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  17971. BEGIN_JUCE_NAMESPACE
  17972. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  17973. public Thread,
  17974. private Timer
  17975. {
  17976. public:
  17977. SharedBufferingAudioSourceThread()
  17978. : Thread ("Audio Buffer"),
  17979. sources (8)
  17980. {
  17981. }
  17982. ~SharedBufferingAudioSourceThread()
  17983. {
  17984. stopThread (10000);
  17985. clearSingletonInstance();
  17986. }
  17987. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  17988. void addSource (BufferingAudioSource* source)
  17989. {
  17990. const ScopedLock sl (lock);
  17991. if (! sources.contains ((void*) source))
  17992. {
  17993. sources.add ((void*) source);
  17994. startThread();
  17995. stopTimer();
  17996. }
  17997. notify();
  17998. }
  17999. void removeSource (BufferingAudioSource* source)
  18000. {
  18001. const ScopedLock sl (lock);
  18002. sources.removeValue ((void*) source);
  18003. if (sources.size() == 0)
  18004. startTimer (5000);
  18005. }
  18006. private:
  18007. VoidArray sources;
  18008. CriticalSection lock;
  18009. void run()
  18010. {
  18011. while (! threadShouldExit())
  18012. {
  18013. bool busy = false;
  18014. for (int i = sources.size(); --i >= 0;)
  18015. {
  18016. if (threadShouldExit())
  18017. return;
  18018. const ScopedLock sl (lock);
  18019. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  18020. if (b != 0 && b->readNextBufferChunk())
  18021. busy = true;
  18022. }
  18023. if (! busy)
  18024. wait (500);
  18025. }
  18026. }
  18027. void timerCallback()
  18028. {
  18029. stopTimer();
  18030. if (sources.size() == 0)
  18031. deleteInstance();
  18032. }
  18033. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18034. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18035. };
  18036. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18037. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18038. const bool deleteSourceWhenDeleted_,
  18039. int numberOfSamplesToBuffer_)
  18040. : source (source_),
  18041. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18042. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18043. buffer (2, 0),
  18044. bufferValidStart (0),
  18045. bufferValidEnd (0),
  18046. nextPlayPos (0),
  18047. wasSourceLooping (false)
  18048. {
  18049. jassert (source_ != 0);
  18050. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18051. // not using a larger buffer..
  18052. }
  18053. BufferingAudioSource::~BufferingAudioSource()
  18054. {
  18055. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18056. if (thread != 0)
  18057. thread->removeSource (this);
  18058. if (deleteSourceWhenDeleted)
  18059. delete source;
  18060. }
  18061. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18062. {
  18063. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18064. sampleRate = sampleRate_;
  18065. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18066. buffer.clear();
  18067. bufferValidStart = 0;
  18068. bufferValidEnd = 0;
  18069. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18070. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18071. buffer.getNumSamples() / 2))
  18072. {
  18073. SharedBufferingAudioSourceThread::getInstance()->notify();
  18074. Thread::sleep (5);
  18075. }
  18076. }
  18077. void BufferingAudioSource::releaseResources()
  18078. {
  18079. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18080. if (thread != 0)
  18081. thread->removeSource (this);
  18082. buffer.setSize (2, 0);
  18083. source->releaseResources();
  18084. }
  18085. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18086. {
  18087. const ScopedLock sl (bufferStartPosLock);
  18088. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18089. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18090. if (validStart == validEnd)
  18091. {
  18092. // total cache miss
  18093. info.clearActiveBufferRegion();
  18094. }
  18095. else
  18096. {
  18097. if (validStart > 0)
  18098. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18099. if (validEnd < info.numSamples)
  18100. info.buffer->clear (info.startSample + validEnd,
  18101. info.numSamples - validEnd); // partial cache miss at end
  18102. if (validStart < validEnd)
  18103. {
  18104. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18105. {
  18106. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18107. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18108. if (startBufferIndex < endBufferIndex)
  18109. {
  18110. info.buffer->copyFrom (chan, info.startSample + validStart,
  18111. buffer,
  18112. chan, startBufferIndex,
  18113. validEnd - validStart);
  18114. }
  18115. else
  18116. {
  18117. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18118. info.buffer->copyFrom (chan, info.startSample + validStart,
  18119. buffer,
  18120. chan, startBufferIndex,
  18121. initialSize);
  18122. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18123. buffer,
  18124. chan, 0,
  18125. (validEnd - validStart) - initialSize);
  18126. }
  18127. }
  18128. }
  18129. nextPlayPos += info.numSamples;
  18130. if (source->isLooping() && nextPlayPos > 0)
  18131. nextPlayPos %= source->getTotalLength();
  18132. }
  18133. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18134. if (thread != 0)
  18135. thread->notify();
  18136. }
  18137. int BufferingAudioSource::getNextReadPosition() const
  18138. {
  18139. return (source->isLooping() && nextPlayPos > 0)
  18140. ? nextPlayPos % source->getTotalLength()
  18141. : nextPlayPos;
  18142. }
  18143. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18144. {
  18145. const ScopedLock sl (bufferStartPosLock);
  18146. nextPlayPos = newPosition;
  18147. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18148. if (thread != 0)
  18149. thread->notify();
  18150. }
  18151. bool BufferingAudioSource::readNextBufferChunk()
  18152. {
  18153. bufferStartPosLock.enter();
  18154. if (wasSourceLooping != isLooping())
  18155. {
  18156. wasSourceLooping = isLooping();
  18157. bufferValidStart = 0;
  18158. bufferValidEnd = 0;
  18159. }
  18160. int newBVS = jmax (0, nextPlayPos);
  18161. int newBVE = newBVS + buffer.getNumSamples() - 4;
  18162. int sectionToReadStart = 0;
  18163. int sectionToReadEnd = 0;
  18164. const int maxChunkSize = 2048;
  18165. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18166. {
  18167. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18168. sectionToReadStart = newBVS;
  18169. sectionToReadEnd = newBVE;
  18170. bufferValidStart = 0;
  18171. bufferValidEnd = 0;
  18172. }
  18173. else if (abs (newBVS - bufferValidStart) > 512
  18174. || abs (newBVE - bufferValidEnd) > 512)
  18175. {
  18176. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18177. sectionToReadStart = bufferValidEnd;
  18178. sectionToReadEnd = newBVE;
  18179. bufferValidStart = newBVS;
  18180. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18181. }
  18182. bufferStartPosLock.exit();
  18183. if (sectionToReadStart != sectionToReadEnd)
  18184. {
  18185. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18186. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18187. if (bufferIndexStart < bufferIndexEnd)
  18188. {
  18189. readBufferSection (sectionToReadStart,
  18190. sectionToReadEnd - sectionToReadStart,
  18191. bufferIndexStart);
  18192. }
  18193. else
  18194. {
  18195. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18196. readBufferSection (sectionToReadStart,
  18197. initialSize,
  18198. bufferIndexStart);
  18199. readBufferSection (sectionToReadStart + initialSize,
  18200. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18201. 0);
  18202. }
  18203. const ScopedLock sl2 (bufferStartPosLock);
  18204. bufferValidStart = newBVS;
  18205. bufferValidEnd = newBVE;
  18206. return true;
  18207. }
  18208. else
  18209. {
  18210. return false;
  18211. }
  18212. }
  18213. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18214. {
  18215. if (source->getNextReadPosition() != start)
  18216. source->setNextReadPosition (start);
  18217. AudioSourceChannelInfo info;
  18218. info.buffer = &buffer;
  18219. info.startSample = bufferOffset;
  18220. info.numSamples = length;
  18221. source->getNextAudioBlock (info);
  18222. }
  18223. END_JUCE_NAMESPACE
  18224. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  18225. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18226. BEGIN_JUCE_NAMESPACE
  18227. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18228. const bool deleteSourceWhenDeleted_)
  18229. : requiredNumberOfChannels (2),
  18230. source (source_),
  18231. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18232. buffer (2, 16)
  18233. {
  18234. remappedInfo.buffer = &buffer;
  18235. remappedInfo.startSample = 0;
  18236. }
  18237. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18238. {
  18239. if (deleteSourceWhenDeleted)
  18240. delete source;
  18241. }
  18242. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18243. {
  18244. const ScopedLock sl (lock);
  18245. requiredNumberOfChannels = requiredNumberOfChannels_;
  18246. }
  18247. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18248. {
  18249. const ScopedLock sl (lock);
  18250. remappedInputs.clear();
  18251. remappedOutputs.clear();
  18252. }
  18253. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18254. {
  18255. const ScopedLock sl (lock);
  18256. while (remappedInputs.size() < destIndex)
  18257. remappedInputs.add (-1);
  18258. remappedInputs.set (destIndex, sourceIndex);
  18259. }
  18260. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18261. {
  18262. const ScopedLock sl (lock);
  18263. while (remappedOutputs.size() < sourceIndex)
  18264. remappedOutputs.add (-1);
  18265. remappedOutputs.set (sourceIndex, destIndex);
  18266. }
  18267. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18268. {
  18269. const ScopedLock sl (lock);
  18270. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18271. return remappedInputs.getUnchecked (inputChannelIndex);
  18272. return -1;
  18273. }
  18274. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18275. {
  18276. const ScopedLock sl (lock);
  18277. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18278. return remappedOutputs .getUnchecked (outputChannelIndex);
  18279. return -1;
  18280. }
  18281. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18282. {
  18283. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18284. }
  18285. void ChannelRemappingAudioSource::releaseResources()
  18286. {
  18287. source->releaseResources();
  18288. }
  18289. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18290. {
  18291. const ScopedLock sl (lock);
  18292. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18293. const int numChans = bufferToFill.buffer->getNumChannels();
  18294. int i;
  18295. for (i = 0; i < buffer.getNumChannels(); ++i)
  18296. {
  18297. const int remappedChan = getRemappedInputChannel (i);
  18298. if (remappedChan >= 0 && remappedChan < numChans)
  18299. {
  18300. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18301. remappedChan,
  18302. bufferToFill.startSample,
  18303. bufferToFill.numSamples);
  18304. }
  18305. else
  18306. {
  18307. buffer.clear (i, 0, bufferToFill.numSamples);
  18308. }
  18309. }
  18310. remappedInfo.numSamples = bufferToFill.numSamples;
  18311. source->getNextAudioBlock (remappedInfo);
  18312. bufferToFill.clearActiveBufferRegion();
  18313. for (i = 0; i < requiredNumberOfChannels; ++i)
  18314. {
  18315. const int remappedChan = getRemappedOutputChannel (i);
  18316. if (remappedChan >= 0 && remappedChan < numChans)
  18317. {
  18318. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18319. buffer, i, 0, bufferToFill.numSamples);
  18320. }
  18321. }
  18322. }
  18323. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18324. {
  18325. XmlElement* e = new XmlElement (T("MAPPINGS"));
  18326. String ins, outs;
  18327. int i;
  18328. const ScopedLock sl (lock);
  18329. for (i = 0; i < remappedInputs.size(); ++i)
  18330. ins << remappedInputs.getUnchecked(i) << T(' ');
  18331. for (i = 0; i < remappedOutputs.size(); ++i)
  18332. outs << remappedOutputs.getUnchecked(i) << T(' ');
  18333. e->setAttribute (T("inputs"), ins.trimEnd());
  18334. e->setAttribute (T("outputs"), outs.trimEnd());
  18335. return e;
  18336. }
  18337. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18338. {
  18339. if (e.hasTagName (T("MAPPINGS")))
  18340. {
  18341. const ScopedLock sl (lock);
  18342. clearAllMappings();
  18343. StringArray ins, outs;
  18344. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  18345. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  18346. int i;
  18347. for (i = 0; i < ins.size(); ++i)
  18348. remappedInputs.add (ins[i].getIntValue());
  18349. for (i = 0; i < outs.size(); ++i)
  18350. remappedOutputs.add (outs[i].getIntValue());
  18351. }
  18352. }
  18353. END_JUCE_NAMESPACE
  18354. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18355. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18356. BEGIN_JUCE_NAMESPACE
  18357. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18358. const bool deleteInputWhenDeleted_)
  18359. : input (inputSource),
  18360. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18361. {
  18362. jassert (inputSource != 0);
  18363. for (int i = 2; --i >= 0;)
  18364. iirFilters.add (new IIRFilter());
  18365. }
  18366. IIRFilterAudioSource::~IIRFilterAudioSource()
  18367. {
  18368. if (deleteInputWhenDeleted)
  18369. delete input;
  18370. }
  18371. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18372. {
  18373. for (int i = iirFilters.size(); --i >= 0;)
  18374. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18375. }
  18376. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18377. {
  18378. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18379. for (int i = iirFilters.size(); --i >= 0;)
  18380. iirFilters.getUnchecked(i)->reset();
  18381. }
  18382. void IIRFilterAudioSource::releaseResources()
  18383. {
  18384. input->releaseResources();
  18385. }
  18386. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18387. {
  18388. input->getNextAudioBlock (bufferToFill);
  18389. const int numChannels = bufferToFill.buffer->getNumChannels();
  18390. while (numChannels > iirFilters.size())
  18391. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18392. for (int i = 0; i < numChannels; ++i)
  18393. iirFilters.getUnchecked(i)
  18394. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18395. bufferToFill.numSamples);
  18396. }
  18397. END_JUCE_NAMESPACE
  18398. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18399. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  18400. BEGIN_JUCE_NAMESPACE
  18401. MixerAudioSource::MixerAudioSource()
  18402. : tempBuffer (2, 0),
  18403. currentSampleRate (0.0),
  18404. bufferSizeExpected (0)
  18405. {
  18406. }
  18407. MixerAudioSource::~MixerAudioSource()
  18408. {
  18409. removeAllInputs();
  18410. }
  18411. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18412. {
  18413. if (input != 0 && ! inputs.contains (input))
  18414. {
  18415. lock.enter();
  18416. double localRate = currentSampleRate;
  18417. int localBufferSize = bufferSizeExpected;
  18418. lock.exit();
  18419. if (localRate != 0.0)
  18420. input->prepareToPlay (localBufferSize, localRate);
  18421. const ScopedLock sl (lock);
  18422. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18423. inputs.add (input);
  18424. }
  18425. }
  18426. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18427. {
  18428. if (input != 0)
  18429. {
  18430. lock.enter();
  18431. const int index = inputs.indexOf ((void*) input);
  18432. if (index >= 0)
  18433. {
  18434. inputsToDelete.shiftBits (index, 1);
  18435. inputs.remove (index);
  18436. }
  18437. lock.exit();
  18438. if (index >= 0)
  18439. {
  18440. input->releaseResources();
  18441. if (deleteInput)
  18442. delete input;
  18443. }
  18444. }
  18445. }
  18446. void MixerAudioSource::removeAllInputs()
  18447. {
  18448. lock.enter();
  18449. VoidArray inputsCopy (inputs);
  18450. BitArray inputsToDeleteCopy (inputsToDelete);
  18451. inputs.clear();
  18452. lock.exit();
  18453. for (int i = inputsCopy.size(); --i >= 0;)
  18454. if (inputsToDeleteCopy[i])
  18455. delete (AudioSource*) inputsCopy[i];
  18456. }
  18457. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18458. {
  18459. tempBuffer.setSize (2, samplesPerBlockExpected);
  18460. const ScopedLock sl (lock);
  18461. currentSampleRate = sampleRate;
  18462. bufferSizeExpected = samplesPerBlockExpected;
  18463. for (int i = inputs.size(); --i >= 0;)
  18464. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  18465. sampleRate);
  18466. }
  18467. void MixerAudioSource::releaseResources()
  18468. {
  18469. const ScopedLock sl (lock);
  18470. for (int i = inputs.size(); --i >= 0;)
  18471. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  18472. tempBuffer.setSize (2, 0);
  18473. currentSampleRate = 0;
  18474. bufferSizeExpected = 0;
  18475. }
  18476. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18477. {
  18478. const ScopedLock sl (lock);
  18479. if (inputs.size() > 0)
  18480. {
  18481. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  18482. if (inputs.size() > 1)
  18483. {
  18484. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  18485. info.buffer->getNumSamples());
  18486. AudioSourceChannelInfo info2;
  18487. info2.buffer = &tempBuffer;
  18488. info2.numSamples = info.numSamples;
  18489. info2.startSample = 0;
  18490. for (int i = 1; i < inputs.size(); ++i)
  18491. {
  18492. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  18493. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  18494. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  18495. }
  18496. }
  18497. }
  18498. else
  18499. {
  18500. info.clearActiveBufferRegion();
  18501. }
  18502. }
  18503. END_JUCE_NAMESPACE
  18504. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  18505. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  18506. BEGIN_JUCE_NAMESPACE
  18507. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  18508. const bool deleteInputWhenDeleted_)
  18509. : input (inputSource),
  18510. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  18511. ratio (1.0),
  18512. lastRatio (1.0),
  18513. buffer (2, 0),
  18514. sampsInBuffer (0)
  18515. {
  18516. jassert (input != 0);
  18517. }
  18518. ResamplingAudioSource::~ResamplingAudioSource()
  18519. {
  18520. if (deleteInputWhenDeleted)
  18521. delete input;
  18522. }
  18523. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  18524. {
  18525. jassert (samplesInPerOutputSample > 0);
  18526. const ScopedLock sl (ratioLock);
  18527. ratio = jmax (0.0, samplesInPerOutputSample);
  18528. }
  18529. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  18530. double sampleRate)
  18531. {
  18532. const ScopedLock sl (ratioLock);
  18533. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18534. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  18535. buffer.clear();
  18536. sampsInBuffer = 0;
  18537. bufferPos = 0;
  18538. subSampleOffset = 0.0;
  18539. createLowPass (ratio);
  18540. resetFilters();
  18541. }
  18542. void ResamplingAudioSource::releaseResources()
  18543. {
  18544. input->releaseResources();
  18545. buffer.setSize (2, 0);
  18546. }
  18547. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18548. {
  18549. const ScopedLock sl (ratioLock);
  18550. if (lastRatio != ratio)
  18551. {
  18552. createLowPass (ratio);
  18553. lastRatio = ratio;
  18554. }
  18555. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  18556. int bufferSize = buffer.getNumSamples();
  18557. if (bufferSize < sampsNeeded + 8)
  18558. {
  18559. bufferPos %= bufferSize;
  18560. bufferSize = sampsNeeded + 32;
  18561. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  18562. }
  18563. bufferPos %= bufferSize;
  18564. int endOfBufferPos = bufferPos + sampsInBuffer;
  18565. while (sampsNeeded > sampsInBuffer)
  18566. {
  18567. endOfBufferPos %= bufferSize;
  18568. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  18569. bufferSize - endOfBufferPos);
  18570. AudioSourceChannelInfo readInfo;
  18571. readInfo.buffer = &buffer;
  18572. readInfo.numSamples = numToDo;
  18573. readInfo.startSample = endOfBufferPos;
  18574. input->getNextAudioBlock (readInfo);
  18575. if (ratio > 1.0001)
  18576. {
  18577. // for down-sampling, pre-apply the filter..
  18578. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18579. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  18580. }
  18581. sampsInBuffer += numToDo;
  18582. endOfBufferPos += numToDo;
  18583. }
  18584. float* dl = info.buffer->getSampleData (0, info.startSample);
  18585. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  18586. const float* const bl = buffer.getSampleData (0, 0);
  18587. const float* const br = buffer.getSampleData (1, 0);
  18588. int nextPos = (bufferPos + 1) % bufferSize;
  18589. for (int m = info.numSamples; --m >= 0;)
  18590. {
  18591. const float alpha = (float) subSampleOffset;
  18592. const float invAlpha = 1.0f - alpha;
  18593. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  18594. if (dr != 0)
  18595. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  18596. subSampleOffset += ratio;
  18597. jassert (sampsInBuffer > 0);
  18598. while (subSampleOffset >= 1.0)
  18599. {
  18600. if (++bufferPos >= bufferSize)
  18601. bufferPos = 0;
  18602. --sampsInBuffer;
  18603. nextPos = (bufferPos + 1) % bufferSize;
  18604. subSampleOffset -= 1.0;
  18605. }
  18606. }
  18607. if (ratio < 0.9999)
  18608. {
  18609. // for up-sampling, apply the filter after transposing..
  18610. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18611. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  18612. }
  18613. else if (ratio <= 1.0001)
  18614. {
  18615. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  18616. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18617. {
  18618. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  18619. FilterState& fs = filterStates[i];
  18620. if (info.numSamples > 1)
  18621. {
  18622. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  18623. }
  18624. else
  18625. {
  18626. fs.y2 = fs.y1;
  18627. fs.x2 = fs.x1;
  18628. }
  18629. fs.y1 = fs.x1 = *endOfBuffer;
  18630. }
  18631. }
  18632. jassert (sampsInBuffer >= 0);
  18633. }
  18634. void ResamplingAudioSource::createLowPass (const double ratio)
  18635. {
  18636. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  18637. : 0.5 * ratio;
  18638. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  18639. const double nSquared = n * n;
  18640. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18641. setFilterCoefficients (c1,
  18642. c1 * 2.0f,
  18643. c1,
  18644. 1.0,
  18645. c1 * 2.0 * (1.0 - nSquared),
  18646. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18647. }
  18648. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  18649. {
  18650. const double a = 1.0 / c4;
  18651. c1 *= a;
  18652. c2 *= a;
  18653. c3 *= a;
  18654. c5 *= a;
  18655. c6 *= a;
  18656. coefficients[0] = c1;
  18657. coefficients[1] = c2;
  18658. coefficients[2] = c3;
  18659. coefficients[3] = c4;
  18660. coefficients[4] = c5;
  18661. coefficients[5] = c6;
  18662. }
  18663. void ResamplingAudioSource::resetFilters()
  18664. {
  18665. zeromem (filterStates, sizeof (filterStates));
  18666. }
  18667. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  18668. {
  18669. while (--num >= 0)
  18670. {
  18671. const double in = *samples;
  18672. double out = coefficients[0] * in
  18673. + coefficients[1] * fs.x1
  18674. + coefficients[2] * fs.x2
  18675. - coefficients[4] * fs.y1
  18676. - coefficients[5] * fs.y2;
  18677. #if JUCE_INTEL
  18678. if (! (out < -1.0e-8 || out > 1.0e-8))
  18679. out = 0;
  18680. #endif
  18681. fs.x2 = fs.x1;
  18682. fs.x1 = in;
  18683. fs.y2 = fs.y1;
  18684. fs.y1 = out;
  18685. *samples++ = (float) out;
  18686. }
  18687. }
  18688. END_JUCE_NAMESPACE
  18689. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  18690. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18691. BEGIN_JUCE_NAMESPACE
  18692. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  18693. : frequency (1000.0),
  18694. sampleRate (44100.0),
  18695. currentPhase (0.0),
  18696. phasePerSample (0.0),
  18697. amplitude (0.5f)
  18698. {
  18699. }
  18700. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  18701. {
  18702. }
  18703. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  18704. {
  18705. amplitude = newAmplitude;
  18706. }
  18707. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  18708. {
  18709. frequency = newFrequencyHz;
  18710. phasePerSample = 0.0;
  18711. }
  18712. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18713. double sampleRate_)
  18714. {
  18715. currentPhase = 0.0;
  18716. phasePerSample = 0.0;
  18717. sampleRate = sampleRate_;
  18718. }
  18719. void ToneGeneratorAudioSource::releaseResources()
  18720. {
  18721. }
  18722. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18723. {
  18724. if (phasePerSample == 0.0)
  18725. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  18726. for (int i = 0; i < info.numSamples; ++i)
  18727. {
  18728. const float sample = amplitude * (float) sin (currentPhase);
  18729. currentPhase += phasePerSample;
  18730. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  18731. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  18732. }
  18733. }
  18734. END_JUCE_NAMESPACE
  18735. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18736. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  18737. BEGIN_JUCE_NAMESPACE
  18738. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  18739. : sampleRate (0),
  18740. bufferSize (0),
  18741. useDefaultInputChannels (true),
  18742. useDefaultOutputChannels (true)
  18743. {
  18744. }
  18745. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  18746. {
  18747. return outputDeviceName == other.outputDeviceName
  18748. && inputDeviceName == other.inputDeviceName
  18749. && sampleRate == other.sampleRate
  18750. && bufferSize == other.bufferSize
  18751. && inputChannels == other.inputChannels
  18752. && useDefaultInputChannels == other.useDefaultInputChannels
  18753. && outputChannels == other.outputChannels
  18754. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  18755. }
  18756. AudioDeviceManager::AudioDeviceManager()
  18757. : currentAudioDevice (0),
  18758. numInputChansNeeded (0),
  18759. numOutputChansNeeded (2),
  18760. lastExplicitSettings (0),
  18761. listNeedsScanning (true),
  18762. useInputNames (false),
  18763. inputLevelMeasurementEnabledCount (0),
  18764. inputLevel (0),
  18765. testSound (0),
  18766. tempBuffer (2, 2),
  18767. enabledMidiInputs (4),
  18768. midiCallbacks (4),
  18769. midiCallbackDevices (4),
  18770. defaultMidiOutput (0),
  18771. cpuUsageMs (0),
  18772. timeToCpuScale (0)
  18773. {
  18774. callbackHandler.owner = this;
  18775. }
  18776. AudioDeviceManager::~AudioDeviceManager()
  18777. {
  18778. deleteAndZero (currentAudioDevice);
  18779. deleteAndZero (defaultMidiOutput);
  18780. delete lastExplicitSettings;
  18781. delete testSound;
  18782. }
  18783. void AudioDeviceManager::createDeviceTypesIfNeeded()
  18784. {
  18785. if (availableDeviceTypes.size() == 0)
  18786. {
  18787. createAudioDeviceTypes (availableDeviceTypes);
  18788. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  18789. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  18790. if (availableDeviceTypes.size() > 0)
  18791. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  18792. }
  18793. }
  18794. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  18795. {
  18796. scanDevicesIfNeeded();
  18797. return availableDeviceTypes;
  18798. }
  18799. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  18800. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  18801. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  18802. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  18803. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  18804. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  18805. {
  18806. #if JUCE_WINDOWS
  18807. #if JUCE_WASAPI
  18808. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  18809. list.add (juce_createAudioIODeviceType_WASAPI());
  18810. #endif
  18811. #if JUCE_DIRECTSOUND
  18812. list.add (juce_createAudioIODeviceType_DirectSound());
  18813. #endif
  18814. #if JUCE_ASIO
  18815. list.add (juce_createAudioIODeviceType_ASIO());
  18816. #endif
  18817. #endif
  18818. #if JUCE_MAC
  18819. list.add (juce_createAudioIODeviceType_CoreAudio());
  18820. #endif
  18821. #if JUCE_LINUX && JUCE_ALSA
  18822. list.add (juce_createAudioIODeviceType_ALSA());
  18823. #endif
  18824. }
  18825. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  18826. const int numOutputChannelsNeeded,
  18827. const XmlElement* const e,
  18828. const bool selectDefaultDeviceOnFailure,
  18829. const String& preferredDefaultDeviceName,
  18830. const AudioDeviceSetup* preferredSetupOptions)
  18831. {
  18832. scanDevicesIfNeeded();
  18833. numInputChansNeeded = numInputChannelsNeeded;
  18834. numOutputChansNeeded = numOutputChannelsNeeded;
  18835. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  18836. {
  18837. delete lastExplicitSettings;
  18838. lastExplicitSettings = new XmlElement (*e);
  18839. String error;
  18840. AudioDeviceSetup setup;
  18841. if (preferredSetupOptions != 0)
  18842. setup = *preferredSetupOptions;
  18843. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  18844. {
  18845. setup.inputDeviceName = setup.outputDeviceName
  18846. = e->getStringAttribute (T("audioDeviceName"));
  18847. }
  18848. else
  18849. {
  18850. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  18851. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  18852. }
  18853. currentDeviceType = e->getStringAttribute (T("deviceType"));
  18854. if (currentDeviceType.isEmpty())
  18855. {
  18856. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  18857. if (type != 0)
  18858. currentDeviceType = type->getTypeName();
  18859. else if (availableDeviceTypes.size() > 0)
  18860. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  18861. }
  18862. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  18863. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  18864. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  18865. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  18866. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  18867. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  18868. error = setAudioDeviceSetup (setup, true);
  18869. midiInsFromXml.clear();
  18870. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  18871. midiInsFromXml.add (c->getStringAttribute (T("name")));
  18872. const StringArray allMidiIns (MidiInput::getDevices());
  18873. for (int i = allMidiIns.size(); --i >= 0;)
  18874. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  18875. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  18876. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  18877. false, preferredDefaultDeviceName);
  18878. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  18879. return error;
  18880. }
  18881. else
  18882. {
  18883. AudioDeviceSetup setup;
  18884. if (preferredSetupOptions != 0)
  18885. {
  18886. setup = *preferredSetupOptions;
  18887. }
  18888. else if (preferredDefaultDeviceName.isNotEmpty())
  18889. {
  18890. for (int j = availableDeviceTypes.size(); --j >= 0;)
  18891. {
  18892. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  18893. StringArray outs (type->getDeviceNames (false));
  18894. int i;
  18895. for (i = 0; i < outs.size(); ++i)
  18896. {
  18897. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  18898. {
  18899. setup.outputDeviceName = outs[i];
  18900. break;
  18901. }
  18902. }
  18903. StringArray ins (type->getDeviceNames (true));
  18904. for (i = 0; i < ins.size(); ++i)
  18905. {
  18906. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  18907. {
  18908. setup.inputDeviceName = ins[i];
  18909. break;
  18910. }
  18911. }
  18912. }
  18913. }
  18914. insertDefaultDeviceNames (setup);
  18915. return setAudioDeviceSetup (setup, false);
  18916. }
  18917. }
  18918. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  18919. {
  18920. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18921. if (type != 0)
  18922. {
  18923. if (setup.outputDeviceName.isEmpty())
  18924. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  18925. if (setup.inputDeviceName.isEmpty())
  18926. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  18927. }
  18928. }
  18929. XmlElement* AudioDeviceManager::createStateXml() const
  18930. {
  18931. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  18932. }
  18933. void AudioDeviceManager::scanDevicesIfNeeded()
  18934. {
  18935. if (listNeedsScanning)
  18936. {
  18937. listNeedsScanning = false;
  18938. createDeviceTypesIfNeeded();
  18939. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18940. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  18941. }
  18942. }
  18943. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  18944. {
  18945. scanDevicesIfNeeded();
  18946. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18947. {
  18948. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  18949. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  18950. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  18951. {
  18952. return type;
  18953. }
  18954. }
  18955. return 0;
  18956. }
  18957. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  18958. {
  18959. setup = currentSetup;
  18960. }
  18961. void AudioDeviceManager::deleteCurrentDevice()
  18962. {
  18963. deleteAndZero (currentAudioDevice);
  18964. currentSetup.inputDeviceName = String::empty;
  18965. currentSetup.outputDeviceName = String::empty;
  18966. }
  18967. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  18968. const bool treatAsChosenDevice)
  18969. {
  18970. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18971. {
  18972. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  18973. && currentDeviceType != type)
  18974. {
  18975. currentDeviceType = type;
  18976. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  18977. insertDefaultDeviceNames (s);
  18978. setAudioDeviceSetup (s, treatAsChosenDevice);
  18979. sendChangeMessage (this);
  18980. break;
  18981. }
  18982. }
  18983. }
  18984. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  18985. {
  18986. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18987. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  18988. return availableDeviceTypes[i];
  18989. return availableDeviceTypes[0];
  18990. }
  18991. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  18992. const bool treatAsChosenDevice)
  18993. {
  18994. jassert (&newSetup != &currentSetup); // this will have no effect
  18995. if (newSetup == currentSetup && currentAudioDevice != 0)
  18996. return String::empty;
  18997. if (! (newSetup == currentSetup))
  18998. sendChangeMessage (this);
  18999. stopDevice();
  19000. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19001. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19002. String error;
  19003. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19004. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19005. {
  19006. deleteCurrentDevice();
  19007. if (treatAsChosenDevice)
  19008. updateXml();
  19009. return String::empty;
  19010. }
  19011. if (currentSetup.inputDeviceName != newInputDeviceName
  19012. || currentSetup.outputDeviceName != newOutputDeviceName
  19013. || currentAudioDevice == 0)
  19014. {
  19015. deleteCurrentDevice();
  19016. scanDevicesIfNeeded();
  19017. if (newOutputDeviceName.isNotEmpty()
  19018. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19019. {
  19020. return "No such device: " + newOutputDeviceName;
  19021. }
  19022. if (newInputDeviceName.isNotEmpty()
  19023. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19024. {
  19025. return "No such device: " + newInputDeviceName;
  19026. }
  19027. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19028. if (currentAudioDevice == 0)
  19029. 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!";
  19030. else
  19031. error = currentAudioDevice->getLastError();
  19032. if (error.isNotEmpty())
  19033. {
  19034. deleteCurrentDevice();
  19035. return error;
  19036. }
  19037. if (newSetup.useDefaultInputChannels)
  19038. {
  19039. inputChannels.clear();
  19040. inputChannels.setRange (0, numInputChansNeeded, true);
  19041. }
  19042. if (newSetup.useDefaultOutputChannels)
  19043. {
  19044. outputChannels.clear();
  19045. outputChannels.setRange (0, numOutputChansNeeded, true);
  19046. }
  19047. if (newInputDeviceName.isEmpty())
  19048. inputChannels.clear();
  19049. if (newOutputDeviceName.isEmpty())
  19050. outputChannels.clear();
  19051. }
  19052. if (! newSetup.useDefaultInputChannels)
  19053. inputChannels = newSetup.inputChannels;
  19054. if (! newSetup.useDefaultOutputChannels)
  19055. outputChannels = newSetup.outputChannels;
  19056. currentSetup = newSetup;
  19057. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19058. error = currentAudioDevice->open (inputChannels,
  19059. outputChannels,
  19060. currentSetup.sampleRate,
  19061. currentSetup.bufferSize);
  19062. if (error.isEmpty())
  19063. {
  19064. currentDeviceType = currentAudioDevice->getTypeName();
  19065. currentAudioDevice->start (&callbackHandler);
  19066. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19067. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19068. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19069. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19070. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19071. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19072. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19073. if (treatAsChosenDevice)
  19074. updateXml();
  19075. }
  19076. else
  19077. {
  19078. deleteCurrentDevice();
  19079. }
  19080. return error;
  19081. }
  19082. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19083. {
  19084. jassert (currentAudioDevice != 0);
  19085. if (rate > 0)
  19086. {
  19087. bool ok = false;
  19088. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19089. {
  19090. const double sr = currentAudioDevice->getSampleRate (i);
  19091. if (sr == rate)
  19092. ok = true;
  19093. }
  19094. if (! ok)
  19095. rate = 0;
  19096. }
  19097. if (rate == 0)
  19098. {
  19099. double lowestAbove44 = 0.0;
  19100. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19101. {
  19102. const double sr = currentAudioDevice->getSampleRate (i);
  19103. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19104. lowestAbove44 = sr;
  19105. }
  19106. if (lowestAbove44 == 0.0)
  19107. rate = currentAudioDevice->getSampleRate (0);
  19108. else
  19109. rate = lowestAbove44;
  19110. }
  19111. return rate;
  19112. }
  19113. void AudioDeviceManager::stopDevice()
  19114. {
  19115. if (currentAudioDevice != 0)
  19116. currentAudioDevice->stop();
  19117. deleteAndZero (testSound);
  19118. }
  19119. void AudioDeviceManager::closeAudioDevice()
  19120. {
  19121. stopDevice();
  19122. deleteAndZero (currentAudioDevice);
  19123. }
  19124. void AudioDeviceManager::restartLastAudioDevice()
  19125. {
  19126. if (currentAudioDevice == 0)
  19127. {
  19128. if (currentSetup.inputDeviceName.isEmpty()
  19129. && currentSetup.outputDeviceName.isEmpty())
  19130. {
  19131. // This method will only reload the last device that was running
  19132. // before closeAudioDevice() was called - you need to actually open
  19133. // one first, with setAudioDevice().
  19134. jassertfalse
  19135. return;
  19136. }
  19137. AudioDeviceSetup s (currentSetup);
  19138. setAudioDeviceSetup (s, false);
  19139. }
  19140. }
  19141. void AudioDeviceManager::updateXml()
  19142. {
  19143. delete lastExplicitSettings;
  19144. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  19145. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  19146. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  19147. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  19148. if (currentAudioDevice != 0)
  19149. {
  19150. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  19151. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19152. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  19153. if (! currentSetup.useDefaultInputChannels)
  19154. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  19155. if (! currentSetup.useDefaultOutputChannels)
  19156. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  19157. }
  19158. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19159. {
  19160. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19161. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  19162. lastExplicitSettings->addChildElement (m);
  19163. }
  19164. if (midiInsFromXml.size() > 0)
  19165. {
  19166. // Add any midi devices that have been enabled before, but which aren't currently
  19167. // open because the device has been disconnected.
  19168. const StringArray availableMidiDevices (MidiInput::getDevices());
  19169. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19170. {
  19171. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19172. {
  19173. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19174. m->setAttribute (T("name"), midiInsFromXml[i]);
  19175. lastExplicitSettings->addChildElement (m);
  19176. }
  19177. }
  19178. }
  19179. if (defaultMidiOutputName.isNotEmpty())
  19180. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  19181. }
  19182. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19183. {
  19184. {
  19185. const ScopedLock sl (audioCallbackLock);
  19186. if (callbacks.contains (newCallback))
  19187. return;
  19188. }
  19189. if (currentAudioDevice != 0 && newCallback != 0)
  19190. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19191. const ScopedLock sl (audioCallbackLock);
  19192. callbacks.add (newCallback);
  19193. }
  19194. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19195. {
  19196. if (callback != 0)
  19197. {
  19198. bool needsDeinitialising = currentAudioDevice != 0;
  19199. {
  19200. const ScopedLock sl (audioCallbackLock);
  19201. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19202. callbacks.removeValue (callback);
  19203. }
  19204. if (needsDeinitialising)
  19205. callback->audioDeviceStopped();
  19206. }
  19207. }
  19208. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19209. int numInputChannels,
  19210. float** outputChannelData,
  19211. int numOutputChannels,
  19212. int numSamples)
  19213. {
  19214. const ScopedLock sl (audioCallbackLock);
  19215. if (inputLevelMeasurementEnabledCount > 0)
  19216. {
  19217. for (int j = 0; j < numSamples; ++j)
  19218. {
  19219. float s = 0;
  19220. for (int i = 0; i < numInputChannels; ++i)
  19221. s += fabsf (inputChannelData[i][j]);
  19222. s /= numInputChannels;
  19223. const double decayFactor = 0.99992;
  19224. if (s > inputLevel)
  19225. inputLevel = s;
  19226. else if (inputLevel > 0.001f)
  19227. inputLevel *= decayFactor;
  19228. else
  19229. inputLevel = 0;
  19230. }
  19231. }
  19232. if (callbacks.size() > 0)
  19233. {
  19234. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19235. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19236. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19237. outputChannelData, numOutputChannels, numSamples);
  19238. float** const tempChans = tempBuffer.getArrayOfChannels();
  19239. for (int i = callbacks.size(); --i > 0;)
  19240. {
  19241. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19242. tempChans, numOutputChannels, numSamples);
  19243. for (int chan = 0; chan < numOutputChannels; ++chan)
  19244. {
  19245. const float* const src = tempChans [chan];
  19246. float* const dst = outputChannelData [chan];
  19247. if (src != 0 && dst != 0)
  19248. for (int j = 0; j < numSamples; ++j)
  19249. dst[j] += src[j];
  19250. }
  19251. }
  19252. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19253. const double filterAmount = 0.2;
  19254. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19255. }
  19256. else
  19257. {
  19258. for (int i = 0; i < numOutputChannels; ++i)
  19259. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19260. }
  19261. if (testSound != 0)
  19262. {
  19263. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19264. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19265. for (int i = 0; i < numOutputChannels; ++i)
  19266. for (int j = 0; j < numSamps; ++j)
  19267. outputChannelData [i][j] += src[j];
  19268. testSoundPosition += numSamps;
  19269. if (testSoundPosition >= testSound->getNumSamples())
  19270. {
  19271. delete testSound;
  19272. testSound = 0;
  19273. }
  19274. }
  19275. }
  19276. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19277. {
  19278. cpuUsageMs = 0;
  19279. const double sampleRate = device->getCurrentSampleRate();
  19280. const int blockSize = device->getCurrentBufferSizeSamples();
  19281. if (sampleRate > 0.0 && blockSize > 0)
  19282. {
  19283. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19284. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19285. }
  19286. {
  19287. const ScopedLock sl (audioCallbackLock);
  19288. for (int i = callbacks.size(); --i >= 0;)
  19289. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19290. }
  19291. sendChangeMessage (this);
  19292. }
  19293. void AudioDeviceManager::audioDeviceStoppedInt()
  19294. {
  19295. cpuUsageMs = 0;
  19296. timeToCpuScale = 0;
  19297. sendChangeMessage (this);
  19298. const ScopedLock sl (audioCallbackLock);
  19299. for (int i = callbacks.size(); --i >= 0;)
  19300. callbacks.getUnchecked(i)->audioDeviceStopped();
  19301. }
  19302. double AudioDeviceManager::getCpuUsage() const
  19303. {
  19304. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19305. }
  19306. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19307. const bool enabled)
  19308. {
  19309. if (enabled != isMidiInputEnabled (name))
  19310. {
  19311. if (enabled)
  19312. {
  19313. const int index = MidiInput::getDevices().indexOf (name);
  19314. if (index >= 0)
  19315. {
  19316. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19317. if (min != 0)
  19318. {
  19319. enabledMidiInputs.add (min);
  19320. min->start();
  19321. }
  19322. }
  19323. }
  19324. else
  19325. {
  19326. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19327. if (enabledMidiInputs[i]->getName() == name)
  19328. enabledMidiInputs.remove (i);
  19329. }
  19330. updateXml();
  19331. sendChangeMessage (this);
  19332. }
  19333. }
  19334. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19335. {
  19336. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19337. if (enabledMidiInputs[i]->getName() == name)
  19338. return true;
  19339. return false;
  19340. }
  19341. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19342. MidiInputCallback* callback)
  19343. {
  19344. removeMidiInputCallback (name, callback);
  19345. if (name.isEmpty())
  19346. {
  19347. midiCallbacks.add (callback);
  19348. midiCallbackDevices.add (0);
  19349. }
  19350. else
  19351. {
  19352. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19353. {
  19354. if (enabledMidiInputs[i]->getName() == name)
  19355. {
  19356. const ScopedLock sl (midiCallbackLock);
  19357. midiCallbacks.add (callback);
  19358. midiCallbackDevices.add (enabledMidiInputs[i]);
  19359. break;
  19360. }
  19361. }
  19362. }
  19363. }
  19364. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19365. MidiInputCallback* /*callback*/)
  19366. {
  19367. const ScopedLock sl (midiCallbackLock);
  19368. for (int i = midiCallbacks.size(); --i >= 0;)
  19369. {
  19370. String devName;
  19371. if (midiCallbackDevices.getUnchecked(i) != 0)
  19372. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19373. if (devName == name)
  19374. {
  19375. midiCallbacks.remove (i);
  19376. midiCallbackDevices.remove (i);
  19377. }
  19378. }
  19379. }
  19380. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19381. const MidiMessage& message)
  19382. {
  19383. if (! message.isActiveSense())
  19384. {
  19385. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19386. const ScopedLock sl (midiCallbackLock);
  19387. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19388. {
  19389. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19390. if (md == source || (md == 0 && isDefaultSource))
  19391. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19392. }
  19393. }
  19394. }
  19395. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19396. {
  19397. if (defaultMidiOutputName != deviceName)
  19398. {
  19399. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19400. {
  19401. const ScopedLock sl (audioCallbackLock);
  19402. oldCallbacks = callbacks;
  19403. callbacks.clear();
  19404. }
  19405. if (currentAudioDevice != 0)
  19406. for (int i = oldCallbacks.size(); --i >= 0;)
  19407. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19408. deleteAndZero (defaultMidiOutput);
  19409. defaultMidiOutputName = deviceName;
  19410. if (deviceName.isNotEmpty())
  19411. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19412. if (currentAudioDevice != 0)
  19413. for (int i = oldCallbacks.size(); --i >= 0;)
  19414. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19415. {
  19416. const ScopedLock sl (audioCallbackLock);
  19417. callbacks = oldCallbacks;
  19418. }
  19419. updateXml();
  19420. sendChangeMessage (this);
  19421. }
  19422. }
  19423. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19424. int numInputChannels,
  19425. float** outputChannelData,
  19426. int numOutputChannels,
  19427. int numSamples)
  19428. {
  19429. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19430. }
  19431. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19432. {
  19433. owner->audioDeviceAboutToStartInt (device);
  19434. }
  19435. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19436. {
  19437. owner->audioDeviceStoppedInt();
  19438. }
  19439. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19440. {
  19441. owner->handleIncomingMidiMessageInt (source, message);
  19442. }
  19443. void AudioDeviceManager::playTestSound()
  19444. {
  19445. audioCallbackLock.enter();
  19446. AudioSampleBuffer* oldSound = testSound;
  19447. testSound = 0;
  19448. audioCallbackLock.exit();
  19449. delete oldSound;
  19450. testSoundPosition = 0;
  19451. if (currentAudioDevice != 0)
  19452. {
  19453. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  19454. const int soundLength = (int) sampleRate;
  19455. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  19456. float* samples = newSound->getSampleData (0);
  19457. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  19458. const float amplitude = 0.5f;
  19459. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19460. for (int i = 0; i < soundLength; ++i)
  19461. samples[i] = amplitude * (float) sin (i * phasePerSample);
  19462. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  19463. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  19464. const ScopedLock sl (audioCallbackLock);
  19465. testSound = newSound;
  19466. }
  19467. }
  19468. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  19469. {
  19470. const ScopedLock sl (audioCallbackLock);
  19471. if (enableMeasurement)
  19472. ++inputLevelMeasurementEnabledCount;
  19473. else
  19474. --inputLevelMeasurementEnabledCount;
  19475. inputLevel = 0;
  19476. }
  19477. double AudioDeviceManager::getCurrentInputLevel() const
  19478. {
  19479. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  19480. return inputLevel;
  19481. }
  19482. END_JUCE_NAMESPACE
  19483. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  19484. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  19485. BEGIN_JUCE_NAMESPACE
  19486. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  19487. : name (deviceName),
  19488. typeName (typeName_)
  19489. {
  19490. }
  19491. AudioIODevice::~AudioIODevice()
  19492. {
  19493. }
  19494. bool AudioIODevice::hasControlPanel() const
  19495. {
  19496. return false;
  19497. }
  19498. bool AudioIODevice::showControlPanel()
  19499. {
  19500. jassertfalse // this should only be called for devices which return true from
  19501. // their hasControlPanel() method.
  19502. return false;
  19503. }
  19504. END_JUCE_NAMESPACE
  19505. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  19506. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  19507. BEGIN_JUCE_NAMESPACE
  19508. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  19509. : typeName (name)
  19510. {
  19511. }
  19512. AudioIODeviceType::~AudioIODeviceType()
  19513. {
  19514. }
  19515. END_JUCE_NAMESPACE
  19516. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  19517. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  19518. BEGIN_JUCE_NAMESPACE
  19519. MidiOutput::MidiOutput() throw()
  19520. : Thread ("midi out"),
  19521. internal (0),
  19522. firstMessage (0)
  19523. {
  19524. }
  19525. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  19526. const int len,
  19527. const double sampleNumber) throw()
  19528. : message (data, len, sampleNumber)
  19529. {
  19530. }
  19531. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  19532. const double millisecondCounterToStartAt,
  19533. double samplesPerSecondForBuffer) throw()
  19534. {
  19535. // You've got to call startBackgroundThread() for this to actually work..
  19536. jassert (isThreadRunning());
  19537. // this needs to be a value in the future - RTFM for this method!
  19538. jassert (millisecondCounterToStartAt > 0);
  19539. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  19540. MidiBuffer::Iterator i (buffer);
  19541. const uint8* data;
  19542. int len, time;
  19543. while (i.getNextEvent (data, len, time))
  19544. {
  19545. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  19546. PendingMessage* const m
  19547. = new PendingMessage (data, len, eventTime);
  19548. const ScopedLock sl (lock);
  19549. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  19550. {
  19551. m->next = firstMessage;
  19552. firstMessage = m;
  19553. }
  19554. else
  19555. {
  19556. PendingMessage* mm = firstMessage;
  19557. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  19558. mm = mm->next;
  19559. m->next = mm->next;
  19560. mm->next = m;
  19561. }
  19562. }
  19563. notify();
  19564. }
  19565. void MidiOutput::clearAllPendingMessages() throw()
  19566. {
  19567. const ScopedLock sl (lock);
  19568. while (firstMessage != 0)
  19569. {
  19570. PendingMessage* const m = firstMessage;
  19571. firstMessage = firstMessage->next;
  19572. delete m;
  19573. }
  19574. }
  19575. void MidiOutput::startBackgroundThread() throw()
  19576. {
  19577. startThread (9);
  19578. }
  19579. void MidiOutput::stopBackgroundThread() throw()
  19580. {
  19581. stopThread (5000);
  19582. }
  19583. void MidiOutput::run()
  19584. {
  19585. while (! threadShouldExit())
  19586. {
  19587. uint32 now = Time::getMillisecondCounter();
  19588. uint32 eventTime = 0;
  19589. uint32 timeToWait = 500;
  19590. lock.enter();
  19591. PendingMessage* message = firstMessage;
  19592. if (message != 0)
  19593. {
  19594. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  19595. if (eventTime > now + 20)
  19596. {
  19597. timeToWait = jmax (10, eventTime - now - 100);
  19598. message = 0;
  19599. }
  19600. else
  19601. {
  19602. firstMessage = message->next;
  19603. }
  19604. }
  19605. lock.exit();
  19606. if (message != 0)
  19607. {
  19608. if (eventTime > now)
  19609. {
  19610. Time::waitForMillisecondCounter (eventTime);
  19611. if (threadShouldExit())
  19612. break;
  19613. }
  19614. if (eventTime > now - 200)
  19615. sendMessageNow (message->message);
  19616. delete message;
  19617. }
  19618. else
  19619. {
  19620. jassert (timeToWait < 1000 * 30);
  19621. wait (timeToWait);
  19622. }
  19623. }
  19624. clearAllPendingMessages();
  19625. }
  19626. END_JUCE_NAMESPACE
  19627. /********* End of inlined file: juce_MidiOutput.cpp *********/
  19628. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  19629. BEGIN_JUCE_NAMESPACE
  19630. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19631. {
  19632. const double maxVal = (double) 0x7fff;
  19633. char* intData = (char*) dest;
  19634. if (dest != (void*) source || destBytesPerSample <= 4)
  19635. {
  19636. for (int i = 0; i < numSamples; ++i)
  19637. {
  19638. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19639. intData += destBytesPerSample;
  19640. }
  19641. }
  19642. else
  19643. {
  19644. intData += destBytesPerSample * numSamples;
  19645. for (int i = numSamples; --i >= 0;)
  19646. {
  19647. intData -= destBytesPerSample;
  19648. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19649. }
  19650. }
  19651. }
  19652. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19653. {
  19654. const double maxVal = (double) 0x7fff;
  19655. char* intData = (char*) dest;
  19656. if (dest != (void*) source || destBytesPerSample <= 4)
  19657. {
  19658. for (int i = 0; i < numSamples; ++i)
  19659. {
  19660. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19661. intData += destBytesPerSample;
  19662. }
  19663. }
  19664. else
  19665. {
  19666. intData += destBytesPerSample * numSamples;
  19667. for (int i = numSamples; --i >= 0;)
  19668. {
  19669. intData -= destBytesPerSample;
  19670. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19671. }
  19672. }
  19673. }
  19674. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19675. {
  19676. const double maxVal = (double) 0x7fffff;
  19677. char* intData = (char*) dest;
  19678. if (dest != (void*) source || destBytesPerSample <= 4)
  19679. {
  19680. for (int i = 0; i < numSamples; ++i)
  19681. {
  19682. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19683. intData += destBytesPerSample;
  19684. }
  19685. }
  19686. else
  19687. {
  19688. intData += destBytesPerSample * numSamples;
  19689. for (int i = numSamples; --i >= 0;)
  19690. {
  19691. intData -= destBytesPerSample;
  19692. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19693. }
  19694. }
  19695. }
  19696. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19697. {
  19698. const double maxVal = (double) 0x7fffff;
  19699. char* intData = (char*) dest;
  19700. if (dest != (void*) source || destBytesPerSample <= 4)
  19701. {
  19702. for (int i = 0; i < numSamples; ++i)
  19703. {
  19704. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19705. intData += destBytesPerSample;
  19706. }
  19707. }
  19708. else
  19709. {
  19710. intData += destBytesPerSample * numSamples;
  19711. for (int i = numSamples; --i >= 0;)
  19712. {
  19713. intData -= destBytesPerSample;
  19714. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19715. }
  19716. }
  19717. }
  19718. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19719. {
  19720. const double maxVal = (double) 0x7fffffff;
  19721. char* intData = (char*) dest;
  19722. if (dest != (void*) source || destBytesPerSample <= 4)
  19723. {
  19724. for (int i = 0; i < numSamples; ++i)
  19725. {
  19726. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19727. intData += destBytesPerSample;
  19728. }
  19729. }
  19730. else
  19731. {
  19732. intData += destBytesPerSample * numSamples;
  19733. for (int i = numSamples; --i >= 0;)
  19734. {
  19735. intData -= destBytesPerSample;
  19736. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19737. }
  19738. }
  19739. }
  19740. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19741. {
  19742. const double maxVal = (double) 0x7fffffff;
  19743. char* intData = (char*) dest;
  19744. if (dest != (void*) source || destBytesPerSample <= 4)
  19745. {
  19746. for (int i = 0; i < numSamples; ++i)
  19747. {
  19748. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19749. intData += destBytesPerSample;
  19750. }
  19751. }
  19752. else
  19753. {
  19754. intData += destBytesPerSample * numSamples;
  19755. for (int i = numSamples; --i >= 0;)
  19756. {
  19757. intData -= destBytesPerSample;
  19758. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19759. }
  19760. }
  19761. }
  19762. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19763. {
  19764. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19765. char* d = (char*) dest;
  19766. for (int i = 0; i < numSamples; ++i)
  19767. {
  19768. *(float*)d = source[i];
  19769. #if JUCE_BIG_ENDIAN
  19770. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19771. #endif
  19772. d += destBytesPerSample;
  19773. }
  19774. }
  19775. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19776. {
  19777. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19778. char* d = (char*) dest;
  19779. for (int i = 0; i < numSamples; ++i)
  19780. {
  19781. *(float*)d = source[i];
  19782. #if JUCE_LITTLE_ENDIAN
  19783. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19784. #endif
  19785. d += destBytesPerSample;
  19786. }
  19787. }
  19788. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19789. {
  19790. const float scale = 1.0f / 0x7fff;
  19791. const char* intData = (const char*) source;
  19792. if (source != (void*) dest || srcBytesPerSample >= 4)
  19793. {
  19794. for (int i = 0; i < numSamples; ++i)
  19795. {
  19796. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19797. intData += srcBytesPerSample;
  19798. }
  19799. }
  19800. else
  19801. {
  19802. intData += srcBytesPerSample * numSamples;
  19803. for (int i = numSamples; --i >= 0;)
  19804. {
  19805. intData -= srcBytesPerSample;
  19806. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19807. }
  19808. }
  19809. }
  19810. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19811. {
  19812. const float scale = 1.0f / 0x7fff;
  19813. const char* intData = (const char*) source;
  19814. if (source != (void*) dest || srcBytesPerSample >= 4)
  19815. {
  19816. for (int i = 0; i < numSamples; ++i)
  19817. {
  19818. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19819. intData += srcBytesPerSample;
  19820. }
  19821. }
  19822. else
  19823. {
  19824. intData += srcBytesPerSample * numSamples;
  19825. for (int i = numSamples; --i >= 0;)
  19826. {
  19827. intData -= srcBytesPerSample;
  19828. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19829. }
  19830. }
  19831. }
  19832. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19833. {
  19834. const float scale = 1.0f / 0x7fffff;
  19835. const char* intData = (const char*) source;
  19836. if (source != (void*) dest || srcBytesPerSample >= 4)
  19837. {
  19838. for (int i = 0; i < numSamples; ++i)
  19839. {
  19840. dest[i] = scale * (short) littleEndian24Bit (intData);
  19841. intData += srcBytesPerSample;
  19842. }
  19843. }
  19844. else
  19845. {
  19846. intData += srcBytesPerSample * numSamples;
  19847. for (int i = numSamples; --i >= 0;)
  19848. {
  19849. intData -= srcBytesPerSample;
  19850. dest[i] = scale * (short) littleEndian24Bit (intData);
  19851. }
  19852. }
  19853. }
  19854. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19855. {
  19856. const float scale = 1.0f / 0x7fffff;
  19857. const char* intData = (const char*) source;
  19858. if (source != (void*) dest || srcBytesPerSample >= 4)
  19859. {
  19860. for (int i = 0; i < numSamples; ++i)
  19861. {
  19862. dest[i] = scale * (short) bigEndian24Bit (intData);
  19863. intData += srcBytesPerSample;
  19864. }
  19865. }
  19866. else
  19867. {
  19868. intData += srcBytesPerSample * numSamples;
  19869. for (int i = numSamples; --i >= 0;)
  19870. {
  19871. intData -= srcBytesPerSample;
  19872. dest[i] = scale * (short) bigEndian24Bit (intData);
  19873. }
  19874. }
  19875. }
  19876. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19877. {
  19878. const float scale = 1.0f / 0x7fffffff;
  19879. const char* intData = (const char*) source;
  19880. if (source != (void*) dest || srcBytesPerSample >= 4)
  19881. {
  19882. for (int i = 0; i < numSamples; ++i)
  19883. {
  19884. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19885. intData += srcBytesPerSample;
  19886. }
  19887. }
  19888. else
  19889. {
  19890. intData += srcBytesPerSample * numSamples;
  19891. for (int i = numSamples; --i >= 0;)
  19892. {
  19893. intData -= srcBytesPerSample;
  19894. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19895. }
  19896. }
  19897. }
  19898. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19899. {
  19900. const float scale = 1.0f / 0x7fffffff;
  19901. const char* intData = (const char*) source;
  19902. if (source != (void*) dest || srcBytesPerSample >= 4)
  19903. {
  19904. for (int i = 0; i < numSamples; ++i)
  19905. {
  19906. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19907. intData += srcBytesPerSample;
  19908. }
  19909. }
  19910. else
  19911. {
  19912. intData += srcBytesPerSample * numSamples;
  19913. for (int i = numSamples; --i >= 0;)
  19914. {
  19915. intData -= srcBytesPerSample;
  19916. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19917. }
  19918. }
  19919. }
  19920. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19921. {
  19922. const char* s = (const char*) source;
  19923. for (int i = 0; i < numSamples; ++i)
  19924. {
  19925. dest[i] = *(float*)s;
  19926. #if JUCE_BIG_ENDIAN
  19927. uint32* const d = (uint32*) (dest + i);
  19928. *d = swapByteOrder (*d);
  19929. #endif
  19930. s += srcBytesPerSample;
  19931. }
  19932. }
  19933. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19934. {
  19935. const char* s = (const char*) source;
  19936. for (int i = 0; i < numSamples; ++i)
  19937. {
  19938. dest[i] = *(float*)s;
  19939. #if JUCE_LITTLE_ENDIAN
  19940. uint32* const d = (uint32*) (dest + i);
  19941. *d = swapByteOrder (*d);
  19942. #endif
  19943. s += srcBytesPerSample;
  19944. }
  19945. }
  19946. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  19947. const float* const source,
  19948. void* const dest,
  19949. const int numSamples)
  19950. {
  19951. switch (destFormat)
  19952. {
  19953. case int16LE:
  19954. convertFloatToInt16LE (source, dest, numSamples);
  19955. break;
  19956. case int16BE:
  19957. convertFloatToInt16BE (source, dest, numSamples);
  19958. break;
  19959. case int24LE:
  19960. convertFloatToInt24LE (source, dest, numSamples);
  19961. break;
  19962. case int24BE:
  19963. convertFloatToInt24BE (source, dest, numSamples);
  19964. break;
  19965. case int32LE:
  19966. convertFloatToInt32LE (source, dest, numSamples);
  19967. break;
  19968. case int32BE:
  19969. convertFloatToInt32BE (source, dest, numSamples);
  19970. break;
  19971. case float32LE:
  19972. convertFloatToFloat32LE (source, dest, numSamples);
  19973. break;
  19974. case float32BE:
  19975. convertFloatToFloat32BE (source, dest, numSamples);
  19976. break;
  19977. default:
  19978. jassertfalse
  19979. break;
  19980. }
  19981. }
  19982. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  19983. const void* const source,
  19984. float* const dest,
  19985. const int numSamples)
  19986. {
  19987. switch (sourceFormat)
  19988. {
  19989. case int16LE:
  19990. convertInt16LEToFloat (source, dest, numSamples);
  19991. break;
  19992. case int16BE:
  19993. convertInt16BEToFloat (source, dest, numSamples);
  19994. break;
  19995. case int24LE:
  19996. convertInt24LEToFloat (source, dest, numSamples);
  19997. break;
  19998. case int24BE:
  19999. convertInt24BEToFloat (source, dest, numSamples);
  20000. break;
  20001. case int32LE:
  20002. convertInt32LEToFloat (source, dest, numSamples);
  20003. break;
  20004. case int32BE:
  20005. convertInt32BEToFloat (source, dest, numSamples);
  20006. break;
  20007. case float32LE:
  20008. convertFloat32LEToFloat (source, dest, numSamples);
  20009. break;
  20010. case float32BE:
  20011. convertFloat32BEToFloat (source, dest, numSamples);
  20012. break;
  20013. default:
  20014. jassertfalse
  20015. break;
  20016. }
  20017. }
  20018. void AudioDataConverters::interleaveSamples (const float** const source,
  20019. float* const dest,
  20020. const int numSamples,
  20021. const int numChannels)
  20022. {
  20023. for (int chan = 0; chan < numChannels; ++chan)
  20024. {
  20025. int i = chan;
  20026. const float* src = source [chan];
  20027. for (int j = 0; j < numSamples; ++j)
  20028. {
  20029. dest [i] = src [j];
  20030. i += numChannels;
  20031. }
  20032. }
  20033. }
  20034. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20035. float** const dest,
  20036. const int numSamples,
  20037. const int numChannels)
  20038. {
  20039. for (int chan = 0; chan < numChannels; ++chan)
  20040. {
  20041. int i = chan;
  20042. float* dst = dest [chan];
  20043. for (int j = 0; j < numSamples; ++j)
  20044. {
  20045. dst [j] = source [i];
  20046. i += numChannels;
  20047. }
  20048. }
  20049. }
  20050. END_JUCE_NAMESPACE
  20051. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  20052. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  20053. BEGIN_JUCE_NAMESPACE
  20054. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20055. const int numSamples) throw()
  20056. : numChannels (numChannels_),
  20057. size (numSamples)
  20058. {
  20059. jassert (numSamples >= 0);
  20060. jassert (numChannels_ > 0);
  20061. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  20062. allocatedData = (float*) juce_malloc (allocatedBytes);
  20063. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  20064. float* chan = allocatedData;
  20065. for (int i = 0; i < numChannels_; ++i)
  20066. {
  20067. channels[i] = chan;
  20068. chan += numSamples;
  20069. }
  20070. channels [numChannels_] = 0;
  20071. }
  20072. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20073. const int numChannels_,
  20074. const int numSamples) throw()
  20075. : numChannels (numChannels_),
  20076. size (numSamples),
  20077. allocatedBytes (0),
  20078. allocatedData (0)
  20079. {
  20080. jassert (numChannels_ > 0);
  20081. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20082. if (numChannels_ < numElementsInArray (preallocatedChannelSpace))
  20083. channels = (float**) preallocatedChannelSpace;
  20084. else
  20085. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  20086. for (int i = 0; i < numChannels_; ++i)
  20087. {
  20088. // you have to pass in the same number of valid pointers as numChannels
  20089. jassert (dataToReferTo[i] != 0);
  20090. channels[i] = dataToReferTo[i];
  20091. }
  20092. channels [numChannels_] = 0;
  20093. }
  20094. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20095. const int numChannels_,
  20096. const int numSamples) throw()
  20097. {
  20098. jassert (numChannels_ > 0);
  20099. juce_free (allocatedData);
  20100. allocatedData = 0;
  20101. allocatedBytes = 0;
  20102. if (numChannels_ > numChannels)
  20103. channels = (float**) juce_realloc (channels, (numChannels_ + 1) * sizeof (float*));
  20104. numChannels = numChannels_;
  20105. size = numSamples;
  20106. for (int i = 0; i < numChannels_; ++i)
  20107. {
  20108. // you have to pass in the same number of valid pointers as numChannels
  20109. jassert (dataToReferTo[i] != 0);
  20110. channels[i] = dataToReferTo[i];
  20111. }
  20112. channels [numChannels_] = 0;
  20113. }
  20114. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20115. : numChannels (other.numChannels),
  20116. size (other.size)
  20117. {
  20118. channels = (float**) juce_malloc ((other.numChannels + 1) * sizeof (float*));
  20119. if (other.allocatedData != 0)
  20120. {
  20121. allocatedBytes = numChannels * size * sizeof (float) + 32;
  20122. allocatedData = (float*) juce_malloc (allocatedBytes);
  20123. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  20124. float* chan = allocatedData;
  20125. for (int i = 0; i < numChannels; ++i)
  20126. {
  20127. channels[i] = chan;
  20128. chan += size;
  20129. }
  20130. channels [numChannels] = 0;
  20131. }
  20132. else
  20133. {
  20134. allocatedData = 0;
  20135. allocatedBytes = 0;
  20136. memcpy (channels, other.channels, sizeof (channels));
  20137. }
  20138. }
  20139. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20140. {
  20141. if (this != &other)
  20142. {
  20143. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20144. const int numBytes = size * sizeof (float);
  20145. for (int i = 0; i < numChannels; ++i)
  20146. memcpy (channels[i], other.channels[i], numBytes);
  20147. }
  20148. return *this;
  20149. }
  20150. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20151. {
  20152. juce_free (allocatedData);
  20153. if (channels != (float**) preallocatedChannelSpace)
  20154. juce_free (channels);
  20155. }
  20156. void AudioSampleBuffer::setSize (const int newNumChannels,
  20157. const int newNumSamples,
  20158. const bool keepExistingContent,
  20159. const bool clearExtraSpace,
  20160. const bool avoidReallocating) throw()
  20161. {
  20162. jassert (newNumChannels > 0);
  20163. if (newNumSamples != size || newNumChannels != numChannels)
  20164. {
  20165. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  20166. if (keepExistingContent)
  20167. {
  20168. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20169. : (float*) juce_malloc (newTotalBytes);
  20170. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  20171. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  20172. {
  20173. memcpy (newData + i * newNumSamples,
  20174. channels[i],
  20175. sizeToCopy);
  20176. }
  20177. juce_free (allocatedData);
  20178. allocatedData = newData;
  20179. allocatedBytes = newTotalBytes;
  20180. }
  20181. else
  20182. {
  20183. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20184. {
  20185. if (clearExtraSpace)
  20186. zeromem (allocatedData, newTotalBytes);
  20187. }
  20188. else
  20189. {
  20190. juce_free (allocatedData);
  20191. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20192. : (float*) juce_malloc (newTotalBytes);
  20193. allocatedBytes = newTotalBytes;
  20194. }
  20195. }
  20196. size = newNumSamples;
  20197. if (newNumChannels > numChannels)
  20198. channels = (float**) juce_realloc (channels, (newNumChannels + 1) * sizeof (float*));
  20199. numChannels = newNumChannels;
  20200. float* chan = allocatedData;
  20201. for (int i = 0; i < newNumChannels; ++i)
  20202. {
  20203. channels[i] = chan;
  20204. chan += size;
  20205. }
  20206. channels [newNumChannels] = 0;
  20207. }
  20208. }
  20209. void AudioSampleBuffer::clear() throw()
  20210. {
  20211. for (int i = 0; i < numChannels; ++i)
  20212. zeromem (channels[i], size * sizeof (float));
  20213. }
  20214. void AudioSampleBuffer::clear (const int startSample,
  20215. const int numSamples) throw()
  20216. {
  20217. jassert (startSample >= 0 && startSample + numSamples <= size);
  20218. for (int i = 0; i < numChannels; ++i)
  20219. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20220. }
  20221. void AudioSampleBuffer::clear (const int channel,
  20222. const int startSample,
  20223. const int numSamples) throw()
  20224. {
  20225. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20226. jassert (startSample >= 0 && startSample + numSamples <= size);
  20227. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20228. }
  20229. void AudioSampleBuffer::applyGain (const int channel,
  20230. const int startSample,
  20231. int numSamples,
  20232. const float gain) throw()
  20233. {
  20234. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20235. jassert (startSample >= 0 && startSample + numSamples <= size);
  20236. if (gain != 1.0f)
  20237. {
  20238. float* d = channels [channel] + startSample;
  20239. if (gain == 0.0f)
  20240. {
  20241. zeromem (d, sizeof (float) * numSamples);
  20242. }
  20243. else
  20244. {
  20245. while (--numSamples >= 0)
  20246. *d++ *= gain;
  20247. }
  20248. }
  20249. }
  20250. void AudioSampleBuffer::applyGainRamp (const int channel,
  20251. const int startSample,
  20252. int numSamples,
  20253. float startGain,
  20254. float endGain) throw()
  20255. {
  20256. if (startGain == endGain)
  20257. {
  20258. applyGain (channel, startSample, numSamples, startGain);
  20259. }
  20260. else
  20261. {
  20262. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20263. jassert (startSample >= 0 && startSample + numSamples <= size);
  20264. const float increment = (endGain - startGain) / numSamples;
  20265. float* d = channels [channel] + startSample;
  20266. while (--numSamples >= 0)
  20267. {
  20268. *d++ *= startGain;
  20269. startGain += increment;
  20270. }
  20271. }
  20272. }
  20273. void AudioSampleBuffer::applyGain (const int startSample,
  20274. const int numSamples,
  20275. const float gain) throw()
  20276. {
  20277. for (int i = 0; i < numChannels; ++i)
  20278. applyGain (i, startSample, numSamples, gain);
  20279. }
  20280. void AudioSampleBuffer::addFrom (const int destChannel,
  20281. const int destStartSample,
  20282. const AudioSampleBuffer& source,
  20283. const int sourceChannel,
  20284. const int sourceStartSample,
  20285. int numSamples,
  20286. const float gain) throw()
  20287. {
  20288. jassert (&source != this || sourceChannel != destChannel);
  20289. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20290. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20291. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20292. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20293. if (gain != 0.0f && numSamples > 0)
  20294. {
  20295. float* d = channels [destChannel] + destStartSample;
  20296. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20297. if (gain != 1.0f)
  20298. {
  20299. while (--numSamples >= 0)
  20300. *d++ += gain * *s++;
  20301. }
  20302. else
  20303. {
  20304. while (--numSamples >= 0)
  20305. *d++ += *s++;
  20306. }
  20307. }
  20308. }
  20309. void AudioSampleBuffer::addFrom (const int destChannel,
  20310. const int destStartSample,
  20311. const float* source,
  20312. int numSamples,
  20313. const float gain) throw()
  20314. {
  20315. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20316. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20317. jassert (source != 0);
  20318. if (gain != 0.0f && numSamples > 0)
  20319. {
  20320. float* d = channels [destChannel] + destStartSample;
  20321. if (gain != 1.0f)
  20322. {
  20323. while (--numSamples >= 0)
  20324. *d++ += gain * *source++;
  20325. }
  20326. else
  20327. {
  20328. while (--numSamples >= 0)
  20329. *d++ += *source++;
  20330. }
  20331. }
  20332. }
  20333. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20334. const int destStartSample,
  20335. const float* source,
  20336. int numSamples,
  20337. float startGain,
  20338. const float endGain) throw()
  20339. {
  20340. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20341. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20342. jassert (source != 0);
  20343. if (startGain == endGain)
  20344. {
  20345. addFrom (destChannel,
  20346. destStartSample,
  20347. source,
  20348. numSamples,
  20349. startGain);
  20350. }
  20351. else
  20352. {
  20353. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20354. {
  20355. const float increment = (endGain - startGain) / numSamples;
  20356. float* d = channels [destChannel] + destStartSample;
  20357. while (--numSamples >= 0)
  20358. {
  20359. *d++ += startGain * *source++;
  20360. startGain += increment;
  20361. }
  20362. }
  20363. }
  20364. }
  20365. void AudioSampleBuffer::copyFrom (const int destChannel,
  20366. const int destStartSample,
  20367. const AudioSampleBuffer& source,
  20368. const int sourceChannel,
  20369. const int sourceStartSample,
  20370. int numSamples) throw()
  20371. {
  20372. jassert (&source != this || sourceChannel != destChannel);
  20373. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20374. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20375. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20376. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20377. if (numSamples > 0)
  20378. {
  20379. memcpy (channels [destChannel] + destStartSample,
  20380. source.channels [sourceChannel] + sourceStartSample,
  20381. sizeof (float) * numSamples);
  20382. }
  20383. }
  20384. void AudioSampleBuffer::copyFrom (const int destChannel,
  20385. const int destStartSample,
  20386. const float* source,
  20387. int numSamples) throw()
  20388. {
  20389. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20390. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20391. jassert (source != 0);
  20392. if (numSamples > 0)
  20393. {
  20394. memcpy (channels [destChannel] + destStartSample,
  20395. source,
  20396. sizeof (float) * numSamples);
  20397. }
  20398. }
  20399. void AudioSampleBuffer::copyFrom (const int destChannel,
  20400. const int destStartSample,
  20401. const float* source,
  20402. int numSamples,
  20403. const float gain) throw()
  20404. {
  20405. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20406. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20407. jassert (source != 0);
  20408. if (numSamples > 0 && gain != 0)
  20409. {
  20410. float* d = channels [destChannel] + destStartSample;
  20411. if (gain != 1.0f)
  20412. {
  20413. while (--numSamples >= 0)
  20414. *d++ = gain * *source++;
  20415. }
  20416. else
  20417. {
  20418. memcpy (d, source, sizeof (float) * numSamples);
  20419. }
  20420. }
  20421. }
  20422. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20423. const int destStartSample,
  20424. const float* source,
  20425. int numSamples,
  20426. float startGain,
  20427. float endGain) throw()
  20428. {
  20429. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20430. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20431. jassert (source != 0);
  20432. if (startGain == endGain)
  20433. {
  20434. copyFrom (destChannel,
  20435. destStartSample,
  20436. source,
  20437. numSamples,
  20438. startGain);
  20439. }
  20440. else
  20441. {
  20442. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20443. {
  20444. const float increment = (endGain - startGain) / numSamples;
  20445. float* d = channels [destChannel] + destStartSample;
  20446. while (--numSamples >= 0)
  20447. {
  20448. *d++ = startGain * *source++;
  20449. startGain += increment;
  20450. }
  20451. }
  20452. }
  20453. }
  20454. void AudioSampleBuffer::findMinMax (const int channel,
  20455. const int startSample,
  20456. int numSamples,
  20457. float& minVal,
  20458. float& maxVal) const throw()
  20459. {
  20460. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20461. jassert (startSample >= 0 && startSample + numSamples <= size);
  20462. if (numSamples <= 0)
  20463. {
  20464. minVal = 0.0f;
  20465. maxVal = 0.0f;
  20466. }
  20467. else
  20468. {
  20469. const float* d = channels [channel] + startSample;
  20470. float mn = *d++;
  20471. float mx = mn;
  20472. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  20473. {
  20474. const float samp = *d++;
  20475. if (samp > mx)
  20476. mx = samp;
  20477. if (samp < mn)
  20478. mn = samp;
  20479. }
  20480. maxVal = mx;
  20481. minVal = mn;
  20482. }
  20483. }
  20484. float AudioSampleBuffer::getMagnitude (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. float mn, mx;
  20491. findMinMax (channel, startSample, numSamples, mn, mx);
  20492. return jmax (mn, -mn, mx, -mx);
  20493. }
  20494. float AudioSampleBuffer::getMagnitude (const int startSample,
  20495. const int numSamples) const throw()
  20496. {
  20497. float mag = 0.0f;
  20498. for (int i = 0; i < numChannels; ++i)
  20499. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  20500. return mag;
  20501. }
  20502. float AudioSampleBuffer::getRMSLevel (const int channel,
  20503. const int startSample,
  20504. const int numSamples) const throw()
  20505. {
  20506. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20507. jassert (startSample >= 0 && startSample + numSamples <= size);
  20508. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  20509. return 0.0f;
  20510. const float* const data = channels [channel] + startSample;
  20511. double sum = 0.0;
  20512. for (int i = 0; i < numSamples; ++i)
  20513. {
  20514. const float sample = data [i];
  20515. sum += sample * sample;
  20516. }
  20517. return (float) sqrt (sum / numSamples);
  20518. }
  20519. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  20520. const int startSample,
  20521. const int numSamples,
  20522. const int readerStartSample,
  20523. const bool useLeftChan,
  20524. const bool useRightChan) throw()
  20525. {
  20526. jassert (reader != 0);
  20527. jassert (startSample >= 0 && startSample + numSamples <= size);
  20528. if (numSamples > 0)
  20529. {
  20530. int* chans[3];
  20531. if (useLeftChan == useRightChan)
  20532. {
  20533. chans[0] = (int*) getSampleData (0, startSample);
  20534. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  20535. }
  20536. else if (useLeftChan || (reader->numChannels == 1))
  20537. {
  20538. chans[0] = (int*) getSampleData (0, startSample);
  20539. chans[1] = 0;
  20540. }
  20541. else if (useRightChan)
  20542. {
  20543. chans[0] = 0;
  20544. chans[1] = (int*) getSampleData (0, startSample);
  20545. }
  20546. chans[2] = 0;
  20547. reader->read (chans, 2, readerStartSample, numSamples, true);
  20548. if (! reader->usesFloatingPointData)
  20549. {
  20550. for (int j = 0; j < 2; ++j)
  20551. {
  20552. float* const d = (float*) (chans[j]);
  20553. if (d != 0)
  20554. {
  20555. const float multiplier = 1.0f / 0x7fffffff;
  20556. for (int i = 0; i < numSamples; ++i)
  20557. d[i] = *(int*)(d + i) * multiplier;
  20558. }
  20559. }
  20560. }
  20561. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  20562. {
  20563. // if this is a stereo buffer and the source was mono, dupe the first channel..
  20564. memcpy (getSampleData (1, startSample),
  20565. getSampleData (0, startSample),
  20566. sizeof (float) * numSamples);
  20567. }
  20568. }
  20569. }
  20570. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  20571. const int startSample,
  20572. const int numSamples) const throw()
  20573. {
  20574. jassert (startSample >= 0 && startSample + numSamples <= size);
  20575. if (numSamples > 0)
  20576. {
  20577. int* chans [3];
  20578. if (writer->isFloatingPoint())
  20579. {
  20580. chans[0] = (int*) getSampleData (0, startSample);
  20581. if (numChannels > 1)
  20582. chans[1] = (int*) getSampleData (1, startSample);
  20583. else
  20584. chans[1] = 0;
  20585. chans[2] = 0;
  20586. writer->write ((const int**) chans, numSamples);
  20587. }
  20588. else
  20589. {
  20590. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  20591. if (numChannels > 1)
  20592. chans[1] = chans[0] + numSamples;
  20593. else
  20594. chans[1] = 0;
  20595. chans[2] = 0;
  20596. for (int j = 0; j < 2; ++j)
  20597. {
  20598. int* const dest = chans[j];
  20599. if (dest != 0)
  20600. {
  20601. const float* const src = channels [j] + startSample;
  20602. for (int i = 0; i < numSamples; ++i)
  20603. {
  20604. const double samp = src[i];
  20605. if (samp <= -1.0)
  20606. dest[i] = INT_MIN;
  20607. else if (samp >= 1.0)
  20608. dest[i] = INT_MAX;
  20609. else
  20610. dest[i] = roundDoubleToInt (INT_MAX * samp);
  20611. }
  20612. }
  20613. }
  20614. writer->write ((const int**) chans, numSamples);
  20615. juce_free (chans[0]);
  20616. }
  20617. }
  20618. }
  20619. END_JUCE_NAMESPACE
  20620. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  20621. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  20622. BEGIN_JUCE_NAMESPACE
  20623. IIRFilter::IIRFilter() throw()
  20624. : active (false)
  20625. {
  20626. reset();
  20627. }
  20628. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  20629. : active (other.active)
  20630. {
  20631. const ScopedLock sl (other.processLock);
  20632. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20633. reset();
  20634. }
  20635. IIRFilter::~IIRFilter() throw()
  20636. {
  20637. }
  20638. void IIRFilter::reset() throw()
  20639. {
  20640. const ScopedLock sl (processLock);
  20641. x1 = 0;
  20642. x2 = 0;
  20643. y1 = 0;
  20644. y2 = 0;
  20645. }
  20646. float IIRFilter::processSingleSampleRaw (const float in) throw()
  20647. {
  20648. float out = coefficients[0] * in
  20649. + coefficients[1] * x1
  20650. + coefficients[2] * x2
  20651. - coefficients[4] * y1
  20652. - coefficients[5] * y2;
  20653. #if JUCE_INTEL
  20654. if (! (out < -1.0e-8 || out > 1.0e-8))
  20655. out = 0;
  20656. #endif
  20657. x2 = x1;
  20658. x1 = in;
  20659. y2 = y1;
  20660. y1 = out;
  20661. return out;
  20662. }
  20663. void IIRFilter::processSamples (float* const samples,
  20664. const int numSamples) throw()
  20665. {
  20666. const ScopedLock sl (processLock);
  20667. if (active)
  20668. {
  20669. for (int i = 0; i < numSamples; ++i)
  20670. {
  20671. const float in = samples[i];
  20672. float out = coefficients[0] * in
  20673. + coefficients[1] * x1
  20674. + coefficients[2] * x2
  20675. - coefficients[4] * y1
  20676. - coefficients[5] * y2;
  20677. #if JUCE_INTEL
  20678. if (! (out < -1.0e-8 || out > 1.0e-8))
  20679. out = 0;
  20680. #endif
  20681. x2 = x1;
  20682. x1 = in;
  20683. y2 = y1;
  20684. y1 = out;
  20685. samples[i] = out;
  20686. }
  20687. }
  20688. }
  20689. void IIRFilter::makeLowPass (const double sampleRate,
  20690. const double frequency) throw()
  20691. {
  20692. jassert (sampleRate > 0);
  20693. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  20694. const double nSquared = n * n;
  20695. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20696. setCoefficients (c1,
  20697. c1 * 2.0f,
  20698. c1,
  20699. 1.0,
  20700. c1 * 2.0 * (1.0 - nSquared),
  20701. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20702. }
  20703. void IIRFilter::makeHighPass (const double sampleRate,
  20704. const double frequency) throw()
  20705. {
  20706. const double n = tan (double_Pi * frequency / sampleRate);
  20707. const double nSquared = n * n;
  20708. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20709. setCoefficients (c1,
  20710. c1 * -2.0f,
  20711. c1,
  20712. 1.0,
  20713. c1 * 2.0 * (nSquared - 1.0),
  20714. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20715. }
  20716. void IIRFilter::makeLowShelf (const double sampleRate,
  20717. const double cutOffFrequency,
  20718. const double Q,
  20719. const float gainFactor) throw()
  20720. {
  20721. jassert (sampleRate > 0);
  20722. jassert (Q > 0);
  20723. const double A = jmax (0.0f, gainFactor);
  20724. const double aminus1 = A - 1.0;
  20725. const double aplus1 = A + 1.0;
  20726. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20727. const double coso = cos (omega);
  20728. const double beta = sin (omega) * sqrt (A) / Q;
  20729. const double aminus1TimesCoso = aminus1 * coso;
  20730. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  20731. A * 2.0 * (aminus1 - aplus1 * coso),
  20732. A * (aplus1 - aminus1TimesCoso - beta),
  20733. aplus1 + aminus1TimesCoso + beta,
  20734. -2.0 * (aminus1 + aplus1 * coso),
  20735. aplus1 + aminus1TimesCoso - beta);
  20736. }
  20737. void IIRFilter::makeHighShelf (const double sampleRate,
  20738. const double cutOffFrequency,
  20739. const double Q,
  20740. const float gainFactor) throw()
  20741. {
  20742. jassert (sampleRate > 0);
  20743. jassert (Q > 0);
  20744. const double A = jmax (0.0f, gainFactor);
  20745. const double aminus1 = A - 1.0;
  20746. const double aplus1 = A + 1.0;
  20747. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20748. const double coso = cos (omega);
  20749. const double beta = sin (omega) * sqrt (A) / Q;
  20750. const double aminus1TimesCoso = aminus1 * coso;
  20751. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  20752. A * -2.0 * (aminus1 + aplus1 * coso),
  20753. A * (aplus1 + aminus1TimesCoso - beta),
  20754. aplus1 - aminus1TimesCoso + beta,
  20755. 2.0 * (aminus1 - aplus1 * coso),
  20756. aplus1 - aminus1TimesCoso - beta);
  20757. }
  20758. void IIRFilter::makeBandPass (const double sampleRate,
  20759. const double centreFrequency,
  20760. const double Q,
  20761. const float gainFactor) throw()
  20762. {
  20763. jassert (sampleRate > 0);
  20764. jassert (Q > 0);
  20765. const double A = jmax (0.0f, gainFactor);
  20766. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  20767. const double alpha = 0.5 * sin (omega) / Q;
  20768. const double c2 = -2.0 * cos (omega);
  20769. const double alphaTimesA = alpha * A;
  20770. const double alphaOverA = alpha / A;
  20771. setCoefficients (1.0 + alphaTimesA,
  20772. c2,
  20773. 1.0 - alphaTimesA,
  20774. 1.0 + alphaOverA,
  20775. c2,
  20776. 1.0 - alphaOverA);
  20777. }
  20778. void IIRFilter::makeInactive() throw()
  20779. {
  20780. const ScopedLock sl (processLock);
  20781. active = false;
  20782. }
  20783. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  20784. {
  20785. const ScopedLock sl (processLock);
  20786. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20787. active = other.active;
  20788. }
  20789. void IIRFilter::setCoefficients (double c1,
  20790. double c2,
  20791. double c3,
  20792. double c4,
  20793. double c5,
  20794. double c6) throw()
  20795. {
  20796. const double a = 1.0 / c4;
  20797. c1 *= a;
  20798. c2 *= a;
  20799. c3 *= a;
  20800. c5 *= a;
  20801. c6 *= a;
  20802. const ScopedLock sl (processLock);
  20803. coefficients[0] = (float) c1;
  20804. coefficients[1] = (float) c2;
  20805. coefficients[2] = (float) c3;
  20806. coefficients[3] = (float) c4;
  20807. coefficients[4] = (float) c5;
  20808. coefficients[5] = (float) c6;
  20809. active = true;
  20810. }
  20811. END_JUCE_NAMESPACE
  20812. /********* End of inlined file: juce_IIRFilter.cpp *********/
  20813. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  20814. BEGIN_JUCE_NAMESPACE
  20815. MidiBuffer::MidiBuffer() throw()
  20816. : ArrayAllocationBase <uint8> (32),
  20817. bytesUsed (0)
  20818. {
  20819. }
  20820. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  20821. : ArrayAllocationBase <uint8> (32),
  20822. bytesUsed (0)
  20823. {
  20824. addEvent (message, 0);
  20825. }
  20826. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  20827. : ArrayAllocationBase <uint8> (32),
  20828. bytesUsed (other.bytesUsed)
  20829. {
  20830. ensureAllocatedSize (bytesUsed);
  20831. memcpy (elements, other.elements, bytesUsed);
  20832. }
  20833. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  20834. {
  20835. if (this != &other)
  20836. {
  20837. bytesUsed = other.bytesUsed;
  20838. ensureAllocatedSize (bytesUsed);
  20839. if (bytesUsed > 0)
  20840. memcpy (elements, other.elements, bytesUsed);
  20841. }
  20842. return *this;
  20843. }
  20844. void MidiBuffer::swap (MidiBuffer& other)
  20845. {
  20846. swapVariables <uint8*> (this->elements, other.elements);
  20847. swapVariables <int> (this->numAllocated, other.numAllocated);
  20848. swapVariables <int> (this->bytesUsed, other.bytesUsed);
  20849. }
  20850. MidiBuffer::~MidiBuffer() throw()
  20851. {
  20852. }
  20853. void MidiBuffer::clear() throw()
  20854. {
  20855. bytesUsed = 0;
  20856. }
  20857. void MidiBuffer::clear (const int startSample,
  20858. const int numSamples) throw()
  20859. {
  20860. uint8* const start = findEventAfter (elements, startSample - 1);
  20861. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  20862. if (end > start)
  20863. {
  20864. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  20865. if (bytesToMove > 0)
  20866. memmove (start, end, bytesToMove);
  20867. bytesUsed -= (int) (end - start);
  20868. }
  20869. }
  20870. void MidiBuffer::addEvent (const MidiMessage& m,
  20871. const int sampleNumber) throw()
  20872. {
  20873. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  20874. }
  20875. static int findActualEventLength (const uint8* const data,
  20876. const int maxBytes) throw()
  20877. {
  20878. unsigned int byte = (unsigned int) *data;
  20879. int size = 0;
  20880. if (byte == 0xf0 || byte == 0xf7)
  20881. {
  20882. const uint8* d = data + 1;
  20883. while (d < data + maxBytes)
  20884. if (*d++ == 0xf7)
  20885. break;
  20886. size = (int) (d - data);
  20887. }
  20888. else if (byte == 0xff)
  20889. {
  20890. int n;
  20891. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  20892. size = jmin (maxBytes, n + 2 + bytesLeft);
  20893. }
  20894. else if (byte >= 0x80)
  20895. {
  20896. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  20897. }
  20898. return size;
  20899. }
  20900. void MidiBuffer::addEvent (const uint8* const newData,
  20901. const int maxBytes,
  20902. const int sampleNumber) throw()
  20903. {
  20904. const int numBytes = findActualEventLength (newData, maxBytes);
  20905. if (numBytes > 0)
  20906. {
  20907. ensureAllocatedSize (bytesUsed + numBytes + 6);
  20908. uint8* d = findEventAfter (elements, sampleNumber);
  20909. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  20910. if (bytesToMove > 0)
  20911. memmove (d + numBytes + 6,
  20912. d,
  20913. bytesToMove);
  20914. *(int*) d = sampleNumber;
  20915. d += 4;
  20916. *(uint16*) d = (uint16) numBytes;
  20917. d += 2;
  20918. memcpy (d, newData, numBytes);
  20919. bytesUsed += numBytes + 6;
  20920. }
  20921. }
  20922. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  20923. const int startSample,
  20924. const int numSamples,
  20925. const int sampleDeltaToAdd) throw()
  20926. {
  20927. Iterator i (otherBuffer);
  20928. i.setNextSamplePosition (startSample);
  20929. const uint8* data;
  20930. int size, position;
  20931. while (i.getNextEvent (data, size, position)
  20932. && (position < startSample + numSamples || numSamples < 0))
  20933. {
  20934. addEvent (data, size, position + sampleDeltaToAdd);
  20935. }
  20936. }
  20937. bool MidiBuffer::isEmpty() const throw()
  20938. {
  20939. return bytesUsed == 0;
  20940. }
  20941. int MidiBuffer::getNumEvents() const throw()
  20942. {
  20943. int n = 0;
  20944. const uint8* d = elements;
  20945. const uint8* const end = elements + bytesUsed;
  20946. while (d < end)
  20947. {
  20948. d += 4;
  20949. d += 2 + *(const uint16*) d;
  20950. ++n;
  20951. }
  20952. return n;
  20953. }
  20954. int MidiBuffer::getFirstEventTime() const throw()
  20955. {
  20956. return (bytesUsed > 0) ? *(const int*) elements : 0;
  20957. }
  20958. int MidiBuffer::getLastEventTime() const throw()
  20959. {
  20960. if (bytesUsed == 0)
  20961. return 0;
  20962. const uint8* d = elements;
  20963. const uint8* const endData = d + bytesUsed;
  20964. for (;;)
  20965. {
  20966. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  20967. if (nextOne >= endData)
  20968. return *(const int*) d;
  20969. d = nextOne;
  20970. }
  20971. }
  20972. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  20973. {
  20974. const uint8* const endData = elements + bytesUsed;
  20975. while (d < endData && *(int*) d <= samplePosition)
  20976. {
  20977. d += 4;
  20978. d += 2 + *(uint16*) d;
  20979. }
  20980. return d;
  20981. }
  20982. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  20983. : buffer (buffer),
  20984. data (buffer.elements)
  20985. {
  20986. }
  20987. MidiBuffer::Iterator::~Iterator() throw()
  20988. {
  20989. }
  20990. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  20991. {
  20992. data = buffer.elements;
  20993. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  20994. while (data < dataEnd && *(int*) data < samplePosition)
  20995. {
  20996. data += 4;
  20997. data += 2 + *(uint16*) data;
  20998. }
  20999. }
  21000. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  21001. int& numBytes,
  21002. int& samplePosition) throw()
  21003. {
  21004. if (data >= buffer.elements + buffer.bytesUsed)
  21005. return false;
  21006. samplePosition = *(int*) data;
  21007. data += 4;
  21008. numBytes = *(uint16*) data;
  21009. data += 2;
  21010. midiData = data;
  21011. data += numBytes;
  21012. return true;
  21013. }
  21014. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  21015. int& samplePosition) throw()
  21016. {
  21017. if (data >= buffer.elements + buffer.bytesUsed)
  21018. return false;
  21019. samplePosition = *(int*) data;
  21020. data += 4;
  21021. const int numBytes = *(uint16*) data;
  21022. data += 2;
  21023. result = MidiMessage (data, numBytes, samplePosition);
  21024. data += numBytes;
  21025. return true;
  21026. }
  21027. END_JUCE_NAMESPACE
  21028. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  21029. /********* Start of inlined file: juce_MidiFile.cpp *********/
  21030. BEGIN_JUCE_NAMESPACE
  21031. struct TempoInfo
  21032. {
  21033. double bpm, timestamp;
  21034. };
  21035. struct TimeSigInfo
  21036. {
  21037. int numerator, denominator;
  21038. double timestamp;
  21039. };
  21040. MidiFile::MidiFile() throw()
  21041. : numTracks (0),
  21042. timeFormat ((short)(unsigned short)0xe728)
  21043. {
  21044. }
  21045. MidiFile::~MidiFile() throw()
  21046. {
  21047. clear();
  21048. }
  21049. void MidiFile::clear() throw()
  21050. {
  21051. while (numTracks > 0)
  21052. delete tracks [--numTracks];
  21053. }
  21054. int MidiFile::getNumTracks() const throw()
  21055. {
  21056. return numTracks;
  21057. }
  21058. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21059. {
  21060. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  21061. }
  21062. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  21063. {
  21064. jassert (numTracks < numElementsInArray (tracks));
  21065. if (numTracks < numElementsInArray (tracks))
  21066. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  21067. }
  21068. short MidiFile::getTimeFormat() const throw()
  21069. {
  21070. return timeFormat;
  21071. }
  21072. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21073. {
  21074. timeFormat = (short)ticks;
  21075. }
  21076. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21077. const int subframeResolution) throw()
  21078. {
  21079. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21080. }
  21081. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21082. {
  21083. for (int i = numTracks; --i >= 0;)
  21084. {
  21085. const int numEvents = tracks[i]->getNumEvents();
  21086. for (int j = 0; j < numEvents; ++j)
  21087. {
  21088. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  21089. if (m.isTempoMetaEvent())
  21090. tempoChangeEvents.addEvent (m);
  21091. }
  21092. }
  21093. }
  21094. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21095. {
  21096. for (int i = numTracks; --i >= 0;)
  21097. {
  21098. const int numEvents = tracks[i]->getNumEvents();
  21099. for (int j = 0; j < numEvents; ++j)
  21100. {
  21101. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  21102. if (m.isTimeSignatureMetaEvent())
  21103. timeSigEvents.addEvent (m);
  21104. }
  21105. }
  21106. }
  21107. double MidiFile::getLastTimestamp() const
  21108. {
  21109. double t = 0.0;
  21110. for (int i = numTracks; --i >= 0;)
  21111. t = jmax (t, tracks[i]->getEndTime());
  21112. return t;
  21113. }
  21114. static bool parseMidiHeader (const char* &data,
  21115. short& timeFormat,
  21116. short& fileType,
  21117. short& numberOfTracks)
  21118. {
  21119. unsigned int ch = (int) bigEndianInt (data);
  21120. data += 4;
  21121. if (ch != bigEndianInt ("MThd"))
  21122. {
  21123. bool ok = false;
  21124. if (ch == bigEndianInt ("RIFF"))
  21125. {
  21126. for (int i = 0; i < 8; ++i)
  21127. {
  21128. ch = bigEndianInt (data);
  21129. data += 4;
  21130. if (ch == bigEndianInt ("MThd"))
  21131. {
  21132. ok = true;
  21133. break;
  21134. }
  21135. }
  21136. }
  21137. if (! ok)
  21138. return false;
  21139. }
  21140. unsigned int bytesRemaining = bigEndianInt (data);
  21141. data += 4;
  21142. fileType = (short)bigEndianShort (data);
  21143. data += 2;
  21144. numberOfTracks = (short)bigEndianShort (data);
  21145. data += 2;
  21146. timeFormat = (short)bigEndianShort (data);
  21147. data += 2;
  21148. bytesRemaining -= 6;
  21149. data += bytesRemaining;
  21150. return true;
  21151. }
  21152. bool MidiFile::readFrom (InputStream& sourceStream)
  21153. {
  21154. clear();
  21155. MemoryBlock data;
  21156. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21157. // (put a sanity-check on the file size, as midi files are generally small)
  21158. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21159. {
  21160. int size = data.getSize();
  21161. const char* d = (char*) data.getData();
  21162. short fileType, expectedTracks;
  21163. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21164. {
  21165. size -= (int) (d - (char*) data.getData());
  21166. int track = 0;
  21167. while (size > 0 && track < expectedTracks)
  21168. {
  21169. const int chunkType = (int)bigEndianInt (d);
  21170. d += 4;
  21171. const int chunkSize = (int)bigEndianInt (d);
  21172. d += 4;
  21173. if (chunkSize <= 0)
  21174. break;
  21175. if (size < 0)
  21176. return false;
  21177. if (chunkType == (int)bigEndianInt ("MTrk"))
  21178. {
  21179. readNextTrack (d, chunkSize);
  21180. }
  21181. size -= chunkSize + 8;
  21182. d += chunkSize;
  21183. ++track;
  21184. }
  21185. return true;
  21186. }
  21187. }
  21188. return false;
  21189. }
  21190. // a comparator that puts all the note-offs before note-ons that have the same time
  21191. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21192. const MidiMessageSequence::MidiEventHolder* const second) throw()
  21193. {
  21194. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21195. if (diff == 0)
  21196. {
  21197. if (first->message.isNoteOff() && second->message.isNoteOn())
  21198. return -1;
  21199. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21200. return 1;
  21201. else
  21202. return 0;
  21203. }
  21204. else
  21205. {
  21206. return (diff > 0) ? 1 : -1;
  21207. }
  21208. }
  21209. void MidiFile::readNextTrack (const char* data, int size)
  21210. {
  21211. double time = 0;
  21212. char lastStatusByte = 0;
  21213. MidiMessageSequence result;
  21214. while (size > 0)
  21215. {
  21216. int bytesUsed;
  21217. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  21218. data += bytesUsed;
  21219. size -= bytesUsed;
  21220. time += delay;
  21221. int messSize = 0;
  21222. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  21223. if (messSize <= 0)
  21224. break;
  21225. size -= messSize;
  21226. data += messSize;
  21227. result.addEvent (mm);
  21228. const char firstByte = *(mm.getRawData());
  21229. if ((firstByte & 0xf0) != 0xf0)
  21230. lastStatusByte = firstByte;
  21231. }
  21232. // use a sort that puts all the note-offs before note-ons that have the same time
  21233. result.list.sort (*this, true);
  21234. result.updateMatchedPairs();
  21235. addTrack (result);
  21236. }
  21237. static double convertTicksToSeconds (const double time,
  21238. const MidiMessageSequence& tempoEvents,
  21239. const int timeFormat)
  21240. {
  21241. if (timeFormat > 0)
  21242. {
  21243. int numer = 4, denom = 4;
  21244. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21245. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21246. double secsPerTick = 0.5 * tickLen;
  21247. const int numEvents = tempoEvents.getNumEvents();
  21248. for (int i = 0; i < numEvents; ++i)
  21249. {
  21250. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21251. if (time <= m.getTimeStamp())
  21252. break;
  21253. if (timeFormat > 0)
  21254. {
  21255. correctedTempoTime = correctedTempoTime
  21256. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21257. }
  21258. else
  21259. {
  21260. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21261. }
  21262. tempoTime = m.getTimeStamp();
  21263. if (m.isTempoMetaEvent())
  21264. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21265. else if (m.isTimeSignatureMetaEvent())
  21266. m.getTimeSignatureInfo (numer, denom);
  21267. while (i + 1 < numEvents)
  21268. {
  21269. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21270. if (m2.getTimeStamp() == tempoTime)
  21271. {
  21272. ++i;
  21273. if (m2.isTempoMetaEvent())
  21274. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21275. else if (m2.isTimeSignatureMetaEvent())
  21276. m2.getTimeSignatureInfo (numer, denom);
  21277. }
  21278. else
  21279. {
  21280. break;
  21281. }
  21282. }
  21283. }
  21284. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21285. }
  21286. else
  21287. {
  21288. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21289. }
  21290. }
  21291. void MidiFile::convertTimestampTicksToSeconds()
  21292. {
  21293. MidiMessageSequence tempoEvents;
  21294. findAllTempoEvents (tempoEvents);
  21295. findAllTimeSigEvents (tempoEvents);
  21296. for (int i = 0; i < numTracks; ++i)
  21297. {
  21298. MidiMessageSequence& ms = *tracks[i];
  21299. for (int j = ms.getNumEvents(); --j >= 0;)
  21300. {
  21301. MidiMessage& m = ms.getEventPointer(j)->message;
  21302. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  21303. tempoEvents,
  21304. timeFormat));
  21305. }
  21306. }
  21307. }
  21308. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21309. {
  21310. unsigned int buffer = v & 0x7F;
  21311. while ((v >>= 7) != 0)
  21312. {
  21313. buffer <<= 8;
  21314. buffer |= ((v & 0x7F) | 0x80);
  21315. }
  21316. for (;;)
  21317. {
  21318. out.writeByte ((char) buffer);
  21319. if (buffer & 0x80)
  21320. buffer >>= 8;
  21321. else
  21322. break;
  21323. }
  21324. }
  21325. bool MidiFile::writeTo (OutputStream& out)
  21326. {
  21327. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  21328. out.writeIntBigEndian (6);
  21329. out.writeShortBigEndian (1); // type
  21330. out.writeShortBigEndian (numTracks);
  21331. out.writeShortBigEndian (timeFormat);
  21332. for (int i = 0; i < numTracks; ++i)
  21333. writeTrack (out, i);
  21334. out.flush();
  21335. return true;
  21336. }
  21337. void MidiFile::writeTrack (OutputStream& mainOut,
  21338. const int trackNum)
  21339. {
  21340. MemoryOutputStream out;
  21341. const MidiMessageSequence& ms = *tracks[trackNum];
  21342. int lastTick = 0;
  21343. char lastStatusByte = 0;
  21344. for (int i = 0; i < ms.getNumEvents(); ++i)
  21345. {
  21346. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21347. const int tick = roundDoubleToInt (mm.getTimeStamp());
  21348. const int delta = jmax (0, tick - lastTick);
  21349. writeVariableLengthInt (out, delta);
  21350. lastTick = tick;
  21351. const char statusByte = *(mm.getRawData());
  21352. if ((statusByte == lastStatusByte)
  21353. && ((statusByte & 0xf0) != 0xf0)
  21354. && i > 0
  21355. && mm.getRawDataSize() > 1)
  21356. {
  21357. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21358. }
  21359. else
  21360. {
  21361. out.write (mm.getRawData(), mm.getRawDataSize());
  21362. }
  21363. lastStatusByte = statusByte;
  21364. }
  21365. out.writeByte (0);
  21366. const MidiMessage m (MidiMessage::endOfTrack());
  21367. out.write (m.getRawData(),
  21368. m.getRawDataSize());
  21369. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  21370. mainOut.writeIntBigEndian (out.getDataSize());
  21371. mainOut.write (out.getData(), out.getDataSize());
  21372. }
  21373. END_JUCE_NAMESPACE
  21374. /********* End of inlined file: juce_MidiFile.cpp *********/
  21375. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  21376. BEGIN_JUCE_NAMESPACE
  21377. MidiKeyboardState::MidiKeyboardState()
  21378. : listeners (2)
  21379. {
  21380. zeromem (noteStates, sizeof (noteStates));
  21381. }
  21382. MidiKeyboardState::~MidiKeyboardState()
  21383. {
  21384. }
  21385. void MidiKeyboardState::reset()
  21386. {
  21387. const ScopedLock sl (lock);
  21388. zeromem (noteStates, sizeof (noteStates));
  21389. eventsToAdd.clear();
  21390. }
  21391. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21392. {
  21393. jassert (midiChannel >= 0 && midiChannel <= 16);
  21394. return ((unsigned int) n) < 128
  21395. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21396. }
  21397. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21398. {
  21399. return ((unsigned int) n) < 128
  21400. && (noteStates[n] & midiChannelMask) != 0;
  21401. }
  21402. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21403. {
  21404. jassert (midiChannel >= 0 && midiChannel <= 16);
  21405. jassert (((unsigned int) midiNoteNumber) < 128);
  21406. const ScopedLock sl (lock);
  21407. if (((unsigned int) midiNoteNumber) < 128)
  21408. {
  21409. const int timeNow = (int) Time::getMillisecondCounter();
  21410. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21411. eventsToAdd.clear (0, timeNow - 500);
  21412. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21413. }
  21414. }
  21415. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21416. {
  21417. if (((unsigned int) midiNoteNumber) < 128)
  21418. {
  21419. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21420. for (int i = listeners.size(); --i >= 0;)
  21421. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21422. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21423. }
  21424. }
  21425. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21426. {
  21427. const ScopedLock sl (lock);
  21428. if (isNoteOn (midiChannel, midiNoteNumber))
  21429. {
  21430. const int timeNow = (int) Time::getMillisecondCounter();
  21431. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21432. eventsToAdd.clear (0, timeNow - 500);
  21433. noteOffInternal (midiChannel, midiNoteNumber);
  21434. }
  21435. }
  21436. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21437. {
  21438. if (isNoteOn (midiChannel, midiNoteNumber))
  21439. {
  21440. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21441. for (int i = listeners.size(); --i >= 0;)
  21442. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21443. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  21444. }
  21445. }
  21446. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21447. {
  21448. const ScopedLock sl (lock);
  21449. if (midiChannel <= 0)
  21450. {
  21451. for (int i = 1; i <= 16; ++i)
  21452. allNotesOff (i);
  21453. }
  21454. else
  21455. {
  21456. for (int i = 0; i < 128; ++i)
  21457. noteOff (midiChannel, i);
  21458. }
  21459. }
  21460. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21461. {
  21462. if (message.isNoteOn())
  21463. {
  21464. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21465. }
  21466. else if (message.isNoteOff())
  21467. {
  21468. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21469. }
  21470. else if (message.isAllNotesOff())
  21471. {
  21472. for (int i = 0; i < 128; ++i)
  21473. noteOffInternal (message.getChannel(), i);
  21474. }
  21475. }
  21476. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  21477. const int startSample,
  21478. const int numSamples,
  21479. const bool injectIndirectEvents)
  21480. {
  21481. MidiBuffer::Iterator i (buffer);
  21482. MidiMessage message (0xf4, 0.0);
  21483. int time;
  21484. const ScopedLock sl (lock);
  21485. while (i.getNextEvent (message, time))
  21486. processNextMidiEvent (message);
  21487. if (injectIndirectEvents)
  21488. {
  21489. MidiBuffer::Iterator i2 (eventsToAdd);
  21490. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  21491. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  21492. while (i2.getNextEvent (message, time))
  21493. {
  21494. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  21495. buffer.addEvent (message, startSample + pos);
  21496. }
  21497. }
  21498. eventsToAdd.clear();
  21499. }
  21500. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  21501. {
  21502. const ScopedLock sl (lock);
  21503. listeners.addIfNotAlreadyThere (listener);
  21504. }
  21505. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  21506. {
  21507. const ScopedLock sl (lock);
  21508. listeners.removeValue (listener);
  21509. }
  21510. END_JUCE_NAMESPACE
  21511. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  21512. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  21513. BEGIN_JUCE_NAMESPACE
  21514. int MidiMessage::readVariableLengthVal (const uint8* data,
  21515. int& numBytesUsed) throw()
  21516. {
  21517. numBytesUsed = 0;
  21518. int v = 0;
  21519. int i;
  21520. do
  21521. {
  21522. i = (int) *data++;
  21523. if (++numBytesUsed > 6)
  21524. break;
  21525. v = (v << 7) + (i & 0x7f);
  21526. } while (i & 0x80);
  21527. return v;
  21528. }
  21529. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  21530. {
  21531. // this method only works for valid starting bytes of a short midi message
  21532. jassert (firstByte >= 0x80
  21533. && firstByte != 0xf0
  21534. && firstByte != 0xf7);
  21535. static const char messageLengths[] =
  21536. {
  21537. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21538. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21539. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21540. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21541. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21542. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21543. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21544. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  21545. };
  21546. return messageLengths [firstByte & 0x7f];
  21547. }
  21548. MidiMessage::MidiMessage (const uint8* const d,
  21549. const int dataSize,
  21550. const double t) throw()
  21551. : timeStamp (t),
  21552. message (0),
  21553. size (dataSize)
  21554. {
  21555. jassert (dataSize > 0);
  21556. if (dataSize <= 4)
  21557. data = (uint8*) &message;
  21558. else
  21559. data = (uint8*) juce_malloc (dataSize);
  21560. memcpy (data, d, dataSize);
  21561. // check that the length matches the data..
  21562. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  21563. }
  21564. MidiMessage::MidiMessage (const int byte1,
  21565. const double t) throw()
  21566. : timeStamp (t),
  21567. data ((uint8*) &message),
  21568. size (1)
  21569. {
  21570. data[0] = (uint8) byte1;
  21571. // check that the length matches the data..
  21572. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  21573. }
  21574. MidiMessage::MidiMessage (const int byte1,
  21575. const int byte2,
  21576. const double t) throw()
  21577. : timeStamp (t),
  21578. data ((uint8*) &message),
  21579. size (2)
  21580. {
  21581. data[0] = (uint8) byte1;
  21582. data[1] = (uint8) byte2;
  21583. // check that the length matches the data..
  21584. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  21585. }
  21586. MidiMessage::MidiMessage (const int byte1,
  21587. const int byte2,
  21588. const int byte3,
  21589. const double t) throw()
  21590. : timeStamp (t),
  21591. data ((uint8*) &message),
  21592. size (3)
  21593. {
  21594. data[0] = (uint8) byte1;
  21595. data[1] = (uint8) byte2;
  21596. data[2] = (uint8) byte3;
  21597. // check that the length matches the data..
  21598. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  21599. }
  21600. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  21601. : timeStamp (other.timeStamp),
  21602. message (other.message),
  21603. size (other.size)
  21604. {
  21605. if (other.data != (uint8*) &other.message)
  21606. {
  21607. data = (uint8*) juce_malloc (size);
  21608. memcpy (data, other.data, size);
  21609. }
  21610. else
  21611. {
  21612. data = (uint8*) &message;
  21613. }
  21614. }
  21615. MidiMessage::MidiMessage (const MidiMessage& other,
  21616. const double newTimeStamp) throw()
  21617. : timeStamp (newTimeStamp),
  21618. message (other.message),
  21619. size (other.size)
  21620. {
  21621. if (other.data != (uint8*) &other.message)
  21622. {
  21623. data = (uint8*) juce_malloc (size);
  21624. memcpy (data, other.data, size);
  21625. }
  21626. else
  21627. {
  21628. data = (uint8*) &message;
  21629. }
  21630. }
  21631. MidiMessage::MidiMessage (const uint8* src,
  21632. int sz,
  21633. int& numBytesUsed,
  21634. const uint8 lastStatusByte,
  21635. double t) throw()
  21636. : timeStamp (t),
  21637. data ((uint8*) &message),
  21638. message (0)
  21639. {
  21640. unsigned int byte = (unsigned int) *src;
  21641. if (byte < 0x80)
  21642. {
  21643. byte = (unsigned int) (uint8) lastStatusByte;
  21644. numBytesUsed = -1;
  21645. }
  21646. else
  21647. {
  21648. numBytesUsed = 0;
  21649. --sz;
  21650. ++src;
  21651. }
  21652. if (byte >= 0x80)
  21653. {
  21654. if (byte == 0xf0)
  21655. {
  21656. const uint8* d = (const uint8*) src;
  21657. while (d < src + sz)
  21658. {
  21659. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  21660. {
  21661. if (*d == 0xf7) // include an 0xf7 if we hit one
  21662. ++d;
  21663. break;
  21664. }
  21665. ++d;
  21666. }
  21667. size = 1 + (int) (d - src);
  21668. data = (uint8*) juce_malloc (size);
  21669. *data = (uint8) byte;
  21670. memcpy (data + 1, src, size - 1);
  21671. }
  21672. else if (byte == 0xff)
  21673. {
  21674. int n;
  21675. const int bytesLeft = readVariableLengthVal (src + 1, n);
  21676. size = jmin (sz + 1, n + 2 + bytesLeft);
  21677. data = (uint8*) juce_malloc (size);
  21678. *data = (uint8) byte;
  21679. memcpy (data + 1, src, size - 1);
  21680. }
  21681. else
  21682. {
  21683. size = getMessageLengthFromFirstByte ((uint8) byte);
  21684. *data = (uint8) byte;
  21685. if (size > 1)
  21686. {
  21687. data[1] = src[0];
  21688. if (size > 2)
  21689. data[2] = src[1];
  21690. }
  21691. }
  21692. numBytesUsed += size;
  21693. }
  21694. else
  21695. {
  21696. message = 0;
  21697. size = 0;
  21698. }
  21699. }
  21700. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  21701. {
  21702. if (this == &other)
  21703. return *this;
  21704. timeStamp = other.timeStamp;
  21705. size = other.size;
  21706. message = other.message;
  21707. if (data != (uint8*) &message)
  21708. juce_free (data);
  21709. if (other.data != (uint8*) &other.message)
  21710. {
  21711. data = (uint8*) juce_malloc (size);
  21712. memcpy (data, other.data, size);
  21713. }
  21714. else
  21715. {
  21716. data = (uint8*) &message;
  21717. }
  21718. return *this;
  21719. }
  21720. MidiMessage::~MidiMessage() throw()
  21721. {
  21722. if (data != (uint8*) &message)
  21723. juce_free (data);
  21724. }
  21725. int MidiMessage::getChannel() const throw()
  21726. {
  21727. if ((data[0] & 0xf0) != 0xf0)
  21728. return (data[0] & 0xf) + 1;
  21729. else
  21730. return 0;
  21731. }
  21732. bool MidiMessage::isForChannel (const int channel) const throw()
  21733. {
  21734. return ((data[0] & 0xf) == channel - 1)
  21735. && ((data[0] & 0xf0) != 0xf0);
  21736. }
  21737. void MidiMessage::setChannel (const int channel) throw()
  21738. {
  21739. if ((data[0] & 0xf0) != (uint8) 0xf0)
  21740. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  21741. | (uint8)(channel - 1));
  21742. }
  21743. bool MidiMessage::isNoteOn() const throw()
  21744. {
  21745. return ((data[0] & 0xf0) == 0x90)
  21746. && (data[2] != 0);
  21747. }
  21748. bool MidiMessage::isNoteOff() const throw()
  21749. {
  21750. return ((data[0] & 0xf0) == 0x80)
  21751. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  21752. }
  21753. bool MidiMessage::isNoteOnOrOff() const throw()
  21754. {
  21755. const int d = data[0] & 0xf0;
  21756. return (d == 0x90) || (d == 0x80);
  21757. }
  21758. int MidiMessage::getNoteNumber() const throw()
  21759. {
  21760. return data[1];
  21761. }
  21762. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  21763. {
  21764. if (isNoteOnOrOff())
  21765. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  21766. }
  21767. uint8 MidiMessage::getVelocity() const throw()
  21768. {
  21769. if (isNoteOnOrOff())
  21770. return data[2];
  21771. else
  21772. return 0;
  21773. }
  21774. float MidiMessage::getFloatVelocity() const throw()
  21775. {
  21776. return getVelocity() * (1.0f / 127.0f);
  21777. }
  21778. void MidiMessage::setVelocity (const float newVelocity) throw()
  21779. {
  21780. if (isNoteOnOrOff())
  21781. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  21782. }
  21783. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  21784. {
  21785. if (isNoteOnOrOff())
  21786. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  21787. }
  21788. bool MidiMessage::isAftertouch() const throw()
  21789. {
  21790. return (data[0] & 0xf0) == 0xa0;
  21791. }
  21792. int MidiMessage::getAfterTouchValue() const throw()
  21793. {
  21794. return data[2];
  21795. }
  21796. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  21797. const int noteNum,
  21798. const int aftertouchValue) throw()
  21799. {
  21800. jassert (channel > 0 && channel <= 16);
  21801. jassert (((unsigned int) noteNum) <= 127);
  21802. jassert (((unsigned int) aftertouchValue) <= 127);
  21803. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  21804. noteNum & 0x7f,
  21805. aftertouchValue & 0x7f);
  21806. }
  21807. bool MidiMessage::isChannelPressure() const throw()
  21808. {
  21809. return (data[0] & 0xf0) == 0xd0;
  21810. }
  21811. int MidiMessage::getChannelPressureValue() const throw()
  21812. {
  21813. jassert (isChannelPressure());
  21814. return data[1];
  21815. }
  21816. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  21817. const int pressure) throw()
  21818. {
  21819. jassert (channel > 0 && channel <= 16);
  21820. jassert (((unsigned int) pressure) <= 127);
  21821. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  21822. pressure & 0x7f);
  21823. }
  21824. bool MidiMessage::isProgramChange() const throw()
  21825. {
  21826. return (data[0] & 0xf0) == 0xc0;
  21827. }
  21828. int MidiMessage::getProgramChangeNumber() const throw()
  21829. {
  21830. return data[1];
  21831. }
  21832. const MidiMessage MidiMessage::programChange (const int channel,
  21833. const int programNumber) throw()
  21834. {
  21835. jassert (channel > 0 && channel <= 16);
  21836. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  21837. programNumber & 0x7f);
  21838. }
  21839. bool MidiMessage::isPitchWheel() const throw()
  21840. {
  21841. return (data[0] & 0xf0) == 0xe0;
  21842. }
  21843. int MidiMessage::getPitchWheelValue() const throw()
  21844. {
  21845. return data[1] | (data[2] << 7);
  21846. }
  21847. const MidiMessage MidiMessage::pitchWheel (const int channel,
  21848. const int position) throw()
  21849. {
  21850. jassert (channel > 0 && channel <= 16);
  21851. jassert (((unsigned int) position) <= 0x3fff);
  21852. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  21853. position & 127,
  21854. (position >> 7) & 127);
  21855. }
  21856. bool MidiMessage::isController() const throw()
  21857. {
  21858. return (data[0] & 0xf0) == 0xb0;
  21859. }
  21860. int MidiMessage::getControllerNumber() const throw()
  21861. {
  21862. jassert (isController());
  21863. return data[1];
  21864. }
  21865. int MidiMessage::getControllerValue() const throw()
  21866. {
  21867. jassert (isController());
  21868. return data[2];
  21869. }
  21870. const MidiMessage MidiMessage::controllerEvent (const int channel,
  21871. const int controllerType,
  21872. const int value) throw()
  21873. {
  21874. // the channel must be between 1 and 16 inclusive
  21875. jassert (channel > 0 && channel <= 16);
  21876. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  21877. controllerType & 127,
  21878. value & 127);
  21879. }
  21880. const MidiMessage MidiMessage::noteOn (const int channel,
  21881. const int noteNumber,
  21882. const float velocity) throw()
  21883. {
  21884. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  21885. }
  21886. const MidiMessage MidiMessage::noteOn (const int channel,
  21887. const int noteNumber,
  21888. const uint8 velocity) throw()
  21889. {
  21890. jassert (channel > 0 && channel <= 16);
  21891. jassert (((unsigned int) noteNumber) <= 127);
  21892. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  21893. noteNumber & 127,
  21894. jlimit (0, 127, roundFloatToInt (velocity)));
  21895. }
  21896. const MidiMessage MidiMessage::noteOff (const int channel,
  21897. const int noteNumber) throw()
  21898. {
  21899. jassert (channel > 0 && channel <= 16);
  21900. jassert (((unsigned int) noteNumber) <= 127);
  21901. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  21902. }
  21903. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  21904. {
  21905. jassert (channel > 0 && channel <= 16);
  21906. return controllerEvent (channel, 123, 0);
  21907. }
  21908. bool MidiMessage::isAllNotesOff() const throw()
  21909. {
  21910. return (data[0] & 0xf0) == 0xb0
  21911. && data[1] == 123;
  21912. }
  21913. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  21914. {
  21915. return controllerEvent (channel, 120, 0);
  21916. }
  21917. bool MidiMessage::isAllSoundOff() const throw()
  21918. {
  21919. return (data[0] & 0xf0) == 0xb0
  21920. && data[1] == 120;
  21921. }
  21922. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  21923. {
  21924. return controllerEvent (channel, 121, 0);
  21925. }
  21926. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  21927. {
  21928. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  21929. uint8 buf[8];
  21930. buf[0] = 0xf0;
  21931. buf[1] = 0x7f;
  21932. buf[2] = 0x7f;
  21933. buf[3] = 0x04;
  21934. buf[4] = 0x01;
  21935. buf[5] = (uint8) (vol & 0x7f);
  21936. buf[6] = (uint8) (vol >> 7);
  21937. buf[7] = 0xf7;
  21938. return MidiMessage (buf, 8);
  21939. }
  21940. bool MidiMessage::isSysEx() const throw()
  21941. {
  21942. return *data == 0xf0;
  21943. }
  21944. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  21945. const int dataSize) throw()
  21946. {
  21947. MemoryBlock mm (dataSize + 2);
  21948. uint8* const m = (uint8*) mm.getData();
  21949. m[0] = 0xf0;
  21950. memcpy (m + 1, sysexData, dataSize);
  21951. m[dataSize + 1] = 0xf7;
  21952. return MidiMessage (m, dataSize + 2);
  21953. }
  21954. const uint8* MidiMessage::getSysExData() const throw()
  21955. {
  21956. return (isSysEx()) ? getRawData() + 1
  21957. : 0;
  21958. }
  21959. int MidiMessage::getSysExDataSize() const throw()
  21960. {
  21961. return (isSysEx()) ? size - 2
  21962. : 0;
  21963. }
  21964. bool MidiMessage::isMetaEvent() const throw()
  21965. {
  21966. return *data == 0xff;
  21967. }
  21968. bool MidiMessage::isActiveSense() const throw()
  21969. {
  21970. return *data == 0xfe;
  21971. }
  21972. int MidiMessage::getMetaEventType() const throw()
  21973. {
  21974. if (*data != 0xff)
  21975. return -1;
  21976. else
  21977. return data[1];
  21978. }
  21979. int MidiMessage::getMetaEventLength() const throw()
  21980. {
  21981. if (*data == 0xff)
  21982. {
  21983. int n;
  21984. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  21985. }
  21986. return 0;
  21987. }
  21988. const uint8* MidiMessage::getMetaEventData() const throw()
  21989. {
  21990. int n;
  21991. const uint8* d = data + 2;
  21992. readVariableLengthVal (d, n);
  21993. return d + n;
  21994. }
  21995. bool MidiMessage::isTrackMetaEvent() const throw()
  21996. {
  21997. return getMetaEventType() == 0;
  21998. }
  21999. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22000. {
  22001. return getMetaEventType() == 47;
  22002. }
  22003. bool MidiMessage::isTextMetaEvent() const throw()
  22004. {
  22005. const int t = getMetaEventType();
  22006. return t > 0 && t < 16;
  22007. }
  22008. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  22009. {
  22010. return String ((const char*) getMetaEventData(),
  22011. getMetaEventLength());
  22012. }
  22013. bool MidiMessage::isTrackNameEvent() const throw()
  22014. {
  22015. return (data[1] == 3)
  22016. && (*data == 0xff);
  22017. }
  22018. bool MidiMessage::isTempoMetaEvent() const throw()
  22019. {
  22020. return (data[1] == 81)
  22021. && (*data == 0xff);
  22022. }
  22023. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22024. {
  22025. return (data[1] == 0x20)
  22026. && (*data == 0xff)
  22027. && (data[2] == 1);
  22028. }
  22029. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22030. {
  22031. return data[3] + 1;
  22032. }
  22033. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22034. {
  22035. if (! isTempoMetaEvent())
  22036. return 0.0;
  22037. const uint8* const d = getMetaEventData();
  22038. return (((unsigned int) d[0] << 16)
  22039. | ((unsigned int) d[1] << 8)
  22040. | d[2])
  22041. / 1000000.0;
  22042. }
  22043. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22044. {
  22045. if (timeFormat > 0)
  22046. {
  22047. if (! isTempoMetaEvent())
  22048. return 0.5 / timeFormat;
  22049. return getTempoSecondsPerQuarterNote() / timeFormat;
  22050. }
  22051. else
  22052. {
  22053. const int frameCode = (-timeFormat) >> 8;
  22054. double framesPerSecond;
  22055. switch (frameCode)
  22056. {
  22057. case 24: framesPerSecond = 24.0; break;
  22058. case 25: framesPerSecond = 25.0; break;
  22059. case 29: framesPerSecond = 29.97; break;
  22060. case 30: framesPerSecond = 30.0; break;
  22061. default: framesPerSecond = 30.0; break;
  22062. }
  22063. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22064. }
  22065. }
  22066. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22067. {
  22068. uint8 d[8];
  22069. d[0] = 0xff;
  22070. d[1] = 81;
  22071. d[2] = 3;
  22072. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22073. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22074. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22075. return MidiMessage (d, 6, 0.0);
  22076. }
  22077. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22078. {
  22079. return (data[1] == 0x58)
  22080. && (*data == (uint8) 0xff);
  22081. }
  22082. void MidiMessage::getTimeSignatureInfo (int& numerator,
  22083. int& denominator) const throw()
  22084. {
  22085. if (isTimeSignatureMetaEvent())
  22086. {
  22087. const uint8* const d = getMetaEventData();
  22088. numerator = d[0];
  22089. denominator = 1 << d[1];
  22090. }
  22091. else
  22092. {
  22093. numerator = 4;
  22094. denominator = 4;
  22095. }
  22096. }
  22097. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  22098. const int denominator) throw()
  22099. {
  22100. uint8 d[8];
  22101. d[0] = 0xff;
  22102. d[1] = 0x58;
  22103. d[2] = 0x04;
  22104. d[3] = (uint8) numerator;
  22105. int n = 1;
  22106. int powerOfTwo = 0;
  22107. while (n < denominator)
  22108. {
  22109. n <<= 1;
  22110. ++powerOfTwo;
  22111. }
  22112. d[4] = (uint8) powerOfTwo;
  22113. d[5] = 0x01;
  22114. d[6] = 96;
  22115. return MidiMessage (d, 7, 0.0);
  22116. }
  22117. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22118. {
  22119. uint8 d[8];
  22120. d[0] = 0xff;
  22121. d[1] = 0x20;
  22122. d[2] = 0x01;
  22123. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22124. return MidiMessage (d, 4, 0.0);
  22125. }
  22126. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22127. {
  22128. return getMetaEventType() == 89;
  22129. }
  22130. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22131. {
  22132. return (int) *getMetaEventData();
  22133. }
  22134. const MidiMessage MidiMessage::endOfTrack() throw()
  22135. {
  22136. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22137. }
  22138. bool MidiMessage::isSongPositionPointer() const throw()
  22139. {
  22140. return *data == 0xf2;
  22141. }
  22142. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22143. {
  22144. return data[1] | (data[2] << 7);
  22145. }
  22146. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22147. {
  22148. return MidiMessage (0xf2,
  22149. positionInMidiBeats & 127,
  22150. (positionInMidiBeats >> 7) & 127);
  22151. }
  22152. bool MidiMessage::isMidiStart() const throw()
  22153. {
  22154. return *data == 0xfa;
  22155. }
  22156. const MidiMessage MidiMessage::midiStart() throw()
  22157. {
  22158. return MidiMessage (0xfa);
  22159. }
  22160. bool MidiMessage::isMidiContinue() const throw()
  22161. {
  22162. return *data == 0xfb;
  22163. }
  22164. const MidiMessage MidiMessage::midiContinue() throw()
  22165. {
  22166. return MidiMessage (0xfb);
  22167. }
  22168. bool MidiMessage::isMidiStop() const throw()
  22169. {
  22170. return *data == 0xfc;
  22171. }
  22172. const MidiMessage MidiMessage::midiStop() throw()
  22173. {
  22174. return MidiMessage (0xfc);
  22175. }
  22176. bool MidiMessage::isMidiClock() const throw()
  22177. {
  22178. return *data == 0xf8;
  22179. }
  22180. const MidiMessage MidiMessage::midiClock() throw()
  22181. {
  22182. return MidiMessage (0xf8);
  22183. }
  22184. bool MidiMessage::isQuarterFrame() const throw()
  22185. {
  22186. return *data == 0xf1;
  22187. }
  22188. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22189. {
  22190. return ((int) data[1]) >> 4;
  22191. }
  22192. int MidiMessage::getQuarterFrameValue() const throw()
  22193. {
  22194. return ((int) data[1]) & 0x0f;
  22195. }
  22196. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22197. const int value) throw()
  22198. {
  22199. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22200. }
  22201. bool MidiMessage::isFullFrame() const throw()
  22202. {
  22203. return data[0] == 0xf0
  22204. && data[1] == 0x7f
  22205. && size >= 10
  22206. && data[3] == 0x01
  22207. && data[4] == 0x01;
  22208. }
  22209. void MidiMessage::getFullFrameParameters (int& hours,
  22210. int& minutes,
  22211. int& seconds,
  22212. int& frames,
  22213. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22214. {
  22215. jassert (isFullFrame());
  22216. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22217. hours = data[5] & 0x1f;
  22218. minutes = data[6];
  22219. seconds = data[7];
  22220. frames = data[8];
  22221. }
  22222. const MidiMessage MidiMessage::fullFrame (const int hours,
  22223. const int minutes,
  22224. const int seconds,
  22225. const int frames,
  22226. MidiMessage::SmpteTimecodeType timecodeType)
  22227. {
  22228. uint8 d[10];
  22229. d[0] = 0xf0;
  22230. d[1] = 0x7f;
  22231. d[2] = 0x7f;
  22232. d[3] = 0x01;
  22233. d[4] = 0x01;
  22234. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22235. d[6] = (uint8) minutes;
  22236. d[7] = (uint8) seconds;
  22237. d[8] = (uint8) frames;
  22238. d[9] = 0xf7;
  22239. return MidiMessage (d, 10, 0.0);
  22240. }
  22241. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22242. {
  22243. return data[0] == 0xf0
  22244. && data[1] == 0x7f
  22245. && data[3] == 0x06
  22246. && size > 5;
  22247. }
  22248. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22249. {
  22250. jassert (isMidiMachineControlMessage());
  22251. return (MidiMachineControlCommand) data[4];
  22252. }
  22253. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22254. {
  22255. uint8 d[6];
  22256. d[0] = 0xf0;
  22257. d[1] = 0x7f;
  22258. d[2] = 0x00;
  22259. d[3] = 0x06;
  22260. d[4] = (uint8) command;
  22261. d[5] = 0xf7;
  22262. return MidiMessage (d, 6, 0.0);
  22263. }
  22264. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22265. int& minutes,
  22266. int& seconds,
  22267. int& frames) const throw()
  22268. {
  22269. if (size >= 12
  22270. && data[0] == 0xf0
  22271. && data[1] == 0x7f
  22272. && data[3] == 0x06
  22273. && data[4] == 0x44
  22274. && data[5] == 0x06
  22275. && data[6] == 0x01)
  22276. {
  22277. hours = data[7] % 24; // (that some machines send out hours > 24)
  22278. minutes = data[8];
  22279. seconds = data[9];
  22280. frames = data[10];
  22281. return true;
  22282. }
  22283. return false;
  22284. }
  22285. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22286. int minutes,
  22287. int seconds,
  22288. int frames)
  22289. {
  22290. uint8 d[12];
  22291. d[0] = 0xf0;
  22292. d[1] = 0x7f;
  22293. d[2] = 0x00;
  22294. d[3] = 0x06;
  22295. d[4] = 0x44;
  22296. d[5] = 0x06;
  22297. d[6] = 0x01;
  22298. d[7] = (uint8) hours;
  22299. d[8] = (uint8) minutes;
  22300. d[9] = (uint8) seconds;
  22301. d[10] = (uint8) frames;
  22302. d[11] = 0xf7;
  22303. return MidiMessage (d, 12, 0.0);
  22304. }
  22305. const String MidiMessage::getMidiNoteName (int note,
  22306. bool useSharps,
  22307. bool includeOctaveNumber,
  22308. int octaveNumForMiddleC) throw()
  22309. {
  22310. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22311. "F", "F#", "G", "G#", "A",
  22312. "A#", "B" };
  22313. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22314. "F", "Gb", "G", "Ab", "A",
  22315. "Bb", "B" };
  22316. if (((unsigned int) note) < 128)
  22317. {
  22318. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22319. : flatNoteNames [note % 12]);
  22320. if (includeOctaveNumber)
  22321. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22322. else
  22323. return s;
  22324. }
  22325. return String::empty;
  22326. }
  22327. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22328. {
  22329. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22330. return 440.0 * pow (2.0, noteNumber / 12.0);
  22331. }
  22332. const String MidiMessage::getGMInstrumentName (int n) throw()
  22333. {
  22334. const char *names[] =
  22335. {
  22336. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22337. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22338. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22339. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22340. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22341. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22342. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22343. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22344. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22345. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22346. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22347. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22348. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22349. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22350. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22351. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22352. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22353. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22354. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22355. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22356. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22357. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22358. "Applause", "Gunshot"
  22359. };
  22360. return (((unsigned int) n) < 128) ? names[n]
  22361. : (const char*)0;
  22362. }
  22363. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22364. {
  22365. const char* names[] =
  22366. {
  22367. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22368. "Bass", "Strings", "Ensemble", "Brass",
  22369. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22370. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22371. };
  22372. return (((unsigned int) n) <= 15) ? names[n]
  22373. : (const char*)0;
  22374. }
  22375. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22376. {
  22377. const char* names[] =
  22378. {
  22379. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22380. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22381. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22382. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22383. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22384. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22385. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22386. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22387. "Mute Triangle", "Open Triangle"
  22388. };
  22389. return (n >= 35 && n <= 81) ? names [n - 35]
  22390. : (const char*)0;
  22391. }
  22392. const String MidiMessage::getControllerName (int n) throw()
  22393. {
  22394. const char* names[] =
  22395. {
  22396. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22397. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22398. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22399. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22400. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22401. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22402. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22403. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22404. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22405. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22406. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22407. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22408. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22409. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22410. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22411. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22412. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22413. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22414. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22416. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22417. "Poly Operation"
  22418. };
  22419. return (((unsigned int) n) < 128) ? names[n]
  22420. : (const char*)0;
  22421. }
  22422. END_JUCE_NAMESPACE
  22423. /********* End of inlined file: juce_MidiMessage.cpp *********/
  22424. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  22425. BEGIN_JUCE_NAMESPACE
  22426. MidiMessageCollector::MidiMessageCollector()
  22427. : lastCallbackTime (0),
  22428. sampleRate (44100.0001)
  22429. {
  22430. }
  22431. MidiMessageCollector::~MidiMessageCollector()
  22432. {
  22433. }
  22434. void MidiMessageCollector::reset (const double sampleRate_)
  22435. {
  22436. jassert (sampleRate_ > 0);
  22437. const ScopedLock sl (midiCallbackLock);
  22438. sampleRate = sampleRate_;
  22439. incomingMessages.clear();
  22440. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22441. }
  22442. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22443. {
  22444. // you need to call reset() to set the correct sample rate before using this object
  22445. jassert (sampleRate != 44100.0001);
  22446. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22447. // for details of what the number should be.
  22448. jassert (message.getTimeStamp() != 0);
  22449. const ScopedLock sl (midiCallbackLock);
  22450. const int sampleNumber
  22451. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22452. incomingMessages.addEvent (message, sampleNumber);
  22453. // if the messages don't get used for over a second, we'd better
  22454. // get rid of any old ones to avoid the queue getting too big
  22455. if (sampleNumber > sampleRate)
  22456. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22457. }
  22458. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22459. const int numSamples)
  22460. {
  22461. // you need to call reset() to set the correct sample rate before using this object
  22462. jassert (sampleRate != 44100.0001);
  22463. const double timeNow = Time::getMillisecondCounterHiRes();
  22464. const double msElapsed = timeNow - lastCallbackTime;
  22465. const ScopedLock sl (midiCallbackLock);
  22466. lastCallbackTime = timeNow;
  22467. if (! incomingMessages.isEmpty())
  22468. {
  22469. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  22470. int startSample = 0;
  22471. int scale = 1 << 16;
  22472. const uint8* midiData;
  22473. int numBytes, samplePosition;
  22474. MidiBuffer::Iterator iter (incomingMessages);
  22475. if (numSourceSamples > numSamples)
  22476. {
  22477. // if our list of events is longer than the buffer we're being
  22478. // asked for, scale them down to squeeze them all in..
  22479. const int maxBlockLengthToUse = numSamples << 5;
  22480. if (numSourceSamples > maxBlockLengthToUse)
  22481. {
  22482. startSample = numSourceSamples - maxBlockLengthToUse;
  22483. numSourceSamples = maxBlockLengthToUse;
  22484. iter.setNextSamplePosition (startSample);
  22485. }
  22486. scale = (numSamples << 10) / numSourceSamples;
  22487. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22488. {
  22489. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22490. destBuffer.addEvent (midiData, numBytes,
  22491. jlimit (0, numSamples - 1, samplePosition));
  22492. }
  22493. }
  22494. else
  22495. {
  22496. // if our event list is shorter than the number we need, put them
  22497. // towards the end of the buffer
  22498. startSample = numSamples - numSourceSamples;
  22499. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22500. {
  22501. destBuffer.addEvent (midiData, numBytes,
  22502. jlimit (0, numSamples - 1, samplePosition + startSample));
  22503. }
  22504. }
  22505. incomingMessages.clear();
  22506. }
  22507. }
  22508. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  22509. {
  22510. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  22511. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22512. addMessageToQueue (m);
  22513. }
  22514. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  22515. {
  22516. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  22517. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22518. addMessageToQueue (m);
  22519. }
  22520. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  22521. {
  22522. addMessageToQueue (message);
  22523. }
  22524. END_JUCE_NAMESPACE
  22525. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  22526. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  22527. BEGIN_JUCE_NAMESPACE
  22528. MidiMessageSequence::MidiMessageSequence()
  22529. {
  22530. }
  22531. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  22532. {
  22533. list.ensureStorageAllocated (other.list.size());
  22534. for (int i = 0; i < other.list.size(); ++i)
  22535. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22536. }
  22537. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  22538. {
  22539. if (this != &other)
  22540. {
  22541. clear();
  22542. for (int i = 0; i < other.list.size(); ++i)
  22543. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22544. }
  22545. return *this;
  22546. }
  22547. MidiMessageSequence::~MidiMessageSequence()
  22548. {
  22549. }
  22550. void MidiMessageSequence::clear()
  22551. {
  22552. list.clear();
  22553. }
  22554. int MidiMessageSequence::getNumEvents() const
  22555. {
  22556. return list.size();
  22557. }
  22558. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  22559. {
  22560. return list [index];
  22561. }
  22562. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  22563. {
  22564. const MidiEventHolder* const meh = list [index];
  22565. if (meh != 0 && meh->noteOffObject != 0)
  22566. return meh->noteOffObject->message.getTimeStamp();
  22567. else
  22568. return 0.0;
  22569. }
  22570. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  22571. {
  22572. const MidiEventHolder* const meh = list [index];
  22573. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  22574. }
  22575. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  22576. {
  22577. return list.indexOf (event);
  22578. }
  22579. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  22580. {
  22581. const int numEvents = list.size();
  22582. int i;
  22583. for (i = 0; i < numEvents; ++i)
  22584. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  22585. break;
  22586. return i;
  22587. }
  22588. double MidiMessageSequence::getStartTime() const
  22589. {
  22590. if (list.size() > 0)
  22591. return list.getUnchecked(0)->message.getTimeStamp();
  22592. else
  22593. return 0;
  22594. }
  22595. double MidiMessageSequence::getEndTime() const
  22596. {
  22597. if (list.size() > 0)
  22598. return list.getLast()->message.getTimeStamp();
  22599. else
  22600. return 0;
  22601. }
  22602. double MidiMessageSequence::getEventTime (const int index) const
  22603. {
  22604. if (((unsigned int) index) < (unsigned int) list.size())
  22605. return list.getUnchecked (index)->message.getTimeStamp();
  22606. return 0.0;
  22607. }
  22608. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  22609. double timeAdjustment)
  22610. {
  22611. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  22612. timeAdjustment += newMessage.getTimeStamp();
  22613. newOne->message.setTimeStamp (timeAdjustment);
  22614. int i;
  22615. for (i = list.size(); --i >= 0;)
  22616. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  22617. break;
  22618. list.insert (i + 1, newOne);
  22619. }
  22620. void MidiMessageSequence::deleteEvent (const int index,
  22621. const bool deleteMatchingNoteUp)
  22622. {
  22623. if (((unsigned int) index) < (unsigned int) list.size())
  22624. {
  22625. if (deleteMatchingNoteUp)
  22626. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  22627. list.remove (index);
  22628. }
  22629. }
  22630. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  22631. double timeAdjustment,
  22632. double firstAllowableTime,
  22633. double endOfAllowableDestTimes)
  22634. {
  22635. firstAllowableTime -= timeAdjustment;
  22636. endOfAllowableDestTimes -= timeAdjustment;
  22637. for (int i = 0; i < other.list.size(); ++i)
  22638. {
  22639. const MidiMessage& m = other.list.getUnchecked(i)->message;
  22640. const double t = m.getTimeStamp();
  22641. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  22642. {
  22643. MidiEventHolder* const newOne = new MidiEventHolder (m);
  22644. newOne->message.setTimeStamp (timeAdjustment + t);
  22645. list.add (newOne);
  22646. }
  22647. }
  22648. sort();
  22649. }
  22650. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22651. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22652. {
  22653. const double diff = first->message.getTimeStamp()
  22654. - second->message.getTimeStamp();
  22655. return (diff > 0) - (diff < 0);
  22656. }
  22657. void MidiMessageSequence::sort()
  22658. {
  22659. list.sort (*this, true);
  22660. }
  22661. void MidiMessageSequence::updateMatchedPairs()
  22662. {
  22663. for (int i = 0; i < list.size(); ++i)
  22664. {
  22665. const MidiMessage& m1 = list.getUnchecked(i)->message;
  22666. if (m1.isNoteOn())
  22667. {
  22668. list.getUnchecked(i)->noteOffObject = 0;
  22669. const int note = m1.getNoteNumber();
  22670. const int chan = m1.getChannel();
  22671. const int len = list.size();
  22672. for (int j = i + 1; j < len; ++j)
  22673. {
  22674. const MidiMessage& m = list.getUnchecked(j)->message;
  22675. if (m.getNoteNumber() == note && m.getChannel() == chan)
  22676. {
  22677. if (m.isNoteOff())
  22678. {
  22679. list.getUnchecked(i)->noteOffObject = list[j];
  22680. break;
  22681. }
  22682. else if (m.isNoteOn())
  22683. {
  22684. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  22685. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  22686. list.getUnchecked(i)->noteOffObject = list[j];
  22687. break;
  22688. }
  22689. }
  22690. }
  22691. }
  22692. }
  22693. }
  22694. void MidiMessageSequence::addTimeToMessages (const double delta)
  22695. {
  22696. for (int i = list.size(); --i >= 0;)
  22697. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  22698. + delta);
  22699. }
  22700. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  22701. MidiMessageSequence& destSequence,
  22702. const bool alsoIncludeMetaEvents) const
  22703. {
  22704. for (int i = 0; i < list.size(); ++i)
  22705. {
  22706. const MidiMessage& mm = list.getUnchecked(i)->message;
  22707. if (mm.isForChannel (channelNumberToExtract)
  22708. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  22709. {
  22710. destSequence.addEvent (mm);
  22711. }
  22712. }
  22713. }
  22714. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  22715. {
  22716. for (int i = 0; i < list.size(); ++i)
  22717. {
  22718. const MidiMessage& mm = list.getUnchecked(i)->message;
  22719. if (mm.isSysEx())
  22720. destSequence.addEvent (mm);
  22721. }
  22722. }
  22723. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  22724. {
  22725. for (int i = list.size(); --i >= 0;)
  22726. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  22727. list.remove(i);
  22728. }
  22729. void MidiMessageSequence::deleteSysExMessages()
  22730. {
  22731. for (int i = list.size(); --i >= 0;)
  22732. if (list.getUnchecked(i)->message.isSysEx())
  22733. list.remove(i);
  22734. }
  22735. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  22736. const double time,
  22737. OwnedArray<MidiMessage>& dest)
  22738. {
  22739. bool doneProg = false;
  22740. bool donePitchWheel = false;
  22741. Array <int> doneControllers (32);
  22742. for (int i = list.size(); --i >= 0;)
  22743. {
  22744. const MidiMessage& mm = list.getUnchecked(i)->message;
  22745. if (mm.isForChannel (channelNumber)
  22746. && mm.getTimeStamp() <= time)
  22747. {
  22748. if (mm.isProgramChange())
  22749. {
  22750. if (! doneProg)
  22751. {
  22752. dest.add (new MidiMessage (mm, 0.0));
  22753. doneProg = true;
  22754. }
  22755. }
  22756. else if (mm.isController())
  22757. {
  22758. if (! doneControllers.contains (mm.getControllerNumber()))
  22759. {
  22760. dest.add (new MidiMessage (mm, 0.0));
  22761. doneControllers.add (mm.getControllerNumber());
  22762. }
  22763. }
  22764. else if (mm.isPitchWheel())
  22765. {
  22766. if (! donePitchWheel)
  22767. {
  22768. dest.add (new MidiMessage (mm, 0.0));
  22769. donePitchWheel = true;
  22770. }
  22771. }
  22772. }
  22773. }
  22774. }
  22775. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  22776. : message (message_),
  22777. noteOffObject (0)
  22778. {
  22779. }
  22780. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  22781. {
  22782. }
  22783. END_JUCE_NAMESPACE
  22784. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  22785. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  22786. BEGIN_JUCE_NAMESPACE
  22787. AudioPluginFormat::AudioPluginFormat() throw()
  22788. {
  22789. }
  22790. AudioPluginFormat::~AudioPluginFormat()
  22791. {
  22792. }
  22793. END_JUCE_NAMESPACE
  22794. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  22795. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22796. BEGIN_JUCE_NAMESPACE
  22797. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  22798. {
  22799. }
  22800. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  22801. {
  22802. clearSingletonInstance();
  22803. }
  22804. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  22805. void AudioPluginFormatManager::addDefaultFormats()
  22806. {
  22807. #ifdef JUCE_DEBUG
  22808. // you should only call this method once!
  22809. for (int i = formats.size(); --i >= 0;)
  22810. {
  22811. #if JUCE_PLUGINHOST_VST
  22812. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  22813. #endif
  22814. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22815. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  22816. #endif
  22817. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22818. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  22819. #endif
  22820. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22821. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  22822. #endif
  22823. }
  22824. #endif
  22825. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22826. formats.add (new AudioUnitPluginFormat());
  22827. #endif
  22828. #if JUCE_PLUGINHOST_VST
  22829. formats.add (new VSTPluginFormat());
  22830. #endif
  22831. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22832. formats.add (new DirectXPluginFormat());
  22833. #endif
  22834. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22835. formats.add (new LADSPAPluginFormat());
  22836. #endif
  22837. }
  22838. int AudioPluginFormatManager::getNumFormats() throw()
  22839. {
  22840. return formats.size();
  22841. }
  22842. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  22843. {
  22844. return formats [index];
  22845. }
  22846. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  22847. {
  22848. formats.add (format);
  22849. }
  22850. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  22851. String& errorMessage) const
  22852. {
  22853. AudioPluginInstance* result = 0;
  22854. for (int i = 0; i < formats.size(); ++i)
  22855. {
  22856. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  22857. if (result != 0)
  22858. break;
  22859. }
  22860. if (result == 0)
  22861. {
  22862. if (! doesPluginStillExist (description))
  22863. errorMessage = TRANS ("This plug-in file no longer exists");
  22864. else
  22865. errorMessage = TRANS ("This plug-in failed to load correctly");
  22866. }
  22867. return result;
  22868. }
  22869. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  22870. {
  22871. for (int i = 0; i < formats.size(); ++i)
  22872. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  22873. return formats.getUnchecked(i)->doesPluginStillExist (description);
  22874. return false;
  22875. }
  22876. END_JUCE_NAMESPACE
  22877. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22878. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  22879. #define JUCE_PLUGIN_HOST 1
  22880. BEGIN_JUCE_NAMESPACE
  22881. AudioPluginInstance::AudioPluginInstance()
  22882. {
  22883. }
  22884. AudioPluginInstance::~AudioPluginInstance()
  22885. {
  22886. }
  22887. END_JUCE_NAMESPACE
  22888. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  22889. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  22890. BEGIN_JUCE_NAMESPACE
  22891. KnownPluginList::KnownPluginList()
  22892. {
  22893. }
  22894. KnownPluginList::~KnownPluginList()
  22895. {
  22896. }
  22897. void KnownPluginList::clear()
  22898. {
  22899. if (types.size() > 0)
  22900. {
  22901. types.clear();
  22902. sendChangeMessage (this);
  22903. }
  22904. }
  22905. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  22906. {
  22907. for (int i = 0; i < types.size(); ++i)
  22908. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  22909. return types.getUnchecked(i);
  22910. return 0;
  22911. }
  22912. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  22913. {
  22914. for (int i = 0; i < types.size(); ++i)
  22915. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  22916. return types.getUnchecked(i);
  22917. return 0;
  22918. }
  22919. bool KnownPluginList::addType (const PluginDescription& type)
  22920. {
  22921. for (int i = types.size(); --i >= 0;)
  22922. {
  22923. if (types.getUnchecked(i)->isDuplicateOf (type))
  22924. {
  22925. // strange - found a duplicate plugin with different info..
  22926. jassert (types.getUnchecked(i)->name == type.name);
  22927. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  22928. *types.getUnchecked(i) = type;
  22929. return false;
  22930. }
  22931. }
  22932. types.add (new PluginDescription (type));
  22933. sendChangeMessage (this);
  22934. return true;
  22935. }
  22936. void KnownPluginList::removeType (const int index) throw()
  22937. {
  22938. types.remove (index);
  22939. sendChangeMessage (this);
  22940. }
  22941. static Time getFileModTime (const String& fileOrIdentifier) throw()
  22942. {
  22943. if (fileOrIdentifier.startsWithChar (T('/'))
  22944. || fileOrIdentifier[1] == T(':'))
  22945. {
  22946. return File (fileOrIdentifier).getLastModificationTime();
  22947. }
  22948. return Time (0);
  22949. }
  22950. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  22951. {
  22952. return t1 != t2 || t1 == Time (0);
  22953. }
  22954. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  22955. {
  22956. if (getTypeForFile (fileOrIdentifier) == 0)
  22957. return false;
  22958. for (int i = types.size(); --i >= 0;)
  22959. {
  22960. const PluginDescription* const d = types.getUnchecked(i);
  22961. if (d->fileOrIdentifier == fileOrIdentifier
  22962. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22963. {
  22964. return false;
  22965. }
  22966. }
  22967. return true;
  22968. }
  22969. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  22970. const bool dontRescanIfAlreadyInList,
  22971. OwnedArray <PluginDescription>& typesFound,
  22972. AudioPluginFormat& format)
  22973. {
  22974. bool addedOne = false;
  22975. if (dontRescanIfAlreadyInList
  22976. && getTypeForFile (fileOrIdentifier) != 0)
  22977. {
  22978. bool needsRescanning = false;
  22979. for (int i = types.size(); --i >= 0;)
  22980. {
  22981. const PluginDescription* const d = types.getUnchecked(i);
  22982. if (d->fileOrIdentifier == fileOrIdentifier)
  22983. {
  22984. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22985. needsRescanning = true;
  22986. else
  22987. typesFound.add (new PluginDescription (*d));
  22988. }
  22989. }
  22990. if (! needsRescanning)
  22991. return false;
  22992. }
  22993. OwnedArray <PluginDescription> found;
  22994. format.findAllTypesForFile (found, fileOrIdentifier);
  22995. for (int i = 0; i < found.size(); ++i)
  22996. {
  22997. PluginDescription* const desc = found.getUnchecked(i);
  22998. jassert (desc != 0);
  22999. if (addType (*desc))
  23000. addedOne = true;
  23001. typesFound.add (new PluginDescription (*desc));
  23002. }
  23003. return addedOne;
  23004. }
  23005. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23006. OwnedArray <PluginDescription>& typesFound)
  23007. {
  23008. for (int i = 0; i < files.size(); ++i)
  23009. {
  23010. bool loaded = false;
  23011. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23012. {
  23013. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23014. if (scanAndAddFile (files[i], true, typesFound, *format))
  23015. loaded = true;
  23016. }
  23017. if (! loaded)
  23018. {
  23019. const File f (files[i]);
  23020. if (f.isDirectory())
  23021. {
  23022. StringArray s;
  23023. {
  23024. OwnedArray <File> subFiles;
  23025. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23026. for (int j = 0; j < subFiles.size(); ++j)
  23027. s.add (subFiles.getUnchecked (j)->getFullPathName());
  23028. }
  23029. scanAndAddDragAndDroppedFiles (s, typesFound);
  23030. }
  23031. }
  23032. }
  23033. }
  23034. class PluginSorter
  23035. {
  23036. public:
  23037. KnownPluginList::SortMethod method;
  23038. PluginSorter() throw() {}
  23039. int compareElements (const PluginDescription* const first,
  23040. const PluginDescription* const second) const throw()
  23041. {
  23042. int diff = 0;
  23043. if (method == KnownPluginList::sortByCategory)
  23044. diff = first->category.compareLexicographically (second->category);
  23045. else if (method == KnownPluginList::sortByManufacturer)
  23046. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23047. else if (method == KnownPluginList::sortByFileSystemLocation)
  23048. diff = first->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  23049. .upToLastOccurrenceOf (T("/"), false, false)
  23050. .compare (second->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  23051. .upToLastOccurrenceOf (T("/"), false, false));
  23052. if (diff == 0)
  23053. diff = first->name.compareLexicographically (second->name);
  23054. return diff;
  23055. }
  23056. };
  23057. void KnownPluginList::sort (const SortMethod method)
  23058. {
  23059. if (method != defaultOrder)
  23060. {
  23061. PluginSorter sorter;
  23062. sorter.method = method;
  23063. types.sort (sorter, true);
  23064. sendChangeMessage (this);
  23065. }
  23066. }
  23067. XmlElement* KnownPluginList::createXml() const
  23068. {
  23069. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  23070. for (int i = 0; i < types.size(); ++i)
  23071. e->addChildElement (types.getUnchecked(i)->createXml());
  23072. return e;
  23073. }
  23074. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23075. {
  23076. clear();
  23077. if (xml.hasTagName (T("KNOWNPLUGINS")))
  23078. {
  23079. forEachXmlChildElement (xml, e)
  23080. {
  23081. PluginDescription info;
  23082. if (info.loadFromXml (*e))
  23083. addType (info);
  23084. }
  23085. }
  23086. }
  23087. const int menuIdBase = 0x324503f4;
  23088. // This is used to turn a bunch of paths into a nested menu structure.
  23089. struct PluginFilesystemTree
  23090. {
  23091. private:
  23092. String folder;
  23093. OwnedArray <PluginFilesystemTree> subFolders;
  23094. Array <PluginDescription*> plugins;
  23095. void addPlugin (PluginDescription* const pd, const String& path)
  23096. {
  23097. if (path.isEmpty())
  23098. {
  23099. plugins.add (pd);
  23100. }
  23101. else
  23102. {
  23103. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  23104. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  23105. for (int i = subFolders.size(); --i >= 0;)
  23106. {
  23107. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23108. {
  23109. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23110. return;
  23111. }
  23112. }
  23113. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23114. newFolder->folder = firstSubFolder;
  23115. subFolders.add (newFolder);
  23116. newFolder->addPlugin (pd, remainingPath);
  23117. }
  23118. }
  23119. // removes any deeply nested folders that don't contain any actual plugins
  23120. void optimise()
  23121. {
  23122. for (int i = subFolders.size(); --i >= 0;)
  23123. {
  23124. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23125. sub->optimise();
  23126. if (sub->plugins.size() == 0)
  23127. {
  23128. for (int j = 0; j < sub->subFolders.size(); ++j)
  23129. subFolders.add (sub->subFolders.getUnchecked(j));
  23130. sub->subFolders.clear (false);
  23131. subFolders.remove (i);
  23132. }
  23133. }
  23134. }
  23135. public:
  23136. void buildTree (const Array <PluginDescription*>& allPlugins)
  23137. {
  23138. for (int i = 0; i < allPlugins.size(); ++i)
  23139. {
  23140. String path (allPlugins.getUnchecked(i)
  23141. ->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  23142. .upToLastOccurrenceOf (T("/"), false, false));
  23143. if (path.substring (1, 2) == T(":"))
  23144. path = path.substring (2);
  23145. addPlugin (allPlugins.getUnchecked(i), path);
  23146. }
  23147. optimise();
  23148. }
  23149. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23150. {
  23151. int i;
  23152. for (i = 0; i < subFolders.size(); ++i)
  23153. {
  23154. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23155. PopupMenu subMenu;
  23156. sub->addToMenu (subMenu, allPlugins);
  23157. #if JUCE_MAC
  23158. // avoid the special AU formatting nonsense on Mac..
  23159. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (T(":"), false, false), subMenu);
  23160. #else
  23161. m.addSubMenu (sub->folder, subMenu);
  23162. #endif
  23163. }
  23164. for (i = 0; i < plugins.size(); ++i)
  23165. {
  23166. PluginDescription* const plugin = plugins.getUnchecked(i);
  23167. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23168. plugin->name, true, false);
  23169. }
  23170. }
  23171. };
  23172. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23173. {
  23174. Array <PluginDescription*> sorted;
  23175. {
  23176. PluginSorter sorter;
  23177. sorter.method = sortMethod;
  23178. for (int i = 0; i < types.size(); ++i)
  23179. sorted.addSorted (sorter, types.getUnchecked(i));
  23180. }
  23181. if (sortMethod == sortByCategory
  23182. || sortMethod == sortByManufacturer)
  23183. {
  23184. String lastSubMenuName;
  23185. PopupMenu sub;
  23186. for (int i = 0; i < sorted.size(); ++i)
  23187. {
  23188. const PluginDescription* const pd = sorted.getUnchecked(i);
  23189. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23190. : pd->manufacturerName);
  23191. if (! thisSubMenuName.containsNonWhitespaceChars())
  23192. thisSubMenuName = T("Other");
  23193. if (thisSubMenuName != lastSubMenuName)
  23194. {
  23195. if (sub.getNumItems() > 0)
  23196. {
  23197. menu.addSubMenu (lastSubMenuName, sub);
  23198. sub.clear();
  23199. }
  23200. lastSubMenuName = thisSubMenuName;
  23201. }
  23202. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23203. }
  23204. if (sub.getNumItems() > 0)
  23205. menu.addSubMenu (lastSubMenuName, sub);
  23206. }
  23207. else if (sortMethod == sortByFileSystemLocation)
  23208. {
  23209. PluginFilesystemTree root;
  23210. root.buildTree (sorted);
  23211. root.addToMenu (menu, types);
  23212. }
  23213. else
  23214. {
  23215. for (int i = 0; i < sorted.size(); ++i)
  23216. {
  23217. const PluginDescription* const pd = sorted.getUnchecked(i);
  23218. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23219. }
  23220. }
  23221. }
  23222. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23223. {
  23224. const int i = menuResultCode - menuIdBase;
  23225. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23226. }
  23227. END_JUCE_NAMESPACE
  23228. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  23229. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  23230. BEGIN_JUCE_NAMESPACE
  23231. PluginDescription::PluginDescription() throw()
  23232. : uid (0),
  23233. isInstrument (false),
  23234. numInputChannels (0),
  23235. numOutputChannels (0)
  23236. {
  23237. }
  23238. PluginDescription::~PluginDescription() throw()
  23239. {
  23240. }
  23241. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23242. : name (other.name),
  23243. pluginFormatName (other.pluginFormatName),
  23244. category (other.category),
  23245. manufacturerName (other.manufacturerName),
  23246. version (other.version),
  23247. fileOrIdentifier (other.fileOrIdentifier),
  23248. lastFileModTime (other.lastFileModTime),
  23249. uid (other.uid),
  23250. isInstrument (other.isInstrument),
  23251. numInputChannels (other.numInputChannels),
  23252. numOutputChannels (other.numOutputChannels)
  23253. {
  23254. }
  23255. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23256. {
  23257. name = other.name;
  23258. pluginFormatName = other.pluginFormatName;
  23259. category = other.category;
  23260. manufacturerName = other.manufacturerName;
  23261. version = other.version;
  23262. fileOrIdentifier = other.fileOrIdentifier;
  23263. uid = other.uid;
  23264. isInstrument = other.isInstrument;
  23265. lastFileModTime = other.lastFileModTime;
  23266. numInputChannels = other.numInputChannels;
  23267. numOutputChannels = other.numOutputChannels;
  23268. return *this;
  23269. }
  23270. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23271. {
  23272. return fileOrIdentifier == other.fileOrIdentifier
  23273. && uid == other.uid;
  23274. }
  23275. const String PluginDescription::createIdentifierString() const throw()
  23276. {
  23277. return pluginFormatName
  23278. + T("-") + name
  23279. + T("-") + String::toHexString (fileOrIdentifier.hashCode())
  23280. + T("-") + String::toHexString (uid);
  23281. }
  23282. XmlElement* PluginDescription::createXml() const
  23283. {
  23284. XmlElement* const e = new XmlElement (T("PLUGIN"));
  23285. e->setAttribute (T("name"), name);
  23286. e->setAttribute (T("format"), pluginFormatName);
  23287. e->setAttribute (T("category"), category);
  23288. e->setAttribute (T("manufacturer"), manufacturerName);
  23289. e->setAttribute (T("version"), version);
  23290. e->setAttribute (T("file"), fileOrIdentifier);
  23291. e->setAttribute (T("uid"), String::toHexString (uid));
  23292. e->setAttribute (T("isInstrument"), isInstrument);
  23293. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  23294. e->setAttribute (T("numInputs"), numInputChannels);
  23295. e->setAttribute (T("numOutputs"), numOutputChannels);
  23296. return e;
  23297. }
  23298. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23299. {
  23300. if (xml.hasTagName (T("PLUGIN")))
  23301. {
  23302. name = xml.getStringAttribute (T("name"));
  23303. pluginFormatName = xml.getStringAttribute (T("format"));
  23304. category = xml.getStringAttribute (T("category"));
  23305. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  23306. version = xml.getStringAttribute (T("version"));
  23307. fileOrIdentifier = xml.getStringAttribute (T("file"));
  23308. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  23309. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  23310. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  23311. numInputChannels = xml.getIntAttribute (T("numInputs"));
  23312. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  23313. return true;
  23314. }
  23315. return false;
  23316. }
  23317. END_JUCE_NAMESPACE
  23318. /********* End of inlined file: juce_PluginDescription.cpp *********/
  23319. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23320. BEGIN_JUCE_NAMESPACE
  23321. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23322. AudioPluginFormat& formatToLookFor,
  23323. FileSearchPath directoriesToSearch,
  23324. const bool recursive,
  23325. const File& deadMansPedalFile_)
  23326. : list (listToAddTo),
  23327. format (formatToLookFor),
  23328. deadMansPedalFile (deadMansPedalFile_),
  23329. nextIndex (0),
  23330. progress (0)
  23331. {
  23332. directoriesToSearch.removeRedundantPaths();
  23333. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23334. // If any plugins have crashed recently when being loaded, move them to the
  23335. // end of the list to give the others a chance to load correctly..
  23336. const StringArray crashedPlugins (getDeadMansPedalFile());
  23337. for (int i = 0; i < crashedPlugins.size(); ++i)
  23338. {
  23339. const String f = crashedPlugins[i];
  23340. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23341. if (f == filesOrIdentifiersToScan[j])
  23342. filesOrIdentifiersToScan.move (j, -1);
  23343. }
  23344. }
  23345. PluginDirectoryScanner::~PluginDirectoryScanner()
  23346. {
  23347. }
  23348. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23349. {
  23350. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23351. }
  23352. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23353. {
  23354. String file (filesOrIdentifiersToScan [nextIndex]);
  23355. if (file.isNotEmpty())
  23356. {
  23357. if (! list.isListingUpToDate (file))
  23358. {
  23359. OwnedArray <PluginDescription> typesFound;
  23360. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23361. StringArray crashedPlugins (getDeadMansPedalFile());
  23362. crashedPlugins.removeString (file);
  23363. crashedPlugins.add (file);
  23364. setDeadMansPedalFile (crashedPlugins);
  23365. list.scanAndAddFile (file,
  23366. dontRescanIfAlreadyInList,
  23367. typesFound,
  23368. format);
  23369. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23370. crashedPlugins.removeString (file);
  23371. setDeadMansPedalFile (crashedPlugins);
  23372. if (typesFound.size() == 0)
  23373. failedFiles.add (file);
  23374. }
  23375. ++nextIndex;
  23376. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23377. }
  23378. return nextIndex < filesOrIdentifiersToScan.size();
  23379. }
  23380. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23381. {
  23382. StringArray lines;
  23383. if (deadMansPedalFile != File::nonexistent)
  23384. {
  23385. lines.addLines (deadMansPedalFile.loadFileAsString());
  23386. lines.removeEmptyStrings();
  23387. }
  23388. return lines;
  23389. }
  23390. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23391. {
  23392. if (deadMansPedalFile != File::nonexistent)
  23393. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23394. }
  23395. END_JUCE_NAMESPACE
  23396. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23397. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  23398. BEGIN_JUCE_NAMESPACE
  23399. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23400. const File& deadMansPedalFile_,
  23401. PropertiesFile* const propertiesToUse_)
  23402. : list (listToEdit),
  23403. deadMansPedalFile (deadMansPedalFile_),
  23404. propertiesToUse (propertiesToUse_)
  23405. {
  23406. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23407. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23408. optionsButton->addButtonListener (this);
  23409. optionsButton->setTriggeredOnMouseDown (true);
  23410. setSize (400, 600);
  23411. list.addChangeListener (this);
  23412. }
  23413. PluginListComponent::~PluginListComponent()
  23414. {
  23415. list.removeChangeListener (this);
  23416. deleteAllChildren();
  23417. }
  23418. void PluginListComponent::resized()
  23419. {
  23420. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23421. optionsButton->changeWidthToFitText (24);
  23422. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23423. }
  23424. void PluginListComponent::changeListenerCallback (void*)
  23425. {
  23426. listBox->updateContent();
  23427. listBox->repaint();
  23428. }
  23429. int PluginListComponent::getNumRows()
  23430. {
  23431. return list.getNumTypes();
  23432. }
  23433. void PluginListComponent::paintListBoxItem (int row,
  23434. Graphics& g,
  23435. int width, int height,
  23436. bool rowIsSelected)
  23437. {
  23438. if (rowIsSelected)
  23439. g.fillAll (findColour (TextEditor::highlightColourId));
  23440. const PluginDescription* const pd = list.getType (row);
  23441. if (pd != 0)
  23442. {
  23443. GlyphArrangement ga;
  23444. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23445. g.setColour (Colours::black);
  23446. ga.draw (g);
  23447. float x, y, r, b;
  23448. ga.getBoundingBox (0, -1, x, y, r, b, false);
  23449. String desc;
  23450. desc << pd->pluginFormatName
  23451. << (pd->isInstrument ? " instrument" : " effect")
  23452. << " - "
  23453. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23454. << " / "
  23455. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23456. if (pd->manufacturerName.isNotEmpty())
  23457. desc << " - " << pd->manufacturerName;
  23458. if (pd->version.isNotEmpty())
  23459. desc << " - " << pd->version;
  23460. if (pd->category.isNotEmpty())
  23461. desc << " - category: '" << pd->category << '\'';
  23462. g.setColour (Colours::grey);
  23463. ga.clear();
  23464. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  23465. ga.draw (g);
  23466. }
  23467. }
  23468. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23469. {
  23470. list.removeType (lastRowSelected);
  23471. }
  23472. void PluginListComponent::buttonClicked (Button* b)
  23473. {
  23474. if (optionsButton == b)
  23475. {
  23476. PopupMenu menu;
  23477. menu.addItem (1, TRANS("Clear list"));
  23478. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23479. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23480. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23481. menu.addSeparator();
  23482. menu.addItem (2, TRANS("Sort alphabetically"));
  23483. menu.addItem (3, TRANS("Sort by category"));
  23484. menu.addItem (4, TRANS("Sort by manufacturer"));
  23485. menu.addSeparator();
  23486. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23487. {
  23488. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23489. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23490. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23491. }
  23492. const int r = menu.showAt (optionsButton);
  23493. if (r == 1)
  23494. {
  23495. list.clear();
  23496. }
  23497. else if (r == 2)
  23498. {
  23499. list.sort (KnownPluginList::sortAlphabetically);
  23500. }
  23501. else if (r == 3)
  23502. {
  23503. list.sort (KnownPluginList::sortByCategory);
  23504. }
  23505. else if (r == 4)
  23506. {
  23507. list.sort (KnownPluginList::sortByManufacturer);
  23508. }
  23509. else if (r == 5)
  23510. {
  23511. const SparseSet <int> selected (listBox->getSelectedRows());
  23512. for (int i = list.getNumTypes(); --i >= 0;)
  23513. if (selected.contains (i))
  23514. list.removeType (i);
  23515. }
  23516. else if (r == 6)
  23517. {
  23518. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  23519. if (desc != 0)
  23520. {
  23521. if (File (desc->fileOrIdentifier).existsAsFile())
  23522. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  23523. }
  23524. }
  23525. else if (r == 7)
  23526. {
  23527. for (int i = list.getNumTypes(); --i >= 0;)
  23528. {
  23529. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  23530. {
  23531. list.removeType (i);
  23532. }
  23533. }
  23534. }
  23535. else if (r != 0)
  23536. {
  23537. typeToScan = r - 10;
  23538. startTimer (1);
  23539. }
  23540. }
  23541. }
  23542. void PluginListComponent::timerCallback()
  23543. {
  23544. stopTimer();
  23545. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  23546. }
  23547. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  23548. {
  23549. return true;
  23550. }
  23551. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  23552. {
  23553. OwnedArray <PluginDescription> typesFound;
  23554. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  23555. }
  23556. void PluginListComponent::scanFor (AudioPluginFormat* format)
  23557. {
  23558. if (format == 0)
  23559. return;
  23560. FileSearchPath path (format->getDefaultLocationsToSearch());
  23561. if (propertiesToUse != 0)
  23562. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23563. {
  23564. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  23565. FileSearchPathListComponent pathList;
  23566. pathList.setSize (500, 300);
  23567. pathList.setPath (path);
  23568. aw.addCustomComponent (&pathList);
  23569. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  23570. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23571. if (aw.runModalLoop() == 0)
  23572. return;
  23573. path = pathList.getPath();
  23574. }
  23575. if (propertiesToUse != 0)
  23576. {
  23577. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23578. propertiesToUse->saveIfNeeded();
  23579. }
  23580. double progress = 0.0;
  23581. AlertWindow aw (TRANS("Scanning for plugins..."),
  23582. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  23583. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23584. aw.addProgressBarComponent (progress);
  23585. aw.enterModalState();
  23586. MessageManager::getInstance()->runDispatchLoopUntil (300);
  23587. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  23588. for (;;)
  23589. {
  23590. aw.setMessage (TRANS("Testing:\n\n")
  23591. + scanner.getNextPluginFileThatWillBeScanned());
  23592. MessageManager::getInstance()->runDispatchLoopUntil (20);
  23593. if (! scanner.scanNextFile (true))
  23594. break;
  23595. if (! aw.isCurrentlyModal())
  23596. break;
  23597. progress = scanner.getProgress();
  23598. }
  23599. if (scanner.getFailedFiles().size() > 0)
  23600. {
  23601. StringArray shortNames;
  23602. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  23603. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  23604. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  23605. TRANS("Scan complete"),
  23606. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  23607. + shortNames.joinIntoString (", "));
  23608. }
  23609. }
  23610. END_JUCE_NAMESPACE
  23611. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  23612. /********* Start of inlined file: juce_AudioUnitPluginFormat.mm *********/
  23613. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  23614. #include <AudioUnit/AudioUnit.h>
  23615. #include <AudioUnit/AUCocoaUIView.h>
  23616. #include <CoreAudioKit/AUGenericView.h>
  23617. #if JUCE_SUPPORT_CARBON
  23618. #include <AudioToolbox/AudioUnitUtilities.h>
  23619. #include <AudioUnit/AudioUnitCarbonView.h>
  23620. #endif
  23621. BEGIN_JUCE_NAMESPACE
  23622. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  23623. #endif
  23624. #if JUCE_MAC
  23625. #if MACOS_10_3_OR_EARLIER
  23626. #define kAudioUnitType_Generator 'augn'
  23627. #endif
  23628. // Change this to disable logging of various activities
  23629. #ifndef AU_LOGGING
  23630. #define AU_LOGGING 1
  23631. #endif
  23632. #if AU_LOGGING
  23633. #define log(a) Logger::writeToLog(a);
  23634. #else
  23635. #define log(a)
  23636. #endif
  23637. static int insideCallback = 0;
  23638. static const String osTypeToString (OSType type) throw()
  23639. {
  23640. char s[4];
  23641. s[0] = (char) (((uint32) type) >> 24);
  23642. s[1] = (char) (((uint32) type) >> 16);
  23643. s[2] = (char) (((uint32) type) >> 8);
  23644. s[3] = (char) ((uint32) type);
  23645. return String (s, 4);
  23646. }
  23647. static OSType stringToOSType (const String& s1) throw()
  23648. {
  23649. const String s (s1 + " ");
  23650. return (((OSType) (unsigned char) s[0]) << 24)
  23651. | (((OSType) (unsigned char) s[1]) << 16)
  23652. | (((OSType) (unsigned char) s[2]) << 8)
  23653. | ((OSType) (unsigned char) s[3]);
  23654. }
  23655. static const tchar* auIdentifierPrefix = T("AudioUnit:");
  23656. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  23657. {
  23658. jassert (osTypeToString ('abcd') == T("abcd")); // agh, must have got the endianness wrong..
  23659. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  23660. String s (auIdentifierPrefix);
  23661. if (desc.componentType == kAudioUnitType_MusicDevice)
  23662. s << "Synths/";
  23663. else if (desc.componentType == kAudioUnitType_MusicEffect
  23664. || desc.componentType == kAudioUnitType_Effect)
  23665. s << "Effects/";
  23666. else if (desc.componentType == kAudioUnitType_Generator)
  23667. s << "Generators/";
  23668. else if (desc.componentType == kAudioUnitType_Panner)
  23669. s << "Panners/";
  23670. s << osTypeToString (desc.componentType)
  23671. << T(",")
  23672. << osTypeToString (desc.componentSubType)
  23673. << T(",")
  23674. << osTypeToString (desc.componentManufacturer);
  23675. return s;
  23676. }
  23677. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  23678. {
  23679. Handle componentNameHandle = NewHandle (sizeof (void*));
  23680. Handle componentInfoHandle = NewHandle (sizeof (void*));
  23681. if (componentNameHandle != 0 && componentInfoHandle != 0)
  23682. {
  23683. ComponentDescription desc;
  23684. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  23685. {
  23686. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  23687. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  23688. if (nameString != 0 && nameString[0] != 0)
  23689. {
  23690. const String all ((const char*) nameString + 1, nameString[0]);
  23691. DBG ("name: "+ all);
  23692. manufacturer = all.upToFirstOccurrenceOf (T(":"), false, false).trim();
  23693. name = all.fromFirstOccurrenceOf (T(":"), false, false).trim();
  23694. }
  23695. if (infoString != 0 && infoString[0] != 0)
  23696. {
  23697. const String all ((const char*) infoString + 1, infoString[0]);
  23698. DBG ("info: " + all);
  23699. }
  23700. if (name.isEmpty())
  23701. name = "<Unknown>";
  23702. }
  23703. DisposeHandle (componentNameHandle);
  23704. DisposeHandle (componentInfoHandle);
  23705. }
  23706. }
  23707. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  23708. String& name, String& version, String& manufacturer)
  23709. {
  23710. zerostruct (desc);
  23711. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  23712. {
  23713. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (T(':')),
  23714. fileOrIdentifier.lastIndexOfChar (T('/'))) + 1));
  23715. StringArray tokens;
  23716. tokens.addTokens (s, T(","), 0);
  23717. tokens.trim();
  23718. tokens.removeEmptyStrings();
  23719. if (tokens.size() == 3)
  23720. {
  23721. desc.componentType = stringToOSType (tokens[0]);
  23722. desc.componentSubType = stringToOSType (tokens[1]);
  23723. desc.componentManufacturer = stringToOSType (tokens[2]);
  23724. ComponentRecord* comp = FindNextComponent (0, &desc);
  23725. if (comp != 0)
  23726. {
  23727. getAUDetails (comp, name, manufacturer);
  23728. return true;
  23729. }
  23730. }
  23731. }
  23732. return false;
  23733. }
  23734. class AudioUnitPluginWindowCarbon;
  23735. class AudioUnitPluginWindowCocoa;
  23736. class AudioUnitPluginInstance : public AudioPluginInstance
  23737. {
  23738. public:
  23739. ~AudioUnitPluginInstance();
  23740. // AudioPluginInstance methods:
  23741. void fillInPluginDescription (PluginDescription& desc) const
  23742. {
  23743. desc.name = pluginName;
  23744. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  23745. desc.uid = ((int) componentDesc.componentType)
  23746. ^ ((int) componentDesc.componentSubType)
  23747. ^ ((int) componentDesc.componentManufacturer);
  23748. desc.lastFileModTime = 0;
  23749. desc.pluginFormatName = "AudioUnit";
  23750. desc.category = getCategory();
  23751. desc.manufacturerName = manufacturer;
  23752. desc.version = version;
  23753. desc.numInputChannels = getNumInputChannels();
  23754. desc.numOutputChannels = getNumOutputChannels();
  23755. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  23756. }
  23757. const String getName() const { return pluginName; }
  23758. bool acceptsMidi() const { return wantsMidiMessages; }
  23759. bool producesMidi() const { return false; }
  23760. // AudioProcessor methods:
  23761. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23762. void releaseResources();
  23763. void processBlock (AudioSampleBuffer& buffer,
  23764. MidiBuffer& midiMessages);
  23765. AudioProcessorEditor* createEditor();
  23766. const String getInputChannelName (const int index) const;
  23767. bool isInputChannelStereoPair (int index) const;
  23768. const String getOutputChannelName (const int index) const;
  23769. bool isOutputChannelStereoPair (int index) const;
  23770. int getNumParameters();
  23771. float getParameter (int index);
  23772. void setParameter (int index, float newValue);
  23773. const String getParameterName (int index);
  23774. const String getParameterText (int index);
  23775. bool isParameterAutomatable (int index) const;
  23776. int getNumPrograms();
  23777. int getCurrentProgram();
  23778. void setCurrentProgram (int index);
  23779. const String getProgramName (int index);
  23780. void changeProgramName (int index, const String& newName);
  23781. void getStateInformation (MemoryBlock& destData);
  23782. void getCurrentProgramStateInformation (MemoryBlock& destData);
  23783. void setStateInformation (const void* data, int sizeInBytes);
  23784. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  23785. juce_UseDebuggingNewOperator
  23786. private:
  23787. friend class AudioUnitPluginWindowCarbon;
  23788. friend class AudioUnitPluginWindowCocoa;
  23789. friend class AudioUnitPluginFormat;
  23790. ComponentDescription componentDesc;
  23791. String pluginName, manufacturer, version;
  23792. String fileOrIdentifier;
  23793. CriticalSection lock;
  23794. bool initialised, wantsMidiMessages, wasPlaying;
  23795. AudioBufferList* outputBufferList;
  23796. AudioTimeStamp timeStamp;
  23797. AudioSampleBuffer* currentBuffer;
  23798. AudioUnit audioUnit;
  23799. Array <int> parameterIds;
  23800. bool getComponentDescFromFile (const String& fileOrIdentifier);
  23801. void initialise();
  23802. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23803. const AudioTimeStamp* inTimeStamp,
  23804. UInt32 inBusNumber,
  23805. UInt32 inNumberFrames,
  23806. AudioBufferList* ioData) const;
  23807. static OSStatus renderGetInputCallback (void* inRefCon,
  23808. AudioUnitRenderActionFlags* ioActionFlags,
  23809. const AudioTimeStamp* inTimeStamp,
  23810. UInt32 inBusNumber,
  23811. UInt32 inNumberFrames,
  23812. AudioBufferList* ioData)
  23813. {
  23814. return ((AudioUnitPluginInstance*) inRefCon)
  23815. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  23816. }
  23817. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  23818. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  23819. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  23820. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23821. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23822. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  23823. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  23824. {
  23825. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  23826. }
  23827. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  23828. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  23829. Float64* outCurrentMeasureDownBeat)
  23830. {
  23831. return ((AudioUnitPluginInstance*) inHostUserData)
  23832. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  23833. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  23834. }
  23835. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23836. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23837. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  23838. {
  23839. return ((AudioUnitPluginInstance*) inHostUserData)
  23840. ->getTransportState (outIsPlaying, outTransportStateChanged,
  23841. outCurrentSampleInTimeLine, outIsCycling,
  23842. outCycleStartBeat, outCycleEndBeat);
  23843. }
  23844. void getNumChannels (int& numIns, int& numOuts)
  23845. {
  23846. numIns = 0;
  23847. numOuts = 0;
  23848. AUChannelInfo supportedChannels [128];
  23849. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  23850. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  23851. 0, supportedChannels, &supportedChannelsSize) == noErr
  23852. && supportedChannelsSize > 0)
  23853. {
  23854. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  23855. {
  23856. numIns = jmax (numIns, supportedChannels[i].inChannels);
  23857. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  23858. }
  23859. }
  23860. else
  23861. {
  23862. // (this really means the plugin will take any number of ins/outs as long
  23863. // as they are the same)
  23864. numIns = numOuts = 2;
  23865. }
  23866. }
  23867. const String getCategory() const;
  23868. AudioUnitPluginInstance (const String& fileOrIdentifier);
  23869. };
  23870. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  23871. : fileOrIdentifier (fileOrIdentifier),
  23872. initialised (false),
  23873. wantsMidiMessages (false),
  23874. audioUnit (0),
  23875. outputBufferList (0),
  23876. currentBuffer (0)
  23877. {
  23878. try
  23879. {
  23880. ++insideCallback;
  23881. log (T("Opening AU: ") + fileOrIdentifier);
  23882. if (getComponentDescFromFile (fileOrIdentifier))
  23883. {
  23884. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  23885. if (comp != 0)
  23886. {
  23887. audioUnit = (AudioUnit) OpenComponent (comp);
  23888. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  23889. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  23890. }
  23891. }
  23892. --insideCallback;
  23893. }
  23894. catch (...)
  23895. {
  23896. --insideCallback;
  23897. }
  23898. }
  23899. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  23900. {
  23901. {
  23902. const ScopedLock sl (lock);
  23903. jassert (insideCallback == 0);
  23904. if (audioUnit != 0)
  23905. {
  23906. AudioUnitUninitialize (audioUnit);
  23907. CloseComponent (audioUnit);
  23908. audioUnit = 0;
  23909. }
  23910. }
  23911. juce_free (outputBufferList);
  23912. }
  23913. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  23914. {
  23915. zerostruct (componentDesc);
  23916. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  23917. return true;
  23918. const File file (fileOrIdentifier);
  23919. if (! file.hasFileExtension (T(".component")))
  23920. return false;
  23921. const char* const utf8 = fileOrIdentifier.toUTF8();
  23922. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  23923. strlen (utf8), file.isDirectory());
  23924. if (url != 0)
  23925. {
  23926. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  23927. CFRelease (url);
  23928. if (bundleRef != 0)
  23929. {
  23930. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  23931. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  23932. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  23933. if (pluginName.isEmpty())
  23934. pluginName = file.getFileNameWithoutExtension();
  23935. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  23936. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  23937. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  23938. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  23939. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  23940. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  23941. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  23942. UseResFile (resFileId);
  23943. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  23944. {
  23945. Handle h = Get1IndResource ('thng', i);
  23946. if (h != 0)
  23947. {
  23948. HLock (h);
  23949. const uint32* const types = (const uint32*) *h;
  23950. if (types[0] == kAudioUnitType_MusicDevice
  23951. || types[0] == kAudioUnitType_MusicEffect
  23952. || types[0] == kAudioUnitType_Effect
  23953. || types[0] == kAudioUnitType_Generator
  23954. || types[0] == kAudioUnitType_Panner)
  23955. {
  23956. componentDesc.componentType = types[0];
  23957. componentDesc.componentSubType = types[1];
  23958. componentDesc.componentManufacturer = types[2];
  23959. break;
  23960. }
  23961. HUnlock (h);
  23962. ReleaseResource (h);
  23963. }
  23964. }
  23965. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  23966. CFRelease (bundleRef);
  23967. }
  23968. }
  23969. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  23970. }
  23971. void AudioUnitPluginInstance::initialise()
  23972. {
  23973. if (initialised || audioUnit == 0)
  23974. return;
  23975. log (T("Initialising AU: ") + pluginName);
  23976. parameterIds.clear();
  23977. {
  23978. UInt32 paramListSize = 0;
  23979. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23980. 0, 0, &paramListSize);
  23981. if (paramListSize > 0)
  23982. {
  23983. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  23984. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23985. 0, &parameterIds.getReference(0), &paramListSize);
  23986. }
  23987. }
  23988. {
  23989. AURenderCallbackStruct info;
  23990. zerostruct (info);
  23991. info.inputProcRefCon = this;
  23992. info.inputProc = renderGetInputCallback;
  23993. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  23994. 0, &info, sizeof (info));
  23995. }
  23996. {
  23997. HostCallbackInfo info;
  23998. zerostruct (info);
  23999. info.hostUserData = this;
  24000. info.beatAndTempoProc = getBeatAndTempoCallback;
  24001. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24002. info.transportStateProc = getTransportStateCallback;
  24003. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24004. 0, &info, sizeof (info));
  24005. }
  24006. int numIns, numOuts;
  24007. getNumChannels (numIns, numOuts);
  24008. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24009. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24010. setLatencySamples (0);
  24011. }
  24012. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24013. int samplesPerBlockExpected)
  24014. {
  24015. initialise();
  24016. if (initialised)
  24017. {
  24018. int numIns, numOuts;
  24019. getNumChannels (numIns, numOuts);
  24020. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24021. Float64 latencySecs = 0.0;
  24022. UInt32 latencySize = sizeof (latencySecs);
  24023. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24024. 0, &latencySecs, &latencySize);
  24025. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  24026. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24027. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24028. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24029. AudioStreamBasicDescription stream;
  24030. zerostruct (stream);
  24031. stream.mSampleRate = sampleRate_;
  24032. stream.mFormatID = kAudioFormatLinearPCM;
  24033. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24034. stream.mFramesPerPacket = 1;
  24035. stream.mBytesPerPacket = 4;
  24036. stream.mBytesPerFrame = 4;
  24037. stream.mBitsPerChannel = 32;
  24038. stream.mChannelsPerFrame = numIns;
  24039. OSStatus err = AudioUnitSetProperty (audioUnit,
  24040. kAudioUnitProperty_StreamFormat,
  24041. kAudioUnitScope_Input,
  24042. 0, &stream, sizeof (stream));
  24043. stream.mChannelsPerFrame = numOuts;
  24044. err = AudioUnitSetProperty (audioUnit,
  24045. kAudioUnitProperty_StreamFormat,
  24046. kAudioUnitScope_Output,
  24047. 0, &stream, sizeof (stream));
  24048. juce_free (outputBufferList);
  24049. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  24050. outputBufferList->mNumberBuffers = numOuts;
  24051. for (int i = numOuts; --i >= 0;)
  24052. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24053. zerostruct (timeStamp);
  24054. timeStamp.mSampleTime = 0;
  24055. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24056. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24057. currentBuffer = 0;
  24058. wasPlaying = false;
  24059. }
  24060. }
  24061. void AudioUnitPluginInstance::releaseResources()
  24062. {
  24063. if (initialised)
  24064. {
  24065. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24066. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24067. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24068. juce_free (outputBufferList);
  24069. outputBufferList = 0;
  24070. currentBuffer = 0;
  24071. }
  24072. }
  24073. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24074. const AudioTimeStamp* inTimeStamp,
  24075. UInt32 inBusNumber,
  24076. UInt32 inNumberFrames,
  24077. AudioBufferList* ioData) const
  24078. {
  24079. if (inBusNumber == 0
  24080. && currentBuffer != 0)
  24081. {
  24082. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24083. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24084. {
  24085. if (i < currentBuffer->getNumChannels())
  24086. {
  24087. memcpy (ioData->mBuffers[i].mData,
  24088. currentBuffer->getSampleData (i, 0),
  24089. sizeof (float) * inNumberFrames);
  24090. }
  24091. else
  24092. {
  24093. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24094. }
  24095. }
  24096. }
  24097. return noErr;
  24098. }
  24099. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24100. MidiBuffer& midiMessages)
  24101. {
  24102. const int numSamples = buffer.getNumSamples();
  24103. if (initialised)
  24104. {
  24105. AudioUnitRenderActionFlags flags = 0;
  24106. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24107. for (int i = getNumOutputChannels(); --i >= 0;)
  24108. {
  24109. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24110. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24111. }
  24112. currentBuffer = &buffer;
  24113. if (wantsMidiMessages)
  24114. {
  24115. const uint8* midiEventData;
  24116. int midiEventSize, midiEventPosition;
  24117. MidiBuffer::Iterator i (midiMessages);
  24118. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24119. {
  24120. if (midiEventSize <= 3)
  24121. MusicDeviceMIDIEvent (audioUnit,
  24122. midiEventData[0], midiEventData[1], midiEventData[2],
  24123. midiEventPosition);
  24124. else
  24125. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24126. }
  24127. midiMessages.clear();
  24128. }
  24129. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24130. 0, numSamples, outputBufferList);
  24131. timeStamp.mSampleTime += numSamples;
  24132. }
  24133. else
  24134. {
  24135. // Not initialised, so just bypass..
  24136. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24137. buffer.clear (i, 0, buffer.getNumSamples());
  24138. }
  24139. }
  24140. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24141. {
  24142. AudioPlayHead* const ph = getPlayHead();
  24143. AudioPlayHead::CurrentPositionInfo result;
  24144. if (ph != 0 && ph->getCurrentPosition (result))
  24145. {
  24146. if (outCurrentBeat != 0)
  24147. *outCurrentBeat = result.ppqPosition;
  24148. if (outCurrentTempo != 0)
  24149. *outCurrentTempo = result.bpm;
  24150. }
  24151. else
  24152. {
  24153. if (outCurrentBeat != 0)
  24154. *outCurrentBeat = 0;
  24155. if (outCurrentTempo != 0)
  24156. *outCurrentTempo = 120.0;
  24157. }
  24158. return noErr;
  24159. }
  24160. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24161. Float32* outTimeSig_Numerator,
  24162. UInt32* outTimeSig_Denominator,
  24163. Float64* outCurrentMeasureDownBeat) const
  24164. {
  24165. AudioPlayHead* const ph = getPlayHead();
  24166. AudioPlayHead::CurrentPositionInfo result;
  24167. if (ph != 0 && ph->getCurrentPosition (result))
  24168. {
  24169. if (outTimeSig_Numerator != 0)
  24170. *outTimeSig_Numerator = result.timeSigNumerator;
  24171. if (outTimeSig_Denominator != 0)
  24172. *outTimeSig_Denominator = result.timeSigDenominator;
  24173. if (outDeltaSampleOffsetToNextBeat != 0)
  24174. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24175. if (outCurrentMeasureDownBeat != 0)
  24176. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24177. }
  24178. else
  24179. {
  24180. if (outDeltaSampleOffsetToNextBeat != 0)
  24181. *outDeltaSampleOffsetToNextBeat = 0;
  24182. if (outTimeSig_Numerator != 0)
  24183. *outTimeSig_Numerator = 4;
  24184. if (outTimeSig_Denominator != 0)
  24185. *outTimeSig_Denominator = 4;
  24186. if (outCurrentMeasureDownBeat != 0)
  24187. *outCurrentMeasureDownBeat = 0;
  24188. }
  24189. return noErr;
  24190. }
  24191. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24192. Boolean* outTransportStateChanged,
  24193. Float64* outCurrentSampleInTimeLine,
  24194. Boolean* outIsCycling,
  24195. Float64* outCycleStartBeat,
  24196. Float64* outCycleEndBeat)
  24197. {
  24198. AudioPlayHead* const ph = getPlayHead();
  24199. AudioPlayHead::CurrentPositionInfo result;
  24200. if (ph != 0 && ph->getCurrentPosition (result))
  24201. {
  24202. if (outIsPlaying != 0)
  24203. *outIsPlaying = result.isPlaying;
  24204. if (outTransportStateChanged != 0)
  24205. {
  24206. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24207. wasPlaying = result.isPlaying;
  24208. }
  24209. if (outCurrentSampleInTimeLine != 0)
  24210. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  24211. if (outIsCycling != 0)
  24212. *outIsCycling = false;
  24213. if (outCycleStartBeat != 0)
  24214. *outCycleStartBeat = 0;
  24215. if (outCycleEndBeat != 0)
  24216. *outCycleEndBeat = 0;
  24217. }
  24218. else
  24219. {
  24220. if (outIsPlaying != 0)
  24221. *outIsPlaying = false;
  24222. if (outTransportStateChanged != 0)
  24223. *outTransportStateChanged = false;
  24224. if (outCurrentSampleInTimeLine != 0)
  24225. *outCurrentSampleInTimeLine = 0;
  24226. if (outIsCycling != 0)
  24227. *outIsCycling = false;
  24228. if (outCycleStartBeat != 0)
  24229. *outCycleStartBeat = 0;
  24230. if (outCycleEndBeat != 0)
  24231. *outCycleEndBeat = 0;
  24232. }
  24233. return noErr;
  24234. }
  24235. static VoidArray activeWindows;
  24236. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24237. {
  24238. public:
  24239. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24240. : AudioProcessorEditor (&plugin_),
  24241. plugin (plugin_),
  24242. wrapper (0)
  24243. {
  24244. addAndMakeVisible (wrapper = new NSViewComponent());
  24245. activeWindows.add (this);
  24246. setOpaque (true);
  24247. setVisible (true);
  24248. setSize (100, 100);
  24249. createView (createGenericViewIfNeeded);
  24250. }
  24251. ~AudioUnitPluginWindowCocoa()
  24252. {
  24253. const bool wasValid = isValid();
  24254. wrapper->setView (0);
  24255. activeWindows.removeValue (this);
  24256. if (wasValid)
  24257. plugin.editorBeingDeleted (this);
  24258. delete wrapper;
  24259. }
  24260. bool isValid() const { return wrapper->getView() != 0; }
  24261. void paint (Graphics& g)
  24262. {
  24263. g.fillAll (Colours::white);
  24264. }
  24265. void resized()
  24266. {
  24267. wrapper->setSize (getWidth(), getHeight());
  24268. }
  24269. private:
  24270. AudioUnitPluginInstance& plugin;
  24271. NSViewComponent* wrapper;
  24272. bool createView (const bool createGenericViewIfNeeded)
  24273. {
  24274. NSView* pluginView = 0;
  24275. UInt32 dataSize = 0;
  24276. Boolean isWritable = false;
  24277. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24278. 0, &dataSize, &isWritable) == noErr
  24279. && dataSize != 0
  24280. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24281. 0, &dataSize, &isWritable) == noErr)
  24282. {
  24283. AudioUnitCocoaViewInfo* info = (AudioUnitCocoaViewInfo*) juce_calloc (dataSize);
  24284. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24285. 0, info, &dataSize) == noErr)
  24286. {
  24287. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24288. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24289. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24290. Class viewClass = [viewBundle classNamed: viewClassName];
  24291. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24292. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24293. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24294. {
  24295. id factory = [[[viewClass alloc] init] autorelease];
  24296. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24297. withSize: NSMakeSize (getWidth(), getHeight())];
  24298. }
  24299. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24300. {
  24301. CFRelease (info->mCocoaAUViewClass[i]);
  24302. CFRelease (info->mCocoaAUViewBundleLocation);
  24303. }
  24304. }
  24305. juce_free (info);
  24306. }
  24307. if (createGenericViewIfNeeded && (pluginView == 0))
  24308. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24309. wrapper->setView (pluginView);
  24310. if (pluginView != 0)
  24311. setSize ([pluginView frame].size.width,
  24312. [pluginView frame].size.height);
  24313. return pluginView != 0;
  24314. }
  24315. };
  24316. #if JUCE_SUPPORT_CARBON
  24317. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24318. {
  24319. public:
  24320. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24321. : AudioProcessorEditor (&plugin_),
  24322. plugin (plugin_),
  24323. viewComponent (0)
  24324. {
  24325. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24326. activeWindows.add (this);
  24327. setOpaque (true);
  24328. setVisible (true);
  24329. setSize (400, 300);
  24330. ComponentDescription viewList [16];
  24331. UInt32 viewListSize = sizeof (viewList);
  24332. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24333. 0, &viewList, &viewListSize);
  24334. componentRecord = FindNextComponent (0, &viewList[0]);
  24335. }
  24336. ~AudioUnitPluginWindowCarbon()
  24337. {
  24338. deleteAndZero (innerWrapper);
  24339. activeWindows.removeValue (this);
  24340. if (isValid())
  24341. plugin.editorBeingDeleted (this);
  24342. }
  24343. bool isValid() const throw() { return componentRecord != 0; }
  24344. void paint (Graphics& g)
  24345. {
  24346. g.fillAll (Colours::black);
  24347. }
  24348. void resized()
  24349. {
  24350. innerWrapper->setSize (getWidth(), getHeight());
  24351. }
  24352. bool keyStateChanged (const bool)
  24353. {
  24354. return false;
  24355. }
  24356. bool keyPressed (const KeyPress&)
  24357. {
  24358. return false;
  24359. }
  24360. void broughtToFront()
  24361. {
  24362. activeWindows.removeValue (this);
  24363. activeWindows.add (this);
  24364. }
  24365. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24366. AudioUnitCarbonView getViewComponent()
  24367. {
  24368. if (viewComponent == 0 && componentRecord != 0)
  24369. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24370. return viewComponent;
  24371. }
  24372. void closeViewComponent()
  24373. {
  24374. if (viewComponent != 0)
  24375. {
  24376. CloseComponent (viewComponent);
  24377. viewComponent = 0;
  24378. }
  24379. }
  24380. juce_UseDebuggingNewOperator
  24381. private:
  24382. AudioUnitPluginInstance& plugin;
  24383. ComponentRecord* componentRecord;
  24384. AudioUnitCarbonView viewComponent;
  24385. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24386. {
  24387. public:
  24388. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24389. : owner (owner_)
  24390. {
  24391. }
  24392. ~InnerWrapperComponent()
  24393. {
  24394. deleteWindow();
  24395. }
  24396. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24397. {
  24398. log (T("Opening AU GUI: ") + owner->plugin.getName());
  24399. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24400. if (viewComponent == 0)
  24401. return 0;
  24402. Float32Point pos = { 0, 0 };
  24403. Float32Point size = { 250, 200 };
  24404. HIViewRef pluginView = 0;
  24405. AudioUnitCarbonViewCreate (viewComponent,
  24406. owner->getAudioUnit(),
  24407. windowRef,
  24408. rootView,
  24409. &pos,
  24410. &size,
  24411. (ControlRef*) &pluginView);
  24412. return pluginView;
  24413. }
  24414. void removeView (HIViewRef)
  24415. {
  24416. log (T("Closing AU GUI: ") + owner->plugin.getName());
  24417. owner->closeViewComponent();
  24418. }
  24419. private:
  24420. AudioUnitPluginWindowCarbon* const owner;
  24421. };
  24422. friend class InnerWrapperComponent;
  24423. InnerWrapperComponent* innerWrapper;
  24424. };
  24425. #endif
  24426. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24427. {
  24428. AudioProcessorEditor* w = new AudioUnitPluginWindowCocoa (*this, false);
  24429. if (! ((AudioUnitPluginWindowCocoa*) w)->isValid())
  24430. deleteAndZero (w);
  24431. #if JUCE_SUPPORT_CARBON
  24432. if (w == 0)
  24433. {
  24434. w = new AudioUnitPluginWindowCarbon (*this);
  24435. if (! ((AudioUnitPluginWindowCarbon*) w)->isValid())
  24436. deleteAndZero (w);
  24437. }
  24438. #endif
  24439. if (w == 0)
  24440. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24441. return w;
  24442. }
  24443. const String AudioUnitPluginInstance::getCategory() const
  24444. {
  24445. const char* result = 0;
  24446. switch (componentDesc.componentType)
  24447. {
  24448. case kAudioUnitType_Effect:
  24449. case kAudioUnitType_MusicEffect:
  24450. result = "Effect";
  24451. break;
  24452. case kAudioUnitType_MusicDevice:
  24453. result = "Synth";
  24454. break;
  24455. case kAudioUnitType_Generator:
  24456. result = "Generator";
  24457. break;
  24458. case kAudioUnitType_Panner:
  24459. result = "Panner";
  24460. break;
  24461. default:
  24462. break;
  24463. }
  24464. return result;
  24465. }
  24466. int AudioUnitPluginInstance::getNumParameters()
  24467. {
  24468. return parameterIds.size();
  24469. }
  24470. float AudioUnitPluginInstance::getParameter (int index)
  24471. {
  24472. const ScopedLock sl (lock);
  24473. Float32 value = 0.0f;
  24474. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24475. {
  24476. AudioUnitGetParameter (audioUnit,
  24477. (UInt32) parameterIds.getUnchecked (index),
  24478. kAudioUnitScope_Global, 0,
  24479. &value);
  24480. }
  24481. return value;
  24482. }
  24483. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24484. {
  24485. const ScopedLock sl (lock);
  24486. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24487. {
  24488. AudioUnitSetParameter (audioUnit,
  24489. (UInt32) parameterIds.getUnchecked (index),
  24490. kAudioUnitScope_Global, 0,
  24491. newValue, 0);
  24492. }
  24493. }
  24494. const String AudioUnitPluginInstance::getParameterName (int index)
  24495. {
  24496. AudioUnitParameterInfo info;
  24497. zerostruct (info);
  24498. UInt32 sz = sizeof (info);
  24499. String name;
  24500. if (AudioUnitGetProperty (audioUnit,
  24501. kAudioUnitProperty_ParameterInfo,
  24502. kAudioUnitScope_Global,
  24503. parameterIds [index], &info, &sz) == noErr)
  24504. {
  24505. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  24506. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  24507. else
  24508. name = String (info.name, sizeof (info.name));
  24509. }
  24510. return name;
  24511. }
  24512. const String AudioUnitPluginInstance::getParameterText (int index)
  24513. {
  24514. return String (getParameter (index));
  24515. }
  24516. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  24517. {
  24518. AudioUnitParameterInfo info;
  24519. UInt32 sz = sizeof (info);
  24520. if (AudioUnitGetProperty (audioUnit,
  24521. kAudioUnitProperty_ParameterInfo,
  24522. kAudioUnitScope_Global,
  24523. parameterIds [index], &info, &sz) == noErr)
  24524. {
  24525. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  24526. }
  24527. return true;
  24528. }
  24529. int AudioUnitPluginInstance::getNumPrograms()
  24530. {
  24531. CFArrayRef presets;
  24532. UInt32 sz = sizeof (CFArrayRef);
  24533. int num = 0;
  24534. if (AudioUnitGetProperty (audioUnit,
  24535. kAudioUnitProperty_FactoryPresets,
  24536. kAudioUnitScope_Global,
  24537. 0, &presets, &sz) == noErr)
  24538. {
  24539. num = (int) CFArrayGetCount (presets);
  24540. CFRelease (presets);
  24541. }
  24542. return num;
  24543. }
  24544. int AudioUnitPluginInstance::getCurrentProgram()
  24545. {
  24546. AUPreset current;
  24547. current.presetNumber = 0;
  24548. UInt32 sz = sizeof (AUPreset);
  24549. AudioUnitGetProperty (audioUnit,
  24550. kAudioUnitProperty_FactoryPresets,
  24551. kAudioUnitScope_Global,
  24552. 0, &current, &sz);
  24553. return current.presetNumber;
  24554. }
  24555. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  24556. {
  24557. AUPreset current;
  24558. current.presetNumber = newIndex;
  24559. current.presetName = 0;
  24560. AudioUnitSetProperty (audioUnit,
  24561. kAudioUnitProperty_FactoryPresets,
  24562. kAudioUnitScope_Global,
  24563. 0, &current, sizeof (AUPreset));
  24564. }
  24565. const String AudioUnitPluginInstance::getProgramName (int index)
  24566. {
  24567. String s;
  24568. CFArrayRef presets;
  24569. UInt32 sz = sizeof (CFArrayRef);
  24570. if (AudioUnitGetProperty (audioUnit,
  24571. kAudioUnitProperty_FactoryPresets,
  24572. kAudioUnitScope_Global,
  24573. 0, &presets, &sz) == noErr)
  24574. {
  24575. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  24576. {
  24577. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  24578. if (p != 0 && p->presetNumber == index)
  24579. {
  24580. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  24581. break;
  24582. }
  24583. }
  24584. CFRelease (presets);
  24585. }
  24586. return s;
  24587. }
  24588. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  24589. {
  24590. jassertfalse // xxx not implemented!
  24591. }
  24592. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  24593. {
  24594. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  24595. return T("Input ") + String (index + 1);
  24596. return String::empty;
  24597. }
  24598. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  24599. {
  24600. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  24601. return false;
  24602. return true;
  24603. }
  24604. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  24605. {
  24606. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  24607. return T("Output ") + String (index + 1);
  24608. return String::empty;
  24609. }
  24610. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  24611. {
  24612. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  24613. return false;
  24614. return true;
  24615. }
  24616. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  24617. {
  24618. getCurrentProgramStateInformation (destData);
  24619. }
  24620. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24621. {
  24622. CFPropertyListRef propertyList = 0;
  24623. UInt32 sz = sizeof (CFPropertyListRef);
  24624. if (AudioUnitGetProperty (audioUnit,
  24625. kAudioUnitProperty_ClassInfo,
  24626. kAudioUnitScope_Global,
  24627. 0, &propertyList, &sz) == noErr)
  24628. {
  24629. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  24630. CFWriteStreamOpen (stream);
  24631. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  24632. CFWriteStreamClose (stream);
  24633. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  24634. destData.setSize (bytesWritten);
  24635. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  24636. CFRelease (data);
  24637. CFRelease (stream);
  24638. CFRelease (propertyList);
  24639. }
  24640. }
  24641. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24642. {
  24643. setCurrentProgramStateInformation (data, sizeInBytes);
  24644. }
  24645. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24646. {
  24647. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  24648. (const UInt8*) data,
  24649. sizeInBytes,
  24650. kCFAllocatorNull);
  24651. CFReadStreamOpen (stream);
  24652. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  24653. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  24654. stream,
  24655. 0,
  24656. kCFPropertyListImmutable,
  24657. &format,
  24658. 0);
  24659. CFRelease (stream);
  24660. if (propertyList != 0)
  24661. AudioUnitSetProperty (audioUnit,
  24662. kAudioUnitProperty_ClassInfo,
  24663. kAudioUnitScope_Global,
  24664. 0, &propertyList, sizeof (propertyList));
  24665. }
  24666. AudioUnitPluginFormat::AudioUnitPluginFormat()
  24667. {
  24668. }
  24669. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  24670. {
  24671. }
  24672. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24673. const String& fileOrIdentifier)
  24674. {
  24675. if (! fileMightContainThisPluginType (fileOrIdentifier))
  24676. return;
  24677. PluginDescription desc;
  24678. desc.fileOrIdentifier = fileOrIdentifier;
  24679. desc.uid = 0;
  24680. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  24681. if (instance == 0)
  24682. return;
  24683. try
  24684. {
  24685. instance->fillInPluginDescription (desc);
  24686. results.add (new PluginDescription (desc));
  24687. }
  24688. catch (...)
  24689. {
  24690. // crashed while loading...
  24691. }
  24692. deleteAndZero (instance);
  24693. }
  24694. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24695. {
  24696. AudioUnitPluginInstance* result = 0;
  24697. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  24698. {
  24699. result = new AudioUnitPluginInstance (desc.fileOrIdentifier);
  24700. if (result->audioUnit != 0)
  24701. {
  24702. result->initialise();
  24703. }
  24704. else
  24705. {
  24706. deleteAndZero (result);
  24707. }
  24708. }
  24709. return result;
  24710. }
  24711. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  24712. const bool /*recursive*/)
  24713. {
  24714. StringArray result;
  24715. ComponentRecord* comp = 0;
  24716. ComponentDescription desc;
  24717. zerostruct (desc);
  24718. for (;;)
  24719. {
  24720. zerostruct (desc);
  24721. comp = FindNextComponent (comp, &desc);
  24722. if (comp == 0)
  24723. break;
  24724. GetComponentInfo (comp, &desc, 0, 0, 0);
  24725. if (desc.componentType == kAudioUnitType_MusicDevice
  24726. || desc.componentType == kAudioUnitType_MusicEffect
  24727. || desc.componentType == kAudioUnitType_Effect
  24728. || desc.componentType == kAudioUnitType_Generator
  24729. || desc.componentType == kAudioUnitType_Panner)
  24730. {
  24731. const String s (createAUPluginIdentifier (desc));
  24732. DBG (s);
  24733. result.add (s);
  24734. }
  24735. }
  24736. return result;
  24737. }
  24738. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  24739. {
  24740. ComponentDescription desc;
  24741. String name, version, manufacturer;
  24742. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  24743. return FindNextComponent (0, &desc) != 0;
  24744. const File f (fileOrIdentifier);
  24745. return f.hasFileExtension (T(".component"))
  24746. && f.isDirectory();
  24747. }
  24748. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  24749. {
  24750. ComponentDescription desc;
  24751. String name, version, manufacturer;
  24752. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  24753. if (name.isEmpty())
  24754. name = fileOrIdentifier;
  24755. return name;
  24756. }
  24757. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  24758. {
  24759. return File (desc.fileOrIdentifier).exists();
  24760. }
  24761. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  24762. {
  24763. return FileSearchPath ("/(Default AudioUnit locations)");
  24764. }
  24765. #endif
  24766. END_JUCE_NAMESPACE
  24767. #undef log
  24768. #endif
  24769. /********* End of inlined file: juce_AudioUnitPluginFormat.mm *********/
  24770. /********* Start of inlined file: juce_VSTPluginFormat.mm *********/
  24771. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  24772. #define JUCE_MAC_VST_INCLUDED 1
  24773. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  24774. #if JUCE_PLUGINHOST_VST
  24775. #if (defined (_WIN32) || defined (_WIN64))
  24776. #undef _WIN32_WINNT
  24777. #define _WIN32_WINNT 0x500
  24778. #undef STRICT
  24779. #define STRICT
  24780. #include <windows.h>
  24781. #include <float.h>
  24782. #pragma warning (disable : 4312 4355)
  24783. #elif defined (LINUX) || defined (__linux__)
  24784. #include <float.h>
  24785. #include <sys/time.h>
  24786. #include <X11/Xlib.h>
  24787. #include <X11/Xutil.h>
  24788. #include <X11/Xatom.h>
  24789. #undef Font
  24790. #undef KeyPress
  24791. #undef Drawable
  24792. #undef Time
  24793. #else
  24794. #ifndef JUCE_MAC_VST_INCLUDED
  24795. // On the mac, this file needs to be compiled indirectly, by using
  24796. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  24797. #error
  24798. #endif
  24799. #include <Cocoa/Cocoa.h>
  24800. #include <Carbon/Carbon.h>
  24801. #endif
  24802. #if ! (JUCE_MAC && JUCE_64BIT)
  24803. BEGIN_JUCE_NAMESPACE
  24804. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24805. #endif
  24806. #undef PRAGMA_ALIGN_SUPPORTED
  24807. #define VST_FORCE_DEPRECATED 0
  24808. #ifdef _MSC_VER
  24809. #pragma warning (push)
  24810. #pragma warning (disable: 4996)
  24811. #endif
  24812. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  24813. your include path if you want to add VST support.
  24814. If you're not interested in VSTs, you can disable them by changing the
  24815. JUCE_PLUGINHOST_VST flag in juce_Config.h
  24816. */
  24817. #include "pluginterfaces/vst2.x/aeffectx.h"
  24818. #ifdef _MSC_VER
  24819. #pragma warning (pop)
  24820. #endif
  24821. #if JUCE_LINUX
  24822. #define Font JUCE_NAMESPACE::Font
  24823. #define KeyPress JUCE_NAMESPACE::KeyPress
  24824. #define Drawable JUCE_NAMESPACE::Drawable
  24825. #define Time JUCE_NAMESPACE::Time
  24826. #endif
  24827. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  24828. #ifdef __aeffect__
  24829. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24830. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24831. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  24832. events to the list.
  24833. This is used by both the VST hosting code and the plugin wrapper.
  24834. */
  24835. class VSTMidiEventList
  24836. {
  24837. public:
  24838. VSTMidiEventList()
  24839. : events (0), numEventsUsed (0), numEventsAllocated (0)
  24840. {
  24841. }
  24842. ~VSTMidiEventList()
  24843. {
  24844. freeEvents();
  24845. }
  24846. void clear()
  24847. {
  24848. numEventsUsed = 0;
  24849. if (events != 0)
  24850. events->numEvents = 0;
  24851. }
  24852. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  24853. {
  24854. ensureSize (numEventsUsed + 1);
  24855. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  24856. events->numEvents = ++numEventsUsed;
  24857. if (numBytes <= 4)
  24858. {
  24859. if (e->type == kVstSysExType)
  24860. {
  24861. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24862. e->type = kVstMidiType;
  24863. e->byteSize = sizeof (VstMidiEvent);
  24864. e->noteLength = 0;
  24865. e->noteOffset = 0;
  24866. e->detune = 0;
  24867. e->noteOffVelocity = 0;
  24868. }
  24869. e->deltaFrames = frameOffset;
  24870. memcpy (e->midiData, midiData, numBytes);
  24871. }
  24872. else
  24873. {
  24874. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  24875. if (se->type == kVstSysExType)
  24876. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  24877. else
  24878. se->sysexDump = (char*) juce_malloc (numBytes);
  24879. memcpy (se->sysexDump, midiData, numBytes);
  24880. se->type = kVstSysExType;
  24881. se->byteSize = sizeof (VstMidiSysexEvent);
  24882. se->deltaFrames = frameOffset;
  24883. se->flags = 0;
  24884. se->dumpBytes = numBytes;
  24885. se->resvd1 = 0;
  24886. se->resvd2 = 0;
  24887. }
  24888. }
  24889. // Handy method to pull the events out of an event buffer supplied by the host
  24890. // or plugin.
  24891. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  24892. {
  24893. for (int i = 0; i < events->numEvents; ++i)
  24894. {
  24895. const VstEvent* const e = events->events[i];
  24896. if (e != 0)
  24897. {
  24898. if (e->type == kVstMidiType)
  24899. {
  24900. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  24901. 4, e->deltaFrames);
  24902. }
  24903. else if (e->type == kVstSysExType)
  24904. {
  24905. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  24906. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  24907. e->deltaFrames);
  24908. }
  24909. }
  24910. }
  24911. }
  24912. void ensureSize (int numEventsNeeded)
  24913. {
  24914. if (numEventsNeeded > numEventsAllocated)
  24915. {
  24916. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  24917. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  24918. if (events == 0)
  24919. events = (VstEvents*) juce_calloc (size);
  24920. else
  24921. events = (VstEvents*) juce_realloc (events, size);
  24922. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  24923. {
  24924. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  24925. (int) sizeof (VstMidiSysexEvent)));
  24926. e->type = kVstMidiType;
  24927. e->byteSize = sizeof (VstMidiEvent);
  24928. events->events[i] = (VstEvent*) e;
  24929. }
  24930. numEventsAllocated = numEventsNeeded;
  24931. }
  24932. }
  24933. void freeEvents()
  24934. {
  24935. if (events != 0)
  24936. {
  24937. for (int i = numEventsAllocated; --i >= 0;)
  24938. {
  24939. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  24940. if (e->type == kVstSysExType)
  24941. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24942. juce_free (e);
  24943. }
  24944. juce_free (events);
  24945. events = 0;
  24946. numEventsUsed = 0;
  24947. numEventsAllocated = 0;
  24948. }
  24949. }
  24950. VstEvents* events;
  24951. private:
  24952. int numEventsUsed, numEventsAllocated;
  24953. };
  24954. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24955. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24956. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  24957. #if ! JUCE_WIN32
  24958. #define _fpreset()
  24959. #define _clearfp()
  24960. #endif
  24961. extern void juce_callAnyTimersSynchronously();
  24962. const int fxbVersionNum = 1;
  24963. struct fxProgram
  24964. {
  24965. long chunkMagic; // 'CcnK'
  24966. long byteSize; // of this chunk, excl. magic + byteSize
  24967. long fxMagic; // 'FxCk'
  24968. long version;
  24969. long fxID; // fx unique id
  24970. long fxVersion;
  24971. long numParams;
  24972. char prgName[28];
  24973. float params[1]; // variable no. of parameters
  24974. };
  24975. struct fxSet
  24976. {
  24977. long chunkMagic; // 'CcnK'
  24978. long byteSize; // of this chunk, excl. magic + byteSize
  24979. long fxMagic; // 'FxBk'
  24980. long version;
  24981. long fxID; // fx unique id
  24982. long fxVersion;
  24983. long numPrograms;
  24984. char future[128];
  24985. fxProgram programs[1]; // variable no. of programs
  24986. };
  24987. struct fxChunkSet
  24988. {
  24989. long chunkMagic; // 'CcnK'
  24990. long byteSize; // of this chunk, excl. magic + byteSize
  24991. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24992. long version;
  24993. long fxID; // fx unique id
  24994. long fxVersion;
  24995. long numPrograms;
  24996. char future[128];
  24997. long chunkSize;
  24998. char chunk[8]; // variable
  24999. };
  25000. struct fxProgramSet
  25001. {
  25002. long chunkMagic; // 'CcnK'
  25003. long byteSize; // of this chunk, excl. magic + byteSize
  25004. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25005. long version;
  25006. long fxID; // fx unique id
  25007. long fxVersion;
  25008. long numPrograms;
  25009. char name[28];
  25010. long chunkSize;
  25011. char chunk[8]; // variable
  25012. };
  25013. #ifdef JUCE_LITTLE_ENDIAN
  25014. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  25015. static float vst_swapFloat (const float x) throw()
  25016. {
  25017. union { uint32 asInt; float asFloat; } n;
  25018. n.asFloat = x;
  25019. n.asInt = swapByteOrder (n.asInt);
  25020. return n.asFloat;
  25021. }
  25022. #else
  25023. #define vst_swap(x) (x)
  25024. #define vst_swapFloat(x) (x)
  25025. #endif
  25026. typedef AEffect* (*MainCall) (audioMasterCallback);
  25027. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25028. static int shellUIDToCreate = 0;
  25029. static int insideVSTCallback = 0;
  25030. class VSTPluginWindow;
  25031. // Change this to disable logging of various VST activities
  25032. #ifndef VST_LOGGING
  25033. #define VST_LOGGING 1
  25034. #endif
  25035. #if VST_LOGGING
  25036. #define log(a) Logger::writeToLog(a);
  25037. #else
  25038. #define log(a)
  25039. #endif
  25040. #if JUCE_MAC && JUCE_PPC
  25041. static void* NewCFMFromMachO (void* const machofp) throw()
  25042. {
  25043. void* result = juce_malloc (8);
  25044. ((void**) result)[0] = machofp;
  25045. ((void**) result)[1] = result;
  25046. return result;
  25047. }
  25048. #endif
  25049. #if JUCE_LINUX
  25050. extern Display* display;
  25051. extern XContext improbableNumber;
  25052. typedef void (*EventProcPtr) (XEvent* ev);
  25053. static bool xErrorTriggered;
  25054. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25055. {
  25056. xErrorTriggered = true;
  25057. return 0;
  25058. }
  25059. static int getPropertyFromXWindow (Window handle, Atom atom)
  25060. {
  25061. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25062. xErrorTriggered = false;
  25063. int userSize;
  25064. unsigned long bytes, userCount;
  25065. unsigned char* data;
  25066. Atom userType;
  25067. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25068. &userType, &userSize, &userCount, &bytes, &data);
  25069. XSetErrorHandler (oldErrorHandler);
  25070. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25071. : 0;
  25072. }
  25073. static Window getChildWindow (Window windowToCheck)
  25074. {
  25075. Window rootWindow, parentWindow;
  25076. Window* childWindows;
  25077. unsigned int numChildren;
  25078. XQueryTree (display,
  25079. windowToCheck,
  25080. &rootWindow,
  25081. &parentWindow,
  25082. &childWindows,
  25083. &numChildren);
  25084. if (numChildren > 0)
  25085. return childWindows [0];
  25086. return 0;
  25087. }
  25088. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25089. {
  25090. if (e.mods.isLeftButtonDown())
  25091. {
  25092. ev.xbutton.button = Button1;
  25093. ev.xbutton.state |= Button1Mask;
  25094. }
  25095. else if (e.mods.isRightButtonDown())
  25096. {
  25097. ev.xbutton.button = Button3;
  25098. ev.xbutton.state |= Button3Mask;
  25099. }
  25100. else if (e.mods.isMiddleButtonDown())
  25101. {
  25102. ev.xbutton.button = Button2;
  25103. ev.xbutton.state |= Button2Mask;
  25104. }
  25105. }
  25106. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25107. {
  25108. if (e.mods.isLeftButtonDown())
  25109. ev.xmotion.state |= Button1Mask;
  25110. else if (e.mods.isRightButtonDown())
  25111. ev.xmotion.state |= Button3Mask;
  25112. else if (e.mods.isMiddleButtonDown())
  25113. ev.xmotion.state |= Button2Mask;
  25114. }
  25115. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25116. {
  25117. if (e.mods.isLeftButtonDown())
  25118. ev.xcrossing.state |= Button1Mask;
  25119. else if (e.mods.isRightButtonDown())
  25120. ev.xcrossing.state |= Button3Mask;
  25121. else if (e.mods.isMiddleButtonDown())
  25122. ev.xcrossing.state |= Button2Mask;
  25123. }
  25124. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25125. {
  25126. if (increment < 0)
  25127. {
  25128. ev.xbutton.button = Button5;
  25129. ev.xbutton.state |= Button5Mask;
  25130. }
  25131. else if (increment > 0)
  25132. {
  25133. ev.xbutton.button = Button4;
  25134. ev.xbutton.state |= Button4Mask;
  25135. }
  25136. }
  25137. #endif
  25138. static VoidArray activeModules;
  25139. class ModuleHandle : public ReferenceCountedObject
  25140. {
  25141. public:
  25142. File file;
  25143. MainCall moduleMain;
  25144. String pluginName;
  25145. static ModuleHandle* findOrCreateModule (const File& file)
  25146. {
  25147. for (int i = activeModules.size(); --i >= 0;)
  25148. {
  25149. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  25150. if (module->file == file)
  25151. return module;
  25152. }
  25153. _fpreset(); // (doesn't do any harm)
  25154. ++insideVSTCallback;
  25155. shellUIDToCreate = 0;
  25156. log ("Attempting to load VST: " + file.getFullPathName());
  25157. ModuleHandle* m = new ModuleHandle (file);
  25158. if (! m->open())
  25159. deleteAndZero (m);
  25160. --insideVSTCallback;
  25161. _fpreset(); // (doesn't do any harm)
  25162. return m;
  25163. }
  25164. ModuleHandle (const File& file_)
  25165. : file (file_),
  25166. moduleMain (0),
  25167. #if JUCE_WIN32 || JUCE_LINUX
  25168. hModule (0)
  25169. #elif JUCE_MAC
  25170. fragId (0),
  25171. resHandle (0),
  25172. bundleRef (0),
  25173. resFileId (0)
  25174. #endif
  25175. {
  25176. activeModules.add (this);
  25177. #if JUCE_WIN32 || JUCE_LINUX
  25178. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25179. #elif JUCE_MAC
  25180. FSRef ref;
  25181. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25182. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25183. #endif
  25184. }
  25185. ~ModuleHandle()
  25186. {
  25187. activeModules.removeValue (this);
  25188. close();
  25189. }
  25190. juce_UseDebuggingNewOperator
  25191. #if JUCE_WIN32 || JUCE_LINUX
  25192. void* hModule;
  25193. String fullParentDirectoryPathName;
  25194. bool open()
  25195. {
  25196. #if JUCE_WIN32
  25197. static bool timePeriodSet = false;
  25198. if (! timePeriodSet)
  25199. {
  25200. timePeriodSet = true;
  25201. timeBeginPeriod (2);
  25202. }
  25203. #endif
  25204. pluginName = file.getFileNameWithoutExtension();
  25205. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25206. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25207. if (moduleMain == 0)
  25208. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25209. return moduleMain != 0;
  25210. }
  25211. void close()
  25212. {
  25213. _fpreset(); // (doesn't do any harm)
  25214. PlatformUtilities::freeDynamicLibrary (hModule);
  25215. }
  25216. void closeEffect (AEffect* eff)
  25217. {
  25218. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25219. }
  25220. #else
  25221. CFragConnectionID fragId;
  25222. Handle resHandle;
  25223. CFBundleRef bundleRef;
  25224. FSSpec parentDirFSSpec;
  25225. short resFileId;
  25226. bool open()
  25227. {
  25228. bool ok = false;
  25229. const String filename (file.getFullPathName());
  25230. if (file.hasFileExtension (T(".vst")))
  25231. {
  25232. const char* const utf8 = filename.toUTF8();
  25233. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25234. strlen (utf8), file.isDirectory());
  25235. if (url != 0)
  25236. {
  25237. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25238. CFRelease (url);
  25239. if (bundleRef != 0)
  25240. {
  25241. if (CFBundleLoadExecutable (bundleRef))
  25242. {
  25243. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25244. if (moduleMain == 0)
  25245. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25246. if (moduleMain != 0)
  25247. {
  25248. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25249. if (name != 0)
  25250. {
  25251. if (CFGetTypeID (name) == CFStringGetTypeID())
  25252. {
  25253. char buffer[1024];
  25254. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25255. pluginName = buffer;
  25256. }
  25257. }
  25258. if (pluginName.isEmpty())
  25259. pluginName = file.getFileNameWithoutExtension();
  25260. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25261. ok = true;
  25262. }
  25263. }
  25264. if (! ok)
  25265. {
  25266. CFBundleUnloadExecutable (bundleRef);
  25267. CFRelease (bundleRef);
  25268. bundleRef = 0;
  25269. }
  25270. }
  25271. }
  25272. }
  25273. #if JUCE_PPC
  25274. else
  25275. {
  25276. FSRef fn;
  25277. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  25278. {
  25279. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25280. if (resFileId != -1)
  25281. {
  25282. const int numEffs = Count1Resources ('aEff');
  25283. for (int i = 0; i < numEffs; ++i)
  25284. {
  25285. resHandle = Get1IndResource ('aEff', i + 1);
  25286. if (resHandle != 0)
  25287. {
  25288. OSType type;
  25289. Str255 name;
  25290. SInt16 id;
  25291. GetResInfo (resHandle, &id, &type, name);
  25292. pluginName = String ((const char*) name + 1, name[0]);
  25293. DetachResource (resHandle);
  25294. HLock (resHandle);
  25295. Ptr ptr;
  25296. Str255 errorText;
  25297. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25298. name, kPrivateCFragCopy,
  25299. &fragId, &ptr, errorText);
  25300. if (err == noErr)
  25301. {
  25302. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25303. ok = true;
  25304. }
  25305. else
  25306. {
  25307. HUnlock (resHandle);
  25308. }
  25309. break;
  25310. }
  25311. }
  25312. if (! ok)
  25313. CloseResFile (resFileId);
  25314. }
  25315. }
  25316. }
  25317. #endif
  25318. return ok;
  25319. }
  25320. void close()
  25321. {
  25322. #if JUCE_PPC
  25323. if (fragId != 0)
  25324. {
  25325. if (moduleMain != 0)
  25326. disposeMachOFromCFM ((void*) moduleMain);
  25327. CloseConnection (&fragId);
  25328. HUnlock (resHandle);
  25329. if (resFileId != 0)
  25330. CloseResFile (resFileId);
  25331. }
  25332. else
  25333. #endif
  25334. if (bundleRef != 0)
  25335. {
  25336. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25337. if (CFGetRetainCount (bundleRef) == 1)
  25338. CFBundleUnloadExecutable (bundleRef);
  25339. if (CFGetRetainCount (bundleRef) > 0)
  25340. CFRelease (bundleRef);
  25341. }
  25342. }
  25343. void closeEffect (AEffect* eff)
  25344. {
  25345. #if JUCE_PPC
  25346. if (fragId != 0)
  25347. {
  25348. VoidArray thingsToDelete;
  25349. thingsToDelete.add ((void*) eff->dispatcher);
  25350. thingsToDelete.add ((void*) eff->process);
  25351. thingsToDelete.add ((void*) eff->setParameter);
  25352. thingsToDelete.add ((void*) eff->getParameter);
  25353. thingsToDelete.add ((void*) eff->processReplacing);
  25354. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25355. for (int i = thingsToDelete.size(); --i >= 0;)
  25356. disposeMachOFromCFM (thingsToDelete[i]);
  25357. }
  25358. else
  25359. #endif
  25360. {
  25361. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25362. }
  25363. }
  25364. #if JUCE_PPC
  25365. static void* newMachOFromCFM (void* cfmfp)
  25366. {
  25367. if (cfmfp == 0)
  25368. return 0;
  25369. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  25370. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25371. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25372. mfp[2] = 0x800c0000;
  25373. mfp[3] = 0x804c0004;
  25374. mfp[4] = 0x7c0903a6;
  25375. mfp[5] = 0x4e800420;
  25376. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25377. return mfp;
  25378. }
  25379. static void disposeMachOFromCFM (void* ptr)
  25380. {
  25381. juce_free (ptr);
  25382. }
  25383. void coerceAEffectFunctionCalls (AEffect* eff)
  25384. {
  25385. if (fragId != 0)
  25386. {
  25387. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25388. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25389. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25390. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25391. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25392. }
  25393. }
  25394. #endif
  25395. #endif
  25396. };
  25397. /**
  25398. An instance of a plugin, created by a VSTPluginFormat.
  25399. */
  25400. class VSTPluginInstance : public AudioPluginInstance,
  25401. private Timer,
  25402. private AsyncUpdater
  25403. {
  25404. public:
  25405. ~VSTPluginInstance();
  25406. // AudioPluginInstance methods:
  25407. void fillInPluginDescription (PluginDescription& desc) const
  25408. {
  25409. desc.name = name;
  25410. desc.fileOrIdentifier = module->file.getFullPathName();
  25411. desc.uid = getUID();
  25412. desc.lastFileModTime = module->file.getLastModificationTime();
  25413. desc.pluginFormatName = "VST";
  25414. desc.category = getCategory();
  25415. {
  25416. char buffer [kVstMaxVendorStrLen + 8];
  25417. zerostruct (buffer);
  25418. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25419. desc.manufacturerName = buffer;
  25420. }
  25421. desc.version = getVersion();
  25422. desc.numInputChannels = getNumInputChannels();
  25423. desc.numOutputChannels = getNumOutputChannels();
  25424. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25425. }
  25426. const String getName() const { return name; }
  25427. int getUID() const throw();
  25428. bool acceptsMidi() const { return wantsMidiMessages; }
  25429. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25430. // AudioProcessor methods:
  25431. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25432. void releaseResources();
  25433. void processBlock (AudioSampleBuffer& buffer,
  25434. MidiBuffer& midiMessages);
  25435. AudioProcessorEditor* createEditor();
  25436. const String getInputChannelName (const int index) const;
  25437. bool isInputChannelStereoPair (int index) const;
  25438. const String getOutputChannelName (const int index) const;
  25439. bool isOutputChannelStereoPair (int index) const;
  25440. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25441. float getParameter (int index);
  25442. void setParameter (int index, float newValue);
  25443. const String getParameterName (int index);
  25444. const String getParameterText (int index);
  25445. bool isParameterAutomatable (int index) const;
  25446. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25447. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25448. void setCurrentProgram (int index);
  25449. const String getProgramName (int index);
  25450. void changeProgramName (int index, const String& newName);
  25451. void getStateInformation (MemoryBlock& destData);
  25452. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25453. void setStateInformation (const void* data, int sizeInBytes);
  25454. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25455. void timerCallback();
  25456. void handleAsyncUpdate();
  25457. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25458. juce_UseDebuggingNewOperator
  25459. private:
  25460. friend class VSTPluginWindow;
  25461. friend class VSTPluginFormat;
  25462. AEffect* effect;
  25463. String name;
  25464. CriticalSection lock;
  25465. bool wantsMidiMessages, initialised, isPowerOn;
  25466. mutable StringArray programNames;
  25467. AudioSampleBuffer tempBuffer;
  25468. CriticalSection midiInLock;
  25469. MidiBuffer incomingMidi;
  25470. VSTMidiEventList midiEventsToSend;
  25471. VstTimeInfo vstHostTime;
  25472. float** channels;
  25473. ReferenceCountedObjectPtr <ModuleHandle> module;
  25474. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25475. bool restoreProgramSettings (const fxProgram* const prog);
  25476. const String getCurrentProgramName();
  25477. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25478. void updateStoredProgramNames();
  25479. void initialise();
  25480. void handleMidiFromPlugin (const VstEvents* const events);
  25481. void createTempParameterStore (MemoryBlock& dest);
  25482. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25483. const String getParameterLabel (int index) const;
  25484. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25485. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25486. void setChunkData (const char* data, int size, bool isPreset);
  25487. bool loadFromFXBFile (const void* data, int numBytes);
  25488. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25489. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25490. const String getVersion() const throw();
  25491. const String getCategory() const throw();
  25492. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25493. void setPower (const bool on);
  25494. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25495. };
  25496. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25497. : effect (0),
  25498. wantsMidiMessages (false),
  25499. initialised (false),
  25500. isPowerOn (false),
  25501. tempBuffer (1, 1),
  25502. channels (0),
  25503. module (module_)
  25504. {
  25505. try
  25506. {
  25507. _fpreset();
  25508. ++insideVSTCallback;
  25509. name = module->pluginName;
  25510. log (T("Creating VST instance: ") + name);
  25511. #if JUCE_MAC
  25512. if (module->resFileId != 0)
  25513. UseResFile (module->resFileId);
  25514. #if JUCE_PPC
  25515. if (module->fragId != 0)
  25516. {
  25517. static void* audioMasterCoerced = 0;
  25518. if (audioMasterCoerced == 0)
  25519. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  25520. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  25521. }
  25522. else
  25523. #endif
  25524. #endif
  25525. {
  25526. effect = module->moduleMain (&audioMaster);
  25527. }
  25528. --insideVSTCallback;
  25529. if (effect != 0 && effect->magic == kEffectMagic)
  25530. {
  25531. #if JUCE_PPC
  25532. module->coerceAEffectFunctionCalls (effect);
  25533. #endif
  25534. jassert (effect->resvd2 == 0);
  25535. jassert (effect->object != 0);
  25536. _fpreset(); // some dodgy plugs fuck around with this
  25537. }
  25538. else
  25539. {
  25540. effect = 0;
  25541. }
  25542. }
  25543. catch (...)
  25544. {
  25545. --insideVSTCallback;
  25546. }
  25547. }
  25548. VSTPluginInstance::~VSTPluginInstance()
  25549. {
  25550. {
  25551. const ScopedLock sl (lock);
  25552. jassert (insideVSTCallback == 0);
  25553. if (effect != 0 && effect->magic == kEffectMagic)
  25554. {
  25555. try
  25556. {
  25557. #if JUCE_MAC
  25558. if (module->resFileId != 0)
  25559. UseResFile (module->resFileId);
  25560. #endif
  25561. // Must delete any editors before deleting the plugin instance!
  25562. jassert (getActiveEditor() == 0);
  25563. _fpreset(); // some dodgy plugs fuck around with this
  25564. module->closeEffect (effect);
  25565. }
  25566. catch (...)
  25567. {}
  25568. }
  25569. module = 0;
  25570. effect = 0;
  25571. }
  25572. juce_free (channels);
  25573. channels = 0;
  25574. }
  25575. void VSTPluginInstance::initialise()
  25576. {
  25577. if (initialised || effect == 0)
  25578. return;
  25579. log (T("Initialising VST: ") + module->pluginName);
  25580. initialised = true;
  25581. dispatch (effIdentify, 0, 0, 0, 0);
  25582. // this code would ask the plugin for its name, but so few plugins
  25583. // actually bother implementing this correctly, that it's better to
  25584. // just ignore it and use the file name instead.
  25585. /* {
  25586. char buffer [256];
  25587. zerostruct (buffer);
  25588. dispatch (effGetEffectName, 0, 0, buffer, 0);
  25589. name = String (buffer).trim();
  25590. if (name.isEmpty())
  25591. name = module->pluginName;
  25592. }
  25593. */
  25594. if (getSampleRate() > 0)
  25595. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  25596. if (getBlockSize() > 0)
  25597. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  25598. dispatch (effOpen, 0, 0, 0, 0);
  25599. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25600. getSampleRate(), getBlockSize());
  25601. if (getNumPrograms() > 1)
  25602. setCurrentProgram (0);
  25603. else
  25604. dispatch (effSetProgram, 0, 0, 0, 0);
  25605. int i;
  25606. for (i = effect->numInputs; --i >= 0;)
  25607. dispatch (effConnectInput, i, 1, 0, 0);
  25608. for (i = effect->numOutputs; --i >= 0;)
  25609. dispatch (effConnectOutput, i, 1, 0, 0);
  25610. updateStoredProgramNames();
  25611. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  25612. setLatencySamples (effect->initialDelay);
  25613. }
  25614. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  25615. int samplesPerBlockExpected)
  25616. {
  25617. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25618. sampleRate_, samplesPerBlockExpected);
  25619. setLatencySamples (effect->initialDelay);
  25620. juce_free (channels);
  25621. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  25622. vstHostTime.tempo = 120.0;
  25623. vstHostTime.timeSigNumerator = 4;
  25624. vstHostTime.timeSigDenominator = 4;
  25625. vstHostTime.sampleRate = sampleRate_;
  25626. vstHostTime.samplePos = 0;
  25627. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  25628. initialise();
  25629. if (initialised)
  25630. {
  25631. wantsMidiMessages = wantsMidiMessages
  25632. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  25633. if (wantsMidiMessages)
  25634. midiEventsToSend.ensureSize (256);
  25635. else
  25636. midiEventsToSend.freeEvents();
  25637. incomingMidi.clear();
  25638. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  25639. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  25640. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  25641. if (! isPowerOn)
  25642. setPower (true);
  25643. // dodgy hack to force some plugins to initialise the sample rate..
  25644. if ((! hasEditor()) && getNumParameters() > 0)
  25645. {
  25646. const float old = getParameter (0);
  25647. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  25648. setParameter (0, old);
  25649. }
  25650. dispatch (effStartProcess, 0, 0, 0, 0);
  25651. }
  25652. }
  25653. void VSTPluginInstance::releaseResources()
  25654. {
  25655. if (initialised)
  25656. {
  25657. dispatch (effStopProcess, 0, 0, 0, 0);
  25658. setPower (false);
  25659. }
  25660. tempBuffer.setSize (1, 1);
  25661. incomingMidi.clear();
  25662. midiEventsToSend.freeEvents();
  25663. juce_free (channels);
  25664. channels = 0;
  25665. }
  25666. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25667. MidiBuffer& midiMessages)
  25668. {
  25669. const int numSamples = buffer.getNumSamples();
  25670. if (initialised)
  25671. {
  25672. AudioPlayHead* playHead = getPlayHead();
  25673. if (playHead != 0)
  25674. {
  25675. AudioPlayHead::CurrentPositionInfo position;
  25676. playHead->getCurrentPosition (position);
  25677. vstHostTime.tempo = position.bpm;
  25678. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  25679. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  25680. vstHostTime.ppqPos = position.ppqPosition;
  25681. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  25682. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  25683. if (position.isPlaying)
  25684. vstHostTime.flags |= kVstTransportPlaying;
  25685. else
  25686. vstHostTime.flags &= ~kVstTransportPlaying;
  25687. }
  25688. #if JUCE_WIN32
  25689. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  25690. #elif JUCE_LINUX
  25691. timeval micro;
  25692. gettimeofday (&micro, 0);
  25693. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  25694. #elif JUCE_MAC
  25695. UnsignedWide micro;
  25696. Microseconds (&micro);
  25697. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  25698. #endif
  25699. if (wantsMidiMessages)
  25700. {
  25701. midiEventsToSend.clear();
  25702. midiEventsToSend.ensureSize (1);
  25703. MidiBuffer::Iterator iter (midiMessages);
  25704. const uint8* midiData;
  25705. int numBytesOfMidiData, samplePosition;
  25706. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  25707. {
  25708. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  25709. jlimit (0, numSamples - 1, samplePosition));
  25710. }
  25711. try
  25712. {
  25713. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  25714. }
  25715. catch (...)
  25716. {}
  25717. }
  25718. int i;
  25719. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  25720. for (i = 0; i < maxChans; ++i)
  25721. channels[i] = buffer.getSampleData (i);
  25722. channels [maxChans] = 0;
  25723. _clearfp();
  25724. if ((effect->flags & effFlagsCanReplacing) != 0)
  25725. {
  25726. try
  25727. {
  25728. effect->processReplacing (effect, channels, channels, numSamples);
  25729. }
  25730. catch (...)
  25731. {}
  25732. }
  25733. else
  25734. {
  25735. tempBuffer.setSize (effect->numOutputs, numSamples);
  25736. tempBuffer.clear();
  25737. float* outs [64];
  25738. for (i = effect->numOutputs; --i >= 0;)
  25739. outs[i] = tempBuffer.getSampleData (i);
  25740. outs [effect->numOutputs] = 0;
  25741. try
  25742. {
  25743. effect->process (effect, channels, outs, numSamples);
  25744. }
  25745. catch (...)
  25746. {}
  25747. for (i = effect->numOutputs; --i >= 0;)
  25748. buffer.copyFrom (i, 0, outs[i], numSamples);
  25749. }
  25750. }
  25751. else
  25752. {
  25753. // Not initialised, so just bypass..
  25754. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25755. buffer.clear (i, 0, buffer.getNumSamples());
  25756. }
  25757. {
  25758. // copy any incoming midi..
  25759. const ScopedLock sl (midiInLock);
  25760. midiMessages = incomingMidi;
  25761. incomingMidi.clear();
  25762. }
  25763. }
  25764. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  25765. {
  25766. if (events != 0)
  25767. {
  25768. const ScopedLock sl (midiInLock);
  25769. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  25770. }
  25771. }
  25772. static Array <VSTPluginWindow*> activeVSTWindows;
  25773. class VSTPluginWindow : public AudioProcessorEditor,
  25774. #if ! JUCE_MAC
  25775. public ComponentMovementWatcher,
  25776. #endif
  25777. public Timer
  25778. {
  25779. public:
  25780. VSTPluginWindow (VSTPluginInstance& plugin_)
  25781. : AudioProcessorEditor (&plugin_),
  25782. #if ! JUCE_MAC
  25783. ComponentMovementWatcher (this),
  25784. #endif
  25785. plugin (plugin_),
  25786. isOpen (false),
  25787. wasShowing (false),
  25788. pluginRefusesToResize (false),
  25789. pluginWantsKeys (false),
  25790. alreadyInside (false),
  25791. recursiveResize (false)
  25792. {
  25793. #if JUCE_WIN32
  25794. sizeCheckCount = 0;
  25795. pluginHWND = 0;
  25796. #elif JUCE_LINUX
  25797. pluginWindow = None;
  25798. pluginProc = None;
  25799. #else
  25800. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25801. #endif
  25802. activeVSTWindows.add (this);
  25803. setSize (1, 1);
  25804. setOpaque (true);
  25805. setVisible (true);
  25806. }
  25807. ~VSTPluginWindow()
  25808. {
  25809. #if JUCE_MAC
  25810. deleteAndZero (innerWrapper);
  25811. #else
  25812. closePluginWindow();
  25813. #endif
  25814. activeVSTWindows.removeValue (this);
  25815. plugin.editorBeingDeleted (this);
  25816. }
  25817. #if ! JUCE_MAC
  25818. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  25819. {
  25820. if (recursiveResize)
  25821. return;
  25822. Component* const topComp = getTopLevelComponent();
  25823. if (topComp->getPeer() != 0)
  25824. {
  25825. int x = 0, y = 0;
  25826. relativePositionToOtherComponent (topComp, x, y);
  25827. recursiveResize = true;
  25828. #if JUCE_WIN32
  25829. if (pluginHWND != 0)
  25830. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  25831. #elif JUCE_LINUX
  25832. if (pluginWindow != 0)
  25833. {
  25834. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  25835. XMoveWindow (display, pluginWindow, x, y);
  25836. XMapRaised (display, pluginWindow);
  25837. }
  25838. #endif
  25839. recursiveResize = false;
  25840. }
  25841. }
  25842. void componentVisibilityChanged (Component&)
  25843. {
  25844. const bool isShowingNow = isShowing();
  25845. if (wasShowing != isShowingNow)
  25846. {
  25847. wasShowing = isShowingNow;
  25848. if (isShowingNow)
  25849. openPluginWindow();
  25850. else
  25851. closePluginWindow();
  25852. }
  25853. componentMovedOrResized (true, true);
  25854. }
  25855. void componentPeerChanged()
  25856. {
  25857. closePluginWindow();
  25858. openPluginWindow();
  25859. }
  25860. #endif
  25861. bool keyStateChanged (const bool)
  25862. {
  25863. return pluginWantsKeys;
  25864. }
  25865. bool keyPressed (const KeyPress&)
  25866. {
  25867. return pluginWantsKeys;
  25868. }
  25869. #if JUCE_MAC
  25870. void paint (Graphics& g)
  25871. {
  25872. g.fillAll (Colours::black);
  25873. }
  25874. #else
  25875. void paint (Graphics& g)
  25876. {
  25877. if (isOpen)
  25878. {
  25879. ComponentPeer* const peer = getPeer();
  25880. if (peer != 0)
  25881. {
  25882. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  25883. getScreenY() - peer->getScreenY(),
  25884. getWidth(), getHeight());
  25885. #if JUCE_LINUX
  25886. if (pluginWindow != 0)
  25887. {
  25888. const Rectangle clip (g.getClipBounds());
  25889. XEvent ev;
  25890. zerostruct (ev);
  25891. ev.xexpose.type = Expose;
  25892. ev.xexpose.display = display;
  25893. ev.xexpose.window = pluginWindow;
  25894. ev.xexpose.x = clip.getX();
  25895. ev.xexpose.y = clip.getY();
  25896. ev.xexpose.width = clip.getWidth();
  25897. ev.xexpose.height = clip.getHeight();
  25898. sendEventToChild (&ev);
  25899. }
  25900. #endif
  25901. }
  25902. }
  25903. else
  25904. {
  25905. g.fillAll (Colours::black);
  25906. }
  25907. }
  25908. #endif
  25909. void timerCallback()
  25910. {
  25911. #if JUCE_WIN32
  25912. if (--sizeCheckCount <= 0)
  25913. {
  25914. sizeCheckCount = 10;
  25915. checkPluginWindowSize();
  25916. }
  25917. #endif
  25918. try
  25919. {
  25920. static bool reentrant = false;
  25921. if (! reentrant)
  25922. {
  25923. reentrant = true;
  25924. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  25925. reentrant = false;
  25926. }
  25927. }
  25928. catch (...)
  25929. {}
  25930. }
  25931. void mouseDown (const MouseEvent& e)
  25932. {
  25933. #if JUCE_LINUX
  25934. if (pluginWindow == 0)
  25935. return;
  25936. toFront (true);
  25937. XEvent ev;
  25938. zerostruct (ev);
  25939. ev.xbutton.display = display;
  25940. ev.xbutton.type = ButtonPress;
  25941. ev.xbutton.window = pluginWindow;
  25942. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25943. ev.xbutton.time = CurrentTime;
  25944. ev.xbutton.x = e.x;
  25945. ev.xbutton.y = e.y;
  25946. ev.xbutton.x_root = e.getScreenX();
  25947. ev.xbutton.y_root = e.getScreenY();
  25948. translateJuceToXButtonModifiers (e, ev);
  25949. sendEventToChild (&ev);
  25950. #elif JUCE_WIN32
  25951. (void) e;
  25952. toFront (true);
  25953. #endif
  25954. }
  25955. void broughtToFront()
  25956. {
  25957. activeVSTWindows.removeValue (this);
  25958. activeVSTWindows.add (this);
  25959. #if JUCE_MAC
  25960. dispatch (effEditTop, 0, 0, 0, 0);
  25961. #endif
  25962. }
  25963. juce_UseDebuggingNewOperator
  25964. private:
  25965. VSTPluginInstance& plugin;
  25966. bool isOpen, wasShowing, recursiveResize;
  25967. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  25968. #if JUCE_WIN32
  25969. HWND pluginHWND;
  25970. void* originalWndProc;
  25971. int sizeCheckCount;
  25972. #elif JUCE_LINUX
  25973. Window pluginWindow;
  25974. EventProcPtr pluginProc;
  25975. #endif
  25976. #if JUCE_MAC
  25977. void openPluginWindow (WindowRef parentWindow)
  25978. {
  25979. if (isOpen || parentWindow == 0)
  25980. return;
  25981. isOpen = true;
  25982. ERect* rect = 0;
  25983. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25984. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  25985. // do this before and after like in the steinberg example
  25986. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25987. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25988. // Install keyboard hooks
  25989. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25990. // double-check it's not too tiny
  25991. int w = 250, h = 150;
  25992. if (rect != 0)
  25993. {
  25994. w = rect->right - rect->left;
  25995. h = rect->bottom - rect->top;
  25996. if (w == 0 || h == 0)
  25997. {
  25998. w = 250;
  25999. h = 150;
  26000. }
  26001. }
  26002. w = jmax (w, 32);
  26003. h = jmax (h, 32);
  26004. setSize (w, h);
  26005. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26006. repaint();
  26007. }
  26008. #else
  26009. void openPluginWindow()
  26010. {
  26011. if (isOpen || getWindowHandle() == 0)
  26012. return;
  26013. log (T("Opening VST UI: ") + plugin.name);
  26014. isOpen = true;
  26015. ERect* rect = 0;
  26016. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26017. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26018. // do this before and after like in the steinberg example
  26019. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26020. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26021. // Install keyboard hooks
  26022. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26023. #if JUCE_WIN32
  26024. originalWndProc = 0;
  26025. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26026. if (pluginHWND == 0)
  26027. {
  26028. isOpen = false;
  26029. setSize (300, 150);
  26030. return;
  26031. }
  26032. #pragma warning (push)
  26033. #pragma warning (disable: 4244)
  26034. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26035. if (! pluginWantsKeys)
  26036. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  26037. #pragma warning (pop)
  26038. int w, h;
  26039. RECT r;
  26040. GetWindowRect (pluginHWND, &r);
  26041. w = r.right - r.left;
  26042. h = r.bottom - r.top;
  26043. if (rect != 0)
  26044. {
  26045. const int rw = rect->right - rect->left;
  26046. const int rh = rect->bottom - rect->top;
  26047. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26048. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26049. {
  26050. // very dodgy logic to decide which size is right.
  26051. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26052. {
  26053. SetWindowPos (pluginHWND, 0,
  26054. 0, 0, rw, rh,
  26055. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26056. GetWindowRect (pluginHWND, &r);
  26057. w = r.right - r.left;
  26058. h = r.bottom - r.top;
  26059. pluginRefusesToResize = (w != rw) || (h != rh);
  26060. w = rw;
  26061. h = rh;
  26062. }
  26063. }
  26064. }
  26065. #elif JUCE_LINUX
  26066. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26067. if (pluginWindow != 0)
  26068. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26069. XInternAtom (display, "_XEventProc", False));
  26070. int w = 250, h = 150;
  26071. if (rect != 0)
  26072. {
  26073. w = rect->right - rect->left;
  26074. h = rect->bottom - rect->top;
  26075. if (w == 0 || h == 0)
  26076. {
  26077. w = 250;
  26078. h = 150;
  26079. }
  26080. }
  26081. if (pluginWindow != 0)
  26082. XMapRaised (display, pluginWindow);
  26083. #endif
  26084. // double-check it's not too tiny
  26085. w = jmax (w, 32);
  26086. h = jmax (h, 32);
  26087. setSize (w, h);
  26088. #if JUCE_WIN32
  26089. checkPluginWindowSize();
  26090. #endif
  26091. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26092. repaint();
  26093. }
  26094. #endif
  26095. #if ! JUCE_MAC
  26096. void closePluginWindow()
  26097. {
  26098. if (isOpen)
  26099. {
  26100. log (T("Closing VST UI: ") + plugin.getName());
  26101. isOpen = false;
  26102. dispatch (effEditClose, 0, 0, 0, 0);
  26103. #if JUCE_WIN32
  26104. #pragma warning (push)
  26105. #pragma warning (disable: 4244)
  26106. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26107. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  26108. #pragma warning (pop)
  26109. stopTimer();
  26110. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26111. DestroyWindow (pluginHWND);
  26112. pluginHWND = 0;
  26113. #elif JUCE_LINUX
  26114. stopTimer();
  26115. pluginWindow = 0;
  26116. pluginProc = 0;
  26117. #endif
  26118. }
  26119. }
  26120. #endif
  26121. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26122. {
  26123. return plugin.dispatch (opcode, index, value, ptr, opt);
  26124. }
  26125. #if JUCE_WIN32
  26126. void checkPluginWindowSize() throw()
  26127. {
  26128. RECT r;
  26129. GetWindowRect (pluginHWND, &r);
  26130. const int w = r.right - r.left;
  26131. const int h = r.bottom - r.top;
  26132. if (isShowing() && w > 0 && h > 0
  26133. && (w != getWidth() || h != getHeight())
  26134. && ! pluginRefusesToResize)
  26135. {
  26136. setSize (w, h);
  26137. sizeCheckCount = 0;
  26138. }
  26139. }
  26140. // hooks to get keyboard events from VST windows..
  26141. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26142. {
  26143. for (int i = activeVSTWindows.size(); --i >= 0;)
  26144. {
  26145. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26146. if (w->pluginHWND == hW)
  26147. {
  26148. if (message == WM_CHAR
  26149. || message == WM_KEYDOWN
  26150. || message == WM_SYSKEYDOWN
  26151. || message == WM_KEYUP
  26152. || message == WM_SYSKEYUP
  26153. || message == WM_APPCOMMAND)
  26154. {
  26155. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26156. message, wParam, lParam);
  26157. }
  26158. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26159. (HWND) w->pluginHWND,
  26160. message,
  26161. wParam,
  26162. lParam);
  26163. }
  26164. }
  26165. return DefWindowProc (hW, message, wParam, lParam);
  26166. }
  26167. #endif
  26168. #if JUCE_LINUX
  26169. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26170. void sendEventToChild (XEvent* event)
  26171. {
  26172. if (pluginProc != 0)
  26173. {
  26174. // if the plugin publishes an event procedure, pass the event directly..
  26175. pluginProc (event);
  26176. }
  26177. else if (pluginWindow != 0)
  26178. {
  26179. // if the plugin has a window, then send the event to the window so that
  26180. // its message thread will pick it up..
  26181. XSendEvent (display, pluginWindow, False, 0L, event);
  26182. XFlush (display);
  26183. }
  26184. }
  26185. void mouseEnter (const MouseEvent& e)
  26186. {
  26187. if (pluginWindow != 0)
  26188. {
  26189. XEvent ev;
  26190. zerostruct (ev);
  26191. ev.xcrossing.display = display;
  26192. ev.xcrossing.type = EnterNotify;
  26193. ev.xcrossing.window = pluginWindow;
  26194. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26195. ev.xcrossing.time = CurrentTime;
  26196. ev.xcrossing.x = e.x;
  26197. ev.xcrossing.y = e.y;
  26198. ev.xcrossing.x_root = e.getScreenX();
  26199. ev.xcrossing.y_root = e.getScreenY();
  26200. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26201. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26202. translateJuceToXCrossingModifiers (e, ev);
  26203. sendEventToChild (&ev);
  26204. }
  26205. }
  26206. void mouseExit (const MouseEvent& e)
  26207. {
  26208. if (pluginWindow != 0)
  26209. {
  26210. XEvent ev;
  26211. zerostruct (ev);
  26212. ev.xcrossing.display = display;
  26213. ev.xcrossing.type = LeaveNotify;
  26214. ev.xcrossing.window = pluginWindow;
  26215. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26216. ev.xcrossing.time = CurrentTime;
  26217. ev.xcrossing.x = e.x;
  26218. ev.xcrossing.y = e.y;
  26219. ev.xcrossing.x_root = e.getScreenX();
  26220. ev.xcrossing.y_root = e.getScreenY();
  26221. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26222. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26223. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26224. translateJuceToXCrossingModifiers (e, ev);
  26225. sendEventToChild (&ev);
  26226. }
  26227. }
  26228. void mouseMove (const MouseEvent& e)
  26229. {
  26230. if (pluginWindow != 0)
  26231. {
  26232. XEvent ev;
  26233. zerostruct (ev);
  26234. ev.xmotion.display = display;
  26235. ev.xmotion.type = MotionNotify;
  26236. ev.xmotion.window = pluginWindow;
  26237. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26238. ev.xmotion.time = CurrentTime;
  26239. ev.xmotion.is_hint = NotifyNormal;
  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. sendEventToChild (&ev);
  26245. }
  26246. }
  26247. void mouseDrag (const MouseEvent& e)
  26248. {
  26249. if (pluginWindow != 0)
  26250. {
  26251. XEvent ev;
  26252. zerostruct (ev);
  26253. ev.xmotion.display = display;
  26254. ev.xmotion.type = MotionNotify;
  26255. ev.xmotion.window = pluginWindow;
  26256. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26257. ev.xmotion.time = CurrentTime;
  26258. ev.xmotion.x = e.x ;
  26259. ev.xmotion.y = e.y;
  26260. ev.xmotion.x_root = e.getScreenX();
  26261. ev.xmotion.y_root = e.getScreenY();
  26262. ev.xmotion.is_hint = NotifyNormal;
  26263. translateJuceToXMotionModifiers (e, ev);
  26264. sendEventToChild (&ev);
  26265. }
  26266. }
  26267. void mouseUp (const MouseEvent& e)
  26268. {
  26269. if (pluginWindow != 0)
  26270. {
  26271. XEvent ev;
  26272. zerostruct (ev);
  26273. ev.xbutton.display = display;
  26274. ev.xbutton.type = ButtonRelease;
  26275. ev.xbutton.window = pluginWindow;
  26276. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26277. ev.xbutton.time = CurrentTime;
  26278. ev.xbutton.x = e.x;
  26279. ev.xbutton.y = e.y;
  26280. ev.xbutton.x_root = e.getScreenX();
  26281. ev.xbutton.y_root = e.getScreenY();
  26282. translateJuceToXButtonModifiers (e, ev);
  26283. sendEventToChild (&ev);
  26284. }
  26285. }
  26286. void mouseWheelMove (const MouseEvent& e,
  26287. float incrementX,
  26288. float incrementY)
  26289. {
  26290. if (pluginWindow != 0)
  26291. {
  26292. XEvent ev;
  26293. zerostruct (ev);
  26294. ev.xbutton.display = display;
  26295. ev.xbutton.type = ButtonPress;
  26296. ev.xbutton.window = pluginWindow;
  26297. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26298. ev.xbutton.time = CurrentTime;
  26299. ev.xbutton.x = e.x;
  26300. ev.xbutton.y = e.y;
  26301. ev.xbutton.x_root = e.getScreenX();
  26302. ev.xbutton.y_root = e.getScreenY();
  26303. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26304. sendEventToChild (&ev);
  26305. // TODO - put a usleep here ?
  26306. ev.xbutton.type = ButtonRelease;
  26307. sendEventToChild (&ev);
  26308. }
  26309. }
  26310. #endif
  26311. #if JUCE_MAC
  26312. #if ! JUCE_SUPPORT_CARBON
  26313. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26314. #endif
  26315. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26316. {
  26317. public:
  26318. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26319. : owner (owner_),
  26320. alreadyInside (false)
  26321. {
  26322. }
  26323. ~InnerWrapperComponent()
  26324. {
  26325. deleteWindow();
  26326. }
  26327. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26328. {
  26329. owner->openPluginWindow (windowRef);
  26330. return 0;
  26331. }
  26332. void removeView (HIViewRef)
  26333. {
  26334. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26335. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26336. }
  26337. bool getEmbeddedViewSize (int& w, int& h)
  26338. {
  26339. ERect* rect = 0;
  26340. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26341. w = rect->right - rect->left;
  26342. h = rect->bottom - rect->top;
  26343. return true;
  26344. }
  26345. void mouseDown (int x, int y)
  26346. {
  26347. if (! alreadyInside)
  26348. {
  26349. alreadyInside = true;
  26350. getTopLevelComponent()->toFront (true);
  26351. owner->dispatch (effEditMouse, x, y, 0, 0);
  26352. alreadyInside = false;
  26353. }
  26354. else
  26355. {
  26356. PostEvent (::mouseDown, 0);
  26357. }
  26358. }
  26359. void paint()
  26360. {
  26361. ComponentPeer* const peer = getPeer();
  26362. if (peer != 0)
  26363. {
  26364. ERect r;
  26365. r.left = getScreenX() - peer->getScreenX();
  26366. r.right = r.left + getWidth();
  26367. r.top = getScreenY() - peer->getScreenY();
  26368. r.bottom = r.top + getHeight();
  26369. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26370. }
  26371. }
  26372. private:
  26373. VSTPluginWindow* const owner;
  26374. bool alreadyInside;
  26375. };
  26376. friend class InnerWrapperComponent;
  26377. InnerWrapperComponent* innerWrapper;
  26378. void resized()
  26379. {
  26380. innerWrapper->setSize (getWidth(), getHeight());
  26381. }
  26382. #endif
  26383. };
  26384. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26385. {
  26386. if (hasEditor())
  26387. return new VSTPluginWindow (*this);
  26388. return 0;
  26389. }
  26390. void VSTPluginInstance::handleAsyncUpdate()
  26391. {
  26392. // indicates that something about the plugin has changed..
  26393. updateHostDisplay();
  26394. }
  26395. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26396. {
  26397. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26398. {
  26399. changeProgramName (getCurrentProgram(), prog->prgName);
  26400. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26401. setParameter (i, vst_swapFloat (prog->params[i]));
  26402. return true;
  26403. }
  26404. return false;
  26405. }
  26406. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26407. const int dataSize)
  26408. {
  26409. if (dataSize < 28)
  26410. return false;
  26411. const fxSet* const set = (const fxSet*) data;
  26412. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26413. || vst_swap (set->version) > fxbVersionNum)
  26414. return false;
  26415. if (vst_swap (set->fxMagic) == 'FxBk')
  26416. {
  26417. // bank of programs
  26418. if (vst_swap (set->numPrograms) >= 0)
  26419. {
  26420. const int oldProg = getCurrentProgram();
  26421. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26422. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26423. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26424. {
  26425. if (i != oldProg)
  26426. {
  26427. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26428. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26429. return false;
  26430. if (vst_swap (set->numPrograms) > 0)
  26431. setCurrentProgram (i);
  26432. if (! restoreProgramSettings (prog))
  26433. return false;
  26434. }
  26435. }
  26436. if (vst_swap (set->numPrograms) > 0)
  26437. setCurrentProgram (oldProg);
  26438. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26439. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26440. return false;
  26441. if (! restoreProgramSettings (prog))
  26442. return false;
  26443. }
  26444. }
  26445. else if (vst_swap (set->fxMagic) == 'FxCk')
  26446. {
  26447. // single program
  26448. const fxProgram* const prog = (const fxProgram*) data;
  26449. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26450. return false;
  26451. changeProgramName (getCurrentProgram(), prog->prgName);
  26452. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26453. setParameter (i, vst_swapFloat (prog->params[i]));
  26454. }
  26455. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26456. {
  26457. // non-preset chunk
  26458. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26459. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26460. return false;
  26461. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26462. }
  26463. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26464. {
  26465. // preset chunk
  26466. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26467. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26468. return false;
  26469. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26470. changeProgramName (getCurrentProgram(), cset->name);
  26471. }
  26472. else
  26473. {
  26474. return false;
  26475. }
  26476. return true;
  26477. }
  26478. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26479. {
  26480. const int numParams = getNumParameters();
  26481. prog->chunkMagic = vst_swap ('CcnK');
  26482. prog->byteSize = 0;
  26483. prog->fxMagic = vst_swap ('FxCk');
  26484. prog->version = vst_swap (fxbVersionNum);
  26485. prog->fxID = vst_swap (getUID());
  26486. prog->fxVersion = vst_swap (getVersionNumber());
  26487. prog->numParams = vst_swap (numParams);
  26488. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  26489. for (int i = 0; i < numParams; ++i)
  26490. prog->params[i] = vst_swapFloat (getParameter (i));
  26491. }
  26492. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26493. {
  26494. const int numPrograms = getNumPrograms();
  26495. const int numParams = getNumParameters();
  26496. if (usesChunks())
  26497. {
  26498. if (isFXB)
  26499. {
  26500. MemoryBlock chunk;
  26501. getChunkData (chunk, false, maxSizeMB);
  26502. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26503. dest.setSize (totalLen, true);
  26504. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  26505. set->chunkMagic = vst_swap ('CcnK');
  26506. set->byteSize = 0;
  26507. set->fxMagic = vst_swap ('FBCh');
  26508. set->version = vst_swap (fxbVersionNum);
  26509. set->fxID = vst_swap (getUID());
  26510. set->fxVersion = vst_swap (getVersionNumber());
  26511. set->numPrograms = vst_swap (numPrograms);
  26512. set->chunkSize = vst_swap (chunk.getSize());
  26513. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26514. }
  26515. else
  26516. {
  26517. MemoryBlock chunk;
  26518. getChunkData (chunk, true, maxSizeMB);
  26519. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  26520. dest.setSize (totalLen, true);
  26521. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  26522. set->chunkMagic = vst_swap ('CcnK');
  26523. set->byteSize = 0;
  26524. set->fxMagic = vst_swap ('FPCh');
  26525. set->version = vst_swap (fxbVersionNum);
  26526. set->fxID = vst_swap (getUID());
  26527. set->fxVersion = vst_swap (getVersionNumber());
  26528. set->numPrograms = vst_swap (numPrograms);
  26529. set->chunkSize = vst_swap (chunk.getSize());
  26530. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  26531. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26532. }
  26533. }
  26534. else
  26535. {
  26536. if (isFXB)
  26537. {
  26538. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26539. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  26540. dest.setSize (len, true);
  26541. fxSet* const set = (fxSet*) dest.getData();
  26542. set->chunkMagic = vst_swap ('CcnK');
  26543. set->byteSize = 0;
  26544. set->fxMagic = vst_swap ('FxBk');
  26545. set->version = vst_swap (fxbVersionNum);
  26546. set->fxID = vst_swap (getUID());
  26547. set->fxVersion = vst_swap (getVersionNumber());
  26548. set->numPrograms = vst_swap (numPrograms);
  26549. const int oldProgram = getCurrentProgram();
  26550. MemoryBlock oldSettings;
  26551. createTempParameterStore (oldSettings);
  26552. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  26553. for (int i = 0; i < numPrograms; ++i)
  26554. {
  26555. if (i != oldProgram)
  26556. {
  26557. setCurrentProgram (i);
  26558. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  26559. }
  26560. }
  26561. setCurrentProgram (oldProgram);
  26562. restoreFromTempParameterStore (oldSettings);
  26563. }
  26564. else
  26565. {
  26566. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26567. dest.setSize (totalLen, true);
  26568. setParamsInProgramBlock ((fxProgram*) dest.getData());
  26569. }
  26570. }
  26571. return true;
  26572. }
  26573. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  26574. {
  26575. if (usesChunks())
  26576. {
  26577. void* data = 0;
  26578. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  26579. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  26580. {
  26581. mb.setSize (bytes);
  26582. mb.copyFrom (data, 0, bytes);
  26583. }
  26584. }
  26585. }
  26586. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  26587. {
  26588. if (size > 0 && usesChunks())
  26589. {
  26590. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  26591. if (! isPreset)
  26592. updateStoredProgramNames();
  26593. }
  26594. }
  26595. void VSTPluginInstance::timerCallback()
  26596. {
  26597. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  26598. stopTimer();
  26599. }
  26600. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  26601. {
  26602. const ScopedLock sl (lock);
  26603. ++insideVSTCallback;
  26604. int result = 0;
  26605. try
  26606. {
  26607. if (effect != 0)
  26608. {
  26609. #if JUCE_MAC
  26610. if (module->resFileId != 0)
  26611. UseResFile (module->resFileId);
  26612. CGrafPtr oldPort;
  26613. if (getActiveEditor() != 0)
  26614. {
  26615. int x = 0, y = 0;
  26616. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  26617. GetPort (&oldPort);
  26618. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  26619. SetOrigin (-x, -y);
  26620. }
  26621. #endif
  26622. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  26623. #if JUCE_MAC
  26624. if (getActiveEditor() != 0)
  26625. SetPort (oldPort);
  26626. module->resFileId = CurResFile();
  26627. #endif
  26628. --insideVSTCallback;
  26629. return result;
  26630. }
  26631. }
  26632. catch (...)
  26633. {
  26634. //char s[512];
  26635. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  26636. }
  26637. --insideVSTCallback;
  26638. return result;
  26639. }
  26640. // handles non plugin-specific callbacks..
  26641. static const int defaultVSTSampleRateValue = 16384;
  26642. static const int defaultVSTBlockSizeValue = 512;
  26643. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26644. {
  26645. (void) index;
  26646. (void) value;
  26647. (void) opt;
  26648. switch (opcode)
  26649. {
  26650. case audioMasterCanDo:
  26651. {
  26652. static const char* canDos[] = { "supplyIdle",
  26653. "sendVstEvents",
  26654. "sendVstMidiEvent",
  26655. "sendVstTimeInfo",
  26656. "receiveVstEvents",
  26657. "receiveVstMidiEvent",
  26658. "supportShell",
  26659. "shellCategory" };
  26660. for (int i = 0; i < numElementsInArray (canDos); ++i)
  26661. if (strcmp (canDos[i], (const char*) ptr) == 0)
  26662. return 1;
  26663. return 0;
  26664. }
  26665. case audioMasterVersion:
  26666. return 0x2400;
  26667. case audioMasterCurrentId:
  26668. return shellUIDToCreate;
  26669. case audioMasterGetNumAutomatableParameters:
  26670. return 0;
  26671. case audioMasterGetAutomationState:
  26672. return 1;
  26673. case audioMasterGetVendorVersion:
  26674. return 0x0101;
  26675. case audioMasterGetVendorString:
  26676. case audioMasterGetProductString:
  26677. {
  26678. String hostName ("Juce VST Host");
  26679. if (JUCEApplication::getInstance() != 0)
  26680. hostName = JUCEApplication::getInstance()->getApplicationName();
  26681. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  26682. }
  26683. break;
  26684. case audioMasterGetSampleRate:
  26685. return (VstIntPtr) defaultVSTSampleRateValue;
  26686. case audioMasterGetBlockSize:
  26687. return (VstIntPtr) defaultVSTBlockSizeValue;
  26688. case audioMasterSetOutputSampleRate:
  26689. return 0;
  26690. default:
  26691. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  26692. break;
  26693. }
  26694. return 0;
  26695. }
  26696. // handles callbacks for a specific plugin
  26697. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26698. {
  26699. switch (opcode)
  26700. {
  26701. case audioMasterAutomate:
  26702. sendParamChangeMessageToListeners (index, opt);
  26703. break;
  26704. case audioMasterProcessEvents:
  26705. handleMidiFromPlugin ((const VstEvents*) ptr);
  26706. break;
  26707. case audioMasterGetTime:
  26708. #ifdef _MSC_VER
  26709. #pragma warning (push)
  26710. #pragma warning (disable: 4311)
  26711. #endif
  26712. return (VstIntPtr) &vstHostTime;
  26713. #ifdef _MSC_VER
  26714. #pragma warning (pop)
  26715. #endif
  26716. break;
  26717. case audioMasterIdle:
  26718. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  26719. {
  26720. ++insideVSTCallback;
  26721. #if JUCE_MAC
  26722. if (getActiveEditor() != 0)
  26723. dispatch (effEditIdle, 0, 0, 0, 0);
  26724. #endif
  26725. juce_callAnyTimersSynchronously();
  26726. handleUpdateNowIfNeeded();
  26727. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  26728. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  26729. --insideVSTCallback;
  26730. }
  26731. break;
  26732. case audioMasterUpdateDisplay:
  26733. triggerAsyncUpdate();
  26734. break;
  26735. case audioMasterTempoAt:
  26736. // returns (10000 * bpm)
  26737. break;
  26738. case audioMasterNeedIdle:
  26739. startTimer (50);
  26740. break;
  26741. case audioMasterSizeWindow:
  26742. if (getActiveEditor() != 0)
  26743. getActiveEditor()->setSize (index, value);
  26744. return 1;
  26745. case audioMasterGetSampleRate:
  26746. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  26747. case audioMasterGetBlockSize:
  26748. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  26749. case audioMasterWantMidi:
  26750. wantsMidiMessages = true;
  26751. break;
  26752. case audioMasterGetDirectory:
  26753. #if JUCE_MAC
  26754. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  26755. #else
  26756. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  26757. #endif
  26758. case audioMasterGetAutomationState:
  26759. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  26760. break;
  26761. // none of these are handled (yet)..
  26762. case audioMasterBeginEdit:
  26763. case audioMasterEndEdit:
  26764. case audioMasterSetTime:
  26765. case audioMasterPinConnected:
  26766. case audioMasterGetParameterQuantization:
  26767. case audioMasterIOChanged:
  26768. case audioMasterGetInputLatency:
  26769. case audioMasterGetOutputLatency:
  26770. case audioMasterGetPreviousPlug:
  26771. case audioMasterGetNextPlug:
  26772. case audioMasterWillReplaceOrAccumulate:
  26773. case audioMasterGetCurrentProcessLevel:
  26774. case audioMasterOfflineStart:
  26775. case audioMasterOfflineRead:
  26776. case audioMasterOfflineWrite:
  26777. case audioMasterOfflineGetCurrentPass:
  26778. case audioMasterOfflineGetCurrentMetaPass:
  26779. case audioMasterVendorSpecific:
  26780. case audioMasterSetIcon:
  26781. case audioMasterGetLanguage:
  26782. case audioMasterOpenWindow:
  26783. case audioMasterCloseWindow:
  26784. break;
  26785. default:
  26786. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26787. }
  26788. return 0;
  26789. }
  26790. // entry point for all callbacks from the plugin
  26791. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  26792. {
  26793. try
  26794. {
  26795. if (effect != 0 && effect->resvd2 != 0)
  26796. {
  26797. return ((VSTPluginInstance*)(effect->resvd2))
  26798. ->handleCallback (opcode, index, value, ptr, opt);
  26799. }
  26800. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26801. }
  26802. catch (...)
  26803. {
  26804. return 0;
  26805. }
  26806. }
  26807. const String VSTPluginInstance::getVersion() const throw()
  26808. {
  26809. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  26810. String s;
  26811. if (v == 0 || v == -1)
  26812. v = getVersionNumber();
  26813. if (v != 0)
  26814. {
  26815. int versionBits[4];
  26816. int n = 0;
  26817. while (v != 0)
  26818. {
  26819. versionBits [n++] = (v & 0xff);
  26820. v >>= 8;
  26821. }
  26822. s << 'V';
  26823. while (n > 0)
  26824. {
  26825. s << versionBits [--n];
  26826. if (n > 0)
  26827. s << '.';
  26828. }
  26829. }
  26830. return s;
  26831. }
  26832. int VSTPluginInstance::getUID() const throw()
  26833. {
  26834. int uid = effect != 0 ? effect->uniqueID : 0;
  26835. if (uid == 0)
  26836. uid = module->file.hashCode();
  26837. return uid;
  26838. }
  26839. const String VSTPluginInstance::getCategory() const throw()
  26840. {
  26841. const char* result = 0;
  26842. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  26843. {
  26844. case kPlugCategEffect:
  26845. result = "Effect";
  26846. break;
  26847. case kPlugCategSynth:
  26848. result = "Synth";
  26849. break;
  26850. case kPlugCategAnalysis:
  26851. result = "Anaylsis";
  26852. break;
  26853. case kPlugCategMastering:
  26854. result = "Mastering";
  26855. break;
  26856. case kPlugCategSpacializer:
  26857. result = "Spacial";
  26858. break;
  26859. case kPlugCategRoomFx:
  26860. result = "Reverb";
  26861. break;
  26862. case kPlugSurroundFx:
  26863. result = "Surround";
  26864. break;
  26865. case kPlugCategRestoration:
  26866. result = "Restoration";
  26867. break;
  26868. case kPlugCategGenerator:
  26869. result = "Tone generation";
  26870. break;
  26871. default:
  26872. break;
  26873. }
  26874. return result;
  26875. }
  26876. float VSTPluginInstance::getParameter (int index)
  26877. {
  26878. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26879. {
  26880. try
  26881. {
  26882. const ScopedLock sl (lock);
  26883. return effect->getParameter (effect, index);
  26884. }
  26885. catch (...)
  26886. {
  26887. }
  26888. }
  26889. return 0.0f;
  26890. }
  26891. void VSTPluginInstance::setParameter (int index, float newValue)
  26892. {
  26893. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26894. {
  26895. try
  26896. {
  26897. const ScopedLock sl (lock);
  26898. if (effect->getParameter (effect, index) != newValue)
  26899. effect->setParameter (effect, index, newValue);
  26900. }
  26901. catch (...)
  26902. {
  26903. }
  26904. }
  26905. }
  26906. const String VSTPluginInstance::getParameterName (int index)
  26907. {
  26908. if (effect != 0)
  26909. {
  26910. jassert (index >= 0 && index < effect->numParams);
  26911. char nm [256];
  26912. zerostruct (nm);
  26913. dispatch (effGetParamName, index, 0, nm, 0);
  26914. return String (nm).trim();
  26915. }
  26916. return String::empty;
  26917. }
  26918. const String VSTPluginInstance::getParameterLabel (int index) const
  26919. {
  26920. if (effect != 0)
  26921. {
  26922. jassert (index >= 0 && index < effect->numParams);
  26923. char nm [256];
  26924. zerostruct (nm);
  26925. dispatch (effGetParamLabel, index, 0, nm, 0);
  26926. return String (nm).trim();
  26927. }
  26928. return String::empty;
  26929. }
  26930. const String VSTPluginInstance::getParameterText (int index)
  26931. {
  26932. if (effect != 0)
  26933. {
  26934. jassert (index >= 0 && index < effect->numParams);
  26935. char nm [256];
  26936. zerostruct (nm);
  26937. dispatch (effGetParamDisplay, index, 0, nm, 0);
  26938. return String (nm).trim();
  26939. }
  26940. return String::empty;
  26941. }
  26942. bool VSTPluginInstance::isParameterAutomatable (int index) const
  26943. {
  26944. if (effect != 0)
  26945. {
  26946. jassert (index >= 0 && index < effect->numParams);
  26947. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  26948. }
  26949. return false;
  26950. }
  26951. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  26952. {
  26953. dest.setSize (64 + 4 * getNumParameters());
  26954. dest.fillWith (0);
  26955. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  26956. float* const p = (float*) (((char*) dest.getData()) + 64);
  26957. for (int i = 0; i < getNumParameters(); ++i)
  26958. p[i] = getParameter(i);
  26959. }
  26960. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  26961. {
  26962. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  26963. float* p = (float*) (((char*) m.getData()) + 64);
  26964. for (int i = 0; i < getNumParameters(); ++i)
  26965. setParameter (i, p[i]);
  26966. }
  26967. void VSTPluginInstance::setCurrentProgram (int newIndex)
  26968. {
  26969. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  26970. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  26971. }
  26972. const String VSTPluginInstance::getProgramName (int index)
  26973. {
  26974. if (index == getCurrentProgram())
  26975. {
  26976. return getCurrentProgramName();
  26977. }
  26978. else if (effect != 0)
  26979. {
  26980. char nm [256];
  26981. zerostruct (nm);
  26982. if (dispatch (effGetProgramNameIndexed,
  26983. jlimit (0, getNumPrograms(), index),
  26984. -1, nm, 0) != 0)
  26985. {
  26986. return String (nm).trim();
  26987. }
  26988. }
  26989. return programNames [index];
  26990. }
  26991. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  26992. {
  26993. if (index == getCurrentProgram())
  26994. {
  26995. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  26996. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  26997. }
  26998. else
  26999. {
  27000. jassertfalse // xxx not implemented!
  27001. }
  27002. }
  27003. void VSTPluginInstance::updateStoredProgramNames()
  27004. {
  27005. if (effect != 0 && getNumPrograms() > 0)
  27006. {
  27007. char nm [256];
  27008. zerostruct (nm);
  27009. // only do this if the plugin can't use indexed names..
  27010. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27011. {
  27012. const int oldProgram = getCurrentProgram();
  27013. MemoryBlock oldSettings;
  27014. createTempParameterStore (oldSettings);
  27015. for (int i = 0; i < getNumPrograms(); ++i)
  27016. {
  27017. setCurrentProgram (i);
  27018. getCurrentProgramName(); // (this updates the list)
  27019. }
  27020. setCurrentProgram (oldProgram);
  27021. restoreFromTempParameterStore (oldSettings);
  27022. }
  27023. }
  27024. }
  27025. const String VSTPluginInstance::getCurrentProgramName()
  27026. {
  27027. if (effect != 0)
  27028. {
  27029. char nm [256];
  27030. zerostruct (nm);
  27031. dispatch (effGetProgramName, 0, 0, nm, 0);
  27032. const int index = getCurrentProgram();
  27033. if (programNames[index].isEmpty())
  27034. {
  27035. while (programNames.size() < index)
  27036. programNames.add (String::empty);
  27037. programNames.set (index, String (nm).trim());
  27038. }
  27039. return String (nm).trim();
  27040. }
  27041. return String::empty;
  27042. }
  27043. const String VSTPluginInstance::getInputChannelName (const int index) const
  27044. {
  27045. if (index >= 0 && index < getNumInputChannels())
  27046. {
  27047. VstPinProperties pinProps;
  27048. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27049. return String (pinProps.label, sizeof (pinProps.label));
  27050. }
  27051. return String::empty;
  27052. }
  27053. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27054. {
  27055. if (index < 0 || index >= getNumInputChannels())
  27056. return false;
  27057. VstPinProperties pinProps;
  27058. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27059. return (pinProps.flags & kVstPinIsStereo) != 0;
  27060. return true;
  27061. }
  27062. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27063. {
  27064. if (index >= 0 && index < getNumOutputChannels())
  27065. {
  27066. VstPinProperties pinProps;
  27067. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27068. return String (pinProps.label, sizeof (pinProps.label));
  27069. }
  27070. return String::empty;
  27071. }
  27072. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27073. {
  27074. if (index < 0 || index >= getNumOutputChannels())
  27075. return false;
  27076. VstPinProperties pinProps;
  27077. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27078. return (pinProps.flags & kVstPinIsStereo) != 0;
  27079. return true;
  27080. }
  27081. void VSTPluginInstance::setPower (const bool on)
  27082. {
  27083. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27084. isPowerOn = on;
  27085. }
  27086. const int defaultMaxSizeMB = 64;
  27087. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27088. {
  27089. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27090. }
  27091. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27092. {
  27093. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27094. }
  27095. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27096. {
  27097. loadFromFXBFile (data, sizeInBytes);
  27098. }
  27099. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27100. {
  27101. loadFromFXBFile (data, sizeInBytes);
  27102. }
  27103. VSTPluginFormat::VSTPluginFormat()
  27104. {
  27105. }
  27106. VSTPluginFormat::~VSTPluginFormat()
  27107. {
  27108. }
  27109. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27110. const String& fileOrIdentifier)
  27111. {
  27112. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27113. return;
  27114. PluginDescription desc;
  27115. desc.fileOrIdentifier = fileOrIdentifier;
  27116. desc.uid = 0;
  27117. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  27118. if (instance == 0)
  27119. return;
  27120. try
  27121. {
  27122. #if JUCE_MAC
  27123. if (instance->module->resFileId != 0)
  27124. UseResFile (instance->module->resFileId);
  27125. #endif
  27126. instance->fillInPluginDescription (desc);
  27127. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27128. if (category != kPlugCategShell)
  27129. {
  27130. // Normal plugin...
  27131. results.add (new PluginDescription (desc));
  27132. ++insideVSTCallback;
  27133. instance->dispatch (effOpen, 0, 0, 0, 0);
  27134. --insideVSTCallback;
  27135. }
  27136. else
  27137. {
  27138. // It's a shell plugin, so iterate all the subtypes...
  27139. char shellEffectName [64];
  27140. for (;;)
  27141. {
  27142. zerostruct (shellEffectName);
  27143. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27144. if (uid == 0)
  27145. {
  27146. break;
  27147. }
  27148. else
  27149. {
  27150. desc.uid = uid;
  27151. desc.name = shellEffectName;
  27152. bool alreadyThere = false;
  27153. for (int i = results.size(); --i >= 0;)
  27154. {
  27155. PluginDescription* const d = results.getUnchecked(i);
  27156. if (d->isDuplicateOf (desc))
  27157. {
  27158. alreadyThere = true;
  27159. break;
  27160. }
  27161. }
  27162. if (! alreadyThere)
  27163. results.add (new PluginDescription (desc));
  27164. }
  27165. }
  27166. }
  27167. }
  27168. catch (...)
  27169. {
  27170. // crashed while loading...
  27171. }
  27172. deleteAndZero (instance);
  27173. }
  27174. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27175. {
  27176. VSTPluginInstance* result = 0;
  27177. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27178. {
  27179. File file (desc.fileOrIdentifier);
  27180. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27181. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27182. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27183. if (module != 0)
  27184. {
  27185. shellUIDToCreate = desc.uid;
  27186. result = new VSTPluginInstance (module);
  27187. if (result->effect != 0)
  27188. {
  27189. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  27190. result->initialise();
  27191. }
  27192. else
  27193. {
  27194. deleteAndZero (result);
  27195. }
  27196. }
  27197. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27198. }
  27199. return result;
  27200. }
  27201. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27202. {
  27203. const File f (fileOrIdentifier);
  27204. #if JUCE_MAC
  27205. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  27206. return true;
  27207. #if JUCE_PPC
  27208. FSRef fileRef;
  27209. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27210. {
  27211. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27212. if (resFileId != -1)
  27213. {
  27214. const int numEffects = Count1Resources ('aEff');
  27215. CloseResFile (resFileId);
  27216. if (numEffects > 0)
  27217. return true;
  27218. }
  27219. }
  27220. #endif
  27221. return false;
  27222. #elif JUCE_WIN32
  27223. return f.existsAsFile()
  27224. && f.hasFileExtension (T(".dll"));
  27225. #elif JUCE_LINUX
  27226. return f.existsAsFile()
  27227. && f.hasFileExtension (T(".so"));
  27228. #endif
  27229. }
  27230. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27231. {
  27232. return fileOrIdentifier;
  27233. }
  27234. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27235. {
  27236. return File (desc.fileOrIdentifier).exists();
  27237. }
  27238. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27239. {
  27240. StringArray results;
  27241. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27242. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27243. return results;
  27244. }
  27245. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27246. {
  27247. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27248. // .component or .vst directories.
  27249. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27250. while (iter.next())
  27251. {
  27252. const File f (iter.getFile());
  27253. bool isPlugin = false;
  27254. if (fileMightContainThisPluginType (f.getFullPathName()))
  27255. {
  27256. isPlugin = true;
  27257. results.add (f.getFullPathName());
  27258. }
  27259. if (recursive && (! isPlugin) && f.isDirectory())
  27260. recursiveFileSearch (results, f, true);
  27261. }
  27262. }
  27263. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27264. {
  27265. #if JUCE_MAC
  27266. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27267. #elif JUCE_WIN32
  27268. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27269. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27270. #elif JUCE_LINUX
  27271. return FileSearchPath ("/usr/lib/vst");
  27272. #endif
  27273. }
  27274. END_JUCE_NAMESPACE
  27275. #endif
  27276. #undef log
  27277. #endif
  27278. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  27279. /********* End of inlined file: juce_VSTPluginFormat.mm *********/
  27280. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  27281. BEGIN_JUCE_NAMESPACE
  27282. AudioProcessor::AudioProcessor()
  27283. : playHead (0),
  27284. activeEditor (0),
  27285. sampleRate (0),
  27286. blockSize (0),
  27287. numInputChannels (0),
  27288. numOutputChannels (0),
  27289. latencySamples (0),
  27290. suspended (false),
  27291. nonRealtime (false)
  27292. {
  27293. }
  27294. AudioProcessor::~AudioProcessor()
  27295. {
  27296. // ooh, nasty - the editor should have been deleted before the filter
  27297. // that it refers to is deleted..
  27298. jassert (activeEditor == 0);
  27299. #ifdef JUCE_DEBUG
  27300. // This will fail if you've called beginParameterChangeGesture() for one
  27301. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27302. jassert (changingParams.countNumberOfSetBits() == 0);
  27303. #endif
  27304. }
  27305. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27306. {
  27307. playHead = newPlayHead;
  27308. }
  27309. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27310. {
  27311. const ScopedLock sl (listenerLock);
  27312. listeners.addIfNotAlreadyThere (newListener);
  27313. }
  27314. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27315. {
  27316. const ScopedLock sl (listenerLock);
  27317. listeners.removeValue (listenerToRemove);
  27318. }
  27319. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27320. const int numOuts,
  27321. const double sampleRate_,
  27322. const int blockSize_) throw()
  27323. {
  27324. numInputChannels = numIns;
  27325. numOutputChannels = numOuts;
  27326. sampleRate = sampleRate_;
  27327. blockSize = blockSize_;
  27328. }
  27329. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27330. {
  27331. nonRealtime = nonRealtime_;
  27332. }
  27333. void AudioProcessor::setLatencySamples (const int newLatency)
  27334. {
  27335. if (latencySamples != newLatency)
  27336. {
  27337. latencySamples = newLatency;
  27338. updateHostDisplay();
  27339. }
  27340. }
  27341. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27342. const float newValue)
  27343. {
  27344. setParameter (parameterIndex, newValue);
  27345. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27346. }
  27347. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27348. {
  27349. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  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->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27357. }
  27358. }
  27359. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27360. {
  27361. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27362. #ifdef JUCE_DEBUG
  27363. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27364. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27365. jassert (! changingParams [parameterIndex]);
  27366. changingParams.setBit (parameterIndex);
  27367. #endif
  27368. for (int i = listeners.size(); --i >= 0;)
  27369. {
  27370. listenerLock.enter();
  27371. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27372. listenerLock.exit();
  27373. if (l != 0)
  27374. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27375. }
  27376. }
  27377. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27378. {
  27379. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27380. #ifdef JUCE_DEBUG
  27381. // This means you've called endParameterChangeGesture without having previously called
  27382. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27383. // calls matched correctly.
  27384. jassert (changingParams [parameterIndex]);
  27385. changingParams.clearBit (parameterIndex);
  27386. #endif
  27387. for (int i = listeners.size(); --i >= 0;)
  27388. {
  27389. listenerLock.enter();
  27390. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27391. listenerLock.exit();
  27392. if (l != 0)
  27393. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27394. }
  27395. }
  27396. void AudioProcessor::updateHostDisplay()
  27397. {
  27398. for (int i = listeners.size(); --i >= 0;)
  27399. {
  27400. listenerLock.enter();
  27401. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27402. listenerLock.exit();
  27403. if (l != 0)
  27404. l->audioProcessorChanged (this);
  27405. }
  27406. }
  27407. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27408. {
  27409. return true;
  27410. }
  27411. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27412. {
  27413. return false;
  27414. }
  27415. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27416. {
  27417. const ScopedLock sl (callbackLock);
  27418. suspended = shouldBeSuspended;
  27419. }
  27420. void AudioProcessor::reset()
  27421. {
  27422. }
  27423. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27424. {
  27425. const ScopedLock sl (callbackLock);
  27426. jassert (activeEditor == editor);
  27427. if (activeEditor == editor)
  27428. activeEditor = 0;
  27429. }
  27430. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27431. {
  27432. if (activeEditor != 0)
  27433. return activeEditor;
  27434. AudioProcessorEditor* const ed = createEditor();
  27435. if (ed != 0)
  27436. {
  27437. // you must give your editor comp a size before returning it..
  27438. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27439. const ScopedLock sl (callbackLock);
  27440. activeEditor = ed;
  27441. }
  27442. return ed;
  27443. }
  27444. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27445. {
  27446. getStateInformation (destData);
  27447. }
  27448. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27449. {
  27450. setStateInformation (data, sizeInBytes);
  27451. }
  27452. // magic number to identify memory blocks that we've stored as XML
  27453. const uint32 magicXmlNumber = 0x21324356;
  27454. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27455. JUCE_NAMESPACE::MemoryBlock& destData)
  27456. {
  27457. const String xmlString (xml.createDocument (String::empty, true, false));
  27458. const int stringLength = xmlString.length();
  27459. destData.setSize (stringLength + 10);
  27460. char* const d = (char*) destData.getData();
  27461. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  27462. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  27463. xmlString.copyToBuffer (d + 8, stringLength);
  27464. }
  27465. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27466. const int sizeInBytes)
  27467. {
  27468. if (sizeInBytes > 8
  27469. && littleEndianInt ((const char*) data) == magicXmlNumber)
  27470. {
  27471. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  27472. if (stringLength > 0)
  27473. {
  27474. XmlDocument doc (String (((const char*) data) + 8,
  27475. jmin ((sizeInBytes - 8), stringLength)));
  27476. return doc.getDocumentElement();
  27477. }
  27478. }
  27479. return 0;
  27480. }
  27481. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27482. {
  27483. }
  27484. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27485. {
  27486. }
  27487. END_JUCE_NAMESPACE
  27488. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  27489. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  27490. BEGIN_JUCE_NAMESPACE
  27491. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  27492. : owner (owner_)
  27493. {
  27494. // the filter must be valid..
  27495. jassert (owner != 0);
  27496. }
  27497. AudioProcessorEditor::~AudioProcessorEditor()
  27498. {
  27499. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  27500. // filter for some reason..
  27501. jassert (owner->getActiveEditor() != this);
  27502. }
  27503. END_JUCE_NAMESPACE
  27504. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  27505. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  27506. BEGIN_JUCE_NAMESPACE
  27507. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  27508. AudioProcessorGraph::Node::Node (const uint32 id_,
  27509. AudioProcessor* const processor_) throw()
  27510. : id (id_),
  27511. processor (processor_),
  27512. isPrepared (false)
  27513. {
  27514. jassert (processor_ != 0);
  27515. }
  27516. AudioProcessorGraph::Node::~Node()
  27517. {
  27518. delete processor;
  27519. }
  27520. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  27521. AudioProcessorGraph* const graph)
  27522. {
  27523. if (! isPrepared)
  27524. {
  27525. isPrepared = true;
  27526. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27527. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  27528. if (ioProc != 0)
  27529. ioProc->setParentGraph (graph);
  27530. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  27531. processor->getNumOutputChannels(),
  27532. sampleRate, blockSize);
  27533. processor->prepareToPlay (sampleRate, blockSize);
  27534. }
  27535. }
  27536. void AudioProcessorGraph::Node::unprepare()
  27537. {
  27538. if (isPrepared)
  27539. {
  27540. isPrepared = false;
  27541. processor->releaseResources();
  27542. }
  27543. }
  27544. AudioProcessorGraph::AudioProcessorGraph()
  27545. : lastNodeId (0),
  27546. renderingBuffers (1, 1),
  27547. currentAudioOutputBuffer (1, 1)
  27548. {
  27549. }
  27550. AudioProcessorGraph::~AudioProcessorGraph()
  27551. {
  27552. clearRenderingSequence();
  27553. clear();
  27554. }
  27555. const String AudioProcessorGraph::getName() const
  27556. {
  27557. return "Audio Graph";
  27558. }
  27559. void AudioProcessorGraph::clear()
  27560. {
  27561. nodes.clear();
  27562. connections.clear();
  27563. triggerAsyncUpdate();
  27564. }
  27565. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  27566. {
  27567. for (int i = nodes.size(); --i >= 0;)
  27568. if (nodes.getUnchecked(i)->id == nodeId)
  27569. return nodes.getUnchecked(i);
  27570. return 0;
  27571. }
  27572. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  27573. uint32 nodeId)
  27574. {
  27575. if (newProcessor == 0)
  27576. {
  27577. jassertfalse
  27578. return 0;
  27579. }
  27580. if (nodeId == 0)
  27581. {
  27582. nodeId = ++lastNodeId;
  27583. }
  27584. else
  27585. {
  27586. // you can't add a node with an id that already exists in the graph..
  27587. jassert (getNodeForId (nodeId) == 0);
  27588. removeNode (nodeId);
  27589. }
  27590. lastNodeId = nodeId;
  27591. Node* const n = new Node (nodeId, newProcessor);
  27592. nodes.add (n);
  27593. triggerAsyncUpdate();
  27594. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27595. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  27596. if (ioProc != 0)
  27597. ioProc->setParentGraph (this);
  27598. return n;
  27599. }
  27600. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  27601. {
  27602. disconnectNode (nodeId);
  27603. for (int i = nodes.size(); --i >= 0;)
  27604. {
  27605. if (nodes.getUnchecked(i)->id == nodeId)
  27606. {
  27607. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27608. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  27609. if (ioProc != 0)
  27610. ioProc->setParentGraph (0);
  27611. nodes.remove (i);
  27612. triggerAsyncUpdate();
  27613. return true;
  27614. }
  27615. }
  27616. return false;
  27617. }
  27618. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  27619. const int sourceChannelIndex,
  27620. const uint32 destNodeId,
  27621. const int destChannelIndex) const throw()
  27622. {
  27623. for (int i = connections.size(); --i >= 0;)
  27624. {
  27625. const Connection* const c = connections.getUnchecked(i);
  27626. if (c->sourceNodeId == sourceNodeId
  27627. && c->destNodeId == destNodeId
  27628. && c->sourceChannelIndex == sourceChannelIndex
  27629. && c->destChannelIndex == destChannelIndex)
  27630. {
  27631. return c;
  27632. }
  27633. }
  27634. return 0;
  27635. }
  27636. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  27637. const uint32 possibleDestNodeId) const throw()
  27638. {
  27639. for (int i = connections.size(); --i >= 0;)
  27640. {
  27641. const Connection* const c = connections.getUnchecked(i);
  27642. if (c->sourceNodeId == possibleSourceNodeId
  27643. && c->destNodeId == possibleDestNodeId)
  27644. {
  27645. return true;
  27646. }
  27647. }
  27648. return false;
  27649. }
  27650. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  27651. const int sourceChannelIndex,
  27652. const uint32 destNodeId,
  27653. const int destChannelIndex) const throw()
  27654. {
  27655. if (sourceChannelIndex < 0
  27656. || destChannelIndex < 0
  27657. || sourceNodeId == destNodeId
  27658. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  27659. return false;
  27660. const Node* const source = getNodeForId (sourceNodeId);
  27661. if (source == 0
  27662. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  27663. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  27664. return false;
  27665. const Node* const dest = getNodeForId (destNodeId);
  27666. if (dest == 0
  27667. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  27668. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  27669. return false;
  27670. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  27671. destNodeId, destChannelIndex) == 0;
  27672. }
  27673. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  27674. const int sourceChannelIndex,
  27675. const uint32 destNodeId,
  27676. const int destChannelIndex)
  27677. {
  27678. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  27679. return false;
  27680. Connection* const c = new Connection();
  27681. c->sourceNodeId = sourceNodeId;
  27682. c->sourceChannelIndex = sourceChannelIndex;
  27683. c->destNodeId = destNodeId;
  27684. c->destChannelIndex = destChannelIndex;
  27685. connections.add (c);
  27686. triggerAsyncUpdate();
  27687. return true;
  27688. }
  27689. void AudioProcessorGraph::removeConnection (const int index)
  27690. {
  27691. connections.remove (index);
  27692. triggerAsyncUpdate();
  27693. }
  27694. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  27695. const uint32 destNodeId, const int destChannelIndex)
  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 == sourceNodeId
  27702. && c->destNodeId == destNodeId
  27703. && c->sourceChannelIndex == sourceChannelIndex
  27704. && c->destChannelIndex == destChannelIndex)
  27705. {
  27706. removeConnection (i);
  27707. doneAnything = true;
  27708. triggerAsyncUpdate();
  27709. }
  27710. }
  27711. return doneAnything;
  27712. }
  27713. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  27714. {
  27715. bool doneAnything = false;
  27716. for (int i = connections.size(); --i >= 0;)
  27717. {
  27718. const Connection* const c = connections.getUnchecked(i);
  27719. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  27720. {
  27721. removeConnection (i);
  27722. doneAnything = true;
  27723. triggerAsyncUpdate();
  27724. }
  27725. }
  27726. return doneAnything;
  27727. }
  27728. bool AudioProcessorGraph::removeIllegalConnections()
  27729. {
  27730. bool doneAnything = false;
  27731. for (int i = connections.size(); --i >= 0;)
  27732. {
  27733. const Connection* const c = connections.getUnchecked(i);
  27734. const Node* const source = getNodeForId (c->sourceNodeId);
  27735. const Node* const dest = getNodeForId (c->destNodeId);
  27736. if (source == 0 || dest == 0
  27737. || (c->sourceChannelIndex != midiChannelIndex
  27738. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  27739. || (c->sourceChannelIndex == midiChannelIndex
  27740. && ! source->processor->producesMidi())
  27741. || (c->destChannelIndex != midiChannelIndex
  27742. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  27743. || (c->destChannelIndex == midiChannelIndex
  27744. && ! dest->processor->acceptsMidi()))
  27745. {
  27746. removeConnection (i);
  27747. doneAnything = true;
  27748. triggerAsyncUpdate();
  27749. }
  27750. }
  27751. return doneAnything;
  27752. }
  27753. namespace GraphRenderingOps
  27754. {
  27755. class AudioGraphRenderingOp
  27756. {
  27757. public:
  27758. AudioGraphRenderingOp() throw() {}
  27759. virtual ~AudioGraphRenderingOp() throw() {}
  27760. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  27761. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  27762. const int numSamples) throw() = 0;
  27763. juce_UseDebuggingNewOperator
  27764. };
  27765. class ClearChannelOp : public AudioGraphRenderingOp
  27766. {
  27767. public:
  27768. ClearChannelOp (const int channelNum_) throw()
  27769. : channelNum (channelNum_)
  27770. {}
  27771. ~ClearChannelOp() throw() {}
  27772. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27773. {
  27774. sharedBufferChans.clear (channelNum, 0, numSamples);
  27775. }
  27776. private:
  27777. const int channelNum;
  27778. ClearChannelOp (const ClearChannelOp&);
  27779. const ClearChannelOp& operator= (const ClearChannelOp&);
  27780. };
  27781. class CopyChannelOp : public AudioGraphRenderingOp
  27782. {
  27783. public:
  27784. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27785. : srcChannelNum (srcChannelNum_),
  27786. dstChannelNum (dstChannelNum_)
  27787. {}
  27788. ~CopyChannelOp() throw() {}
  27789. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27790. {
  27791. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27792. }
  27793. private:
  27794. const int srcChannelNum, dstChannelNum;
  27795. CopyChannelOp (const CopyChannelOp&);
  27796. const CopyChannelOp& operator= (const CopyChannelOp&);
  27797. };
  27798. class AddChannelOp : public AudioGraphRenderingOp
  27799. {
  27800. public:
  27801. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27802. : srcChannelNum (srcChannelNum_),
  27803. dstChannelNum (dstChannelNum_)
  27804. {}
  27805. ~AddChannelOp() throw() {}
  27806. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27807. {
  27808. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27809. }
  27810. private:
  27811. const int srcChannelNum, dstChannelNum;
  27812. AddChannelOp (const AddChannelOp&);
  27813. const AddChannelOp& operator= (const AddChannelOp&);
  27814. };
  27815. class ClearMidiBufferOp : public AudioGraphRenderingOp
  27816. {
  27817. public:
  27818. ClearMidiBufferOp (const int bufferNum_) throw()
  27819. : bufferNum (bufferNum_)
  27820. {}
  27821. ~ClearMidiBufferOp() throw() {}
  27822. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27823. {
  27824. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  27825. }
  27826. private:
  27827. const int bufferNum;
  27828. ClearMidiBufferOp (const ClearMidiBufferOp&);
  27829. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  27830. };
  27831. class CopyMidiBufferOp : public AudioGraphRenderingOp
  27832. {
  27833. public:
  27834. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27835. : srcBufferNum (srcBufferNum_),
  27836. dstBufferNum (dstBufferNum_)
  27837. {}
  27838. ~CopyMidiBufferOp() throw() {}
  27839. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27840. {
  27841. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  27842. }
  27843. private:
  27844. const int srcBufferNum, dstBufferNum;
  27845. CopyMidiBufferOp (const CopyMidiBufferOp&);
  27846. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  27847. };
  27848. class AddMidiBufferOp : public AudioGraphRenderingOp
  27849. {
  27850. public:
  27851. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27852. : srcBufferNum (srcBufferNum_),
  27853. dstBufferNum (dstBufferNum_)
  27854. {}
  27855. ~AddMidiBufferOp() throw() {}
  27856. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27857. {
  27858. sharedMidiBuffers.getUnchecked (dstBufferNum)
  27859. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  27860. }
  27861. private:
  27862. const int srcBufferNum, dstBufferNum;
  27863. AddMidiBufferOp (const AddMidiBufferOp&);
  27864. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  27865. };
  27866. class ProcessBufferOp : public AudioGraphRenderingOp
  27867. {
  27868. public:
  27869. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  27870. const Array <int>& audioChannelsToUse_,
  27871. const int totalChans_,
  27872. const int midiBufferToUse_) throw()
  27873. : node (node_),
  27874. processor (node_->processor),
  27875. audioChannelsToUse (audioChannelsToUse_),
  27876. totalChans (jmax (1, totalChans_)),
  27877. midiBufferToUse (midiBufferToUse_)
  27878. {
  27879. channels = (float**) juce_calloc (sizeof (float*) * totalChans);
  27880. while (audioChannelsToUse.size() < totalChans)
  27881. audioChannelsToUse.add (0);
  27882. }
  27883. ~ProcessBufferOp() throw()
  27884. {
  27885. juce_free (channels);
  27886. }
  27887. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27888. {
  27889. for (int i = totalChans; --i >= 0;)
  27890. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  27891. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  27892. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  27893. }
  27894. const AudioProcessorGraph::Node::Ptr node;
  27895. AudioProcessor* const processor;
  27896. private:
  27897. Array <int> audioChannelsToUse;
  27898. float** channels;
  27899. int totalChans;
  27900. int midiBufferToUse;
  27901. ProcessBufferOp (const ProcessBufferOp&);
  27902. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  27903. };
  27904. /** Used to calculate the correct sequence of rendering ops needed, based on
  27905. the best re-use of shared buffers at each stage.
  27906. */
  27907. class RenderingOpSequenceCalculator
  27908. {
  27909. public:
  27910. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  27911. const VoidArray& orderedNodes_,
  27912. VoidArray& renderingOps)
  27913. : graph (graph_),
  27914. orderedNodes (orderedNodes_)
  27915. {
  27916. nodeIds.add (-2); // first buffer is read-only zeros
  27917. channels.add (0);
  27918. midiNodeIds.add (-2);
  27919. for (int i = 0; i < orderedNodes.size(); ++i)
  27920. {
  27921. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  27922. renderingOps, i);
  27923. markAnyUnusedBuffersAsFree (i);
  27924. }
  27925. }
  27926. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  27927. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  27928. juce_UseDebuggingNewOperator
  27929. private:
  27930. AudioProcessorGraph& graph;
  27931. const VoidArray& orderedNodes;
  27932. Array <int> nodeIds, channels, midiNodeIds;
  27933. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  27934. VoidArray& renderingOps,
  27935. const int ourRenderingIndex)
  27936. {
  27937. const int numIns = node->processor->getNumInputChannels();
  27938. const int numOuts = node->processor->getNumOutputChannels();
  27939. const int totalChans = jmax (numIns, numOuts);
  27940. Array <int> audioChannelsToUse;
  27941. int midiBufferToUse = -1;
  27942. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  27943. {
  27944. // get a list of all the inputs to this node
  27945. Array <int> sourceNodes, sourceOutputChans;
  27946. for (int i = graph.getNumConnections(); --i >= 0;)
  27947. {
  27948. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27949. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  27950. {
  27951. sourceNodes.add (c->sourceNodeId);
  27952. sourceOutputChans.add (c->sourceChannelIndex);
  27953. }
  27954. }
  27955. int bufIndex = -1;
  27956. if (sourceNodes.size() == 0)
  27957. {
  27958. // unconnected input channel
  27959. if (inputChan >= numOuts)
  27960. {
  27961. bufIndex = getReadOnlyEmptyBuffer();
  27962. jassert (bufIndex >= 0);
  27963. }
  27964. else
  27965. {
  27966. bufIndex = getFreeBuffer (false);
  27967. renderingOps.add (new ClearChannelOp (bufIndex));
  27968. }
  27969. }
  27970. else if (sourceNodes.size() == 1)
  27971. {
  27972. // channel with a straightforward single input..
  27973. const int srcNode = sourceNodes.getUnchecked(0);
  27974. const int srcChan = sourceOutputChans.getUnchecked(0);
  27975. bufIndex = getBufferContaining (srcNode, srcChan);
  27976. if (bufIndex < 0)
  27977. {
  27978. // if not found, this is probably a feedback loop
  27979. bufIndex = getReadOnlyEmptyBuffer();
  27980. jassert (bufIndex >= 0);
  27981. }
  27982. if (inputChan < numOuts
  27983. && isBufferNeededLater (ourRenderingIndex,
  27984. inputChan,
  27985. srcNode, srcChan))
  27986. {
  27987. // can't mess up this channel because it's needed later by another node, so we
  27988. // need to use a copy of it..
  27989. const int newFreeBuffer = getFreeBuffer (false);
  27990. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  27991. bufIndex = newFreeBuffer;
  27992. }
  27993. }
  27994. else
  27995. {
  27996. // channel with a mix of several inputs..
  27997. // try to find a re-usable channel from our inputs..
  27998. int reusableInputIndex = -1;
  27999. for (int i = 0; i < sourceNodes.size(); ++i)
  28000. {
  28001. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28002. sourceOutputChans.getUnchecked(i));
  28003. if (sourceBufIndex >= 0
  28004. && ! isBufferNeededLater (ourRenderingIndex,
  28005. inputChan,
  28006. sourceNodes.getUnchecked(i),
  28007. sourceOutputChans.getUnchecked(i)))
  28008. {
  28009. // we've found one of our input chans that can be re-used..
  28010. reusableInputIndex = i;
  28011. bufIndex = sourceBufIndex;
  28012. break;
  28013. }
  28014. }
  28015. if (reusableInputIndex < 0)
  28016. {
  28017. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28018. bufIndex = getFreeBuffer (false);
  28019. jassert (bufIndex != 0);
  28020. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28021. sourceOutputChans.getUnchecked (0));
  28022. if (srcIndex < 0)
  28023. {
  28024. // if not found, this is probably a feedback loop
  28025. renderingOps.add (new ClearChannelOp (bufIndex));
  28026. }
  28027. else
  28028. {
  28029. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28030. }
  28031. reusableInputIndex = 0;
  28032. }
  28033. for (int j = 0; j < sourceNodes.size(); ++j)
  28034. {
  28035. if (j != reusableInputIndex)
  28036. {
  28037. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28038. sourceOutputChans.getUnchecked(j));
  28039. if (srcIndex >= 0)
  28040. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28041. }
  28042. }
  28043. }
  28044. jassert (bufIndex >= 0);
  28045. audioChannelsToUse.add (bufIndex);
  28046. if (inputChan < numOuts)
  28047. markBufferAsContaining (bufIndex, node->id, inputChan);
  28048. }
  28049. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28050. {
  28051. const int bufIndex = getFreeBuffer (false);
  28052. jassert (bufIndex != 0);
  28053. audioChannelsToUse.add (bufIndex);
  28054. markBufferAsContaining (bufIndex, node->id, outputChan);
  28055. }
  28056. // Now the same thing for midi..
  28057. Array <int> midiSourceNodes;
  28058. for (int i = graph.getNumConnections(); --i >= 0;)
  28059. {
  28060. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28061. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28062. midiSourceNodes.add (c->sourceNodeId);
  28063. }
  28064. if (midiSourceNodes.size() == 0)
  28065. {
  28066. // No midi inputs..
  28067. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28068. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28069. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28070. }
  28071. else if (midiSourceNodes.size() == 1)
  28072. {
  28073. // One midi input..
  28074. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28075. AudioProcessorGraph::midiChannelIndex);
  28076. if (midiBufferToUse >= 0)
  28077. {
  28078. if (isBufferNeededLater (ourRenderingIndex,
  28079. AudioProcessorGraph::midiChannelIndex,
  28080. midiSourceNodes.getUnchecked(0),
  28081. AudioProcessorGraph::midiChannelIndex))
  28082. {
  28083. // can't mess up this channel because it's needed later by another node, so we
  28084. // need to use a copy of it..
  28085. const int newFreeBuffer = getFreeBuffer (true);
  28086. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28087. midiBufferToUse = newFreeBuffer;
  28088. }
  28089. }
  28090. else
  28091. {
  28092. // probably a feedback loop, so just use an empty one..
  28093. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28094. }
  28095. }
  28096. else
  28097. {
  28098. // More than one midi input being mixed..
  28099. int reusableInputIndex = -1;
  28100. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28101. {
  28102. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28103. AudioProcessorGraph::midiChannelIndex);
  28104. if (sourceBufIndex >= 0
  28105. && ! isBufferNeededLater (ourRenderingIndex,
  28106. AudioProcessorGraph::midiChannelIndex,
  28107. midiSourceNodes.getUnchecked(i),
  28108. AudioProcessorGraph::midiChannelIndex))
  28109. {
  28110. // we've found one of our input buffers that can be re-used..
  28111. reusableInputIndex = i;
  28112. midiBufferToUse = sourceBufIndex;
  28113. break;
  28114. }
  28115. }
  28116. if (reusableInputIndex < 0)
  28117. {
  28118. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28119. midiBufferToUse = getFreeBuffer (true);
  28120. jassert (midiBufferToUse >= 0);
  28121. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28122. AudioProcessorGraph::midiChannelIndex);
  28123. if (srcIndex >= 0)
  28124. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28125. else
  28126. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28127. reusableInputIndex = 0;
  28128. }
  28129. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28130. {
  28131. if (j != reusableInputIndex)
  28132. {
  28133. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28134. AudioProcessorGraph::midiChannelIndex);
  28135. if (srcIndex >= 0)
  28136. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28137. }
  28138. }
  28139. }
  28140. if (node->processor->producesMidi())
  28141. markBufferAsContaining (midiBufferToUse, node->id,
  28142. AudioProcessorGraph::midiChannelIndex);
  28143. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28144. totalChans, midiBufferToUse));
  28145. }
  28146. int getFreeBuffer (const bool forMidi)
  28147. {
  28148. if (forMidi)
  28149. {
  28150. for (int i = 1; i < midiNodeIds.size(); ++i)
  28151. if (midiNodeIds.getUnchecked(i) < 0)
  28152. return i;
  28153. midiNodeIds.add (-1);
  28154. return midiNodeIds.size() - 1;
  28155. }
  28156. else
  28157. {
  28158. for (int i = 1; i < nodeIds.size(); ++i)
  28159. if (nodeIds.getUnchecked(i) < 0)
  28160. return i;
  28161. nodeIds.add (-1);
  28162. channels.add (0);
  28163. return nodeIds.size() - 1;
  28164. }
  28165. }
  28166. int getReadOnlyEmptyBuffer() const throw()
  28167. {
  28168. return 0;
  28169. }
  28170. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  28171. {
  28172. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28173. {
  28174. for (int i = midiNodeIds.size(); --i >= 0;)
  28175. if (midiNodeIds.getUnchecked(i) == nodeId)
  28176. return i;
  28177. }
  28178. else
  28179. {
  28180. for (int i = nodeIds.size(); --i >= 0;)
  28181. if (nodeIds.getUnchecked(i) == nodeId
  28182. && channels.getUnchecked(i) == outputChannel)
  28183. return i;
  28184. }
  28185. return -1;
  28186. }
  28187. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28188. {
  28189. int i;
  28190. for (i = 0; i < nodeIds.size(); ++i)
  28191. {
  28192. if (nodeIds.getUnchecked(i) >= 0
  28193. && ! isBufferNeededLater (stepIndex, -1,
  28194. nodeIds.getUnchecked(i),
  28195. channels.getUnchecked(i)))
  28196. {
  28197. nodeIds.set (i, -1);
  28198. }
  28199. }
  28200. for (i = 0; i < midiNodeIds.size(); ++i)
  28201. {
  28202. if (midiNodeIds.getUnchecked(i) >= 0
  28203. && ! isBufferNeededLater (stepIndex, -1,
  28204. midiNodeIds.getUnchecked(i),
  28205. AudioProcessorGraph::midiChannelIndex))
  28206. {
  28207. midiNodeIds.set (i, -1);
  28208. }
  28209. }
  28210. }
  28211. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28212. int inputChannelOfIndexToIgnore,
  28213. const int nodeId,
  28214. const int outputChanIndex) const throw()
  28215. {
  28216. while (stepIndexToSearchFrom < orderedNodes.size())
  28217. {
  28218. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28219. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28220. {
  28221. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28222. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28223. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28224. return true;
  28225. }
  28226. else
  28227. {
  28228. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28229. if (i != inputChannelOfIndexToIgnore
  28230. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28231. node->id, i) != 0)
  28232. return true;
  28233. }
  28234. inputChannelOfIndexToIgnore = -1;
  28235. ++stepIndexToSearchFrom;
  28236. }
  28237. return false;
  28238. }
  28239. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28240. {
  28241. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28242. {
  28243. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28244. midiNodeIds.set (bufferNum, nodeId);
  28245. }
  28246. else
  28247. {
  28248. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28249. nodeIds.set (bufferNum, nodeId);
  28250. channels.set (bufferNum, outputIndex);
  28251. }
  28252. }
  28253. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28254. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28255. };
  28256. }
  28257. void AudioProcessorGraph::clearRenderingSequence()
  28258. {
  28259. const ScopedLock sl (renderLock);
  28260. for (int i = renderingOps.size(); --i >= 0;)
  28261. {
  28262. GraphRenderingOps::AudioGraphRenderingOp* const r
  28263. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28264. renderingOps.remove (i);
  28265. delete r;
  28266. }
  28267. }
  28268. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28269. const uint32 possibleDestinationId,
  28270. const int recursionCheck) const throw()
  28271. {
  28272. if (recursionCheck > 0)
  28273. {
  28274. for (int i = connections.size(); --i >= 0;)
  28275. {
  28276. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28277. if (c->destNodeId == possibleDestinationId
  28278. && (c->sourceNodeId == possibleInputId
  28279. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28280. return true;
  28281. }
  28282. }
  28283. return false;
  28284. }
  28285. void AudioProcessorGraph::buildRenderingSequence()
  28286. {
  28287. VoidArray newRenderingOps;
  28288. int numRenderingBuffersNeeded = 2;
  28289. int numMidiBuffersNeeded = 1;
  28290. {
  28291. MessageManagerLock mml;
  28292. VoidArray orderedNodes;
  28293. int i;
  28294. for (i = 0; i < nodes.size(); ++i)
  28295. {
  28296. Node* const node = nodes.getUnchecked(i);
  28297. node->prepare (getSampleRate(), getBlockSize(), this);
  28298. int j = 0;
  28299. for (; j < orderedNodes.size(); ++j)
  28300. if (isAnInputTo (node->id,
  28301. ((Node*) orderedNodes.getUnchecked (j))->id,
  28302. nodes.size() + 1))
  28303. break;
  28304. orderedNodes.insert (j, node);
  28305. }
  28306. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28307. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28308. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28309. }
  28310. VoidArray oldRenderingOps (renderingOps);
  28311. {
  28312. // swap over to the new rendering sequence..
  28313. const ScopedLock sl (renderLock);
  28314. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28315. renderingBuffers.clear();
  28316. for (int i = midiBuffers.size(); --i >= 0;)
  28317. midiBuffers.getUnchecked(i)->clear();
  28318. while (midiBuffers.size() < numMidiBuffersNeeded)
  28319. midiBuffers.add (new MidiBuffer());
  28320. renderingOps = newRenderingOps;
  28321. }
  28322. for (int i = oldRenderingOps.size(); --i >= 0;)
  28323. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28324. }
  28325. void AudioProcessorGraph::handleAsyncUpdate()
  28326. {
  28327. buildRenderingSequence();
  28328. }
  28329. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28330. {
  28331. currentAudioInputBuffer = 0;
  28332. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28333. currentMidiInputBuffer = 0;
  28334. currentMidiOutputBuffer.clear();
  28335. clearRenderingSequence();
  28336. buildRenderingSequence();
  28337. }
  28338. void AudioProcessorGraph::releaseResources()
  28339. {
  28340. for (int i = 0; i < nodes.size(); ++i)
  28341. nodes.getUnchecked(i)->unprepare();
  28342. renderingBuffers.setSize (1, 1);
  28343. midiBuffers.clear();
  28344. currentAudioInputBuffer = 0;
  28345. currentAudioOutputBuffer.setSize (1, 1);
  28346. currentMidiInputBuffer = 0;
  28347. currentMidiOutputBuffer.clear();
  28348. }
  28349. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28350. {
  28351. const int numSamples = buffer.getNumSamples();
  28352. const ScopedLock sl (renderLock);
  28353. currentAudioInputBuffer = &buffer;
  28354. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28355. currentAudioOutputBuffer.clear();
  28356. currentMidiInputBuffer = &midiMessages;
  28357. currentMidiOutputBuffer.clear();
  28358. int i;
  28359. for (i = 0; i < renderingOps.size(); ++i)
  28360. {
  28361. GraphRenderingOps::AudioGraphRenderingOp* const op
  28362. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28363. op->perform (renderingBuffers, midiBuffers, numSamples);
  28364. }
  28365. for (i = 0; i < buffer.getNumChannels(); ++i)
  28366. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28367. }
  28368. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28369. {
  28370. return "Input " + String (channelIndex + 1);
  28371. }
  28372. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28373. {
  28374. return "Output " + String (channelIndex + 1);
  28375. }
  28376. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28377. {
  28378. return true;
  28379. }
  28380. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28381. {
  28382. return true;
  28383. }
  28384. bool AudioProcessorGraph::acceptsMidi() const
  28385. {
  28386. return true;
  28387. }
  28388. bool AudioProcessorGraph::producesMidi() const
  28389. {
  28390. return true;
  28391. }
  28392. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28393. {
  28394. }
  28395. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28396. {
  28397. }
  28398. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28399. : type (type_),
  28400. graph (0)
  28401. {
  28402. }
  28403. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28404. {
  28405. }
  28406. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28407. {
  28408. switch (type)
  28409. {
  28410. case audioOutputNode:
  28411. return "Audio Output";
  28412. case audioInputNode:
  28413. return "Audio Input";
  28414. case midiOutputNode:
  28415. return "Midi Output";
  28416. case midiInputNode:
  28417. return "Midi Input";
  28418. default:
  28419. break;
  28420. }
  28421. return String::empty;
  28422. }
  28423. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28424. {
  28425. d.name = getName();
  28426. d.uid = d.name.hashCode();
  28427. d.category = "I/O devices";
  28428. d.pluginFormatName = "Internal";
  28429. d.manufacturerName = "Raw Material Software";
  28430. d.version = "1.0";
  28431. d.isInstrument = false;
  28432. d.numInputChannels = getNumInputChannels();
  28433. if (type == audioOutputNode && graph != 0)
  28434. d.numInputChannels = graph->getNumInputChannels();
  28435. d.numOutputChannels = getNumOutputChannels();
  28436. if (type == audioInputNode && graph != 0)
  28437. d.numOutputChannels = graph->getNumOutputChannels();
  28438. }
  28439. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28440. {
  28441. jassert (graph != 0);
  28442. }
  28443. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28444. {
  28445. }
  28446. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28447. MidiBuffer& midiMessages)
  28448. {
  28449. jassert (graph != 0);
  28450. switch (type)
  28451. {
  28452. case audioOutputNode:
  28453. {
  28454. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28455. buffer.getNumChannels()); --i >= 0;)
  28456. {
  28457. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28458. }
  28459. break;
  28460. }
  28461. case audioInputNode:
  28462. {
  28463. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28464. buffer.getNumChannels()); --i >= 0;)
  28465. {
  28466. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28467. }
  28468. break;
  28469. }
  28470. case midiOutputNode:
  28471. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28472. break;
  28473. case midiInputNode:
  28474. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28475. break;
  28476. default:
  28477. break;
  28478. }
  28479. }
  28480. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  28481. {
  28482. return type == midiOutputNode;
  28483. }
  28484. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  28485. {
  28486. return type == midiInputNode;
  28487. }
  28488. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  28489. {
  28490. switch (type)
  28491. {
  28492. case audioOutputNode:
  28493. return "Output " + String (channelIndex + 1);
  28494. case midiOutputNode:
  28495. return "Midi Output";
  28496. default:
  28497. break;
  28498. }
  28499. return String::empty;
  28500. }
  28501. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  28502. {
  28503. switch (type)
  28504. {
  28505. case audioInputNode:
  28506. return "Input " + String (channelIndex + 1);
  28507. case midiInputNode:
  28508. return "Midi Input";
  28509. default:
  28510. break;
  28511. }
  28512. return String::empty;
  28513. }
  28514. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  28515. {
  28516. return type == audioInputNode || type == audioOutputNode;
  28517. }
  28518. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  28519. {
  28520. return isInputChannelStereoPair (index);
  28521. }
  28522. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  28523. {
  28524. return type == audioInputNode || type == midiInputNode;
  28525. }
  28526. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  28527. {
  28528. return type == audioOutputNode || type == midiOutputNode;
  28529. }
  28530. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  28531. {
  28532. return 0;
  28533. }
  28534. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  28535. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  28536. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  28537. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  28538. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  28539. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  28540. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  28541. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  28542. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  28543. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  28544. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  28545. {
  28546. }
  28547. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  28548. {
  28549. }
  28550. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  28551. {
  28552. graph = newGraph;
  28553. if (graph != 0)
  28554. {
  28555. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  28556. type == audioInputNode ? graph->getNumInputChannels() : 0,
  28557. getSampleRate(),
  28558. getBlockSize());
  28559. updateHostDisplay();
  28560. }
  28561. }
  28562. END_JUCE_NAMESPACE
  28563. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  28564. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28565. BEGIN_JUCE_NAMESPACE
  28566. AudioProcessorPlayer::AudioProcessorPlayer()
  28567. : processor (0),
  28568. sampleRate (0),
  28569. blockSize (0),
  28570. isPrepared (false),
  28571. numInputChans (0),
  28572. numOutputChans (0),
  28573. tempBuffer (1, 1)
  28574. {
  28575. }
  28576. AudioProcessorPlayer::~AudioProcessorPlayer()
  28577. {
  28578. setProcessor (0);
  28579. }
  28580. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  28581. {
  28582. if (processor != processorToPlay)
  28583. {
  28584. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  28585. {
  28586. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  28587. sampleRate, blockSize);
  28588. processorToPlay->prepareToPlay (sampleRate, blockSize);
  28589. }
  28590. lock.enter();
  28591. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  28592. processor = processorToPlay;
  28593. isPrepared = true;
  28594. lock.exit();
  28595. if (oldOne != 0)
  28596. oldOne->releaseResources();
  28597. }
  28598. }
  28599. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  28600. int numInputChannels,
  28601. float** outputChannelData,
  28602. int numOutputChannels,
  28603. int numSamples)
  28604. {
  28605. // these should have been prepared by audioDeviceAboutToStart()...
  28606. jassert (sampleRate > 0 && blockSize > 0);
  28607. incomingMidi.clear();
  28608. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  28609. int i, totalNumChans = 0;
  28610. if (numInputChannels > numOutputChannels)
  28611. {
  28612. // if there aren't enough output channels for the number of
  28613. // inputs, we need to create some temporary extra ones (can't
  28614. // use the input data in case it gets written to)
  28615. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  28616. false, false, true);
  28617. for (i = 0; i < numOutputChannels; ++i)
  28618. {
  28619. channels[totalNumChans] = outputChannelData[i];
  28620. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28621. ++totalNumChans;
  28622. }
  28623. for (i = numOutputChannels; i < numInputChannels; ++i)
  28624. {
  28625. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  28626. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28627. ++totalNumChans;
  28628. }
  28629. }
  28630. else
  28631. {
  28632. for (i = 0; i < numInputChannels; ++i)
  28633. {
  28634. channels[totalNumChans] = outputChannelData[i];
  28635. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28636. ++totalNumChans;
  28637. }
  28638. for (i = numInputChannels; i < numOutputChannels; ++i)
  28639. {
  28640. channels[totalNumChans] = outputChannelData[i];
  28641. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  28642. ++totalNumChans;
  28643. }
  28644. }
  28645. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  28646. const ScopedLock sl (lock);
  28647. if (processor != 0)
  28648. processor->processBlock (buffer, incomingMidi);
  28649. }
  28650. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  28651. {
  28652. const ScopedLock sl (lock);
  28653. sampleRate = device->getCurrentSampleRate();
  28654. blockSize = device->getCurrentBufferSizeSamples();
  28655. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  28656. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  28657. messageCollector.reset (sampleRate);
  28658. zeromem (channels, sizeof (channels));
  28659. if (processor != 0)
  28660. {
  28661. if (isPrepared)
  28662. processor->releaseResources();
  28663. AudioProcessor* const oldProcessor = processor;
  28664. setProcessor (0);
  28665. setProcessor (oldProcessor);
  28666. }
  28667. }
  28668. void AudioProcessorPlayer::audioDeviceStopped()
  28669. {
  28670. const ScopedLock sl (lock);
  28671. if (processor != 0 && isPrepared)
  28672. processor->releaseResources();
  28673. sampleRate = 0.0;
  28674. blockSize = 0;
  28675. isPrepared = false;
  28676. tempBuffer.setSize (1, 1);
  28677. }
  28678. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  28679. {
  28680. messageCollector.addMessageToQueue (message);
  28681. }
  28682. END_JUCE_NAMESPACE
  28683. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28684. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28685. BEGIN_JUCE_NAMESPACE
  28686. class ProcessorParameterPropertyComp : public PropertyComponent,
  28687. public AudioProcessorListener,
  28688. public AsyncUpdater
  28689. {
  28690. public:
  28691. ProcessorParameterPropertyComp (const String& name,
  28692. AudioProcessor* const owner_,
  28693. const int index_)
  28694. : PropertyComponent (name),
  28695. owner (owner_),
  28696. index (index_)
  28697. {
  28698. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  28699. owner_->addListener (this);
  28700. }
  28701. ~ProcessorParameterPropertyComp()
  28702. {
  28703. owner->removeListener (this);
  28704. deleteAllChildren();
  28705. }
  28706. void refresh()
  28707. {
  28708. slider->setValue (owner->getParameter (index), false);
  28709. }
  28710. void audioProcessorChanged (AudioProcessor*) {}
  28711. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  28712. {
  28713. if (parameterIndex == index)
  28714. triggerAsyncUpdate();
  28715. }
  28716. void handleAsyncUpdate()
  28717. {
  28718. refresh();
  28719. }
  28720. juce_UseDebuggingNewOperator
  28721. private:
  28722. AudioProcessor* const owner;
  28723. const int index;
  28724. Slider* slider;
  28725. class ParamSlider : public Slider
  28726. {
  28727. public:
  28728. ParamSlider (AudioProcessor* const owner_, const int index_)
  28729. : Slider (String::empty),
  28730. owner (owner_),
  28731. index (index_)
  28732. {
  28733. setRange (0.0, 1.0, 0.0);
  28734. setSliderStyle (Slider::LinearBar);
  28735. setTextBoxIsEditable (false);
  28736. setScrollWheelEnabled (false);
  28737. }
  28738. ~ParamSlider()
  28739. {
  28740. }
  28741. void valueChanged()
  28742. {
  28743. const float newVal = (float) getValue();
  28744. if (owner->getParameter (index) != newVal)
  28745. owner->setParameter (index, newVal);
  28746. }
  28747. const String getTextFromValue (double /*value*/)
  28748. {
  28749. return owner->getParameterText (index);
  28750. }
  28751. juce_UseDebuggingNewOperator
  28752. private:
  28753. AudioProcessor* const owner;
  28754. const int index;
  28755. };
  28756. };
  28757. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  28758. : AudioProcessorEditor (owner)
  28759. {
  28760. setOpaque (true);
  28761. addAndMakeVisible (panel = new PropertyPanel());
  28762. Array <PropertyComponent*> params;
  28763. const int numParams = owner->getNumParameters();
  28764. int totalHeight = 0;
  28765. for (int i = 0; i < numParams; ++i)
  28766. {
  28767. String name (owner->getParameterName (i));
  28768. if (name.trim().isEmpty())
  28769. name = "Unnamed";
  28770. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  28771. params.add (pc);
  28772. totalHeight += pc->getPreferredHeight();
  28773. }
  28774. panel->addProperties (params);
  28775. setSize (400, jlimit (25, 400, totalHeight));
  28776. }
  28777. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  28778. {
  28779. deleteAllChildren();
  28780. }
  28781. void GenericAudioProcessorEditor::paint (Graphics& g)
  28782. {
  28783. g.fillAll (Colours::white);
  28784. }
  28785. void GenericAudioProcessorEditor::resized()
  28786. {
  28787. panel->setSize (getWidth(), getHeight());
  28788. }
  28789. END_JUCE_NAMESPACE
  28790. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28791. /********* Start of inlined file: juce_Sampler.cpp *********/
  28792. BEGIN_JUCE_NAMESPACE
  28793. SamplerSound::SamplerSound (const String& name_,
  28794. AudioFormatReader& source,
  28795. const BitArray& midiNotes_,
  28796. const int midiNoteForNormalPitch,
  28797. const double attackTimeSecs,
  28798. const double releaseTimeSecs,
  28799. const double maxSampleLengthSeconds)
  28800. : name (name_),
  28801. midiNotes (midiNotes_),
  28802. midiRootNote (midiNoteForNormalPitch)
  28803. {
  28804. sourceSampleRate = source.sampleRate;
  28805. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  28806. {
  28807. data = 0;
  28808. length = 0;
  28809. attackSamples = 0;
  28810. releaseSamples = 0;
  28811. }
  28812. else
  28813. {
  28814. length = jmin ((int) source.lengthInSamples,
  28815. (int) (maxSampleLengthSeconds * sourceSampleRate));
  28816. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  28817. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  28818. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  28819. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  28820. }
  28821. }
  28822. SamplerSound::~SamplerSound()
  28823. {
  28824. delete data;
  28825. data = 0;
  28826. }
  28827. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  28828. {
  28829. return midiNotes [midiNoteNumber];
  28830. }
  28831. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  28832. {
  28833. return true;
  28834. }
  28835. SamplerVoice::SamplerVoice()
  28836. : pitchRatio (0.0),
  28837. sourceSamplePosition (0.0),
  28838. lgain (0.0f),
  28839. rgain (0.0f),
  28840. isInAttack (false),
  28841. isInRelease (false)
  28842. {
  28843. }
  28844. SamplerVoice::~SamplerVoice()
  28845. {
  28846. }
  28847. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  28848. {
  28849. return dynamic_cast <const SamplerSound*> (sound) != 0;
  28850. }
  28851. void SamplerVoice::startNote (const int midiNoteNumber,
  28852. const float velocity,
  28853. SynthesiserSound* s,
  28854. const int /*currentPitchWheelPosition*/)
  28855. {
  28856. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  28857. jassert (sound != 0); // this object can only play SamplerSounds!
  28858. if (sound != 0)
  28859. {
  28860. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  28861. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  28862. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  28863. sourceSamplePosition = 0.0;
  28864. lgain = velocity;
  28865. rgain = velocity;
  28866. isInAttack = (sound->attackSamples > 0);
  28867. isInRelease = false;
  28868. if (isInAttack)
  28869. {
  28870. attackReleaseLevel = 0.0f;
  28871. attackDelta = (float) (pitchRatio / sound->attackSamples);
  28872. }
  28873. else
  28874. {
  28875. attackReleaseLevel = 1.0f;
  28876. attackDelta = 0.0f;
  28877. }
  28878. if (sound->releaseSamples > 0)
  28879. {
  28880. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  28881. }
  28882. else
  28883. {
  28884. releaseDelta = 0.0f;
  28885. }
  28886. }
  28887. }
  28888. void SamplerVoice::stopNote (const bool allowTailOff)
  28889. {
  28890. if (allowTailOff)
  28891. {
  28892. isInAttack = false;
  28893. isInRelease = true;
  28894. }
  28895. else
  28896. {
  28897. clearCurrentNote();
  28898. }
  28899. }
  28900. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  28901. {
  28902. }
  28903. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  28904. const int /*newValue*/)
  28905. {
  28906. }
  28907. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  28908. {
  28909. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  28910. if (playingSound != 0)
  28911. {
  28912. const float* const inL = playingSound->data->getSampleData (0, 0);
  28913. const float* const inR = playingSound->data->getNumChannels() > 1
  28914. ? playingSound->data->getSampleData (1, 0) : 0;
  28915. float* outL = outputBuffer.getSampleData (0, startSample);
  28916. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  28917. while (--numSamples >= 0)
  28918. {
  28919. const int pos = (int) sourceSamplePosition;
  28920. const float alpha = (float) (sourceSamplePosition - pos);
  28921. const float invAlpha = 1.0f - alpha;
  28922. // just using a very simple linear interpolation here..
  28923. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  28924. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  28925. : l;
  28926. l *= lgain;
  28927. r *= rgain;
  28928. if (isInAttack)
  28929. {
  28930. l *= attackReleaseLevel;
  28931. r *= attackReleaseLevel;
  28932. attackReleaseLevel += attackDelta;
  28933. if (attackReleaseLevel >= 1.0f)
  28934. {
  28935. attackReleaseLevel = 1.0f;
  28936. isInAttack = false;
  28937. }
  28938. }
  28939. else if (isInRelease)
  28940. {
  28941. l *= attackReleaseLevel;
  28942. r *= attackReleaseLevel;
  28943. attackReleaseLevel += releaseDelta;
  28944. if (attackReleaseLevel <= 0.0f)
  28945. {
  28946. stopNote (false);
  28947. break;
  28948. }
  28949. }
  28950. if (outR != 0)
  28951. {
  28952. *outL++ += l;
  28953. *outR++ += r;
  28954. }
  28955. else
  28956. {
  28957. *outL++ += (l + r) * 0.5f;
  28958. }
  28959. sourceSamplePosition += pitchRatio;
  28960. if (sourceSamplePosition > playingSound->length)
  28961. {
  28962. stopNote (false);
  28963. break;
  28964. }
  28965. }
  28966. }
  28967. }
  28968. END_JUCE_NAMESPACE
  28969. /********* End of inlined file: juce_Sampler.cpp *********/
  28970. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  28971. BEGIN_JUCE_NAMESPACE
  28972. SynthesiserSound::SynthesiserSound()
  28973. {
  28974. }
  28975. SynthesiserSound::~SynthesiserSound()
  28976. {
  28977. }
  28978. SynthesiserVoice::SynthesiserVoice()
  28979. : currentSampleRate (44100.0),
  28980. currentlyPlayingNote (-1),
  28981. noteOnTime (0),
  28982. currentlyPlayingSound (0)
  28983. {
  28984. }
  28985. SynthesiserVoice::~SynthesiserVoice()
  28986. {
  28987. }
  28988. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  28989. {
  28990. return currentlyPlayingSound != 0
  28991. && currentlyPlayingSound->appliesToChannel (midiChannel);
  28992. }
  28993. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  28994. {
  28995. currentSampleRate = newRate;
  28996. }
  28997. void SynthesiserVoice::clearCurrentNote()
  28998. {
  28999. currentlyPlayingNote = -1;
  29000. currentlyPlayingSound = 0;
  29001. }
  29002. Synthesiser::Synthesiser()
  29003. : voices (2),
  29004. sounds (2),
  29005. sampleRate (0),
  29006. lastNoteOnCounter (0),
  29007. shouldStealNotes (true)
  29008. {
  29009. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29010. lastPitchWheelValues[i] = 0x2000;
  29011. }
  29012. Synthesiser::~Synthesiser()
  29013. {
  29014. }
  29015. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  29016. {
  29017. const ScopedLock sl (lock);
  29018. return voices [index];
  29019. }
  29020. void Synthesiser::clearVoices()
  29021. {
  29022. const ScopedLock sl (lock);
  29023. voices.clear();
  29024. }
  29025. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29026. {
  29027. const ScopedLock sl (lock);
  29028. voices.add (newVoice);
  29029. }
  29030. void Synthesiser::removeVoice (const int index)
  29031. {
  29032. const ScopedLock sl (lock);
  29033. voices.remove (index);
  29034. }
  29035. void Synthesiser::clearSounds()
  29036. {
  29037. const ScopedLock sl (lock);
  29038. sounds.clear();
  29039. }
  29040. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29041. {
  29042. const ScopedLock sl (lock);
  29043. sounds.add (newSound);
  29044. }
  29045. void Synthesiser::removeSound (const int index)
  29046. {
  29047. const ScopedLock sl (lock);
  29048. sounds.remove (index);
  29049. }
  29050. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29051. {
  29052. shouldStealNotes = shouldStealNotes_;
  29053. }
  29054. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29055. {
  29056. if (sampleRate != newRate)
  29057. {
  29058. const ScopedLock sl (lock);
  29059. allNotesOff (0, false);
  29060. sampleRate = newRate;
  29061. for (int i = voices.size(); --i >= 0;)
  29062. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29063. }
  29064. }
  29065. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29066. const MidiBuffer& midiData,
  29067. int startSample,
  29068. int numSamples)
  29069. {
  29070. // must set the sample rate before using this!
  29071. jassert (sampleRate != 0);
  29072. const ScopedLock sl (lock);
  29073. MidiBuffer::Iterator midiIterator (midiData);
  29074. midiIterator.setNextSamplePosition (startSample);
  29075. MidiMessage m (0xf4, 0.0);
  29076. while (numSamples > 0)
  29077. {
  29078. int midiEventPos;
  29079. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29080. && midiEventPos < startSample + numSamples;
  29081. const int numThisTime = useEvent ? midiEventPos - startSample
  29082. : numSamples;
  29083. if (numThisTime > 0)
  29084. {
  29085. for (int i = voices.size(); --i >= 0;)
  29086. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29087. }
  29088. if (useEvent)
  29089. {
  29090. if (m.isNoteOn())
  29091. {
  29092. const int channel = m.getChannel();
  29093. noteOn (channel,
  29094. m.getNoteNumber(),
  29095. m.getFloatVelocity());
  29096. }
  29097. else if (m.isNoteOff())
  29098. {
  29099. noteOff (m.getChannel(),
  29100. m.getNoteNumber(),
  29101. true);
  29102. }
  29103. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29104. {
  29105. allNotesOff (m.getChannel(), true);
  29106. }
  29107. else if (m.isPitchWheel())
  29108. {
  29109. const int channel = m.getChannel();
  29110. const int wheelPos = m.getPitchWheelValue();
  29111. lastPitchWheelValues [channel - 1] = wheelPos;
  29112. handlePitchWheel (channel, wheelPos);
  29113. }
  29114. else if (m.isController())
  29115. {
  29116. handleController (m.getChannel(),
  29117. m.getControllerNumber(),
  29118. m.getControllerValue());
  29119. }
  29120. }
  29121. startSample += numThisTime;
  29122. numSamples -= numThisTime;
  29123. }
  29124. }
  29125. void Synthesiser::noteOn (const int midiChannel,
  29126. const int midiNoteNumber,
  29127. const float velocity)
  29128. {
  29129. const ScopedLock sl (lock);
  29130. for (int i = sounds.size(); --i >= 0;)
  29131. {
  29132. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29133. if (sound->appliesToNote (midiNoteNumber)
  29134. && sound->appliesToChannel (midiChannel))
  29135. {
  29136. startVoice (findFreeVoice (sound, shouldStealNotes),
  29137. sound, midiChannel, midiNoteNumber, velocity);
  29138. }
  29139. }
  29140. }
  29141. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29142. SynthesiserSound* const sound,
  29143. const int midiChannel,
  29144. const int midiNoteNumber,
  29145. const float velocity)
  29146. {
  29147. if (voice != 0 && sound != 0)
  29148. {
  29149. if (voice->currentlyPlayingSound != 0)
  29150. voice->stopNote (false);
  29151. voice->startNote (midiNoteNumber,
  29152. velocity,
  29153. sound,
  29154. lastPitchWheelValues [midiChannel - 1]);
  29155. voice->currentlyPlayingNote = midiNoteNumber;
  29156. voice->noteOnTime = ++lastNoteOnCounter;
  29157. voice->currentlyPlayingSound = sound;
  29158. }
  29159. }
  29160. void Synthesiser::noteOff (const int midiChannel,
  29161. const int midiNoteNumber,
  29162. const bool allowTailOff)
  29163. {
  29164. const ScopedLock sl (lock);
  29165. for (int i = voices.size(); --i >= 0;)
  29166. {
  29167. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29168. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29169. {
  29170. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29171. if (sound != 0
  29172. && sound->appliesToNote (midiNoteNumber)
  29173. && sound->appliesToChannel (midiChannel))
  29174. {
  29175. voice->stopNote (allowTailOff);
  29176. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29177. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29178. }
  29179. }
  29180. }
  29181. }
  29182. void Synthesiser::allNotesOff (const int midiChannel,
  29183. const bool allowTailOff)
  29184. {
  29185. const ScopedLock sl (lock);
  29186. for (int i = voices.size(); --i >= 0;)
  29187. {
  29188. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29189. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29190. voice->stopNote (allowTailOff);
  29191. }
  29192. }
  29193. void Synthesiser::handlePitchWheel (const int midiChannel,
  29194. const int wheelValue)
  29195. {
  29196. const ScopedLock sl (lock);
  29197. for (int i = voices.size(); --i >= 0;)
  29198. {
  29199. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29200. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29201. {
  29202. voice->pitchWheelMoved (wheelValue);
  29203. }
  29204. }
  29205. }
  29206. void Synthesiser::handleController (const int midiChannel,
  29207. const int controllerNumber,
  29208. const int controllerValue)
  29209. {
  29210. const ScopedLock sl (lock);
  29211. for (int i = voices.size(); --i >= 0;)
  29212. {
  29213. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29214. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29215. voice->controllerMoved (controllerNumber, controllerValue);
  29216. }
  29217. }
  29218. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29219. const bool stealIfNoneAvailable) const
  29220. {
  29221. const ScopedLock sl (lock);
  29222. for (int i = voices.size(); --i >= 0;)
  29223. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29224. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29225. return voices.getUnchecked (i);
  29226. if (stealIfNoneAvailable)
  29227. {
  29228. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29229. SynthesiserVoice* oldest = 0;
  29230. for (int i = voices.size(); --i >= 0;)
  29231. {
  29232. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29233. if (voice->canPlaySound (soundToPlay)
  29234. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29235. oldest = voice;
  29236. }
  29237. jassert (oldest != 0);
  29238. return oldest;
  29239. }
  29240. return 0;
  29241. }
  29242. END_JUCE_NAMESPACE
  29243. /********* End of inlined file: juce_Synthesiser.cpp *********/
  29244. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  29245. BEGIN_JUCE_NAMESPACE
  29246. ActionBroadcaster::ActionBroadcaster() throw()
  29247. {
  29248. // are you trying to create this object before or after juce has been intialised??
  29249. jassert (MessageManager::instance != 0);
  29250. }
  29251. ActionBroadcaster::~ActionBroadcaster()
  29252. {
  29253. // all event-based objects must be deleted BEFORE juce is shut down!
  29254. jassert (MessageManager::instance != 0);
  29255. }
  29256. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29257. {
  29258. actionListenerList.addActionListener (listener);
  29259. }
  29260. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29261. {
  29262. jassert (actionListenerList.isValidMessageListener());
  29263. if (actionListenerList.isValidMessageListener())
  29264. actionListenerList.removeActionListener (listener);
  29265. }
  29266. void ActionBroadcaster::removeAllActionListeners()
  29267. {
  29268. actionListenerList.removeAllActionListeners();
  29269. }
  29270. void ActionBroadcaster::sendActionMessage (const String& message) const
  29271. {
  29272. actionListenerList.sendActionMessage (message);
  29273. }
  29274. END_JUCE_NAMESPACE
  29275. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  29276. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  29277. BEGIN_JUCE_NAMESPACE
  29278. // special message of our own with a string in it
  29279. class ActionMessage : public Message
  29280. {
  29281. public:
  29282. const String message;
  29283. ActionMessage (const String& messageText,
  29284. void* const listener_) throw()
  29285. : message (messageText)
  29286. {
  29287. pointerParameter = listener_;
  29288. }
  29289. ~ActionMessage() throw()
  29290. {
  29291. }
  29292. private:
  29293. ActionMessage (const ActionMessage&);
  29294. const ActionMessage& operator= (const ActionMessage&);
  29295. };
  29296. ActionListenerList::ActionListenerList() throw()
  29297. {
  29298. }
  29299. ActionListenerList::~ActionListenerList() throw()
  29300. {
  29301. }
  29302. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29303. {
  29304. const ScopedLock sl (actionListenerLock_);
  29305. jassert (listener != 0);
  29306. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29307. if (listener != 0)
  29308. actionListeners_.add (listener);
  29309. }
  29310. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29311. {
  29312. const ScopedLock sl (actionListenerLock_);
  29313. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29314. actionListeners_.removeValue (listener);
  29315. }
  29316. void ActionListenerList::removeAllActionListeners() throw()
  29317. {
  29318. const ScopedLock sl (actionListenerLock_);
  29319. actionListeners_.clear();
  29320. }
  29321. void ActionListenerList::sendActionMessage (const String& message) const
  29322. {
  29323. const ScopedLock sl (actionListenerLock_);
  29324. for (int i = actionListeners_.size(); --i >= 0;)
  29325. {
  29326. postMessage (new ActionMessage (message,
  29327. (ActionListener*) actionListeners_.getUnchecked(i)));
  29328. }
  29329. }
  29330. void ActionListenerList::handleMessage (const Message& message)
  29331. {
  29332. const ActionMessage& am = (const ActionMessage&) message;
  29333. if (actionListeners_.contains (am.pointerParameter))
  29334. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  29335. }
  29336. END_JUCE_NAMESPACE
  29337. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  29338. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  29339. BEGIN_JUCE_NAMESPACE
  29340. AsyncUpdater::AsyncUpdater() throw()
  29341. : asyncMessagePending (false)
  29342. {
  29343. internalAsyncHandler.owner = this;
  29344. }
  29345. AsyncUpdater::~AsyncUpdater()
  29346. {
  29347. }
  29348. void AsyncUpdater::triggerAsyncUpdate() throw()
  29349. {
  29350. if (! asyncMessagePending)
  29351. {
  29352. asyncMessagePending = true;
  29353. internalAsyncHandler.postMessage (new Message());
  29354. }
  29355. }
  29356. void AsyncUpdater::cancelPendingUpdate() throw()
  29357. {
  29358. asyncMessagePending = false;
  29359. }
  29360. void AsyncUpdater::handleUpdateNowIfNeeded()
  29361. {
  29362. if (asyncMessagePending)
  29363. {
  29364. asyncMessagePending = false;
  29365. handleAsyncUpdate();
  29366. }
  29367. }
  29368. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29369. {
  29370. owner->handleUpdateNowIfNeeded();
  29371. }
  29372. END_JUCE_NAMESPACE
  29373. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  29374. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  29375. BEGIN_JUCE_NAMESPACE
  29376. ChangeBroadcaster::ChangeBroadcaster() throw()
  29377. {
  29378. // are you trying to create this object before or after juce has been intialised??
  29379. jassert (MessageManager::instance != 0);
  29380. }
  29381. ChangeBroadcaster::~ChangeBroadcaster()
  29382. {
  29383. // all event-based objects must be deleted BEFORE juce is shut down!
  29384. jassert (MessageManager::instance != 0);
  29385. }
  29386. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29387. {
  29388. changeListenerList.addChangeListener (listener);
  29389. }
  29390. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29391. {
  29392. jassert (changeListenerList.isValidMessageListener());
  29393. if (changeListenerList.isValidMessageListener())
  29394. changeListenerList.removeChangeListener (listener);
  29395. }
  29396. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29397. {
  29398. changeListenerList.removeAllChangeListeners();
  29399. }
  29400. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29401. {
  29402. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29403. }
  29404. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29405. {
  29406. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29407. }
  29408. void ChangeBroadcaster::dispatchPendingMessages()
  29409. {
  29410. changeListenerList.dispatchPendingMessages();
  29411. }
  29412. END_JUCE_NAMESPACE
  29413. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  29414. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  29415. BEGIN_JUCE_NAMESPACE
  29416. ChangeListenerList::ChangeListenerList() throw()
  29417. : lastChangedObject (0),
  29418. messagePending (false)
  29419. {
  29420. }
  29421. ChangeListenerList::~ChangeListenerList() throw()
  29422. {
  29423. }
  29424. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29425. {
  29426. const ScopedLock sl (lock);
  29427. jassert (listener != 0);
  29428. if (listener != 0)
  29429. listeners.add (listener);
  29430. }
  29431. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29432. {
  29433. const ScopedLock sl (lock);
  29434. listeners.removeValue (listener);
  29435. }
  29436. void ChangeListenerList::removeAllChangeListeners() throw()
  29437. {
  29438. const ScopedLock sl (lock);
  29439. listeners.clear();
  29440. }
  29441. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29442. {
  29443. const ScopedLock sl (lock);
  29444. if ((! messagePending) && (listeners.size() > 0))
  29445. {
  29446. lastChangedObject = objectThatHasChanged;
  29447. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29448. messagePending = true;
  29449. }
  29450. }
  29451. void ChangeListenerList::handleMessage (const Message& message)
  29452. {
  29453. sendSynchronousChangeMessage (message.pointerParameter);
  29454. }
  29455. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29456. {
  29457. const ScopedLock sl (lock);
  29458. messagePending = false;
  29459. for (int i = listeners.size(); --i >= 0;)
  29460. {
  29461. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  29462. {
  29463. const ScopedUnlock tempUnlocker (lock);
  29464. l->changeListenerCallback (objectThatHasChanged);
  29465. }
  29466. i = jmin (i, listeners.size());
  29467. }
  29468. }
  29469. void ChangeListenerList::dispatchPendingMessages()
  29470. {
  29471. if (messagePending)
  29472. sendSynchronousChangeMessage (lastChangedObject);
  29473. }
  29474. END_JUCE_NAMESPACE
  29475. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  29476. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  29477. BEGIN_JUCE_NAMESPACE
  29478. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29479. const uint32 magicMessageHeaderNumber)
  29480. : Thread ("Juce IPC connection"),
  29481. socket (0),
  29482. pipe (0),
  29483. callbackConnectionState (false),
  29484. useMessageThread (callbacksOnMessageThread),
  29485. magicMessageHeader (magicMessageHeaderNumber),
  29486. pipeReceiveMessageTimeout (-1)
  29487. {
  29488. }
  29489. InterprocessConnection::~InterprocessConnection()
  29490. {
  29491. callbackConnectionState = false;
  29492. disconnect();
  29493. }
  29494. bool InterprocessConnection::connectToSocket (const String& hostName,
  29495. const int portNumber,
  29496. const int timeOutMillisecs)
  29497. {
  29498. disconnect();
  29499. const ScopedLock sl (pipeAndSocketLock);
  29500. socket = new StreamingSocket();
  29501. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  29502. {
  29503. connectionMadeInt();
  29504. startThread();
  29505. return true;
  29506. }
  29507. else
  29508. {
  29509. deleteAndZero (socket);
  29510. return false;
  29511. }
  29512. }
  29513. bool InterprocessConnection::connectToPipe (const String& pipeName,
  29514. const int pipeReceiveMessageTimeoutMs)
  29515. {
  29516. disconnect();
  29517. NamedPipe* const newPipe = new NamedPipe();
  29518. if (newPipe->openExisting (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. bool InterprocessConnection::createPipe (const String& pipeName,
  29532. const int pipeReceiveMessageTimeoutMs)
  29533. {
  29534. disconnect();
  29535. NamedPipe* const newPipe = new NamedPipe();
  29536. if (newPipe->createNewPipe (pipeName))
  29537. {
  29538. const ScopedLock sl (pipeAndSocketLock);
  29539. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29540. initialiseWithPipe (newPipe);
  29541. return true;
  29542. }
  29543. else
  29544. {
  29545. delete newPipe;
  29546. return false;
  29547. }
  29548. }
  29549. void InterprocessConnection::disconnect()
  29550. {
  29551. if (socket != 0)
  29552. socket->close();
  29553. if (pipe != 0)
  29554. {
  29555. pipe->cancelPendingReads();
  29556. pipe->close();
  29557. }
  29558. stopThread (4000);
  29559. {
  29560. const ScopedLock sl (pipeAndSocketLock);
  29561. deleteAndZero (socket);
  29562. deleteAndZero (pipe);
  29563. }
  29564. connectionLostInt();
  29565. }
  29566. bool InterprocessConnection::isConnected() const
  29567. {
  29568. const ScopedLock sl (pipeAndSocketLock);
  29569. return ((socket != 0 && socket->isConnected())
  29570. || (pipe != 0 && pipe->isOpen()))
  29571. && isThreadRunning();
  29572. }
  29573. const String InterprocessConnection::getConnectedHostName() const
  29574. {
  29575. if (pipe != 0)
  29576. {
  29577. return "localhost";
  29578. }
  29579. else if (socket != 0)
  29580. {
  29581. if (! socket->isLocal())
  29582. return socket->getHostName();
  29583. return "localhost";
  29584. }
  29585. return String::empty;
  29586. }
  29587. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  29588. {
  29589. uint32 messageHeader[2];
  29590. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  29591. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  29592. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  29593. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  29594. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  29595. int bytesWritten = 0;
  29596. const ScopedLock sl (pipeAndSocketLock);
  29597. if (socket != 0)
  29598. {
  29599. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  29600. }
  29601. else if (pipe != 0)
  29602. {
  29603. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  29604. }
  29605. if (bytesWritten < 0)
  29606. {
  29607. // error..
  29608. return false;
  29609. }
  29610. return (bytesWritten == messageData.getSize());
  29611. }
  29612. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  29613. {
  29614. jassert (socket == 0);
  29615. socket = socket_;
  29616. connectionMadeInt();
  29617. startThread();
  29618. }
  29619. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  29620. {
  29621. jassert (pipe == 0);
  29622. pipe = pipe_;
  29623. connectionMadeInt();
  29624. startThread();
  29625. }
  29626. const int messageMagicNumber = 0xb734128b;
  29627. void InterprocessConnection::handleMessage (const Message& message)
  29628. {
  29629. if (message.intParameter1 == messageMagicNumber)
  29630. {
  29631. switch (message.intParameter2)
  29632. {
  29633. case 0:
  29634. {
  29635. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  29636. messageReceived (*data);
  29637. delete data;
  29638. break;
  29639. }
  29640. case 1:
  29641. connectionMade();
  29642. break;
  29643. case 2:
  29644. connectionLost();
  29645. break;
  29646. }
  29647. }
  29648. }
  29649. void InterprocessConnection::connectionMadeInt()
  29650. {
  29651. if (! callbackConnectionState)
  29652. {
  29653. callbackConnectionState = true;
  29654. if (useMessageThread)
  29655. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  29656. else
  29657. connectionMade();
  29658. }
  29659. }
  29660. void InterprocessConnection::connectionLostInt()
  29661. {
  29662. if (callbackConnectionState)
  29663. {
  29664. callbackConnectionState = false;
  29665. if (useMessageThread)
  29666. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  29667. else
  29668. connectionLost();
  29669. }
  29670. }
  29671. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  29672. {
  29673. jassert (callbackConnectionState);
  29674. if (useMessageThread)
  29675. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  29676. else
  29677. messageReceived (data);
  29678. }
  29679. bool InterprocessConnection::readNextMessageInt()
  29680. {
  29681. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  29682. uint32 messageHeader[2];
  29683. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  29684. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  29685. if (bytes == sizeof (messageHeader)
  29686. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  29687. {
  29688. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  29689. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  29690. {
  29691. MemoryBlock messageData (bytesInMessage, true);
  29692. int bytesRead = 0;
  29693. while (bytesRead < bytesInMessage)
  29694. {
  29695. if (threadShouldExit())
  29696. return false;
  29697. const int numThisTime = jmin (bytesInMessage, 65536);
  29698. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime, true)
  29699. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  29700. pipeReceiveMessageTimeout);
  29701. if (bytesIn <= 0)
  29702. break;
  29703. bytesRead += bytesIn;
  29704. }
  29705. if (bytesRead >= 0)
  29706. deliverDataInt (messageData);
  29707. }
  29708. }
  29709. else if (bytes < 0)
  29710. {
  29711. {
  29712. const ScopedLock sl (pipeAndSocketLock);
  29713. deleteAndZero (socket);
  29714. }
  29715. connectionLostInt();
  29716. return false;
  29717. }
  29718. return true;
  29719. }
  29720. void InterprocessConnection::run()
  29721. {
  29722. while (! threadShouldExit())
  29723. {
  29724. if (socket != 0)
  29725. {
  29726. const int ready = socket->waitUntilReady (true, 0);
  29727. if (ready < 0)
  29728. {
  29729. {
  29730. const ScopedLock sl (pipeAndSocketLock);
  29731. deleteAndZero (socket);
  29732. }
  29733. connectionLostInt();
  29734. break;
  29735. }
  29736. else if (ready > 0)
  29737. {
  29738. if (! readNextMessageInt())
  29739. break;
  29740. }
  29741. else
  29742. {
  29743. Thread::sleep (2);
  29744. }
  29745. }
  29746. else if (pipe != 0)
  29747. {
  29748. if (! pipe->isOpen())
  29749. {
  29750. {
  29751. const ScopedLock sl (pipeAndSocketLock);
  29752. deleteAndZero (pipe);
  29753. }
  29754. connectionLostInt();
  29755. break;
  29756. }
  29757. else
  29758. {
  29759. if (! readNextMessageInt())
  29760. break;
  29761. }
  29762. }
  29763. else
  29764. {
  29765. break;
  29766. }
  29767. }
  29768. }
  29769. END_JUCE_NAMESPACE
  29770. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  29771. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29772. BEGIN_JUCE_NAMESPACE
  29773. InterprocessConnectionServer::InterprocessConnectionServer()
  29774. : Thread ("Juce IPC server"),
  29775. socket (0)
  29776. {
  29777. }
  29778. InterprocessConnectionServer::~InterprocessConnectionServer()
  29779. {
  29780. stop();
  29781. }
  29782. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  29783. {
  29784. stop();
  29785. socket = new StreamingSocket();
  29786. if (socket->createListener (portNumber))
  29787. {
  29788. startThread();
  29789. return true;
  29790. }
  29791. deleteAndZero (socket);
  29792. return false;
  29793. }
  29794. void InterprocessConnectionServer::stop()
  29795. {
  29796. signalThreadShouldExit();
  29797. if (socket != 0)
  29798. socket->close();
  29799. stopThread (4000);
  29800. deleteAndZero (socket);
  29801. }
  29802. void InterprocessConnectionServer::run()
  29803. {
  29804. while ((! threadShouldExit()) && socket != 0)
  29805. {
  29806. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  29807. if (clientSocket != 0)
  29808. {
  29809. InterprocessConnection* newConnection = createConnectionObject();
  29810. if (newConnection != 0)
  29811. {
  29812. newConnection->initialiseWithSocket (clientSocket);
  29813. }
  29814. else
  29815. {
  29816. delete clientSocket;
  29817. }
  29818. }
  29819. }
  29820. }
  29821. END_JUCE_NAMESPACE
  29822. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29823. /********* Start of inlined file: juce_Message.cpp *********/
  29824. BEGIN_JUCE_NAMESPACE
  29825. Message::Message() throw()
  29826. {
  29827. }
  29828. Message::~Message() throw()
  29829. {
  29830. }
  29831. Message::Message (const int intParameter1_,
  29832. const int intParameter2_,
  29833. const int intParameter3_,
  29834. void* const pointerParameter_) throw()
  29835. : intParameter1 (intParameter1_),
  29836. intParameter2 (intParameter2_),
  29837. intParameter3 (intParameter3_),
  29838. pointerParameter (pointerParameter_)
  29839. {
  29840. }
  29841. END_JUCE_NAMESPACE
  29842. /********* End of inlined file: juce_Message.cpp *********/
  29843. /********* Start of inlined file: juce_MessageListener.cpp *********/
  29844. BEGIN_JUCE_NAMESPACE
  29845. MessageListener::MessageListener() throw()
  29846. {
  29847. // are you trying to create a messagelistener before or after juce has been intialised??
  29848. jassert (MessageManager::instance != 0);
  29849. if (MessageManager::instance != 0)
  29850. MessageManager::instance->messageListeners.add (this);
  29851. }
  29852. MessageListener::~MessageListener()
  29853. {
  29854. if (MessageManager::instance != 0)
  29855. MessageManager::instance->messageListeners.removeValue (this);
  29856. }
  29857. void MessageListener::postMessage (Message* const message) const throw()
  29858. {
  29859. message->messageRecipient = const_cast <MessageListener*> (this);
  29860. if (MessageManager::instance == 0)
  29861. MessageManager::getInstance();
  29862. MessageManager::instance->postMessageToQueue (message);
  29863. }
  29864. bool MessageListener::isValidMessageListener() const throw()
  29865. {
  29866. return (MessageManager::instance != 0)
  29867. && MessageManager::instance->messageListeners.contains (this);
  29868. }
  29869. END_JUCE_NAMESPACE
  29870. /********* End of inlined file: juce_MessageListener.cpp *********/
  29871. /********* Start of inlined file: juce_MessageManager.cpp *********/
  29872. BEGIN_JUCE_NAMESPACE
  29873. // platform-specific functions..
  29874. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  29875. bool juce_postMessageToSystemQueue (void* message);
  29876. MessageManager* MessageManager::instance = 0;
  29877. static const int quitMessageId = 0xfffff321;
  29878. MessageManager::MessageManager() throw()
  29879. : broadcastListeners (0),
  29880. quitMessagePosted (false),
  29881. quitMessageReceived (false),
  29882. threadWithLock (0)
  29883. {
  29884. messageThreadId = Thread::getCurrentThreadId();
  29885. }
  29886. MessageManager::~MessageManager() throw()
  29887. {
  29888. deleteAndZero (broadcastListeners);
  29889. doPlatformSpecificShutdown();
  29890. jassert (instance == this);
  29891. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  29892. }
  29893. MessageManager* MessageManager::getInstance() throw()
  29894. {
  29895. if (instance == 0)
  29896. {
  29897. instance = new MessageManager();
  29898. doPlatformSpecificInitialisation();
  29899. }
  29900. return instance;
  29901. }
  29902. void MessageManager::postMessageToQueue (Message* const message)
  29903. {
  29904. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  29905. delete message;
  29906. }
  29907. CallbackMessage::CallbackMessage() throw() {}
  29908. CallbackMessage::~CallbackMessage() throw() {}
  29909. void CallbackMessage::post()
  29910. {
  29911. if (MessageManager::instance != 0)
  29912. MessageManager::instance->postCallbackMessage (this);
  29913. }
  29914. void MessageManager::postCallbackMessage (Message* const message)
  29915. {
  29916. message->messageRecipient = 0;
  29917. postMessageToQueue (message);
  29918. }
  29919. // not for public use..
  29920. void MessageManager::deliverMessage (void* message)
  29921. {
  29922. Message* const m = (Message*) message;
  29923. MessageListener* const recipient = m->messageRecipient;
  29924. JUCE_TRY
  29925. {
  29926. if (messageListeners.contains (recipient))
  29927. {
  29928. recipient->handleMessage (*m);
  29929. }
  29930. else if (recipient == 0)
  29931. {
  29932. if (m->intParameter1 == quitMessageId)
  29933. {
  29934. quitMessageReceived = true;
  29935. }
  29936. else if (dynamic_cast <CallbackMessage*> (m) != 0)
  29937. {
  29938. (dynamic_cast <CallbackMessage*> (m))->messageCallback();
  29939. }
  29940. }
  29941. }
  29942. JUCE_CATCH_EXCEPTION
  29943. delete m;
  29944. }
  29945. #if ! (JUCE_MAC || JUCE_IPHONE)
  29946. void MessageManager::runDispatchLoop()
  29947. {
  29948. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29949. runDispatchLoopUntil (-1);
  29950. }
  29951. void MessageManager::stopDispatchLoop()
  29952. {
  29953. Message* const m = new Message (quitMessageId, 0, 0, 0);
  29954. m->messageRecipient = 0;
  29955. postMessageToQueue (m);
  29956. quitMessagePosted = true;
  29957. }
  29958. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  29959. {
  29960. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29961. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  29962. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  29963. && ! quitMessageReceived)
  29964. {
  29965. JUCE_TRY
  29966. {
  29967. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  29968. {
  29969. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  29970. if (msToWait > 0)
  29971. Thread::sleep (jmin (5, msToWait));
  29972. }
  29973. }
  29974. JUCE_CATCH_EXCEPTION
  29975. }
  29976. return ! quitMessageReceived;
  29977. }
  29978. #endif
  29979. void MessageManager::deliverBroadcastMessage (const String& value)
  29980. {
  29981. if (broadcastListeners != 0)
  29982. broadcastListeners->sendActionMessage (value);
  29983. }
  29984. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  29985. {
  29986. if (broadcastListeners == 0)
  29987. broadcastListeners = new ActionListenerList();
  29988. broadcastListeners->addActionListener (listener);
  29989. }
  29990. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  29991. {
  29992. if (broadcastListeners != 0)
  29993. broadcastListeners->removeActionListener (listener);
  29994. }
  29995. bool MessageManager::isThisTheMessageThread() const throw()
  29996. {
  29997. return Thread::getCurrentThreadId() == messageThreadId;
  29998. }
  29999. void MessageManager::setCurrentMessageThread (const Thread::ThreadID threadId) throw()
  30000. {
  30001. messageThreadId = threadId;
  30002. }
  30003. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30004. {
  30005. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30006. return thisThread == messageThreadId || thisThread == threadWithLock;
  30007. }
  30008. /* The only safe way to lock the message thread while another thread does
  30009. some work is by posting a special message, whose purpose is to tie up the event
  30010. loop until the other thread has finished its business.
  30011. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30012. get locked before making an event callback, because if the same OS lock gets indirectly
  30013. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30014. in Cocoa).
  30015. */
  30016. class SharedLockingEvents : public ReferenceCountedObject
  30017. {
  30018. public:
  30019. SharedLockingEvents() throw() {}
  30020. ~SharedLockingEvents() {}
  30021. /* This class just holds a couple of events to communicate between the MMLockMessage
  30022. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30023. this shared data must be kept in a separate, ref-counted container. */
  30024. WaitableEvent lockedEvent, releaseEvent;
  30025. };
  30026. class MMLockMessage : public CallbackMessage
  30027. {
  30028. public:
  30029. MMLockMessage (SharedLockingEvents* const events_) throw()
  30030. : events (events_)
  30031. {}
  30032. ~MMLockMessage() throw() {}
  30033. ReferenceCountedObjectPtr <SharedLockingEvents> events;
  30034. void messageCallback()
  30035. {
  30036. events->lockedEvent.signal();
  30037. events->releaseEvent.wait();
  30038. }
  30039. juce_UseDebuggingNewOperator
  30040. MMLockMessage (const MMLockMessage&);
  30041. const MMLockMessage& operator= (const MMLockMessage&);
  30042. };
  30043. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30044. : locked (false),
  30045. needsUnlocking (false)
  30046. {
  30047. init (threadToCheck, 0);
  30048. }
  30049. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30050. : locked (false),
  30051. needsUnlocking (false)
  30052. {
  30053. init (0, jobToCheckForExitSignal);
  30054. }
  30055. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30056. {
  30057. if (MessageManager::instance != 0)
  30058. {
  30059. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30060. {
  30061. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30062. }
  30063. else
  30064. {
  30065. if (threadToCheck == 0 && job == 0)
  30066. {
  30067. MessageManager::instance->lockingLock.enter();
  30068. }
  30069. else
  30070. {
  30071. while (! MessageManager::instance->lockingLock.tryEnter())
  30072. {
  30073. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30074. || (job != 0 && job->shouldExit()))
  30075. return;
  30076. Thread::sleep (1);
  30077. }
  30078. }
  30079. SharedLockingEvents* const events = new SharedLockingEvents();
  30080. sharedEvents = events;
  30081. events->incReferenceCount();
  30082. (new MMLockMessage (events))->post();
  30083. while (! events->lockedEvent.wait (50))
  30084. {
  30085. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30086. || (job != 0 && job->shouldExit()))
  30087. {
  30088. events->releaseEvent.signal();
  30089. events->decReferenceCount();
  30090. MessageManager::instance->lockingLock.exit();
  30091. return;
  30092. }
  30093. }
  30094. jassert (MessageManager::instance->threadWithLock == 0);
  30095. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30096. locked = true;
  30097. needsUnlocking = true;
  30098. }
  30099. }
  30100. }
  30101. MessageManagerLock::~MessageManagerLock() throw()
  30102. {
  30103. if (needsUnlocking && MessageManager::instance != 0)
  30104. {
  30105. jassert (MessageManager::instance->currentThreadHasLockedMessageManager());
  30106. ((SharedLockingEvents*) sharedEvents)->releaseEvent.signal();
  30107. ((SharedLockingEvents*) sharedEvents)->decReferenceCount();
  30108. MessageManager::instance->threadWithLock = 0;
  30109. MessageManager::instance->lockingLock.exit();
  30110. }
  30111. }
  30112. END_JUCE_NAMESPACE
  30113. /********* End of inlined file: juce_MessageManager.cpp *********/
  30114. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  30115. BEGIN_JUCE_NAMESPACE
  30116. class InternalMultiTimerCallback : public Timer
  30117. {
  30118. public:
  30119. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30120. : timerId (timerId_),
  30121. owner (owner_)
  30122. {
  30123. }
  30124. ~InternalMultiTimerCallback()
  30125. {
  30126. }
  30127. void timerCallback()
  30128. {
  30129. owner.timerCallback (timerId);
  30130. }
  30131. const int timerId;
  30132. private:
  30133. MultiTimer& owner;
  30134. };
  30135. MultiTimer::MultiTimer() throw()
  30136. {
  30137. }
  30138. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30139. {
  30140. }
  30141. MultiTimer::~MultiTimer()
  30142. {
  30143. const ScopedLock sl (timerListLock);
  30144. for (int i = timers.size(); --i >= 0;)
  30145. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30146. timers.clear();
  30147. }
  30148. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30149. {
  30150. const ScopedLock sl (timerListLock);
  30151. for (int i = timers.size(); --i >= 0;)
  30152. {
  30153. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30154. if (t->timerId == timerId)
  30155. {
  30156. t->startTimer (intervalInMilliseconds);
  30157. return;
  30158. }
  30159. }
  30160. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  30161. timers.add (newTimer);
  30162. newTimer->startTimer (intervalInMilliseconds);
  30163. }
  30164. void MultiTimer::stopTimer (const int timerId) throw()
  30165. {
  30166. const ScopedLock sl (timerListLock);
  30167. for (int i = timers.size(); --i >= 0;)
  30168. {
  30169. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30170. if (t->timerId == timerId)
  30171. t->stopTimer();
  30172. }
  30173. }
  30174. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30175. {
  30176. const ScopedLock sl (timerListLock);
  30177. for (int i = timers.size(); --i >= 0;)
  30178. {
  30179. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30180. if (t->timerId == timerId)
  30181. return t->isTimerRunning();
  30182. }
  30183. return false;
  30184. }
  30185. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30186. {
  30187. const ScopedLock sl (timerListLock);
  30188. for (int i = timers.size(); --i >= 0;)
  30189. {
  30190. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30191. if (t->timerId == timerId)
  30192. return t->getTimerInterval();
  30193. }
  30194. return 0;
  30195. }
  30196. END_JUCE_NAMESPACE
  30197. /********* End of inlined file: juce_MultiTimer.cpp *********/
  30198. /********* Start of inlined file: juce_Timer.cpp *********/
  30199. BEGIN_JUCE_NAMESPACE
  30200. class InternalTimerThread : private Thread,
  30201. private MessageListener,
  30202. private DeletedAtShutdown,
  30203. private AsyncUpdater
  30204. {
  30205. private:
  30206. friend class Timer;
  30207. static InternalTimerThread* instance;
  30208. static CriticalSection lock;
  30209. Timer* volatile firstTimer;
  30210. bool volatile callbackNeeded;
  30211. InternalTimerThread (const InternalTimerThread&);
  30212. const InternalTimerThread& operator= (const InternalTimerThread&);
  30213. void addTimer (Timer* const t) throw()
  30214. {
  30215. #ifdef JUCE_DEBUG
  30216. Timer* tt = firstTimer;
  30217. while (tt != 0)
  30218. {
  30219. // trying to add a timer that's already here - shouldn't get to this point,
  30220. // so if you get this assertion, let me know!
  30221. jassert (tt != t);
  30222. tt = tt->next;
  30223. }
  30224. jassert (t->previous == 0 && t->next == 0);
  30225. #endif
  30226. Timer* i = firstTimer;
  30227. if (i == 0 || i->countdownMs > t->countdownMs)
  30228. {
  30229. t->next = firstTimer;
  30230. firstTimer = t;
  30231. }
  30232. else
  30233. {
  30234. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30235. i = i->next;
  30236. jassert (i != 0);
  30237. t->next = i->next;
  30238. t->previous = i;
  30239. i->next = t;
  30240. }
  30241. if (t->next != 0)
  30242. t->next->previous = t;
  30243. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30244. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30245. notify();
  30246. }
  30247. void removeTimer (Timer* const t) throw()
  30248. {
  30249. #ifdef JUCE_DEBUG
  30250. Timer* tt = firstTimer;
  30251. bool found = false;
  30252. while (tt != 0)
  30253. {
  30254. if (tt == t)
  30255. {
  30256. found = true;
  30257. break;
  30258. }
  30259. tt = tt->next;
  30260. }
  30261. // trying to remove a timer that's not here - shouldn't get to this point,
  30262. // so if you get this assertion, let me know!
  30263. jassert (found);
  30264. #endif
  30265. if (t->previous != 0)
  30266. {
  30267. jassert (firstTimer != t);
  30268. t->previous->next = t->next;
  30269. }
  30270. else
  30271. {
  30272. jassert (firstTimer == t);
  30273. firstTimer = t->next;
  30274. }
  30275. if (t->next != 0)
  30276. t->next->previous = t->previous;
  30277. t->next = 0;
  30278. t->previous = 0;
  30279. }
  30280. void decrementAllCounters (const int numMillisecs) const
  30281. {
  30282. Timer* t = firstTimer;
  30283. while (t != 0)
  30284. {
  30285. t->countdownMs -= numMillisecs;
  30286. t = t->next;
  30287. }
  30288. }
  30289. void handleAsyncUpdate()
  30290. {
  30291. startThread (7);
  30292. }
  30293. public:
  30294. InternalTimerThread()
  30295. : Thread ("Juce Timer"),
  30296. firstTimer (0),
  30297. callbackNeeded (false)
  30298. {
  30299. triggerAsyncUpdate();
  30300. }
  30301. ~InternalTimerThread() throw()
  30302. {
  30303. stopThread (4000);
  30304. jassert (instance == this || instance == 0);
  30305. if (instance == this)
  30306. instance = 0;
  30307. }
  30308. void run()
  30309. {
  30310. uint32 lastTime = Time::getMillisecondCounter();
  30311. while (! threadShouldExit())
  30312. {
  30313. uint32 now = Time::getMillisecondCounter();
  30314. if (now <= lastTime)
  30315. {
  30316. wait (2);
  30317. continue;
  30318. }
  30319. const int elapsed = now - lastTime;
  30320. lastTime = now;
  30321. lock.enter();
  30322. decrementAllCounters (elapsed);
  30323. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  30324. : 1000;
  30325. lock.exit();
  30326. if (timeUntilFirstTimer <= 0)
  30327. {
  30328. callbackNeeded = true;
  30329. postMessage (new Message());
  30330. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  30331. // so this is how long to wait before assuming the message has been lost and trying again.
  30332. const uint32 messageDeliveryTimeout = now + 2000;
  30333. while (callbackNeeded)
  30334. {
  30335. wait (4);
  30336. if (threadShouldExit())
  30337. return;
  30338. now = Time::getMillisecondCounter();
  30339. if (now > messageDeliveryTimeout)
  30340. break;
  30341. }
  30342. }
  30343. else
  30344. {
  30345. // don't wait for too long because running this loop also helps keep the
  30346. // Time::getApproximateMillisecondTimer value stay up-to-date
  30347. wait (jlimit (1, 50, timeUntilFirstTimer));
  30348. }
  30349. }
  30350. }
  30351. void handleMessage (const Message&)
  30352. {
  30353. const ScopedLock sl (lock);
  30354. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30355. {
  30356. Timer* const t = firstTimer;
  30357. t->countdownMs = t->periodMs;
  30358. removeTimer (t);
  30359. addTimer (t);
  30360. const ScopedUnlock ul (lock);
  30361. JUCE_TRY
  30362. {
  30363. t->timerCallback();
  30364. }
  30365. JUCE_CATCH_EXCEPTION
  30366. }
  30367. callbackNeeded = false;
  30368. }
  30369. static void callAnyTimersSynchronously()
  30370. {
  30371. if (InternalTimerThread::instance != 0)
  30372. {
  30373. const Message m;
  30374. InternalTimerThread::instance->handleMessage (m);
  30375. }
  30376. }
  30377. static inline void add (Timer* const tim) throw()
  30378. {
  30379. if (instance == 0)
  30380. instance = new InternalTimerThread();
  30381. const ScopedLock sl (instance->lock);
  30382. instance->addTimer (tim);
  30383. }
  30384. static inline void remove (Timer* const tim) throw()
  30385. {
  30386. if (instance != 0)
  30387. {
  30388. const ScopedLock sl (instance->lock);
  30389. instance->removeTimer (tim);
  30390. }
  30391. }
  30392. static inline void resetCounter (Timer* const tim,
  30393. const int newCounter) throw()
  30394. {
  30395. if (instance != 0)
  30396. {
  30397. tim->countdownMs = newCounter;
  30398. tim->periodMs = newCounter;
  30399. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30400. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30401. {
  30402. const ScopedLock sl (instance->lock);
  30403. instance->removeTimer (tim);
  30404. instance->addTimer (tim);
  30405. }
  30406. }
  30407. }
  30408. };
  30409. InternalTimerThread* InternalTimerThread::instance = 0;
  30410. CriticalSection InternalTimerThread::lock;
  30411. void juce_callAnyTimersSynchronously()
  30412. {
  30413. InternalTimerThread::callAnyTimersSynchronously();
  30414. }
  30415. #ifdef JUCE_DEBUG
  30416. static SortedSet <Timer*> activeTimers;
  30417. #endif
  30418. Timer::Timer() throw()
  30419. : countdownMs (0),
  30420. periodMs (0),
  30421. previous (0),
  30422. next (0)
  30423. {
  30424. #ifdef JUCE_DEBUG
  30425. activeTimers.add (this);
  30426. #endif
  30427. }
  30428. Timer::Timer (const Timer&) throw()
  30429. : countdownMs (0),
  30430. periodMs (0),
  30431. previous (0),
  30432. next (0)
  30433. {
  30434. #ifdef JUCE_DEBUG
  30435. activeTimers.add (this);
  30436. #endif
  30437. }
  30438. Timer::~Timer()
  30439. {
  30440. stopTimer();
  30441. #ifdef JUCE_DEBUG
  30442. activeTimers.removeValue (this);
  30443. #endif
  30444. }
  30445. void Timer::startTimer (const int interval) 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. countdownMs = interval;
  30455. periodMs = jmax (1, interval);
  30456. InternalTimerThread::add (this);
  30457. }
  30458. else
  30459. {
  30460. InternalTimerThread::resetCounter (this, interval);
  30461. }
  30462. }
  30463. void Timer::stopTimer() throw()
  30464. {
  30465. const ScopedLock sl (InternalTimerThread::lock);
  30466. #ifdef JUCE_DEBUG
  30467. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30468. jassert (activeTimers.contains (this));
  30469. #endif
  30470. if (periodMs > 0)
  30471. {
  30472. InternalTimerThread::remove (this);
  30473. periodMs = 0;
  30474. }
  30475. }
  30476. END_JUCE_NAMESPACE
  30477. /********* End of inlined file: juce_Timer.cpp *********/
  30478. /********* Start of inlined file: juce_Component.cpp *********/
  30479. BEGIN_JUCE_NAMESPACE
  30480. Component* Component::componentUnderMouse = 0;
  30481. Component* Component::currentlyFocusedComponent = 0;
  30482. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  30483. static Array <int> modalReturnValues (4);
  30484. static const int customCommandMessage = 0x7fff0001;
  30485. static const int exitModalStateMessage = 0x7fff0002;
  30486. // these are also used by ComponentPeer
  30487. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  30488. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  30489. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  30490. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  30491. int juce_LastMousePosX = 0;
  30492. int juce_LastMousePosY = 0;
  30493. int juce_MouseClickCounter = 0;
  30494. bool juce_MouseHasMovedSignificantlySincePressed = false;
  30495. static int countMouseClicks() throw()
  30496. {
  30497. int numClicks = 0;
  30498. if (juce_recentMouseDownTimes[0] != 0)
  30499. {
  30500. if (! juce_MouseHasMovedSignificantlySincePressed)
  30501. ++numClicks;
  30502. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  30503. {
  30504. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  30505. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  30506. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  30507. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  30508. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  30509. {
  30510. ++numClicks;
  30511. }
  30512. else
  30513. {
  30514. break;
  30515. }
  30516. }
  30517. }
  30518. return numClicks;
  30519. }
  30520. static int unboundedMouseOffsetX = 0;
  30521. static int unboundedMouseOffsetY = 0;
  30522. static bool isUnboundedMouseModeOn = false;
  30523. static bool isCursorVisibleUntilOffscreen;
  30524. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30525. static uint32 nextComponentUID = 0;
  30526. Component::Component() throw()
  30527. : parentComponent_ (0),
  30528. componentUID (++nextComponentUID),
  30529. numDeepMouseListeners (0),
  30530. childComponentList_ (16),
  30531. lookAndFeel_ (0),
  30532. effect_ (0),
  30533. bufferedImage_ (0),
  30534. mouseListeners_ (0),
  30535. keyListeners_ (0),
  30536. componentListeners_ (0),
  30537. propertySet_ (0),
  30538. componentFlags_ (0)
  30539. {
  30540. }
  30541. Component::Component (const String& name) throw()
  30542. : componentName_ (name),
  30543. parentComponent_ (0),
  30544. componentUID (++nextComponentUID),
  30545. numDeepMouseListeners (0),
  30546. childComponentList_ (16),
  30547. lookAndFeel_ (0),
  30548. effect_ (0),
  30549. bufferedImage_ (0),
  30550. mouseListeners_ (0),
  30551. keyListeners_ (0),
  30552. componentListeners_ (0),
  30553. propertySet_ (0),
  30554. componentFlags_ (0)
  30555. {
  30556. }
  30557. Component::~Component()
  30558. {
  30559. if (parentComponent_ != 0)
  30560. {
  30561. parentComponent_->removeChildComponent (this);
  30562. }
  30563. else if ((currentlyFocusedComponent == this)
  30564. || isParentOf (currentlyFocusedComponent))
  30565. {
  30566. giveAwayFocus();
  30567. }
  30568. if (componentUnderMouse == this)
  30569. componentUnderMouse = 0;
  30570. if (flags.hasHeavyweightPeerFlag)
  30571. removeFromDesktop();
  30572. modalComponentStack.removeValue (this);
  30573. for (int i = childComponentList_.size(); --i >= 0;)
  30574. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  30575. delete bufferedImage_;
  30576. delete mouseListeners_;
  30577. delete keyListeners_;
  30578. delete componentListeners_;
  30579. delete propertySet_;
  30580. }
  30581. void Component::setName (const String& name)
  30582. {
  30583. // if component methods are being called from threads other than the message
  30584. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30585. checkMessageManagerIsLocked
  30586. if (componentName_ != name)
  30587. {
  30588. componentName_ = name;
  30589. if (flags.hasHeavyweightPeerFlag)
  30590. {
  30591. ComponentPeer* const peer = getPeer();
  30592. jassert (peer != 0);
  30593. if (peer != 0)
  30594. peer->setTitle (name);
  30595. }
  30596. if (componentListeners_ != 0)
  30597. {
  30598. const ComponentDeletionWatcher deletionChecker (this);
  30599. for (int i = componentListeners_->size(); --i >= 0;)
  30600. {
  30601. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30602. ->componentNameChanged (*this);
  30603. if (deletionChecker.hasBeenDeleted())
  30604. return;
  30605. i = jmin (i, componentListeners_->size());
  30606. }
  30607. }
  30608. }
  30609. }
  30610. void Component::setVisible (bool shouldBeVisible)
  30611. {
  30612. if (flags.visibleFlag != shouldBeVisible)
  30613. {
  30614. // if component methods are being called from threads other than the message
  30615. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30616. checkMessageManagerIsLocked
  30617. const ComponentDeletionWatcher deletionChecker (this);
  30618. flags.visibleFlag = shouldBeVisible;
  30619. internalRepaint (0, 0, getWidth(), getHeight());
  30620. sendFakeMouseMove();
  30621. if (! shouldBeVisible)
  30622. {
  30623. if (currentlyFocusedComponent == this
  30624. || isParentOf (currentlyFocusedComponent))
  30625. {
  30626. if (parentComponent_ != 0)
  30627. parentComponent_->grabKeyboardFocus();
  30628. else
  30629. giveAwayFocus();
  30630. }
  30631. }
  30632. sendVisibilityChangeMessage();
  30633. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  30634. {
  30635. ComponentPeer* const peer = getPeer();
  30636. jassert (peer != 0);
  30637. if (peer != 0)
  30638. {
  30639. peer->setVisible (shouldBeVisible);
  30640. internalHierarchyChanged();
  30641. }
  30642. }
  30643. }
  30644. }
  30645. void Component::visibilityChanged()
  30646. {
  30647. }
  30648. void Component::sendVisibilityChangeMessage()
  30649. {
  30650. const ComponentDeletionWatcher deletionChecker (this);
  30651. visibilityChanged();
  30652. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  30653. {
  30654. for (int i = componentListeners_->size(); --i >= 0;)
  30655. {
  30656. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30657. ->componentVisibilityChanged (*this);
  30658. if (deletionChecker.hasBeenDeleted())
  30659. return;
  30660. i = jmin (i, componentListeners_->size());
  30661. }
  30662. }
  30663. }
  30664. bool Component::isShowing() const throw()
  30665. {
  30666. if (flags.visibleFlag)
  30667. {
  30668. if (parentComponent_ != 0)
  30669. {
  30670. return parentComponent_->isShowing();
  30671. }
  30672. else
  30673. {
  30674. const ComponentPeer* const peer = getPeer();
  30675. return peer != 0 && ! peer->isMinimised();
  30676. }
  30677. }
  30678. return false;
  30679. }
  30680. class FadeOutProxyComponent : public Component,
  30681. public Timer
  30682. {
  30683. public:
  30684. FadeOutProxyComponent (Component* comp,
  30685. const int fadeLengthMs,
  30686. const int deltaXToMove,
  30687. const int deltaYToMove,
  30688. const float scaleFactorAtEnd)
  30689. : lastTime (0),
  30690. alpha (1.0f),
  30691. scale (1.0f)
  30692. {
  30693. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  30694. setBounds (comp->getBounds());
  30695. comp->getParentComponent()->addAndMakeVisible (this);
  30696. toBehind (comp);
  30697. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  30698. centreX = comp->getX() + comp->getWidth() * 0.5f;
  30699. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  30700. centreY = comp->getY() + comp->getHeight() * 0.5f;
  30701. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  30702. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  30703. setInterceptsMouseClicks (false, false);
  30704. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  30705. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  30706. }
  30707. ~FadeOutProxyComponent()
  30708. {
  30709. delete image;
  30710. }
  30711. void paint (Graphics& g)
  30712. {
  30713. g.setOpacity (alpha);
  30714. g.drawImage (image,
  30715. 0, 0, getWidth(), getHeight(),
  30716. 0, 0, image->getWidth(), image->getHeight());
  30717. }
  30718. void timerCallback()
  30719. {
  30720. const uint32 now = Time::getMillisecondCounter();
  30721. if (lastTime == 0)
  30722. lastTime = now;
  30723. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  30724. lastTime = now;
  30725. alpha += alphaChangePerMs * msPassed;
  30726. if (alpha > 0)
  30727. {
  30728. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  30729. {
  30730. centreX += xChangePerMs * msPassed;
  30731. centreY += yChangePerMs * msPassed;
  30732. scale += scaleChangePerMs * msPassed;
  30733. const int w = roundFloatToInt (image->getWidth() * scale);
  30734. const int h = roundFloatToInt (image->getHeight() * scale);
  30735. setBounds (roundFloatToInt (centreX) - w / 2,
  30736. roundFloatToInt (centreY) - h / 2,
  30737. w, h);
  30738. }
  30739. repaint();
  30740. }
  30741. else
  30742. {
  30743. delete this;
  30744. }
  30745. }
  30746. juce_UseDebuggingNewOperator
  30747. private:
  30748. Image* image;
  30749. uint32 lastTime;
  30750. float alpha, alphaChangePerMs;
  30751. float centreX, xChangePerMs;
  30752. float centreY, yChangePerMs;
  30753. float scale, scaleChangePerMs;
  30754. FadeOutProxyComponent (const FadeOutProxyComponent&);
  30755. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  30756. };
  30757. void Component::fadeOutComponent (const int millisecondsToFade,
  30758. const int deltaXToMove,
  30759. const int deltaYToMove,
  30760. const float scaleFactorAtEnd)
  30761. {
  30762. //xxx won't work for comps without parents
  30763. if (isShowing() && millisecondsToFade > 0)
  30764. new FadeOutProxyComponent (this, millisecondsToFade,
  30765. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  30766. setVisible (false);
  30767. }
  30768. bool Component::isValidComponent() const throw()
  30769. {
  30770. return (this != 0) && isValidMessageListener();
  30771. }
  30772. void* Component::getWindowHandle() const throw()
  30773. {
  30774. const ComponentPeer* const peer = getPeer();
  30775. if (peer != 0)
  30776. return peer->getNativeHandle();
  30777. return 0;
  30778. }
  30779. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  30780. {
  30781. // if component methods are being called from threads other than the message
  30782. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30783. checkMessageManagerIsLocked
  30784. if (! isOpaque())
  30785. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  30786. int currentStyleFlags = 0;
  30787. // don't use getPeer(), so that we only get the peer that's specifically
  30788. // for this comp, and not for one of its parents.
  30789. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  30790. if (peer != 0)
  30791. currentStyleFlags = peer->getStyleFlags();
  30792. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  30793. {
  30794. const ComponentDeletionWatcher deletionChecker (this);
  30795. #if JUCE_LINUX
  30796. // it's wise to give the component a non-zero size before
  30797. // putting it on the desktop, as X windows get confused by this, and
  30798. // a (1, 1) minimum size is enforced here.
  30799. setSize (jmax (1, getWidth()),
  30800. jmax (1, getHeight()));
  30801. #endif
  30802. int x = 0, y = 0;
  30803. relativePositionToGlobal (x, y);
  30804. bool wasFullscreen = false;
  30805. bool wasMinimised = false;
  30806. ComponentBoundsConstrainer* currentConstainer = 0;
  30807. Rectangle oldNonFullScreenBounds;
  30808. if (peer != 0)
  30809. {
  30810. wasFullscreen = peer->isFullScreen();
  30811. wasMinimised = peer->isMinimised();
  30812. currentConstainer = peer->getConstrainer();
  30813. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  30814. removeFromDesktop();
  30815. setTopLeftPosition (x, y);
  30816. }
  30817. if (parentComponent_ != 0)
  30818. parentComponent_->removeChildComponent (this);
  30819. if (! deletionChecker.hasBeenDeleted())
  30820. {
  30821. flags.hasHeavyweightPeerFlag = true;
  30822. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  30823. Desktop::getInstance().addDesktopComponent (this);
  30824. bounds_.setPosition (x, y);
  30825. peer->setBounds (x, y, getWidth(), getHeight(), false);
  30826. peer->setVisible (isVisible());
  30827. if (wasFullscreen)
  30828. {
  30829. peer->setFullScreen (true);
  30830. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  30831. }
  30832. if (wasMinimised)
  30833. peer->setMinimised (true);
  30834. if (isAlwaysOnTop())
  30835. peer->setAlwaysOnTop (true);
  30836. peer->setConstrainer (currentConstainer);
  30837. repaint();
  30838. }
  30839. internalHierarchyChanged();
  30840. }
  30841. }
  30842. void Component::removeFromDesktop()
  30843. {
  30844. // if component methods are being called from threads other than the message
  30845. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30846. checkMessageManagerIsLocked
  30847. if (flags.hasHeavyweightPeerFlag)
  30848. {
  30849. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30850. flags.hasHeavyweightPeerFlag = false;
  30851. jassert (peer != 0);
  30852. delete peer;
  30853. Desktop::getInstance().removeDesktopComponent (this);
  30854. }
  30855. }
  30856. bool Component::isOnDesktop() const throw()
  30857. {
  30858. return flags.hasHeavyweightPeerFlag;
  30859. }
  30860. void Component::userTriedToCloseWindow()
  30861. {
  30862. /* This means that the user's trying to get rid of your window with the 'close window' system
  30863. menu option (on windows) or possibly the task manager - you should really handle this
  30864. and delete or hide your component in an appropriate way.
  30865. If you want to ignore the event and don't want to trigger this assertion, just override
  30866. this method and do nothing.
  30867. */
  30868. jassertfalse
  30869. }
  30870. void Component::minimisationStateChanged (bool)
  30871. {
  30872. }
  30873. void Component::setOpaque (const bool shouldBeOpaque) throw()
  30874. {
  30875. if (shouldBeOpaque != flags.opaqueFlag)
  30876. {
  30877. flags.opaqueFlag = shouldBeOpaque;
  30878. if (flags.hasHeavyweightPeerFlag)
  30879. {
  30880. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30881. if (peer != 0)
  30882. {
  30883. // to make it recreate the heavyweight window
  30884. addToDesktop (peer->getStyleFlags());
  30885. }
  30886. }
  30887. repaint();
  30888. }
  30889. }
  30890. bool Component::isOpaque() const throw()
  30891. {
  30892. return flags.opaqueFlag;
  30893. }
  30894. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  30895. {
  30896. if (shouldBeBuffered != flags.bufferToImageFlag)
  30897. {
  30898. deleteAndZero (bufferedImage_);
  30899. flags.bufferToImageFlag = shouldBeBuffered;
  30900. }
  30901. }
  30902. void Component::toFront (const bool setAsForeground)
  30903. {
  30904. // if component methods are being called from threads other than the message
  30905. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30906. checkMessageManagerIsLocked
  30907. if (flags.hasHeavyweightPeerFlag)
  30908. {
  30909. ComponentPeer* const peer = getPeer();
  30910. if (peer != 0)
  30911. {
  30912. peer->toFront (setAsForeground);
  30913. if (setAsForeground && ! hasKeyboardFocus (true))
  30914. grabKeyboardFocus();
  30915. }
  30916. }
  30917. else if (parentComponent_ != 0)
  30918. {
  30919. if (parentComponent_->childComponentList_.getLast() != this)
  30920. {
  30921. const int index = parentComponent_->childComponentList_.indexOf (this);
  30922. if (index >= 0)
  30923. {
  30924. int insertIndex = -1;
  30925. if (! flags.alwaysOnTopFlag)
  30926. {
  30927. insertIndex = parentComponent_->childComponentList_.size() - 1;
  30928. while (insertIndex > 0
  30929. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30930. {
  30931. --insertIndex;
  30932. }
  30933. }
  30934. if (index != insertIndex)
  30935. {
  30936. parentComponent_->childComponentList_.move (index, insertIndex);
  30937. sendFakeMouseMove();
  30938. repaintParent();
  30939. }
  30940. }
  30941. }
  30942. if (setAsForeground)
  30943. {
  30944. internalBroughtToFront();
  30945. grabKeyboardFocus();
  30946. }
  30947. }
  30948. }
  30949. void Component::toBehind (Component* const other)
  30950. {
  30951. if (other != 0)
  30952. {
  30953. // the two components must belong to the same parent..
  30954. jassert (parentComponent_ == other->parentComponent_);
  30955. if (parentComponent_ != 0)
  30956. {
  30957. const int index = parentComponent_->childComponentList_.indexOf (this);
  30958. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  30959. if (index >= 0
  30960. && otherIndex >= 0
  30961. && index != otherIndex - 1
  30962. && other != this)
  30963. {
  30964. if (index < otherIndex)
  30965. --otherIndex;
  30966. parentComponent_->childComponentList_.move (index, otherIndex);
  30967. sendFakeMouseMove();
  30968. repaintParent();
  30969. }
  30970. }
  30971. else if (isOnDesktop())
  30972. {
  30973. jassert (other->isOnDesktop());
  30974. if (other->isOnDesktop())
  30975. {
  30976. ComponentPeer* const us = getPeer();
  30977. ComponentPeer* const them = other->getPeer();
  30978. jassert (us != 0 && them != 0);
  30979. if (us != 0 && them != 0)
  30980. us->toBehind (them);
  30981. }
  30982. }
  30983. }
  30984. }
  30985. void Component::toBack()
  30986. {
  30987. if (isOnDesktop())
  30988. {
  30989. jassertfalse //xxx need to add this to native window
  30990. }
  30991. else if (parentComponent_ != 0
  30992. && parentComponent_->childComponentList_.getFirst() != this)
  30993. {
  30994. const int index = parentComponent_->childComponentList_.indexOf (this);
  30995. if (index > 0)
  30996. {
  30997. int insertIndex = 0;
  30998. if (flags.alwaysOnTopFlag)
  30999. {
  31000. while (insertIndex < parentComponent_->childComponentList_.size()
  31001. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  31002. {
  31003. ++insertIndex;
  31004. }
  31005. }
  31006. if (index != insertIndex)
  31007. {
  31008. parentComponent_->childComponentList_.move (index, insertIndex);
  31009. sendFakeMouseMove();
  31010. repaintParent();
  31011. }
  31012. }
  31013. }
  31014. }
  31015. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31016. {
  31017. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31018. {
  31019. flags.alwaysOnTopFlag = shouldStayOnTop;
  31020. if (isOnDesktop())
  31021. {
  31022. ComponentPeer* const peer = getPeer();
  31023. jassert (peer != 0);
  31024. if (peer != 0)
  31025. {
  31026. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31027. {
  31028. // some kinds of peer can't change their always-on-top status, so
  31029. // for these, we'll need to create a new window
  31030. const int oldFlags = peer->getStyleFlags();
  31031. removeFromDesktop();
  31032. addToDesktop (oldFlags);
  31033. }
  31034. }
  31035. }
  31036. if (shouldStayOnTop)
  31037. toFront (false);
  31038. internalHierarchyChanged();
  31039. }
  31040. }
  31041. bool Component::isAlwaysOnTop() const throw()
  31042. {
  31043. return flags.alwaysOnTopFlag;
  31044. }
  31045. int Component::proportionOfWidth (const float proportion) const throw()
  31046. {
  31047. return roundDoubleToInt (proportion * bounds_.getWidth());
  31048. }
  31049. int Component::proportionOfHeight (const float proportion) const throw()
  31050. {
  31051. return roundDoubleToInt (proportion * bounds_.getHeight());
  31052. }
  31053. int Component::getParentWidth() const throw()
  31054. {
  31055. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31056. : getParentMonitorArea().getWidth();
  31057. }
  31058. int Component::getParentHeight() const throw()
  31059. {
  31060. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31061. : getParentMonitorArea().getHeight();
  31062. }
  31063. int Component::getScreenX() const throw()
  31064. {
  31065. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  31066. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  31067. : getX());
  31068. }
  31069. int Component::getScreenY() const throw()
  31070. {
  31071. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  31072. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  31073. : getY());
  31074. }
  31075. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  31076. {
  31077. const Component* c = this;
  31078. do
  31079. {
  31080. if (c->flags.hasHeavyweightPeerFlag)
  31081. {
  31082. c->getPeer()->relativePositionToGlobal (x, y);
  31083. break;
  31084. }
  31085. x += c->getX();
  31086. y += c->getY();
  31087. c = c->parentComponent_;
  31088. }
  31089. while (c != 0);
  31090. }
  31091. void Component::globalPositionToRelative (int& x, int& y) const throw()
  31092. {
  31093. if (flags.hasHeavyweightPeerFlag)
  31094. {
  31095. getPeer()->globalPositionToRelative (x, y);
  31096. }
  31097. else
  31098. {
  31099. if (parentComponent_ != 0)
  31100. parentComponent_->globalPositionToRelative (x, y);
  31101. x -= getX();
  31102. y -= getY();
  31103. }
  31104. }
  31105. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  31106. {
  31107. if (targetComponent != 0)
  31108. {
  31109. const Component* c = this;
  31110. do
  31111. {
  31112. if (c == targetComponent)
  31113. return;
  31114. if (c->flags.hasHeavyweightPeerFlag)
  31115. {
  31116. c->getPeer()->relativePositionToGlobal (x, y);
  31117. break;
  31118. }
  31119. x += c->getX();
  31120. y += c->getY();
  31121. c = c->parentComponent_;
  31122. }
  31123. while (c != 0);
  31124. targetComponent->globalPositionToRelative (x, y);
  31125. }
  31126. }
  31127. void Component::setBounds (int x, int y, int w, int h)
  31128. {
  31129. // if component methods are being called from threads other than the message
  31130. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31131. checkMessageManagerIsLocked
  31132. if (w < 0) w = 0;
  31133. if (h < 0) h = 0;
  31134. const bool wasResized = (getWidth() != w || getHeight() != h);
  31135. const bool wasMoved = (getX() != x || getY() != y);
  31136. #ifdef JUCE_DEBUG
  31137. // It's a very bad idea to try to resize a window during its paint() method!
  31138. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31139. #endif
  31140. if (wasMoved || wasResized)
  31141. {
  31142. if (flags.visibleFlag)
  31143. {
  31144. // send a fake mouse move to trigger enter/exit messages if needed..
  31145. sendFakeMouseMove();
  31146. if (! flags.hasHeavyweightPeerFlag)
  31147. repaintParent();
  31148. }
  31149. bounds_.setBounds (x, y, w, h);
  31150. if (wasResized)
  31151. repaint();
  31152. else if (! flags.hasHeavyweightPeerFlag)
  31153. repaintParent();
  31154. if (flags.hasHeavyweightPeerFlag)
  31155. {
  31156. ComponentPeer* const peer = getPeer();
  31157. if (peer != 0)
  31158. {
  31159. if (wasMoved && wasResized)
  31160. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31161. else if (wasMoved)
  31162. peer->setPosition (getX(), getY());
  31163. else if (wasResized)
  31164. peer->setSize (getWidth(), getHeight());
  31165. }
  31166. }
  31167. sendMovedResizedMessages (wasMoved, wasResized);
  31168. }
  31169. }
  31170. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31171. {
  31172. JUCE_TRY
  31173. {
  31174. if (wasMoved)
  31175. moved();
  31176. if (wasResized)
  31177. {
  31178. resized();
  31179. for (int i = childComponentList_.size(); --i >= 0;)
  31180. {
  31181. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31182. i = jmin (i, childComponentList_.size());
  31183. }
  31184. }
  31185. if (parentComponent_ != 0)
  31186. parentComponent_->childBoundsChanged (this);
  31187. if (componentListeners_ != 0)
  31188. {
  31189. const ComponentDeletionWatcher deletionChecker (this);
  31190. for (int i = componentListeners_->size(); --i >= 0;)
  31191. {
  31192. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31193. ->componentMovedOrResized (*this, wasMoved, wasResized);
  31194. if (deletionChecker.hasBeenDeleted())
  31195. return;
  31196. i = jmin (i, componentListeners_->size());
  31197. }
  31198. }
  31199. }
  31200. JUCE_CATCH_EXCEPTION
  31201. }
  31202. void Component::setSize (const int w, const int h)
  31203. {
  31204. setBounds (getX(), getY(), w, h);
  31205. }
  31206. void Component::setTopLeftPosition (const int x, const int y)
  31207. {
  31208. setBounds (x, y, getWidth(), getHeight());
  31209. }
  31210. void Component::setTopRightPosition (const int x, const int y)
  31211. {
  31212. setTopLeftPosition (x - getWidth(), y);
  31213. }
  31214. void Component::setBounds (const Rectangle& r)
  31215. {
  31216. setBounds (r.getX(),
  31217. r.getY(),
  31218. r.getWidth(),
  31219. r.getHeight());
  31220. }
  31221. void Component::setBoundsRelative (const float x, const float y,
  31222. const float w, const float h)
  31223. {
  31224. const int pw = getParentWidth();
  31225. const int ph = getParentHeight();
  31226. setBounds (roundFloatToInt (x * pw),
  31227. roundFloatToInt (y * ph),
  31228. roundFloatToInt (w * pw),
  31229. roundFloatToInt (h * ph));
  31230. }
  31231. void Component::setCentrePosition (const int x, const int y)
  31232. {
  31233. setTopLeftPosition (x - getWidth() / 2,
  31234. y - getHeight() / 2);
  31235. }
  31236. void Component::setCentreRelative (const float x, const float y)
  31237. {
  31238. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  31239. roundFloatToInt (getParentHeight() * y));
  31240. }
  31241. void Component::centreWithSize (const int width, const int height)
  31242. {
  31243. setBounds ((getParentWidth() - width) / 2,
  31244. (getParentHeight() - height) / 2,
  31245. width,
  31246. height);
  31247. }
  31248. void Component::setBoundsInset (const BorderSize& borders)
  31249. {
  31250. setBounds (borders.getLeft(),
  31251. borders.getTop(),
  31252. getParentWidth() - (borders.getLeftAndRight()),
  31253. getParentHeight() - (borders.getTopAndBottom()));
  31254. }
  31255. void Component::setBoundsToFit (int x, int y, int width, int height,
  31256. const Justification& justification,
  31257. const bool onlyReduceInSize)
  31258. {
  31259. // it's no good calling this method unless both the component and
  31260. // target rectangle have a finite size.
  31261. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31262. if (getWidth() > 0 && getHeight() > 0
  31263. && width > 0 && height > 0)
  31264. {
  31265. int newW, newH;
  31266. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31267. {
  31268. newW = getWidth();
  31269. newH = getHeight();
  31270. }
  31271. else
  31272. {
  31273. const double imageRatio = getHeight() / (double) getWidth();
  31274. const double targetRatio = height / (double) width;
  31275. if (imageRatio <= targetRatio)
  31276. {
  31277. newW = width;
  31278. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  31279. }
  31280. else
  31281. {
  31282. newH = height;
  31283. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  31284. }
  31285. }
  31286. if (newW > 0 && newH > 0)
  31287. {
  31288. int newX, newY;
  31289. justification.applyToRectangle (newX, newY, newW, newH,
  31290. x, y, width, height);
  31291. setBounds (newX, newY, newW, newH);
  31292. }
  31293. }
  31294. }
  31295. bool Component::hitTest (int x, int y)
  31296. {
  31297. if (! flags.ignoresMouseClicksFlag)
  31298. return true;
  31299. if (flags.allowChildMouseClicksFlag)
  31300. {
  31301. for (int i = getNumChildComponents(); --i >= 0;)
  31302. {
  31303. Component* const c = getChildComponent (i);
  31304. if (c->isVisible()
  31305. && c->bounds_.contains (x, y)
  31306. && c->hitTest (x - c->getX(),
  31307. y - c->getY()))
  31308. {
  31309. return true;
  31310. }
  31311. }
  31312. }
  31313. return false;
  31314. }
  31315. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31316. const bool allowClicksOnChildComponents) throw()
  31317. {
  31318. flags.ignoresMouseClicksFlag = ! allowClicks;
  31319. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31320. }
  31321. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31322. bool& allowsClicksOnChildComponents) const throw()
  31323. {
  31324. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31325. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31326. }
  31327. bool Component::contains (const int x, const int y)
  31328. {
  31329. if (((unsigned int) x) < (unsigned int) getWidth()
  31330. && ((unsigned int) y) < (unsigned int) getHeight()
  31331. && hitTest (x, y))
  31332. {
  31333. if (parentComponent_ != 0)
  31334. {
  31335. return parentComponent_->contains (x + getX(),
  31336. y + getY());
  31337. }
  31338. else if (flags.hasHeavyweightPeerFlag)
  31339. {
  31340. const ComponentPeer* const peer = getPeer();
  31341. if (peer != 0)
  31342. return peer->contains (x, y, true);
  31343. }
  31344. }
  31345. return false;
  31346. }
  31347. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31348. {
  31349. if (! contains (x, y))
  31350. return false;
  31351. Component* p = this;
  31352. while (p->parentComponent_ != 0)
  31353. {
  31354. x += p->getX();
  31355. y += p->getY();
  31356. p = p->parentComponent_;
  31357. }
  31358. const Component* const c = p->getComponentAt (x, y);
  31359. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31360. }
  31361. Component* Component::getComponentAt (const int x, const int y)
  31362. {
  31363. if (flags.visibleFlag
  31364. && ((unsigned int) x) < (unsigned int) getWidth()
  31365. && ((unsigned int) y) < (unsigned int) getHeight()
  31366. && hitTest (x, y))
  31367. {
  31368. for (int i = childComponentList_.size(); --i >= 0;)
  31369. {
  31370. Component* const child = childComponentList_.getUnchecked(i);
  31371. Component* const c = child->getComponentAt (x - child->getX(),
  31372. y - child->getY());
  31373. if (c != 0)
  31374. return c;
  31375. }
  31376. return this;
  31377. }
  31378. return 0;
  31379. }
  31380. void Component::addChildComponent (Component* const child, int zOrder)
  31381. {
  31382. // if component methods are being called from threads other than the message
  31383. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31384. checkMessageManagerIsLocked
  31385. if (child != 0 && child->parentComponent_ != this)
  31386. {
  31387. if (child->parentComponent_ != 0)
  31388. child->parentComponent_->removeChildComponent (child);
  31389. else
  31390. child->removeFromDesktop();
  31391. child->parentComponent_ = this;
  31392. if (child->isVisible())
  31393. child->repaintParent();
  31394. if (! child->isAlwaysOnTop())
  31395. {
  31396. if (zOrder < 0 || zOrder > childComponentList_.size())
  31397. zOrder = childComponentList_.size();
  31398. while (zOrder > 0)
  31399. {
  31400. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31401. break;
  31402. --zOrder;
  31403. }
  31404. }
  31405. childComponentList_.insert (zOrder, child);
  31406. child->internalHierarchyChanged();
  31407. internalChildrenChanged();
  31408. }
  31409. }
  31410. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31411. {
  31412. if (child != 0)
  31413. {
  31414. child->setVisible (true);
  31415. addChildComponent (child, zOrder);
  31416. }
  31417. }
  31418. void Component::removeChildComponent (Component* const child)
  31419. {
  31420. removeChildComponent (childComponentList_.indexOf (child));
  31421. }
  31422. Component* Component::removeChildComponent (const int index)
  31423. {
  31424. // if component methods are being called from threads other than the message
  31425. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31426. checkMessageManagerIsLocked
  31427. Component* const child = childComponentList_ [index];
  31428. if (child != 0)
  31429. {
  31430. sendFakeMouseMove();
  31431. child->repaintParent();
  31432. childComponentList_.remove (index);
  31433. child->parentComponent_ = 0;
  31434. JUCE_TRY
  31435. {
  31436. if ((currentlyFocusedComponent == child)
  31437. || child->isParentOf (currentlyFocusedComponent))
  31438. {
  31439. // get rid first to force the grabKeyboardFocus to change to us.
  31440. giveAwayFocus();
  31441. grabKeyboardFocus();
  31442. }
  31443. }
  31444. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31445. catch (const std::exception& e)
  31446. {
  31447. currentlyFocusedComponent = 0;
  31448. Desktop::getInstance().triggerFocusCallback();
  31449. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31450. }
  31451. catch (...)
  31452. {
  31453. currentlyFocusedComponent = 0;
  31454. Desktop::getInstance().triggerFocusCallback();
  31455. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31456. }
  31457. #endif
  31458. child->internalHierarchyChanged();
  31459. internalChildrenChanged();
  31460. }
  31461. return child;
  31462. }
  31463. void Component::removeAllChildren()
  31464. {
  31465. for (int i = childComponentList_.size(); --i >= 0;)
  31466. removeChildComponent (i);
  31467. }
  31468. void Component::deleteAllChildren()
  31469. {
  31470. for (int i = childComponentList_.size(); --i >= 0;)
  31471. delete (removeChildComponent (i));
  31472. }
  31473. int Component::getNumChildComponents() const throw()
  31474. {
  31475. return childComponentList_.size();
  31476. }
  31477. Component* Component::getChildComponent (const int index) const throw()
  31478. {
  31479. return childComponentList_ [index];
  31480. }
  31481. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31482. {
  31483. return childComponentList_.indexOf (const_cast <Component*> (child));
  31484. }
  31485. Component* Component::getTopLevelComponent() const throw()
  31486. {
  31487. const Component* comp = this;
  31488. while (comp->parentComponent_ != 0)
  31489. comp = comp->parentComponent_;
  31490. return (Component*) comp;
  31491. }
  31492. bool Component::isParentOf (const Component* possibleChild) const throw()
  31493. {
  31494. while (possibleChild->isValidComponent())
  31495. {
  31496. possibleChild = possibleChild->parentComponent_;
  31497. if (possibleChild == this)
  31498. return true;
  31499. }
  31500. return false;
  31501. }
  31502. void Component::parentHierarchyChanged()
  31503. {
  31504. }
  31505. void Component::childrenChanged()
  31506. {
  31507. }
  31508. void Component::internalChildrenChanged()
  31509. {
  31510. const ComponentDeletionWatcher deletionChecker (this);
  31511. const bool hasListeners = componentListeners_ != 0;
  31512. childrenChanged();
  31513. if (hasListeners)
  31514. {
  31515. if (deletionChecker.hasBeenDeleted())
  31516. return;
  31517. for (int i = componentListeners_->size(); --i >= 0;)
  31518. {
  31519. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31520. ->componentChildrenChanged (*this);
  31521. if (deletionChecker.hasBeenDeleted())
  31522. return;
  31523. i = jmin (i, componentListeners_->size());
  31524. }
  31525. }
  31526. }
  31527. void Component::internalHierarchyChanged()
  31528. {
  31529. parentHierarchyChanged();
  31530. const ComponentDeletionWatcher deletionChecker (this);
  31531. if (componentListeners_ != 0)
  31532. {
  31533. for (int i = componentListeners_->size(); --i >= 0;)
  31534. {
  31535. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31536. ->componentParentHierarchyChanged (*this);
  31537. if (deletionChecker.hasBeenDeleted())
  31538. return;
  31539. i = jmin (i, componentListeners_->size());
  31540. }
  31541. }
  31542. for (int i = childComponentList_.size(); --i >= 0;)
  31543. {
  31544. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  31545. // you really shouldn't delete the parent component during a callback telling you
  31546. // that it's changed..
  31547. jassert (! deletionChecker.hasBeenDeleted());
  31548. if (deletionChecker.hasBeenDeleted())
  31549. return;
  31550. i = jmin (i, childComponentList_.size());
  31551. }
  31552. }
  31553. void* Component::runModalLoopCallback (void* userData)
  31554. {
  31555. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  31556. }
  31557. int Component::runModalLoop()
  31558. {
  31559. if (! MessageManager::getInstance()->isThisTheMessageThread())
  31560. {
  31561. // use a callback so this can be called from non-gui threads
  31562. return (int) (pointer_sized_int)
  31563. MessageManager::getInstance()
  31564. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  31565. }
  31566. Component* const prevFocused = getCurrentlyFocusedComponent();
  31567. ComponentDeletionWatcher* deletionChecker = 0;
  31568. if (prevFocused != 0)
  31569. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  31570. if (! isCurrentlyModal())
  31571. enterModalState();
  31572. JUCE_TRY
  31573. {
  31574. while (flags.currentlyModalFlag && flags.visibleFlag)
  31575. {
  31576. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  31577. break;
  31578. // check whether this component was deleted during the last message
  31579. if (! isValidMessageListener())
  31580. break;
  31581. }
  31582. }
  31583. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31584. catch (const std::exception& e)
  31585. {
  31586. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31587. return 0;
  31588. }
  31589. catch (...)
  31590. {
  31591. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31592. return 0;
  31593. }
  31594. #endif
  31595. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31596. int returnValue = 0;
  31597. if (modalIndex >= 0)
  31598. {
  31599. modalComponentReturnValueKeys.remove (modalIndex);
  31600. returnValue = modalReturnValues.remove (modalIndex);
  31601. }
  31602. modalComponentStack.removeValue (this);
  31603. if (deletionChecker != 0)
  31604. {
  31605. if (! deletionChecker->hasBeenDeleted())
  31606. prevFocused->grabKeyboardFocus();
  31607. delete deletionChecker;
  31608. }
  31609. return returnValue;
  31610. }
  31611. void Component::enterModalState (const bool takeKeyboardFocus)
  31612. {
  31613. // if component methods are being called from threads other than the message
  31614. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31615. checkMessageManagerIsLocked
  31616. // Check for an attempt to make a component modal when it already is!
  31617. // This can cause nasty problems..
  31618. jassert (! flags.currentlyModalFlag);
  31619. if (! isCurrentlyModal())
  31620. {
  31621. modalComponentStack.add (this);
  31622. modalComponentReturnValueKeys.add (this);
  31623. modalReturnValues.add (0);
  31624. flags.currentlyModalFlag = true;
  31625. setVisible (true);
  31626. if (takeKeyboardFocus)
  31627. grabKeyboardFocus();
  31628. }
  31629. }
  31630. void Component::exitModalState (const int returnValue)
  31631. {
  31632. if (isCurrentlyModal())
  31633. {
  31634. if (MessageManager::getInstance()->isThisTheMessageThread())
  31635. {
  31636. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31637. if (modalIndex >= 0)
  31638. {
  31639. modalReturnValues.set (modalIndex, returnValue);
  31640. }
  31641. else
  31642. {
  31643. modalComponentReturnValueKeys.add (this);
  31644. modalReturnValues.add (returnValue);
  31645. }
  31646. modalComponentStack.removeValue (this);
  31647. flags.currentlyModalFlag = false;
  31648. bringModalComponentToFront();
  31649. }
  31650. else
  31651. {
  31652. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  31653. }
  31654. }
  31655. }
  31656. bool Component::isCurrentlyModal() const throw()
  31657. {
  31658. return flags.currentlyModalFlag
  31659. && getCurrentlyModalComponent() == this;
  31660. }
  31661. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  31662. {
  31663. Component* const mc = getCurrentlyModalComponent();
  31664. return mc != 0
  31665. && mc != this
  31666. && (! mc->isParentOf (this))
  31667. && ! mc->canModalEventBeSentToComponent (this);
  31668. }
  31669. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  31670. {
  31671. return modalComponentStack.size();
  31672. }
  31673. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  31674. {
  31675. Component* const c = (Component*) (modalComponentStack [modalComponentStack.size() - index - 1]);
  31676. return c->isValidComponent() ? c : 0;
  31677. }
  31678. void Component::bringModalComponentToFront()
  31679. {
  31680. ComponentPeer* lastOne = 0;
  31681. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  31682. {
  31683. Component* const c = getCurrentlyModalComponent (i);
  31684. if (c == 0)
  31685. break;
  31686. ComponentPeer* peer = c->getPeer();
  31687. if (peer != 0 && peer != lastOne)
  31688. {
  31689. if (lastOne == 0)
  31690. {
  31691. peer->toFront (true);
  31692. peer->grabFocus();
  31693. }
  31694. else
  31695. peer->toBehind (lastOne);
  31696. lastOne = peer;
  31697. }
  31698. }
  31699. }
  31700. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  31701. {
  31702. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  31703. }
  31704. bool Component::isBroughtToFrontOnMouseClick() const throw()
  31705. {
  31706. return flags.bringToFrontOnClickFlag;
  31707. }
  31708. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  31709. {
  31710. cursor_ = cursor;
  31711. if (flags.visibleFlag)
  31712. {
  31713. int mx, my;
  31714. getMouseXYRelative (mx, my);
  31715. if (flags.draggingFlag || reallyContains (mx, my, false))
  31716. {
  31717. internalUpdateMouseCursor (false);
  31718. }
  31719. }
  31720. }
  31721. const MouseCursor Component::getMouseCursor()
  31722. {
  31723. return cursor_;
  31724. }
  31725. void Component::updateMouseCursor() const throw()
  31726. {
  31727. sendFakeMouseMove();
  31728. }
  31729. void Component::internalUpdateMouseCursor (bool forcedUpdate) throw()
  31730. {
  31731. ComponentPeer* const peer = getPeer();
  31732. if (peer != 0)
  31733. {
  31734. MouseCursor mc (getMouseCursor());
  31735. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  31736. || unboundedMouseOffsetY != 0
  31737. || ! isCursorVisibleUntilOffscreen))
  31738. {
  31739. mc = MouseCursor::NoCursor;
  31740. forcedUpdate = true;
  31741. }
  31742. static void* currentCursorHandle = 0;
  31743. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  31744. {
  31745. currentCursorHandle = mc.getHandle();
  31746. mc.showInWindow (peer);
  31747. }
  31748. }
  31749. }
  31750. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  31751. {
  31752. flags.repaintOnMouseActivityFlag = shouldRepaint;
  31753. }
  31754. void Component::repaintParent() throw()
  31755. {
  31756. if (flags.visibleFlag)
  31757. internalRepaint (0, 0, getWidth(), getHeight());
  31758. }
  31759. void Component::repaint() throw()
  31760. {
  31761. repaint (0, 0, getWidth(), getHeight());
  31762. }
  31763. void Component::repaint (const int x, const int y,
  31764. const int w, const int h) throw()
  31765. {
  31766. deleteAndZero (bufferedImage_);
  31767. if (flags.visibleFlag)
  31768. internalRepaint (x, y, w, h);
  31769. }
  31770. void Component::internalRepaint (int x, int y, int w, int h)
  31771. {
  31772. // if component methods are being called from threads other than the message
  31773. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31774. checkMessageManagerIsLocked
  31775. if (x < 0)
  31776. {
  31777. w += x;
  31778. x = 0;
  31779. }
  31780. if (x + w > getWidth())
  31781. w = getWidth() - x;
  31782. if (w > 0)
  31783. {
  31784. if (y < 0)
  31785. {
  31786. h += y;
  31787. y = 0;
  31788. }
  31789. if (y + h > getHeight())
  31790. h = getHeight() - y;
  31791. if (h > 0)
  31792. {
  31793. if (parentComponent_ != 0)
  31794. {
  31795. x += getX();
  31796. y += getY();
  31797. if (parentComponent_->flags.visibleFlag)
  31798. parentComponent_->internalRepaint (x, y, w, h);
  31799. }
  31800. else if (flags.hasHeavyweightPeerFlag)
  31801. {
  31802. ComponentPeer* const peer = getPeer();
  31803. if (peer != 0)
  31804. peer->repaint (x, y, w, h);
  31805. }
  31806. }
  31807. }
  31808. }
  31809. void Component::paintEntireComponent (Graphics& originalContext)
  31810. {
  31811. jassert (! originalContext.isClipEmpty());
  31812. #ifdef JUCE_DEBUG
  31813. flags.isInsidePaintCall = true;
  31814. #endif
  31815. Graphics* g = &originalContext;
  31816. Image* effectImage = 0;
  31817. if (effect_ != 0)
  31818. {
  31819. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31820. getWidth(), getHeight(),
  31821. ! flags.opaqueFlag);
  31822. g = new Graphics (*effectImage);
  31823. }
  31824. g->saveState();
  31825. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  31826. if (! g->isClipEmpty())
  31827. {
  31828. if (bufferedImage_ != 0)
  31829. {
  31830. g->setColour (Colours::black);
  31831. g->drawImageAt (bufferedImage_, 0, 0);
  31832. }
  31833. else
  31834. {
  31835. if (flags.bufferToImageFlag)
  31836. {
  31837. if (bufferedImage_ == 0)
  31838. {
  31839. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31840. getWidth(), getHeight(), ! flags.opaqueFlag);
  31841. Graphics imG (*bufferedImage_);
  31842. paint (imG);
  31843. }
  31844. g->setColour (Colours::black);
  31845. g->drawImageAt (bufferedImage_, 0, 0);
  31846. }
  31847. else
  31848. {
  31849. paint (*g);
  31850. g->resetToDefaultState();
  31851. }
  31852. }
  31853. }
  31854. g->restoreState();
  31855. for (int i = 0; i < childComponentList_.size(); ++i)
  31856. {
  31857. Component* const child = childComponentList_.getUnchecked (i);
  31858. if (child->isVisible())
  31859. {
  31860. g->saveState();
  31861. if (g->reduceClipRegion (child->getX(), child->getY(),
  31862. child->getWidth(), child->getHeight()))
  31863. {
  31864. for (int j = i + 1; j < childComponentList_.size(); ++j)
  31865. {
  31866. const Component* const sibling = childComponentList_.getUnchecked (j);
  31867. if (sibling->flags.opaqueFlag && sibling->isVisible())
  31868. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  31869. sibling->getWidth(), sibling->getHeight());
  31870. }
  31871. if (! g->isClipEmpty())
  31872. {
  31873. g->setOrigin (child->getX(), child->getY());
  31874. child->paintEntireComponent (*g);
  31875. }
  31876. }
  31877. g->restoreState();
  31878. }
  31879. }
  31880. JUCE_TRY
  31881. {
  31882. g->saveState();
  31883. paintOverChildren (*g);
  31884. g->restoreState();
  31885. }
  31886. JUCE_CATCH_EXCEPTION
  31887. if (effect_ != 0)
  31888. {
  31889. delete g;
  31890. effect_->applyEffect (*effectImage, originalContext);
  31891. delete effectImage;
  31892. }
  31893. #ifdef JUCE_DEBUG
  31894. flags.isInsidePaintCall = false;
  31895. #endif
  31896. }
  31897. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  31898. const bool clipImageToComponentBounds)
  31899. {
  31900. Rectangle r (areaToGrab);
  31901. if (clipImageToComponentBounds)
  31902. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  31903. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31904. jmax (1, r.getWidth()),
  31905. jmax (1, r.getHeight()),
  31906. true);
  31907. Graphics imageContext (*componentImage);
  31908. imageContext.setOrigin (-r.getX(),
  31909. -r.getY());
  31910. paintEntireComponent (imageContext);
  31911. return componentImage;
  31912. }
  31913. void Component::setComponentEffect (ImageEffectFilter* const effect)
  31914. {
  31915. if (effect_ != effect)
  31916. {
  31917. effect_ = effect;
  31918. repaint();
  31919. }
  31920. }
  31921. LookAndFeel& Component::getLookAndFeel() const throw()
  31922. {
  31923. const Component* c = this;
  31924. do
  31925. {
  31926. if (c->lookAndFeel_ != 0)
  31927. return *(c->lookAndFeel_);
  31928. c = c->parentComponent_;
  31929. }
  31930. while (c != 0);
  31931. return LookAndFeel::getDefaultLookAndFeel();
  31932. }
  31933. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  31934. {
  31935. if (lookAndFeel_ != newLookAndFeel)
  31936. {
  31937. lookAndFeel_ = newLookAndFeel;
  31938. sendLookAndFeelChange();
  31939. }
  31940. }
  31941. void Component::lookAndFeelChanged()
  31942. {
  31943. }
  31944. void Component::sendLookAndFeelChange()
  31945. {
  31946. repaint();
  31947. lookAndFeelChanged();
  31948. // (it's not a great idea to do anything that would delete this component
  31949. // during the lookAndFeelChanged() callback)
  31950. jassert (isValidComponent());
  31951. const ComponentDeletionWatcher deletionChecker (this);
  31952. for (int i = childComponentList_.size(); --i >= 0;)
  31953. {
  31954. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  31955. if (deletionChecker.hasBeenDeleted())
  31956. return;
  31957. i = jmin (i, childComponentList_.size());
  31958. }
  31959. }
  31960. static const String getColourPropertyName (const int colourId) throw()
  31961. {
  31962. String s;
  31963. s.preallocateStorage (18);
  31964. s << T("jcclr_") << colourId;
  31965. return s;
  31966. }
  31967. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  31968. {
  31969. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  31970. inheritFromParent,
  31971. String::empty));
  31972. if (customColour.isNotEmpty())
  31973. return Colour (customColour.getIntValue());
  31974. return getLookAndFeel().findColour (colourId);
  31975. }
  31976. bool Component::isColourSpecified (const int colourId) const throw()
  31977. {
  31978. return getComponentProperty (getColourPropertyName (colourId),
  31979. false,
  31980. String::empty).isNotEmpty();
  31981. }
  31982. void Component::removeColour (const int colourId)
  31983. {
  31984. if (isColourSpecified (colourId))
  31985. {
  31986. removeComponentProperty (getColourPropertyName (colourId));
  31987. colourChanged();
  31988. }
  31989. }
  31990. void Component::setColour (const int colourId, const Colour& colour)
  31991. {
  31992. const String colourName (getColourPropertyName (colourId));
  31993. const String customColour (getComponentProperty (colourName, false, String::empty));
  31994. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  31995. {
  31996. setComponentProperty (colourName, colour);
  31997. colourChanged();
  31998. }
  31999. }
  32000. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  32001. {
  32002. if (propertySet_ != 0)
  32003. {
  32004. const StringPairArray& props = propertySet_->getAllProperties();
  32005. const StringArray& keys = props.getAllKeys();
  32006. for (int i = 0; i < keys.size(); ++i)
  32007. {
  32008. if (keys[i].startsWith (T("jcclr_")))
  32009. {
  32010. target.setComponentProperty (keys[i],
  32011. props.getAllValues() [i]);
  32012. }
  32013. }
  32014. target.colourChanged();
  32015. }
  32016. }
  32017. void Component::colourChanged()
  32018. {
  32019. }
  32020. const Rectangle Component::getUnclippedArea() const
  32021. {
  32022. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32023. Component* p = parentComponent_;
  32024. int px = getX();
  32025. int py = getY();
  32026. while (p != 0)
  32027. {
  32028. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32029. return Rectangle();
  32030. px += p->getX();
  32031. py += p->getY();
  32032. p = p->parentComponent_;
  32033. }
  32034. return Rectangle (x, y, w, h);
  32035. }
  32036. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  32037. const int deltaX, const int deltaY) const throw()
  32038. {
  32039. for (int i = childComponentList_.size(); --i >= 0;)
  32040. {
  32041. const Component* const c = childComponentList_.getUnchecked(i);
  32042. if (c->isVisible())
  32043. {
  32044. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  32045. if (! newClip.isEmpty())
  32046. {
  32047. if (c->isOpaque())
  32048. {
  32049. g.excludeClipRegion (deltaX + newClip.getX(),
  32050. deltaY + newClip.getY(),
  32051. newClip.getWidth(),
  32052. newClip.getHeight());
  32053. }
  32054. else
  32055. {
  32056. newClip.translate (-c->getX(), -c->getY());
  32057. c->clipObscuredRegions (g, newClip,
  32058. c->getX() + deltaX,
  32059. c->getY() + deltaY);
  32060. }
  32061. }
  32062. }
  32063. }
  32064. }
  32065. void Component::getVisibleArea (RectangleList& result,
  32066. const bool includeSiblings) const
  32067. {
  32068. result.clear();
  32069. const Rectangle unclipped (getUnclippedArea());
  32070. if (! unclipped.isEmpty())
  32071. {
  32072. result.add (unclipped);
  32073. if (includeSiblings)
  32074. {
  32075. const Component* const c = getTopLevelComponent();
  32076. int x = 0, y = 0;
  32077. c->relativePositionToOtherComponent (this, x, y);
  32078. c->subtractObscuredRegions (result, x, y,
  32079. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  32080. this);
  32081. }
  32082. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  32083. result.consolidate();
  32084. }
  32085. }
  32086. void Component::subtractObscuredRegions (RectangleList& result,
  32087. const int deltaX,
  32088. const int deltaY,
  32089. const Rectangle& clipRect,
  32090. const Component* const compToAvoid) const throw()
  32091. {
  32092. for (int i = childComponentList_.size(); --i >= 0;)
  32093. {
  32094. const Component* const c = childComponentList_.getUnchecked(i);
  32095. if (c != compToAvoid && c->isVisible())
  32096. {
  32097. if (c->isOpaque())
  32098. {
  32099. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  32100. childBounds.translate (deltaX, deltaY);
  32101. result.subtract (childBounds);
  32102. }
  32103. else
  32104. {
  32105. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  32106. newClip.translate (-c->getX(), -c->getY());
  32107. c->subtractObscuredRegions (result,
  32108. c->getX() + deltaX,
  32109. c->getY() + deltaY,
  32110. newClip,
  32111. compToAvoid);
  32112. }
  32113. }
  32114. }
  32115. }
  32116. void Component::mouseEnter (const MouseEvent&)
  32117. {
  32118. // base class does nothing
  32119. }
  32120. void Component::mouseExit (const MouseEvent&)
  32121. {
  32122. // base class does nothing
  32123. }
  32124. void Component::mouseDown (const MouseEvent&)
  32125. {
  32126. // base class does nothing
  32127. }
  32128. void Component::mouseUp (const MouseEvent&)
  32129. {
  32130. // base class does nothing
  32131. }
  32132. void Component::mouseDrag (const MouseEvent&)
  32133. {
  32134. // base class does nothing
  32135. }
  32136. void Component::mouseMove (const MouseEvent&)
  32137. {
  32138. // base class does nothing
  32139. }
  32140. void Component::mouseDoubleClick (const MouseEvent&)
  32141. {
  32142. // base class does nothing
  32143. }
  32144. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32145. {
  32146. // the base class just passes this event up to its parent..
  32147. if (parentComponent_ != 0)
  32148. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32149. wheelIncrementX, wheelIncrementY);
  32150. }
  32151. void Component::resized()
  32152. {
  32153. // base class does nothing
  32154. }
  32155. void Component::moved()
  32156. {
  32157. // base class does nothing
  32158. }
  32159. void Component::childBoundsChanged (Component*)
  32160. {
  32161. // base class does nothing
  32162. }
  32163. void Component::parentSizeChanged()
  32164. {
  32165. // base class does nothing
  32166. }
  32167. void Component::addComponentListener (ComponentListener* const newListener) throw()
  32168. {
  32169. if (componentListeners_ == 0)
  32170. componentListeners_ = new VoidArray (4);
  32171. componentListeners_->addIfNotAlreadyThere (newListener);
  32172. }
  32173. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  32174. {
  32175. jassert (isValidComponent());
  32176. if (componentListeners_ != 0)
  32177. componentListeners_->removeValue (listenerToRemove);
  32178. }
  32179. void Component::inputAttemptWhenModal()
  32180. {
  32181. bringModalComponentToFront();
  32182. getLookAndFeel().playAlertSound();
  32183. }
  32184. bool Component::canModalEventBeSentToComponent (const Component*)
  32185. {
  32186. return false;
  32187. }
  32188. void Component::internalModalInputAttempt()
  32189. {
  32190. Component* const current = getCurrentlyModalComponent();
  32191. if (current != 0)
  32192. current->inputAttemptWhenModal();
  32193. }
  32194. void Component::paint (Graphics&)
  32195. {
  32196. // all painting is done in the subclasses
  32197. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32198. }
  32199. void Component::paintOverChildren (Graphics&)
  32200. {
  32201. // all painting is done in the subclasses
  32202. }
  32203. void Component::handleMessage (const Message& message)
  32204. {
  32205. if (message.intParameter1 == exitModalStateMessage)
  32206. {
  32207. exitModalState (message.intParameter2);
  32208. }
  32209. else if (message.intParameter1 == customCommandMessage)
  32210. {
  32211. handleCommandMessage (message.intParameter2);
  32212. }
  32213. }
  32214. void Component::postCommandMessage (const int commandId) throw()
  32215. {
  32216. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32217. }
  32218. void Component::handleCommandMessage (int)
  32219. {
  32220. // used by subclasses
  32221. }
  32222. void Component::addMouseListener (MouseListener* const newListener,
  32223. const bool wantsEventsForAllNestedChildComponents) throw()
  32224. {
  32225. // if component methods are being called from threads other than the message
  32226. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32227. checkMessageManagerIsLocked
  32228. if (mouseListeners_ == 0)
  32229. mouseListeners_ = new VoidArray (4);
  32230. if (! mouseListeners_->contains (newListener))
  32231. {
  32232. if (wantsEventsForAllNestedChildComponents)
  32233. {
  32234. mouseListeners_->insert (0, newListener);
  32235. ++numDeepMouseListeners;
  32236. }
  32237. else
  32238. {
  32239. mouseListeners_->add (newListener);
  32240. }
  32241. }
  32242. }
  32243. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  32244. {
  32245. // if component methods are being called from threads other than the message
  32246. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32247. checkMessageManagerIsLocked
  32248. if (mouseListeners_ != 0)
  32249. {
  32250. const int index = mouseListeners_->indexOf (listenerToRemove);
  32251. if (index >= 0)
  32252. {
  32253. if (index < numDeepMouseListeners)
  32254. --numDeepMouseListeners;
  32255. mouseListeners_->remove (index);
  32256. }
  32257. }
  32258. }
  32259. void Component::internalMouseEnter (int x, int y, int64 time)
  32260. {
  32261. if (isCurrentlyBlockedByAnotherModalComponent())
  32262. {
  32263. // if something else is modal, always just show a normal mouse cursor
  32264. if (componentUnderMouse == this)
  32265. {
  32266. ComponentPeer* const peer = getPeer();
  32267. if (peer != 0)
  32268. {
  32269. MouseCursor mc (MouseCursor::NormalCursor);
  32270. mc.showInWindow (peer);
  32271. }
  32272. }
  32273. return;
  32274. }
  32275. if (! flags.mouseInsideFlag)
  32276. {
  32277. flags.mouseInsideFlag = true;
  32278. flags.mouseOverFlag = true;
  32279. flags.draggingFlag = false;
  32280. if (isValidComponent())
  32281. {
  32282. const ComponentDeletionWatcher deletionChecker (this);
  32283. if (flags.repaintOnMouseActivityFlag)
  32284. repaint();
  32285. const MouseEvent me (x, y,
  32286. ModifierKeys::getCurrentModifiers(),
  32287. this,
  32288. Time (time),
  32289. x, y,
  32290. Time (time),
  32291. 0, false);
  32292. mouseEnter (me);
  32293. if (deletionChecker.hasBeenDeleted())
  32294. return;
  32295. Desktop::getInstance().resetTimer();
  32296. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32297. {
  32298. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  32299. if (deletionChecker.hasBeenDeleted())
  32300. return;
  32301. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32302. }
  32303. if (mouseListeners_ != 0)
  32304. {
  32305. for (int i = mouseListeners_->size(); --i >= 0;)
  32306. {
  32307. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  32308. if (deletionChecker.hasBeenDeleted())
  32309. return;
  32310. i = jmin (i, mouseListeners_->size());
  32311. }
  32312. }
  32313. const Component* p = parentComponent_;
  32314. while (p != 0)
  32315. {
  32316. const ComponentDeletionWatcher parentDeletionChecker (p);
  32317. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32318. {
  32319. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  32320. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32321. return;
  32322. i = jmin (i, p->numDeepMouseListeners);
  32323. }
  32324. p = p->parentComponent_;
  32325. }
  32326. }
  32327. }
  32328. if (componentUnderMouse == this)
  32329. internalUpdateMouseCursor (true);
  32330. }
  32331. void Component::internalMouseExit (int x, int y, int64 time)
  32332. {
  32333. const ComponentDeletionWatcher deletionChecker (this);
  32334. if (flags.draggingFlag)
  32335. {
  32336. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  32337. if (deletionChecker.hasBeenDeleted())
  32338. return;
  32339. }
  32340. enableUnboundedMouseMovement (false);
  32341. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32342. {
  32343. flags.mouseInsideFlag = false;
  32344. flags.mouseOverFlag = false;
  32345. flags.draggingFlag = false;
  32346. if (flags.repaintOnMouseActivityFlag)
  32347. repaint();
  32348. const MouseEvent me (x, y,
  32349. ModifierKeys::getCurrentModifiers(),
  32350. this,
  32351. Time (time),
  32352. x, y,
  32353. Time (time),
  32354. 0, false);
  32355. mouseExit (me);
  32356. if (deletionChecker.hasBeenDeleted())
  32357. return;
  32358. Desktop::getInstance().resetTimer();
  32359. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32360. {
  32361. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  32362. if (deletionChecker.hasBeenDeleted())
  32363. return;
  32364. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32365. }
  32366. if (mouseListeners_ != 0)
  32367. {
  32368. for (int i = mouseListeners_->size(); --i >= 0;)
  32369. {
  32370. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32371. if (deletionChecker.hasBeenDeleted())
  32372. return;
  32373. i = jmin (i, mouseListeners_->size());
  32374. }
  32375. }
  32376. const Component* p = parentComponent_;
  32377. while (p != 0)
  32378. {
  32379. const ComponentDeletionWatcher parentDeletionChecker (p);
  32380. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32381. {
  32382. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  32383. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32384. return;
  32385. i = jmin (i, p->numDeepMouseListeners);
  32386. }
  32387. p = p->parentComponent_;
  32388. }
  32389. }
  32390. }
  32391. class InternalDragRepeater : public Timer
  32392. {
  32393. public:
  32394. InternalDragRepeater()
  32395. {}
  32396. ~InternalDragRepeater()
  32397. {}
  32398. void timerCallback()
  32399. {
  32400. Component* const c = Component::getComponentUnderMouse();
  32401. if (c != 0 && c->isMouseButtonDown())
  32402. {
  32403. int x, y;
  32404. c->getMouseXYRelative (x, y);
  32405. // the offsets have been added on, so must be taken off before calling the
  32406. // drag.. otherwise they'll be added twice
  32407. x -= unboundedMouseOffsetX;
  32408. y -= unboundedMouseOffsetY;
  32409. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  32410. }
  32411. }
  32412. juce_UseDebuggingNewOperator
  32413. };
  32414. static InternalDragRepeater* dragRepeater = 0;
  32415. void Component::beginDragAutoRepeat (const int interval)
  32416. {
  32417. if (interval > 0)
  32418. {
  32419. if (dragRepeater == 0)
  32420. dragRepeater = new InternalDragRepeater();
  32421. if (dragRepeater->getTimerInterval() != interval)
  32422. dragRepeater->startTimer (interval);
  32423. }
  32424. else
  32425. {
  32426. deleteAndZero (dragRepeater);
  32427. }
  32428. }
  32429. void Component::internalMouseDown (const int x, const int y)
  32430. {
  32431. const ComponentDeletionWatcher deletionChecker (this);
  32432. if (isCurrentlyBlockedByAnotherModalComponent())
  32433. {
  32434. internalModalInputAttempt();
  32435. if (deletionChecker.hasBeenDeleted())
  32436. return;
  32437. // If processing the input attempt has exited the modal loop, we'll allow the event
  32438. // to be delivered..
  32439. if (isCurrentlyBlockedByAnotherModalComponent())
  32440. {
  32441. // allow blocked mouse-events to go to global listeners..
  32442. const MouseEvent me (x, y,
  32443. ModifierKeys::getCurrentModifiers(),
  32444. this,
  32445. Time (juce_recentMouseDownTimes[0]),
  32446. x, y,
  32447. Time (juce_recentMouseDownTimes[0]),
  32448. countMouseClicks(),
  32449. false);
  32450. Desktop::getInstance().resetTimer();
  32451. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32452. {
  32453. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32454. if (deletionChecker.hasBeenDeleted())
  32455. return;
  32456. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32457. }
  32458. return;
  32459. }
  32460. }
  32461. {
  32462. Component* c = this;
  32463. while (c != 0)
  32464. {
  32465. if (c->isBroughtToFrontOnMouseClick())
  32466. {
  32467. c->toFront (true);
  32468. if (deletionChecker.hasBeenDeleted())
  32469. return;
  32470. }
  32471. c = c->parentComponent_;
  32472. }
  32473. }
  32474. if (! flags.dontFocusOnMouseClickFlag)
  32475. grabFocusInternal (focusChangedByMouseClick);
  32476. if (! deletionChecker.hasBeenDeleted())
  32477. {
  32478. flags.draggingFlag = true;
  32479. flags.mouseOverFlag = true;
  32480. if (flags.repaintOnMouseActivityFlag)
  32481. repaint();
  32482. const MouseEvent me (x, y,
  32483. ModifierKeys::getCurrentModifiers(),
  32484. this,
  32485. Time (juce_recentMouseDownTimes[0]),
  32486. x, y,
  32487. Time (juce_recentMouseDownTimes[0]),
  32488. countMouseClicks(),
  32489. false);
  32490. mouseDown (me);
  32491. if (deletionChecker.hasBeenDeleted())
  32492. return;
  32493. Desktop::getInstance().resetTimer();
  32494. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32495. {
  32496. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32497. if (deletionChecker.hasBeenDeleted())
  32498. return;
  32499. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32500. }
  32501. if (mouseListeners_ != 0)
  32502. {
  32503. for (int i = mouseListeners_->size(); --i >= 0;)
  32504. {
  32505. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32506. if (deletionChecker.hasBeenDeleted())
  32507. return;
  32508. i = jmin (i, mouseListeners_->size());
  32509. }
  32510. }
  32511. const Component* p = parentComponent_;
  32512. while (p != 0)
  32513. {
  32514. const ComponentDeletionWatcher parentDeletionChecker (p);
  32515. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32516. {
  32517. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  32518. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32519. return;
  32520. i = jmin (i, p->numDeepMouseListeners);
  32521. }
  32522. p = p->parentComponent_;
  32523. }
  32524. }
  32525. }
  32526. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  32527. {
  32528. if (isValidComponent() && flags.draggingFlag)
  32529. {
  32530. flags.draggingFlag = false;
  32531. deleteAndZero (dragRepeater);
  32532. x += unboundedMouseOffsetX;
  32533. y += unboundedMouseOffsetY;
  32534. juce_LastMousePosX = x;
  32535. juce_LastMousePosY = y;
  32536. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32537. const ComponentDeletionWatcher deletionChecker (this);
  32538. if (flags.repaintOnMouseActivityFlag)
  32539. repaint();
  32540. int mdx = juce_recentMouseDownX[0];
  32541. int mdy = juce_recentMouseDownY[0];
  32542. globalPositionToRelative (mdx, mdy);
  32543. const MouseEvent me (x, y,
  32544. oldModifiers,
  32545. this,
  32546. Time (time),
  32547. mdx, mdy,
  32548. Time (juce_recentMouseDownTimes [0]),
  32549. countMouseClicks(),
  32550. juce_MouseHasMovedSignificantlySincePressed
  32551. || juce_recentMouseDownTimes[0] + 300 < time);
  32552. mouseUp (me);
  32553. if (deletionChecker.hasBeenDeleted())
  32554. return;
  32555. Desktop::getInstance().resetTimer();
  32556. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32557. {
  32558. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  32559. if (deletionChecker.hasBeenDeleted())
  32560. return;
  32561. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32562. }
  32563. if (mouseListeners_ != 0)
  32564. {
  32565. for (int i = mouseListeners_->size(); --i >= 0;)
  32566. {
  32567. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32568. if (deletionChecker.hasBeenDeleted())
  32569. return;
  32570. i = jmin (i, mouseListeners_->size());
  32571. }
  32572. }
  32573. {
  32574. const Component* p = parentComponent_;
  32575. while (p != 0)
  32576. {
  32577. const ComponentDeletionWatcher parentDeletionChecker (p);
  32578. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32579. {
  32580. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  32581. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32582. return;
  32583. i = jmin (i, p->numDeepMouseListeners);
  32584. }
  32585. p = p->parentComponent_;
  32586. }
  32587. }
  32588. // check for double-click
  32589. if (me.getNumberOfClicks() >= 2)
  32590. {
  32591. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32592. mouseDoubleClick (me);
  32593. int i;
  32594. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32595. {
  32596. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  32597. if (deletionChecker.hasBeenDeleted())
  32598. return;
  32599. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32600. }
  32601. for (i = numListeners; --i >= 0;)
  32602. {
  32603. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  32604. return;
  32605. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32606. if (ml != 0)
  32607. ml->mouseDoubleClick (me);
  32608. }
  32609. if (deletionChecker.hasBeenDeleted())
  32610. return;
  32611. const Component* p = parentComponent_;
  32612. while (p != 0)
  32613. {
  32614. const ComponentDeletionWatcher parentDeletionChecker (p);
  32615. for (i = p->numDeepMouseListeners; --i >= 0;)
  32616. {
  32617. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  32618. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32619. return;
  32620. i = jmin (i, p->numDeepMouseListeners);
  32621. }
  32622. p = p->parentComponent_;
  32623. }
  32624. }
  32625. }
  32626. enableUnboundedMouseMovement (false);
  32627. }
  32628. void Component::internalMouseDrag (int x, int y, const int64 time)
  32629. {
  32630. if (isValidComponent() && flags.draggingFlag)
  32631. {
  32632. flags.mouseOverFlag = reallyContains (x, y, false);
  32633. x += unboundedMouseOffsetX;
  32634. y += unboundedMouseOffsetY;
  32635. juce_LastMousePosX = x;
  32636. juce_LastMousePosY = y;
  32637. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32638. juce_MouseHasMovedSignificantlySincePressed
  32639. = juce_MouseHasMovedSignificantlySincePressed
  32640. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  32641. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  32642. const ComponentDeletionWatcher deletionChecker (this);
  32643. int mdx = juce_recentMouseDownX[0];
  32644. int mdy = juce_recentMouseDownY[0];
  32645. globalPositionToRelative (mdx, mdy);
  32646. const MouseEvent me (x, y,
  32647. ModifierKeys::getCurrentModifiers(),
  32648. this,
  32649. Time (time),
  32650. mdx, mdy,
  32651. Time (juce_recentMouseDownTimes[0]),
  32652. countMouseClicks(),
  32653. juce_MouseHasMovedSignificantlySincePressed
  32654. || juce_recentMouseDownTimes[0] + 300 < time);
  32655. mouseDrag (me);
  32656. if (deletionChecker.hasBeenDeleted())
  32657. return;
  32658. Desktop::getInstance().resetTimer();
  32659. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32660. {
  32661. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  32662. if (deletionChecker.hasBeenDeleted())
  32663. return;
  32664. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32665. }
  32666. if (mouseListeners_ != 0)
  32667. {
  32668. for (int i = mouseListeners_->size(); --i >= 0;)
  32669. {
  32670. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  32671. if (deletionChecker.hasBeenDeleted())
  32672. return;
  32673. i = jmin (i, mouseListeners_->size());
  32674. }
  32675. }
  32676. const Component* p = parentComponent_;
  32677. while (p != 0)
  32678. {
  32679. const ComponentDeletionWatcher parentDeletionChecker (p);
  32680. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32681. {
  32682. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  32683. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32684. return;
  32685. i = jmin (i, p->numDeepMouseListeners);
  32686. }
  32687. p = p->parentComponent_;
  32688. }
  32689. if (this == componentUnderMouse)
  32690. {
  32691. if (isUnboundedMouseModeOn)
  32692. {
  32693. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  32694. int mx, my;
  32695. Desktop::getMousePosition (mx, my);
  32696. if (! screenArea.contains (mx, my))
  32697. {
  32698. int deltaX = 0, deltaY = 0;
  32699. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  32700. deltaX = getScreenX() + getWidth() / 2 - mx;
  32701. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  32702. deltaY = getScreenY() + getHeight() / 2 - my;
  32703. unboundedMouseOffsetX -= deltaX;
  32704. unboundedMouseOffsetY -= deltaY;
  32705. Desktop::setMousePosition (mx + deltaX,
  32706. my + deltaY);
  32707. }
  32708. else if (isCursorVisibleUntilOffscreen
  32709. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  32710. && screenArea.contains (mx + unboundedMouseOffsetX,
  32711. my + unboundedMouseOffsetY))
  32712. {
  32713. mx += unboundedMouseOffsetX;
  32714. my += unboundedMouseOffsetY;
  32715. unboundedMouseOffsetX = 0;
  32716. unboundedMouseOffsetY = 0;
  32717. Desktop::setMousePosition (mx, my);
  32718. }
  32719. }
  32720. internalUpdateMouseCursor (false);
  32721. }
  32722. }
  32723. }
  32724. void Component::internalMouseMove (const int x, const int y, const int64 time)
  32725. {
  32726. const ComponentDeletionWatcher deletionChecker (this);
  32727. if (isValidComponent())
  32728. {
  32729. const MouseEvent me (x, y,
  32730. ModifierKeys::getCurrentModifiers(),
  32731. this,
  32732. Time (time),
  32733. x, y,
  32734. Time (time),
  32735. 0, false);
  32736. if (isCurrentlyBlockedByAnotherModalComponent())
  32737. {
  32738. // allow blocked mouse-events to go to global listeners..
  32739. Desktop::getInstance().sendMouseMove();
  32740. }
  32741. else
  32742. {
  32743. if (this == componentUnderMouse)
  32744. internalUpdateMouseCursor (false);
  32745. flags.mouseOverFlag = true;
  32746. mouseMove (me);
  32747. if (deletionChecker.hasBeenDeleted())
  32748. return;
  32749. Desktop::getInstance().resetTimer();
  32750. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32751. {
  32752. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  32753. if (deletionChecker.hasBeenDeleted())
  32754. return;
  32755. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32756. }
  32757. if (mouseListeners_ != 0)
  32758. {
  32759. for (int i = mouseListeners_->size(); --i >= 0;)
  32760. {
  32761. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  32762. if (deletionChecker.hasBeenDeleted())
  32763. return;
  32764. i = jmin (i, mouseListeners_->size());
  32765. }
  32766. }
  32767. const Component* p = parentComponent_;
  32768. while (p != 0)
  32769. {
  32770. const ComponentDeletionWatcher parentDeletionChecker (p);
  32771. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32772. {
  32773. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  32774. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32775. return;
  32776. i = jmin (i, p->numDeepMouseListeners);
  32777. }
  32778. p = p->parentComponent_;
  32779. }
  32780. }
  32781. }
  32782. }
  32783. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  32784. {
  32785. const ComponentDeletionWatcher deletionChecker (this);
  32786. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  32787. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  32788. int mx, my;
  32789. getMouseXYRelative (mx, my);
  32790. const MouseEvent me (mx, my,
  32791. ModifierKeys::getCurrentModifiers(),
  32792. this,
  32793. Time (time),
  32794. mx, my,
  32795. Time (time),
  32796. 0, false);
  32797. if (isCurrentlyBlockedByAnotherModalComponent())
  32798. {
  32799. // allow blocked mouse-events to go to global listeners..
  32800. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32801. {
  32802. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32803. if (deletionChecker.hasBeenDeleted())
  32804. return;
  32805. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32806. }
  32807. }
  32808. else
  32809. {
  32810. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32811. if (deletionChecker.hasBeenDeleted())
  32812. return;
  32813. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32814. {
  32815. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32816. if (deletionChecker.hasBeenDeleted())
  32817. return;
  32818. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32819. }
  32820. if (mouseListeners_ != 0)
  32821. {
  32822. for (int i = mouseListeners_->size(); --i >= 0;)
  32823. {
  32824. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32825. if (deletionChecker.hasBeenDeleted())
  32826. return;
  32827. i = jmin (i, mouseListeners_->size());
  32828. }
  32829. }
  32830. const Component* p = parentComponent_;
  32831. while (p != 0)
  32832. {
  32833. const ComponentDeletionWatcher parentDeletionChecker (p);
  32834. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32835. {
  32836. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32837. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32838. return;
  32839. i = jmin (i, p->numDeepMouseListeners);
  32840. }
  32841. p = p->parentComponent_;
  32842. }
  32843. sendFakeMouseMove();
  32844. }
  32845. }
  32846. void Component::sendFakeMouseMove() const
  32847. {
  32848. ComponentPeer* const peer = getPeer();
  32849. if (peer != 0)
  32850. peer->sendFakeMouseMove();
  32851. }
  32852. void Component::broughtToFront()
  32853. {
  32854. }
  32855. void Component::internalBroughtToFront()
  32856. {
  32857. if (isValidComponent())
  32858. {
  32859. if (flags.hasHeavyweightPeerFlag)
  32860. Desktop::getInstance().componentBroughtToFront (this);
  32861. const ComponentDeletionWatcher deletionChecker (this);
  32862. broughtToFront();
  32863. if (deletionChecker.hasBeenDeleted())
  32864. return;
  32865. if (componentListeners_ != 0)
  32866. {
  32867. for (int i = componentListeners_->size(); --i >= 0;)
  32868. {
  32869. ((ComponentListener*) componentListeners_->getUnchecked (i))
  32870. ->componentBroughtToFront (*this);
  32871. if (deletionChecker.hasBeenDeleted())
  32872. return;
  32873. i = jmin (i, componentListeners_->size());
  32874. }
  32875. }
  32876. // when brought to the front and there's a modal component blocking this one,
  32877. // we need to bring the modal one to the front instead..
  32878. Component* const cm = getCurrentlyModalComponent();
  32879. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  32880. bringModalComponentToFront();
  32881. }
  32882. }
  32883. void Component::focusGained (FocusChangeType)
  32884. {
  32885. // base class does nothing
  32886. }
  32887. void Component::internalFocusGain (const FocusChangeType cause)
  32888. {
  32889. const ComponentDeletionWatcher deletionChecker (this);
  32890. focusGained (cause);
  32891. if (! deletionChecker.hasBeenDeleted())
  32892. internalChildFocusChange (cause);
  32893. }
  32894. void Component::focusLost (FocusChangeType)
  32895. {
  32896. // base class does nothing
  32897. }
  32898. void Component::internalFocusLoss (const FocusChangeType cause)
  32899. {
  32900. const ComponentDeletionWatcher deletionChecker (this);
  32901. focusLost (focusChangedDirectly);
  32902. if (! deletionChecker.hasBeenDeleted())
  32903. internalChildFocusChange (cause);
  32904. }
  32905. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  32906. {
  32907. // base class does nothing
  32908. }
  32909. void Component::internalChildFocusChange (FocusChangeType cause)
  32910. {
  32911. const bool childIsNowFocused = hasKeyboardFocus (true);
  32912. if (flags.childCompFocusedFlag != childIsNowFocused)
  32913. {
  32914. flags.childCompFocusedFlag = childIsNowFocused;
  32915. const ComponentDeletionWatcher deletionChecker (this);
  32916. focusOfChildComponentChanged (cause);
  32917. if (deletionChecker.hasBeenDeleted())
  32918. return;
  32919. }
  32920. if (parentComponent_ != 0)
  32921. parentComponent_->internalChildFocusChange (cause);
  32922. }
  32923. bool Component::isEnabled() const throw()
  32924. {
  32925. return (! flags.isDisabledFlag)
  32926. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  32927. }
  32928. void Component::setEnabled (const bool shouldBeEnabled)
  32929. {
  32930. if (flags.isDisabledFlag == shouldBeEnabled)
  32931. {
  32932. flags.isDisabledFlag = ! shouldBeEnabled;
  32933. // if any parent components are disabled, setting our flag won't make a difference,
  32934. // so no need to send a change message
  32935. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  32936. sendEnablementChangeMessage();
  32937. }
  32938. }
  32939. void Component::sendEnablementChangeMessage()
  32940. {
  32941. const ComponentDeletionWatcher deletionChecker (this);
  32942. enablementChanged();
  32943. if (deletionChecker.hasBeenDeleted())
  32944. return;
  32945. for (int i = getNumChildComponents(); --i >= 0;)
  32946. {
  32947. Component* const c = getChildComponent (i);
  32948. if (c != 0)
  32949. {
  32950. c->sendEnablementChangeMessage();
  32951. if (deletionChecker.hasBeenDeleted())
  32952. return;
  32953. }
  32954. }
  32955. }
  32956. void Component::enablementChanged()
  32957. {
  32958. }
  32959. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  32960. {
  32961. flags.wantsFocusFlag = wantsFocus;
  32962. }
  32963. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  32964. {
  32965. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  32966. }
  32967. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  32968. {
  32969. return ! flags.dontFocusOnMouseClickFlag;
  32970. }
  32971. bool Component::getWantsKeyboardFocus() const throw()
  32972. {
  32973. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  32974. }
  32975. void Component::setFocusContainer (const bool isFocusContainer) throw()
  32976. {
  32977. flags.isFocusContainerFlag = isFocusContainer;
  32978. }
  32979. bool Component::isFocusContainer() const throw()
  32980. {
  32981. return flags.isFocusContainerFlag;
  32982. }
  32983. int Component::getExplicitFocusOrder() const throw()
  32984. {
  32985. return getComponentPropertyInt (T("_jexfo"), false, 0);
  32986. }
  32987. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  32988. {
  32989. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  32990. }
  32991. KeyboardFocusTraverser* Component::createFocusTraverser()
  32992. {
  32993. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  32994. return new KeyboardFocusTraverser();
  32995. return parentComponent_->createFocusTraverser();
  32996. }
  32997. void Component::takeKeyboardFocus (const FocusChangeType cause)
  32998. {
  32999. // give the focus to this component
  33000. if (currentlyFocusedComponent != this)
  33001. {
  33002. JUCE_TRY
  33003. {
  33004. // get the focus onto our desktop window
  33005. ComponentPeer* const peer = getPeer();
  33006. if (peer != 0)
  33007. {
  33008. const ComponentDeletionWatcher deletionChecker (this);
  33009. peer->grabFocus();
  33010. if (peer->isFocused() && currentlyFocusedComponent != this)
  33011. {
  33012. Component* const componentLosingFocus = currentlyFocusedComponent;
  33013. currentlyFocusedComponent = this;
  33014. Desktop::getInstance().triggerFocusCallback();
  33015. // call this after setting currentlyFocusedComponent so that the one that's
  33016. // losing it has a chance to see where focus is going
  33017. if (componentLosingFocus->isValidComponent())
  33018. componentLosingFocus->internalFocusLoss (cause);
  33019. if (currentlyFocusedComponent == this)
  33020. {
  33021. focusGained (cause);
  33022. if (! deletionChecker.hasBeenDeleted())
  33023. internalChildFocusChange (cause);
  33024. }
  33025. }
  33026. }
  33027. }
  33028. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33029. catch (const std::exception& e)
  33030. {
  33031. currentlyFocusedComponent = 0;
  33032. Desktop::getInstance().triggerFocusCallback();
  33033. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33034. }
  33035. catch (...)
  33036. {
  33037. currentlyFocusedComponent = 0;
  33038. Desktop::getInstance().triggerFocusCallback();
  33039. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33040. }
  33041. #endif
  33042. }
  33043. }
  33044. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33045. {
  33046. if (isShowing())
  33047. {
  33048. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33049. {
  33050. takeKeyboardFocus (cause);
  33051. }
  33052. else
  33053. {
  33054. if (isParentOf (currentlyFocusedComponent)
  33055. && currentlyFocusedComponent->isShowing())
  33056. {
  33057. // do nothing if the focused component is actually a child of ours..
  33058. }
  33059. else
  33060. {
  33061. // find the default child component..
  33062. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  33063. if (traverser != 0)
  33064. {
  33065. Component* const defaultComp = traverser->getDefaultComponent (this);
  33066. delete traverser;
  33067. if (defaultComp != 0)
  33068. {
  33069. defaultComp->grabFocusInternal (cause, false);
  33070. return;
  33071. }
  33072. }
  33073. if (canTryParent && parentComponent_ != 0)
  33074. {
  33075. // if no children want it and we're allowed to try our parent comp,
  33076. // then pass up to parent, which will try our siblings.
  33077. parentComponent_->grabFocusInternal (cause, true);
  33078. }
  33079. }
  33080. }
  33081. }
  33082. }
  33083. void Component::grabKeyboardFocus()
  33084. {
  33085. // if component methods are being called from threads other than the message
  33086. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33087. checkMessageManagerIsLocked
  33088. grabFocusInternal (focusChangedDirectly);
  33089. }
  33090. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33091. {
  33092. // if component methods are being called from threads other than the message
  33093. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33094. checkMessageManagerIsLocked
  33095. if (parentComponent_ != 0)
  33096. {
  33097. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  33098. if (traverser != 0)
  33099. {
  33100. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33101. : traverser->getPreviousComponent (this);
  33102. delete traverser;
  33103. if (nextComp != 0)
  33104. {
  33105. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33106. {
  33107. const ComponentDeletionWatcher deletionChecker (nextComp);
  33108. internalModalInputAttempt();
  33109. if (deletionChecker.hasBeenDeleted()
  33110. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33111. return;
  33112. }
  33113. nextComp->grabFocusInternal (focusChangedByTabKey);
  33114. return;
  33115. }
  33116. }
  33117. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33118. }
  33119. }
  33120. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  33121. {
  33122. return (currentlyFocusedComponent == this)
  33123. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33124. }
  33125. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33126. {
  33127. return currentlyFocusedComponent;
  33128. }
  33129. void Component::giveAwayFocus()
  33130. {
  33131. // use a copy so we can clear the value before the call
  33132. Component* const componentLosingFocus = currentlyFocusedComponent;
  33133. currentlyFocusedComponent = 0;
  33134. Desktop::getInstance().triggerFocusCallback();
  33135. if (componentLosingFocus->isValidComponent())
  33136. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33137. }
  33138. bool Component::isMouseOver() const throw()
  33139. {
  33140. return flags.mouseOverFlag;
  33141. }
  33142. bool Component::isMouseButtonDown() const throw()
  33143. {
  33144. return flags.draggingFlag;
  33145. }
  33146. bool Component::isMouseOverOrDragging() const throw()
  33147. {
  33148. return flags.mouseOverFlag || flags.draggingFlag;
  33149. }
  33150. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33151. {
  33152. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33153. }
  33154. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  33155. {
  33156. Desktop::getMousePosition (mx, my);
  33157. globalPositionToRelative (mx, my);
  33158. mx += unboundedMouseOffsetX;
  33159. my += unboundedMouseOffsetY;
  33160. }
  33161. void Component::enableUnboundedMouseMovement (bool enable,
  33162. bool keepCursorVisibleUntilOffscreen) throw()
  33163. {
  33164. enable = enable && isMouseButtonDown();
  33165. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  33166. if (enable != isUnboundedMouseModeOn)
  33167. {
  33168. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  33169. || unboundedMouseOffsetX != 0
  33170. || unboundedMouseOffsetY != 0))
  33171. {
  33172. // when released, return the mouse to within the component's bounds
  33173. int mx, my;
  33174. getMouseXYRelative (mx, my);
  33175. mx = jlimit (0, getWidth(), mx);
  33176. my = jlimit (0, getHeight(), my);
  33177. relativePositionToGlobal (mx, my);
  33178. Desktop::setMousePosition (mx, my);
  33179. }
  33180. isUnboundedMouseModeOn = enable;
  33181. unboundedMouseOffsetX = 0;
  33182. unboundedMouseOffsetY = 0;
  33183. internalUpdateMouseCursor (true);
  33184. }
  33185. }
  33186. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  33187. {
  33188. return componentUnderMouse;
  33189. }
  33190. const Rectangle Component::getParentMonitorArea() const throw()
  33191. {
  33192. int centreX = getWidth() / 2;
  33193. int centreY = getHeight() / 2;
  33194. relativePositionToGlobal (centreX, centreY);
  33195. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  33196. }
  33197. void Component::addKeyListener (KeyListener* const newListener) throw()
  33198. {
  33199. if (keyListeners_ == 0)
  33200. keyListeners_ = new VoidArray (4);
  33201. keyListeners_->addIfNotAlreadyThere (newListener);
  33202. }
  33203. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  33204. {
  33205. if (keyListeners_ != 0)
  33206. keyListeners_->removeValue (listenerToRemove);
  33207. }
  33208. bool Component::keyPressed (const KeyPress&)
  33209. {
  33210. return false;
  33211. }
  33212. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33213. {
  33214. return false;
  33215. }
  33216. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33217. {
  33218. if (parentComponent_ != 0)
  33219. parentComponent_->modifierKeysChanged (modifiers);
  33220. }
  33221. void Component::internalModifierKeysChanged()
  33222. {
  33223. sendFakeMouseMove();
  33224. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33225. }
  33226. ComponentPeer* Component::getPeer() const throw()
  33227. {
  33228. if (flags.hasHeavyweightPeerFlag)
  33229. return ComponentPeer::getPeerFor (this);
  33230. else if (parentComponent_ != 0)
  33231. return parentComponent_->getPeer();
  33232. else
  33233. return 0;
  33234. }
  33235. const String Component::getComponentProperty (const String& keyName,
  33236. const bool useParentComponentIfNotFound,
  33237. const String& defaultReturnValue) const throw()
  33238. {
  33239. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33240. return propertySet_->getValue (keyName, defaultReturnValue);
  33241. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33242. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  33243. return defaultReturnValue;
  33244. }
  33245. int Component::getComponentPropertyInt (const String& keyName,
  33246. const bool useParentComponentIfNotFound,
  33247. const int defaultReturnValue) const throw()
  33248. {
  33249. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33250. return propertySet_->getIntValue (keyName, defaultReturnValue);
  33251. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33252. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  33253. return defaultReturnValue;
  33254. }
  33255. double Component::getComponentPropertyDouble (const String& keyName,
  33256. const bool useParentComponentIfNotFound,
  33257. const double defaultReturnValue) const throw()
  33258. {
  33259. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33260. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  33261. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33262. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  33263. return defaultReturnValue;
  33264. }
  33265. bool Component::getComponentPropertyBool (const String& keyName,
  33266. const bool useParentComponentIfNotFound,
  33267. const bool defaultReturnValue) const throw()
  33268. {
  33269. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33270. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  33271. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33272. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  33273. return defaultReturnValue;
  33274. }
  33275. const Colour Component::getComponentPropertyColour (const String& keyName,
  33276. const bool useParentComponentIfNotFound,
  33277. const Colour& defaultReturnValue) const throw()
  33278. {
  33279. return Colour ((uint32) getComponentPropertyInt (keyName,
  33280. useParentComponentIfNotFound,
  33281. defaultReturnValue.getARGB()));
  33282. }
  33283. void Component::setComponentProperty (const String& keyName, const String& 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 int value) throw()
  33290. {
  33291. if (propertySet_ == 0)
  33292. propertySet_ = new PropertySet();
  33293. propertySet_->setValue (keyName, value);
  33294. }
  33295. void Component::setComponentProperty (const String& keyName, const double value) throw()
  33296. {
  33297. if (propertySet_ == 0)
  33298. propertySet_ = new PropertySet();
  33299. propertySet_->setValue (keyName, value);
  33300. }
  33301. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  33302. {
  33303. if (propertySet_ == 0)
  33304. propertySet_ = new PropertySet();
  33305. propertySet_->setValue (keyName, value);
  33306. }
  33307. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  33308. {
  33309. setComponentProperty (keyName, (int) colour.getARGB());
  33310. }
  33311. void Component::removeComponentProperty (const String& keyName) throw()
  33312. {
  33313. if (propertySet_ != 0)
  33314. propertySet_->removeValue (keyName);
  33315. }
  33316. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  33317. : componentToWatch (componentToWatch_),
  33318. componentUID (componentToWatch_->getComponentUID())
  33319. {
  33320. // not possible to check on an already-deleted object..
  33321. jassert (componentToWatch_->isValidComponent());
  33322. }
  33323. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  33324. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  33325. {
  33326. return ! (componentToWatch->isValidComponent()
  33327. && componentToWatch->getComponentUID() == componentUID);
  33328. }
  33329. const Component* ComponentDeletionWatcher::getComponent() const throw()
  33330. {
  33331. return hasBeenDeleted() ? 0 : componentToWatch;
  33332. }
  33333. END_JUCE_NAMESPACE
  33334. /********* End of inlined file: juce_Component.cpp *********/
  33335. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  33336. BEGIN_JUCE_NAMESPACE
  33337. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  33338. {
  33339. }
  33340. void ComponentListener::componentBroughtToFront (Component&)
  33341. {
  33342. }
  33343. void ComponentListener::componentVisibilityChanged (Component&)
  33344. {
  33345. }
  33346. void ComponentListener::componentChildrenChanged (Component&)
  33347. {
  33348. }
  33349. void ComponentListener::componentParentHierarchyChanged (Component&)
  33350. {
  33351. }
  33352. void ComponentListener::componentNameChanged (Component&)
  33353. {
  33354. }
  33355. END_JUCE_NAMESPACE
  33356. /********* End of inlined file: juce_ComponentListener.cpp *********/
  33357. /********* Start of inlined file: juce_Desktop.cpp *********/
  33358. BEGIN_JUCE_NAMESPACE
  33359. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  33360. const bool clipToWorkArea) throw();
  33361. static Desktop* juce_desktopInstance = 0;
  33362. Desktop::Desktop() throw()
  33363. : mouseListeners (2),
  33364. desktopComponents (4),
  33365. monitorCoordsClipped (2),
  33366. monitorCoordsUnclipped (2),
  33367. lastMouseX (0),
  33368. lastMouseY (0),
  33369. kioskModeComponent (0)
  33370. {
  33371. refreshMonitorSizes();
  33372. }
  33373. Desktop::~Desktop() throw()
  33374. {
  33375. jassert (juce_desktopInstance == this);
  33376. juce_desktopInstance = 0;
  33377. // doh! If you don't delete all your windows before exiting, you're going to
  33378. // be leaking memory!
  33379. jassert (desktopComponents.size() == 0);
  33380. }
  33381. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  33382. {
  33383. if (juce_desktopInstance == 0)
  33384. juce_desktopInstance = new Desktop();
  33385. return *juce_desktopInstance;
  33386. }
  33387. void Desktop::refreshMonitorSizes() throw()
  33388. {
  33389. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  33390. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  33391. monitorCoordsClipped.clear();
  33392. monitorCoordsUnclipped.clear();
  33393. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33394. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33395. jassert (monitorCoordsClipped.size() > 0
  33396. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33397. if (oldClipped != monitorCoordsClipped
  33398. || oldUnclipped != monitorCoordsUnclipped)
  33399. {
  33400. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33401. {
  33402. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33403. if (p != 0)
  33404. p->handleScreenSizeChange();
  33405. }
  33406. }
  33407. }
  33408. int Desktop::getNumDisplayMonitors() const throw()
  33409. {
  33410. return monitorCoordsClipped.size();
  33411. }
  33412. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33413. {
  33414. return clippedToWorkArea ? monitorCoordsClipped [index]
  33415. : monitorCoordsUnclipped [index];
  33416. }
  33417. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33418. {
  33419. RectangleList rl;
  33420. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33421. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33422. return rl;
  33423. }
  33424. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33425. {
  33426. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33427. }
  33428. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  33429. {
  33430. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  33431. double bestDistance = 1.0e10;
  33432. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33433. {
  33434. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33435. if (rect.contains (cx, cy))
  33436. return rect;
  33437. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  33438. (double) (rect.getCentreY() - cy));
  33439. if (distance < bestDistance)
  33440. {
  33441. bestDistance = distance;
  33442. best = rect;
  33443. }
  33444. }
  33445. return best;
  33446. }
  33447. int Desktop::getNumComponents() const throw()
  33448. {
  33449. return desktopComponents.size();
  33450. }
  33451. Component* Desktop::getComponent (const int index) const throw()
  33452. {
  33453. return (Component*) desktopComponents [index];
  33454. }
  33455. Component* Desktop::findComponentAt (const int screenX,
  33456. const int screenY) const
  33457. {
  33458. for (int i = desktopComponents.size(); --i >= 0;)
  33459. {
  33460. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  33461. int x = screenX, y = screenY;
  33462. c->globalPositionToRelative (x, y);
  33463. if (c->contains (x, y))
  33464. return c->getComponentAt (x, y);
  33465. }
  33466. return 0;
  33467. }
  33468. void Desktop::addDesktopComponent (Component* const c) throw()
  33469. {
  33470. jassert (c != 0);
  33471. jassert (! desktopComponents.contains (c));
  33472. desktopComponents.addIfNotAlreadyThere (c);
  33473. }
  33474. void Desktop::removeDesktopComponent (Component* const c) throw()
  33475. {
  33476. desktopComponents.removeValue (c);
  33477. }
  33478. void Desktop::componentBroughtToFront (Component* const c) throw()
  33479. {
  33480. const int index = desktopComponents.indexOf (c);
  33481. jassert (index >= 0);
  33482. if (index >= 0)
  33483. desktopComponents.move (index, -1);
  33484. }
  33485. // from Component.cpp
  33486. extern int juce_recentMouseDownX [4];
  33487. extern int juce_recentMouseDownY [4];
  33488. extern int juce_MouseClickCounter;
  33489. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  33490. {
  33491. x = juce_recentMouseDownX [0];
  33492. y = juce_recentMouseDownY [0];
  33493. }
  33494. int Desktop::getMouseButtonClickCounter() throw()
  33495. {
  33496. return juce_MouseClickCounter;
  33497. }
  33498. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  33499. {
  33500. jassert (listener != 0);
  33501. if (listener != 0)
  33502. {
  33503. mouseListeners.add (listener);
  33504. resetTimer();
  33505. }
  33506. }
  33507. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  33508. {
  33509. mouseListeners.removeValue (listener);
  33510. resetTimer();
  33511. }
  33512. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  33513. {
  33514. jassert (listener != 0);
  33515. if (listener != 0)
  33516. focusListeners.add (listener);
  33517. }
  33518. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  33519. {
  33520. focusListeners.removeValue (listener);
  33521. }
  33522. void Desktop::triggerFocusCallback() throw()
  33523. {
  33524. triggerAsyncUpdate();
  33525. }
  33526. void Desktop::handleAsyncUpdate()
  33527. {
  33528. for (int i = focusListeners.size(); --i >= 0;)
  33529. {
  33530. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  33531. i = jmin (i, focusListeners.size());
  33532. }
  33533. }
  33534. void Desktop::timerCallback()
  33535. {
  33536. int x, y;
  33537. getMousePosition (x, y);
  33538. if (lastMouseX != x || lastMouseY != y)
  33539. sendMouseMove();
  33540. }
  33541. void Desktop::sendMouseMove()
  33542. {
  33543. if (mouseListeners.size() > 0)
  33544. {
  33545. startTimer (20);
  33546. int x, y;
  33547. getMousePosition (x, y);
  33548. lastMouseX = x;
  33549. lastMouseY = y;
  33550. Component* const target = findComponentAt (x, y);
  33551. if (target != 0)
  33552. {
  33553. target->globalPositionToRelative (x, y);
  33554. ComponentDeletionWatcher deletionChecker (target);
  33555. const MouseEvent me (x, y,
  33556. ModifierKeys::getCurrentModifiers(),
  33557. target,
  33558. Time::getCurrentTime(),
  33559. x, y,
  33560. Time::getCurrentTime(),
  33561. 0, false);
  33562. for (int i = mouseListeners.size(); --i >= 0;)
  33563. {
  33564. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  33565. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  33566. else
  33567. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  33568. if (deletionChecker.hasBeenDeleted())
  33569. return;
  33570. i = jmin (i, mouseListeners.size());
  33571. }
  33572. }
  33573. }
  33574. }
  33575. void Desktop::resetTimer() throw()
  33576. {
  33577. if (mouseListeners.size() == 0)
  33578. stopTimer();
  33579. else
  33580. startTimer (100);
  33581. getMousePosition (lastMouseX, lastMouseY);
  33582. }
  33583. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33584. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33585. {
  33586. if (kioskModeComponent != componentToUse)
  33587. {
  33588. // agh! Don't delete a component without first stopping it being the kiosk comp
  33589. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33590. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33591. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33592. if (kioskModeComponent->isValidComponent())
  33593. {
  33594. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33595. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33596. }
  33597. kioskModeComponent = componentToUse;
  33598. if (kioskModeComponent != 0)
  33599. {
  33600. jassert (kioskModeComponent->isValidComponent());
  33601. // Only components that are already on the desktop can be put into kiosk mode!
  33602. jassert (kioskModeComponent->isOnDesktop());
  33603. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33604. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33605. }
  33606. }
  33607. }
  33608. END_JUCE_NAMESPACE
  33609. /********* End of inlined file: juce_Desktop.cpp *********/
  33610. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  33611. BEGIN_JUCE_NAMESPACE
  33612. ArrowButton::ArrowButton (const String& name,
  33613. float arrowDirectionInRadians,
  33614. const Colour& arrowColour)
  33615. : Button (name),
  33616. colour (arrowColour)
  33617. {
  33618. path.lineTo (0.0f, 1.0f);
  33619. path.lineTo (1.0f, 0.5f);
  33620. path.closeSubPath();
  33621. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33622. 0.5f, 0.5f));
  33623. setComponentEffect (&shadow);
  33624. buttonStateChanged();
  33625. }
  33626. ArrowButton::~ArrowButton()
  33627. {
  33628. }
  33629. void ArrowButton::paintButton (Graphics& g,
  33630. bool /*isMouseOverButton*/,
  33631. bool /*isButtonDown*/)
  33632. {
  33633. g.setColour (colour);
  33634. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33635. (float) offset,
  33636. (float) (getWidth() - 3),
  33637. (float) (getHeight() - 3),
  33638. false));
  33639. }
  33640. void ArrowButton::buttonStateChanged()
  33641. {
  33642. offset = (isDown()) ? 1 : 0;
  33643. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33644. 0.3f, -1, 0);
  33645. }
  33646. END_JUCE_NAMESPACE
  33647. /********* End of inlined file: juce_ArrowButton.cpp *********/
  33648. /********* Start of inlined file: juce_Button.cpp *********/
  33649. BEGIN_JUCE_NAMESPACE
  33650. Button::Button (const String& name)
  33651. : Component (name),
  33652. shortcuts (2),
  33653. keySource (0),
  33654. text (name),
  33655. buttonListeners (2),
  33656. repeatTimer (0),
  33657. buttonPressTime (0),
  33658. lastTimeCallbackTime (0),
  33659. commandManagerToUse (0),
  33660. autoRepeatDelay (-1),
  33661. autoRepeatSpeed (0),
  33662. autoRepeatMinimumDelay (-1),
  33663. radioGroupId (0),
  33664. commandID (0),
  33665. connectedEdgeFlags (0),
  33666. buttonState (buttonNormal),
  33667. isOn (false),
  33668. clickTogglesState (false),
  33669. needsToRelease (false),
  33670. needsRepainting (false),
  33671. isKeyDown (false),
  33672. triggerOnMouseDown (false),
  33673. generateTooltip (false)
  33674. {
  33675. setWantsKeyboardFocus (true);
  33676. }
  33677. Button::~Button()
  33678. {
  33679. if (commandManagerToUse != 0)
  33680. commandManagerToUse->removeListener (this);
  33681. delete repeatTimer;
  33682. clearShortcuts();
  33683. }
  33684. void Button::setButtonText (const String& newText) throw()
  33685. {
  33686. if (text != newText)
  33687. {
  33688. text = newText;
  33689. repaint();
  33690. }
  33691. }
  33692. void Button::setTooltip (const String& newTooltip)
  33693. {
  33694. SettableTooltipClient::setTooltip (newTooltip);
  33695. generateTooltip = false;
  33696. }
  33697. const String Button::getTooltip()
  33698. {
  33699. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33700. {
  33701. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33702. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33703. for (int i = 0; i < keyPresses.size(); ++i)
  33704. {
  33705. const String key (keyPresses.getReference(i).getTextDescription());
  33706. if (key.length() == 1)
  33707. tt << " [shortcut: '" << key << "']";
  33708. else
  33709. tt << " [" << key << ']';
  33710. }
  33711. return tt;
  33712. }
  33713. return SettableTooltipClient::getTooltip();
  33714. }
  33715. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  33716. {
  33717. if (connectedEdgeFlags != connectedEdgeFlags_)
  33718. {
  33719. connectedEdgeFlags = connectedEdgeFlags_;
  33720. repaint();
  33721. }
  33722. }
  33723. void Button::setToggleState (const bool shouldBeOn,
  33724. const bool sendChangeNotification)
  33725. {
  33726. if (shouldBeOn != isOn)
  33727. {
  33728. const ComponentDeletionWatcher deletionWatcher (this);
  33729. isOn = shouldBeOn;
  33730. repaint();
  33731. if (sendChangeNotification)
  33732. sendClickMessage (ModifierKeys());
  33733. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  33734. turnOffOtherButtonsInGroup (sendChangeNotification);
  33735. }
  33736. }
  33737. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33738. {
  33739. clickTogglesState = shouldToggle;
  33740. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33741. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33742. // it is that this button represents, and the button will update its state to reflect this
  33743. // in the applicationCommandListChanged() method.
  33744. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33745. }
  33746. bool Button::getClickingTogglesState() const throw()
  33747. {
  33748. return clickTogglesState;
  33749. }
  33750. void Button::setRadioGroupId (const int newGroupId)
  33751. {
  33752. if (radioGroupId != newGroupId)
  33753. {
  33754. radioGroupId = newGroupId;
  33755. if (isOn)
  33756. turnOffOtherButtonsInGroup (true);
  33757. }
  33758. }
  33759. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33760. {
  33761. Component* const p = getParentComponent();
  33762. if (p != 0 && radioGroupId != 0)
  33763. {
  33764. const ComponentDeletionWatcher deletionWatcher (this);
  33765. for (int i = p->getNumChildComponents(); --i >= 0;)
  33766. {
  33767. Component* const c = p->getChildComponent (i);
  33768. if (c != this)
  33769. {
  33770. Button* const b = dynamic_cast <Button*> (c);
  33771. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33772. {
  33773. b->setToggleState (false, sendChangeNotification);
  33774. if (deletionWatcher.hasBeenDeleted())
  33775. return;
  33776. }
  33777. }
  33778. }
  33779. }
  33780. }
  33781. void Button::enablementChanged()
  33782. {
  33783. updateState (0);
  33784. repaint();
  33785. }
  33786. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  33787. {
  33788. ButtonState state = buttonNormal;
  33789. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33790. {
  33791. int mx, my;
  33792. if (e == 0)
  33793. {
  33794. getMouseXYRelative (mx, my);
  33795. }
  33796. else
  33797. {
  33798. const MouseEvent e2 (e->getEventRelativeTo (this));
  33799. mx = e2.x;
  33800. my = e2.y;
  33801. }
  33802. const bool over = reallyContains (mx, my, true);
  33803. const bool down = isMouseButtonDown();
  33804. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33805. state = buttonDown;
  33806. else if (over)
  33807. state = buttonOver;
  33808. }
  33809. setState (state);
  33810. return state;
  33811. }
  33812. void Button::setState (const ButtonState newState)
  33813. {
  33814. if (buttonState != newState)
  33815. {
  33816. buttonState = newState;
  33817. repaint();
  33818. if (buttonState == buttonDown)
  33819. {
  33820. buttonPressTime = Time::getApproximateMillisecondCounter();
  33821. lastTimeCallbackTime = buttonPressTime;
  33822. }
  33823. sendStateMessage();
  33824. }
  33825. }
  33826. bool Button::isDown() const throw()
  33827. {
  33828. return buttonState == buttonDown;
  33829. }
  33830. bool Button::isOver() const throw()
  33831. {
  33832. return buttonState != buttonNormal;
  33833. }
  33834. void Button::buttonStateChanged()
  33835. {
  33836. }
  33837. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  33838. {
  33839. const uint32 now = Time::getApproximateMillisecondCounter();
  33840. return now > buttonPressTime ? now - buttonPressTime : 0;
  33841. }
  33842. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  33843. {
  33844. triggerOnMouseDown = isTriggeredOnMouseDown;
  33845. }
  33846. void Button::clicked()
  33847. {
  33848. }
  33849. void Button::clicked (const ModifierKeys& /*modifiers*/)
  33850. {
  33851. clicked();
  33852. }
  33853. static const int clickMessageId = 0x2f3f4f99;
  33854. void Button::triggerClick()
  33855. {
  33856. postCommandMessage (clickMessageId);
  33857. }
  33858. void Button::internalClickCallback (const ModifierKeys& modifiers)
  33859. {
  33860. if (clickTogglesState)
  33861. setToggleState ((radioGroupId != 0) || ! isOn, false);
  33862. sendClickMessage (modifiers);
  33863. }
  33864. void Button::flashButtonState() throw()
  33865. {
  33866. if (isEnabled())
  33867. {
  33868. needsToRelease = true;
  33869. setState (buttonDown);
  33870. getRepeatTimer().startTimer (100);
  33871. }
  33872. }
  33873. void Button::handleCommandMessage (int commandId)
  33874. {
  33875. if (commandId == clickMessageId)
  33876. {
  33877. if (isEnabled())
  33878. {
  33879. flashButtonState();
  33880. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33881. }
  33882. }
  33883. else
  33884. {
  33885. Component::handleCommandMessage (commandId);
  33886. }
  33887. }
  33888. void Button::addButtonListener (ButtonListener* const newListener) throw()
  33889. {
  33890. jassert (newListener != 0);
  33891. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  33892. if (newListener != 0)
  33893. buttonListeners.add (newListener);
  33894. }
  33895. void Button::removeButtonListener (ButtonListener* const listener) throw()
  33896. {
  33897. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  33898. buttonListeners.removeValue (listener);
  33899. }
  33900. void Button::sendClickMessage (const ModifierKeys& modifiers)
  33901. {
  33902. const ComponentDeletionWatcher cdw (this);
  33903. if (commandManagerToUse != 0 && commandID != 0)
  33904. {
  33905. ApplicationCommandTarget::InvocationInfo info (commandID);
  33906. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  33907. info.originatingComponent = this;
  33908. commandManagerToUse->invoke (info, true);
  33909. }
  33910. clicked (modifiers);
  33911. if (! cdw.hasBeenDeleted())
  33912. {
  33913. for (int i = buttonListeners.size(); --i >= 0;)
  33914. {
  33915. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33916. if (bl != 0)
  33917. {
  33918. bl->buttonClicked (this);
  33919. if (cdw.hasBeenDeleted())
  33920. return;
  33921. }
  33922. }
  33923. }
  33924. }
  33925. void Button::sendStateMessage()
  33926. {
  33927. const ComponentDeletionWatcher cdw (this);
  33928. buttonStateChanged();
  33929. if (cdw.hasBeenDeleted())
  33930. return;
  33931. for (int i = buttonListeners.size(); --i >= 0;)
  33932. {
  33933. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33934. if (bl != 0)
  33935. {
  33936. bl->buttonStateChanged (this);
  33937. if (cdw.hasBeenDeleted())
  33938. return;
  33939. }
  33940. }
  33941. }
  33942. void Button::paint (Graphics& g)
  33943. {
  33944. if (needsToRelease && isEnabled())
  33945. {
  33946. needsToRelease = false;
  33947. needsRepainting = true;
  33948. }
  33949. paintButton (g, isOver(), isDown());
  33950. }
  33951. void Button::mouseEnter (const MouseEvent& e)
  33952. {
  33953. updateState (&e);
  33954. }
  33955. void Button::mouseExit (const MouseEvent& e)
  33956. {
  33957. updateState (&e);
  33958. }
  33959. void Button::mouseDown (const MouseEvent& e)
  33960. {
  33961. updateState (&e);
  33962. if (isDown())
  33963. {
  33964. if (autoRepeatDelay >= 0)
  33965. getRepeatTimer().startTimer (autoRepeatDelay);
  33966. if (triggerOnMouseDown)
  33967. internalClickCallback (e.mods);
  33968. }
  33969. }
  33970. void Button::mouseUp (const MouseEvent& e)
  33971. {
  33972. const bool wasDown = isDown();
  33973. updateState (&e);
  33974. if (wasDown && isOver() && ! triggerOnMouseDown)
  33975. internalClickCallback (e.mods);
  33976. }
  33977. void Button::mouseDrag (const MouseEvent& e)
  33978. {
  33979. const ButtonState oldState = buttonState;
  33980. updateState (&e);
  33981. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  33982. getRepeatTimer().startTimer (autoRepeatSpeed);
  33983. }
  33984. void Button::focusGained (FocusChangeType)
  33985. {
  33986. updateState (0);
  33987. repaint();
  33988. }
  33989. void Button::focusLost (FocusChangeType)
  33990. {
  33991. updateState (0);
  33992. repaint();
  33993. }
  33994. void Button::setVisible (bool shouldBeVisible)
  33995. {
  33996. if (shouldBeVisible != isVisible())
  33997. {
  33998. Component::setVisible (shouldBeVisible);
  33999. if (! shouldBeVisible)
  34000. needsToRelease = false;
  34001. updateState (0);
  34002. }
  34003. else
  34004. {
  34005. Component::setVisible (shouldBeVisible);
  34006. }
  34007. }
  34008. void Button::parentHierarchyChanged()
  34009. {
  34010. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34011. if (newKeySource != keySource)
  34012. {
  34013. if (keySource->isValidComponent())
  34014. keySource->removeKeyListener (this);
  34015. keySource = newKeySource;
  34016. if (keySource->isValidComponent())
  34017. keySource->addKeyListener (this);
  34018. }
  34019. }
  34020. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34021. const int commandID_,
  34022. const bool generateTooltip_)
  34023. {
  34024. commandID = commandID_;
  34025. generateTooltip = generateTooltip_;
  34026. if (commandManagerToUse != commandManagerToUse_)
  34027. {
  34028. if (commandManagerToUse != 0)
  34029. commandManagerToUse->removeListener (this);
  34030. commandManagerToUse = commandManagerToUse_;
  34031. if (commandManagerToUse != 0)
  34032. commandManagerToUse->addListener (this);
  34033. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34034. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34035. // it is that this button represents, and the button will update its state to reflect this
  34036. // in the applicationCommandListChanged() method.
  34037. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34038. }
  34039. if (commandManagerToUse != 0)
  34040. applicationCommandListChanged();
  34041. else
  34042. setEnabled (true);
  34043. }
  34044. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34045. {
  34046. if (info.commandID == commandID
  34047. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34048. {
  34049. flashButtonState();
  34050. }
  34051. }
  34052. void Button::applicationCommandListChanged()
  34053. {
  34054. if (commandManagerToUse != 0)
  34055. {
  34056. ApplicationCommandInfo info (0);
  34057. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34058. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34059. if (target != 0)
  34060. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34061. }
  34062. }
  34063. void Button::addShortcut (const KeyPress& key)
  34064. {
  34065. if (key.isValid())
  34066. {
  34067. jassert (! isRegisteredForShortcut (key)); // already registered!
  34068. shortcuts.add (key);
  34069. parentHierarchyChanged();
  34070. }
  34071. }
  34072. void Button::clearShortcuts()
  34073. {
  34074. shortcuts.clear();
  34075. parentHierarchyChanged();
  34076. }
  34077. bool Button::isShortcutPressed() const throw()
  34078. {
  34079. if (! isCurrentlyBlockedByAnotherModalComponent())
  34080. {
  34081. for (int i = shortcuts.size(); --i >= 0;)
  34082. if (shortcuts.getReference(i).isCurrentlyDown())
  34083. return true;
  34084. }
  34085. return false;
  34086. }
  34087. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  34088. {
  34089. for (int i = shortcuts.size(); --i >= 0;)
  34090. if (key == shortcuts.getReference(i))
  34091. return true;
  34092. return false;
  34093. }
  34094. bool Button::keyStateChanged (const bool, Component*)
  34095. {
  34096. if (! isEnabled())
  34097. return false;
  34098. const bool wasDown = isKeyDown;
  34099. isKeyDown = isShortcutPressed();
  34100. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34101. getRepeatTimer().startTimer (autoRepeatDelay);
  34102. updateState (0);
  34103. if (isEnabled() && wasDown && ! isKeyDown)
  34104. {
  34105. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34106. // (return immediately - this button may now have been deleted)
  34107. return true;
  34108. }
  34109. return wasDown || isKeyDown;
  34110. }
  34111. bool Button::keyPressed (const KeyPress&, Component*)
  34112. {
  34113. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34114. return isShortcutPressed();
  34115. }
  34116. bool Button::keyPressed (const KeyPress& key)
  34117. {
  34118. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34119. {
  34120. triggerClick();
  34121. return true;
  34122. }
  34123. return false;
  34124. }
  34125. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34126. const int repeatMillisecs,
  34127. const int minimumDelayInMillisecs) throw()
  34128. {
  34129. autoRepeatDelay = initialDelayMillisecs;
  34130. autoRepeatSpeed = repeatMillisecs;
  34131. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34132. }
  34133. void Button::repeatTimerCallback() throw()
  34134. {
  34135. if (needsRepainting)
  34136. {
  34137. getRepeatTimer().stopTimer();
  34138. updateState (0);
  34139. needsRepainting = false;
  34140. }
  34141. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34142. {
  34143. int repeatSpeed = autoRepeatSpeed;
  34144. if (autoRepeatMinimumDelay >= 0)
  34145. {
  34146. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34147. timeHeldDown *= timeHeldDown;
  34148. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34149. }
  34150. repeatSpeed = jmax (1, repeatSpeed);
  34151. getRepeatTimer().startTimer (repeatSpeed);
  34152. const uint32 now = Time::getApproximateMillisecondCounter();
  34153. const int numTimesToCallback
  34154. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34155. lastTimeCallbackTime = now;
  34156. const ComponentDeletionWatcher cdw (this);
  34157. for (int i = numTimesToCallback; --i >= 0;)
  34158. {
  34159. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34160. if (cdw.hasBeenDeleted() || ! isDown())
  34161. return;
  34162. }
  34163. }
  34164. else if (! needsToRelease)
  34165. {
  34166. getRepeatTimer().stopTimer();
  34167. }
  34168. }
  34169. class InternalButtonRepeatTimer : public Timer
  34170. {
  34171. public:
  34172. InternalButtonRepeatTimer (Button& owner_) throw()
  34173. : owner (owner_)
  34174. {
  34175. }
  34176. ~InternalButtonRepeatTimer()
  34177. {
  34178. }
  34179. void timerCallback()
  34180. {
  34181. owner.repeatTimerCallback();
  34182. }
  34183. private:
  34184. Button& owner;
  34185. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  34186. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  34187. };
  34188. Timer& Button::getRepeatTimer() throw()
  34189. {
  34190. if (repeatTimer == 0)
  34191. repeatTimer = new InternalButtonRepeatTimer (*this);
  34192. return *repeatTimer;
  34193. }
  34194. END_JUCE_NAMESPACE
  34195. /********* End of inlined file: juce_Button.cpp *********/
  34196. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  34197. BEGIN_JUCE_NAMESPACE
  34198. DrawableButton::DrawableButton (const String& name,
  34199. const DrawableButton::ButtonStyle buttonStyle)
  34200. : Button (name),
  34201. style (buttonStyle),
  34202. normalImage (0),
  34203. overImage (0),
  34204. downImage (0),
  34205. disabledImage (0),
  34206. normalImageOn (0),
  34207. overImageOn (0),
  34208. downImageOn (0),
  34209. disabledImageOn (0),
  34210. edgeIndent (3)
  34211. {
  34212. if (buttonStyle == ImageOnButtonBackground)
  34213. {
  34214. backgroundOff = Colour (0xffbbbbff);
  34215. backgroundOn = Colour (0xff3333ff);
  34216. }
  34217. else
  34218. {
  34219. backgroundOff = Colours::transparentBlack;
  34220. backgroundOn = Colour (0xaabbbbff);
  34221. }
  34222. }
  34223. DrawableButton::~DrawableButton()
  34224. {
  34225. deleteImages();
  34226. }
  34227. void DrawableButton::deleteImages()
  34228. {
  34229. deleteAndZero (normalImage);
  34230. deleteAndZero (overImage);
  34231. deleteAndZero (downImage);
  34232. deleteAndZero (disabledImage);
  34233. deleteAndZero (normalImageOn);
  34234. deleteAndZero (overImageOn);
  34235. deleteAndZero (downImageOn);
  34236. deleteAndZero (disabledImageOn);
  34237. }
  34238. void DrawableButton::setImages (const Drawable* normal,
  34239. const Drawable* over,
  34240. const Drawable* down,
  34241. const Drawable* disabled,
  34242. const Drawable* normalOn,
  34243. const Drawable* overOn,
  34244. const Drawable* downOn,
  34245. const Drawable* disabledOn)
  34246. {
  34247. deleteImages();
  34248. jassert (normal != 0); // you really need to give it at least a normal image..
  34249. if (normal != 0)
  34250. normalImage = normal->createCopy();
  34251. if (over != 0)
  34252. overImage = over->createCopy();
  34253. if (down != 0)
  34254. downImage = down->createCopy();
  34255. if (disabled != 0)
  34256. disabledImage = disabled->createCopy();
  34257. if (normalOn != 0)
  34258. normalImageOn = normalOn->createCopy();
  34259. if (overOn != 0)
  34260. overImageOn = overOn->createCopy();
  34261. if (downOn != 0)
  34262. downImageOn = downOn->createCopy();
  34263. if (disabledOn != 0)
  34264. disabledImageOn = disabledOn->createCopy();
  34265. repaint();
  34266. }
  34267. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34268. {
  34269. if (style != newStyle)
  34270. {
  34271. style = newStyle;
  34272. repaint();
  34273. }
  34274. }
  34275. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34276. const Colour& toggledOnColour)
  34277. {
  34278. if (backgroundOff != toggledOffColour
  34279. || backgroundOn != toggledOnColour)
  34280. {
  34281. backgroundOff = toggledOffColour;
  34282. backgroundOn = toggledOnColour;
  34283. repaint();
  34284. }
  34285. }
  34286. const Colour& DrawableButton::getBackgroundColour() const throw()
  34287. {
  34288. return getToggleState() ? backgroundOn
  34289. : backgroundOff;
  34290. }
  34291. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34292. {
  34293. edgeIndent = numPixelsIndent;
  34294. repaint();
  34295. }
  34296. void DrawableButton::paintButton (Graphics& g,
  34297. bool isMouseOverButton,
  34298. bool isButtonDown)
  34299. {
  34300. Rectangle imageSpace;
  34301. if (style == ImageOnButtonBackground)
  34302. {
  34303. const int insetX = getWidth() / 4;
  34304. const int insetY = getHeight() / 4;
  34305. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34306. getLookAndFeel().drawButtonBackground (g, *this,
  34307. getBackgroundColour(),
  34308. isMouseOverButton,
  34309. isButtonDown);
  34310. }
  34311. else
  34312. {
  34313. g.fillAll (getBackgroundColour());
  34314. const int textH = (style == ImageAboveTextLabel)
  34315. ? jmin (16, proportionOfHeight (0.25f))
  34316. : 0;
  34317. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34318. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34319. imageSpace.setBounds (indentX, indentY,
  34320. getWidth() - indentX * 2,
  34321. getHeight() - indentY * 2 - textH);
  34322. if (textH > 0)
  34323. {
  34324. g.setFont ((float) textH);
  34325. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34326. g.drawFittedText (getButtonText(),
  34327. 2, getHeight() - textH - 1,
  34328. getWidth() - 4, textH,
  34329. Justification::centred, 1);
  34330. }
  34331. }
  34332. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34333. g.setOpacity (1.0f);
  34334. const Drawable* imageToDraw = 0;
  34335. if (isEnabled())
  34336. {
  34337. imageToDraw = getCurrentImage();
  34338. }
  34339. else
  34340. {
  34341. imageToDraw = getToggleState() ? disabledImageOn
  34342. : disabledImage;
  34343. if (imageToDraw == 0)
  34344. {
  34345. g.setOpacity (0.4f);
  34346. imageToDraw = getNormalImage();
  34347. }
  34348. }
  34349. if (imageToDraw != 0)
  34350. {
  34351. if (style == ImageRaw)
  34352. {
  34353. imageToDraw->draw (g);
  34354. }
  34355. else
  34356. {
  34357. imageToDraw->drawWithin (g,
  34358. imageSpace.getX(),
  34359. imageSpace.getY(),
  34360. imageSpace.getWidth(),
  34361. imageSpace.getHeight(),
  34362. RectanglePlacement::centred);
  34363. }
  34364. }
  34365. }
  34366. const Drawable* DrawableButton::getCurrentImage() const throw()
  34367. {
  34368. if (isDown())
  34369. return getDownImage();
  34370. if (isOver())
  34371. return getOverImage();
  34372. return getNormalImage();
  34373. }
  34374. const Drawable* DrawableButton::getNormalImage() const throw()
  34375. {
  34376. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34377. : normalImage;
  34378. }
  34379. const Drawable* DrawableButton::getOverImage() const throw()
  34380. {
  34381. const Drawable* d = normalImage;
  34382. if (getToggleState())
  34383. {
  34384. if (overImageOn != 0)
  34385. d = overImageOn;
  34386. else if (normalImageOn != 0)
  34387. d = normalImageOn;
  34388. else if (overImage != 0)
  34389. d = overImage;
  34390. }
  34391. else
  34392. {
  34393. if (overImage != 0)
  34394. d = overImage;
  34395. }
  34396. return d;
  34397. }
  34398. const Drawable* DrawableButton::getDownImage() const throw()
  34399. {
  34400. const Drawable* d = normalImage;
  34401. if (getToggleState())
  34402. {
  34403. if (downImageOn != 0)
  34404. d = downImageOn;
  34405. else if (overImageOn != 0)
  34406. d = overImageOn;
  34407. else if (normalImageOn != 0)
  34408. d = normalImageOn;
  34409. else if (downImage != 0)
  34410. d = downImage;
  34411. else
  34412. d = getOverImage();
  34413. }
  34414. else
  34415. {
  34416. if (downImage != 0)
  34417. d = downImage;
  34418. else
  34419. d = getOverImage();
  34420. }
  34421. return d;
  34422. }
  34423. END_JUCE_NAMESPACE
  34424. /********* End of inlined file: juce_DrawableButton.cpp *********/
  34425. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  34426. BEGIN_JUCE_NAMESPACE
  34427. HyperlinkButton::HyperlinkButton (const String& linkText,
  34428. const URL& linkURL)
  34429. : Button (linkText),
  34430. url (linkURL),
  34431. font (14.0f, Font::underlined),
  34432. resizeFont (true),
  34433. justification (Justification::centred)
  34434. {
  34435. setMouseCursor (MouseCursor::PointingHandCursor);
  34436. setTooltip (linkURL.toString (false));
  34437. }
  34438. HyperlinkButton::~HyperlinkButton()
  34439. {
  34440. }
  34441. void HyperlinkButton::setFont (const Font& newFont,
  34442. const bool resizeToMatchComponentHeight,
  34443. const Justification& justificationType)
  34444. {
  34445. font = newFont;
  34446. resizeFont = resizeToMatchComponentHeight;
  34447. justification = justificationType;
  34448. repaint();
  34449. }
  34450. void HyperlinkButton::setURL (const URL& newURL) throw()
  34451. {
  34452. url = newURL;
  34453. setTooltip (newURL.toString (false));
  34454. }
  34455. const Font HyperlinkButton::getFontToUse() const
  34456. {
  34457. Font f (font);
  34458. if (resizeFont)
  34459. f.setHeight (getHeight() * 0.7f);
  34460. return f;
  34461. }
  34462. void HyperlinkButton::changeWidthToFitText()
  34463. {
  34464. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34465. }
  34466. void HyperlinkButton::colourChanged()
  34467. {
  34468. repaint();
  34469. }
  34470. void HyperlinkButton::clicked()
  34471. {
  34472. if (url.isWellFormed())
  34473. url.launchInDefaultBrowser();
  34474. }
  34475. void HyperlinkButton::paintButton (Graphics& g,
  34476. bool isMouseOverButton,
  34477. bool isButtonDown)
  34478. {
  34479. const Colour textColour (findColour (textColourId));
  34480. if (isEnabled())
  34481. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34482. : textColour);
  34483. else
  34484. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34485. g.setFont (getFontToUse());
  34486. g.drawText (getButtonText(),
  34487. 2, 0, getWidth() - 2, getHeight(),
  34488. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34489. true);
  34490. }
  34491. END_JUCE_NAMESPACE
  34492. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  34493. /********* Start of inlined file: juce_ImageButton.cpp *********/
  34494. BEGIN_JUCE_NAMESPACE
  34495. ImageButton::ImageButton (const String& text_)
  34496. : Button (text_),
  34497. scaleImageToFit (true),
  34498. preserveProportions (true),
  34499. alphaThreshold (0),
  34500. imageX (0),
  34501. imageY (0),
  34502. imageW (0),
  34503. imageH (0),
  34504. normalImage (0),
  34505. overImage (0),
  34506. downImage (0)
  34507. {
  34508. }
  34509. ImageButton::~ImageButton()
  34510. {
  34511. deleteImages();
  34512. }
  34513. void ImageButton::deleteImages()
  34514. {
  34515. if (normalImage != 0)
  34516. {
  34517. if (ImageCache::isImageInCache (normalImage))
  34518. ImageCache::release (normalImage);
  34519. else
  34520. delete normalImage;
  34521. }
  34522. if (overImage != 0)
  34523. {
  34524. if (ImageCache::isImageInCache (overImage))
  34525. ImageCache::release (overImage);
  34526. else
  34527. delete overImage;
  34528. }
  34529. if (downImage != 0)
  34530. {
  34531. if (ImageCache::isImageInCache (downImage))
  34532. ImageCache::release (downImage);
  34533. else
  34534. delete downImage;
  34535. }
  34536. }
  34537. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34538. const bool rescaleImagesWhenButtonSizeChanges,
  34539. const bool preserveImageProportions,
  34540. Image* const normalImage_,
  34541. const float imageOpacityWhenNormal,
  34542. const Colour& overlayColourWhenNormal,
  34543. Image* const overImage_,
  34544. const float imageOpacityWhenOver,
  34545. const Colour& overlayColourWhenOver,
  34546. Image* const downImage_,
  34547. const float imageOpacityWhenDown,
  34548. const Colour& overlayColourWhenDown,
  34549. const float hitTestAlphaThreshold)
  34550. {
  34551. deleteImages();
  34552. normalImage = normalImage_;
  34553. overImage = overImage_;
  34554. downImage = downImage_;
  34555. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34556. {
  34557. imageW = normalImage->getWidth();
  34558. imageH = normalImage->getHeight();
  34559. setSize (imageW, imageH);
  34560. }
  34561. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34562. preserveProportions = preserveImageProportions;
  34563. normalOpacity = imageOpacityWhenNormal;
  34564. normalOverlay = overlayColourWhenNormal;
  34565. overOpacity = imageOpacityWhenOver;
  34566. overOverlay = overlayColourWhenOver;
  34567. downOpacity = imageOpacityWhenDown;
  34568. downOverlay = overlayColourWhenDown;
  34569. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  34570. repaint();
  34571. }
  34572. Image* ImageButton::getCurrentImage() const
  34573. {
  34574. if (isDown() || getToggleState())
  34575. return getDownImage();
  34576. if (isOver())
  34577. return getOverImage();
  34578. return getNormalImage();
  34579. }
  34580. Image* ImageButton::getNormalImage() const throw()
  34581. {
  34582. return normalImage;
  34583. }
  34584. Image* ImageButton::getOverImage() const throw()
  34585. {
  34586. return (overImage != 0) ? overImage
  34587. : normalImage;
  34588. }
  34589. Image* ImageButton::getDownImage() const throw()
  34590. {
  34591. return (downImage != 0) ? downImage
  34592. : getOverImage();
  34593. }
  34594. void ImageButton::paintButton (Graphics& g,
  34595. bool isMouseOverButton,
  34596. bool isButtonDown)
  34597. {
  34598. if (! isEnabled())
  34599. {
  34600. isMouseOverButton = false;
  34601. isButtonDown = false;
  34602. }
  34603. Image* const im = getCurrentImage();
  34604. if (im != 0)
  34605. {
  34606. const int iw = im->getWidth();
  34607. const int ih = im->getHeight();
  34608. imageW = getWidth();
  34609. imageH = getHeight();
  34610. imageX = (imageW - iw) >> 1;
  34611. imageY = (imageH - ih) >> 1;
  34612. if (scaleImageToFit)
  34613. {
  34614. if (preserveProportions)
  34615. {
  34616. int newW, newH;
  34617. const float imRatio = ih / (float)iw;
  34618. const float destRatio = imageH / (float)imageW;
  34619. if (imRatio > destRatio)
  34620. {
  34621. newW = roundFloatToInt (imageH / imRatio);
  34622. newH = imageH;
  34623. }
  34624. else
  34625. {
  34626. newW = imageW;
  34627. newH = roundFloatToInt (imageW * imRatio);
  34628. }
  34629. imageX = (imageW - newW) / 2;
  34630. imageY = (imageH - newH) / 2;
  34631. imageW = newW;
  34632. imageH = newH;
  34633. }
  34634. else
  34635. {
  34636. imageX = 0;
  34637. imageY = 0;
  34638. }
  34639. }
  34640. if (! scaleImageToFit)
  34641. {
  34642. imageW = iw;
  34643. imageH = ih;
  34644. }
  34645. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34646. isButtonDown ? downOverlay
  34647. : (isMouseOverButton ? overOverlay
  34648. : normalOverlay),
  34649. isButtonDown ? downOpacity
  34650. : (isMouseOverButton ? overOpacity
  34651. : normalOpacity),
  34652. *this);
  34653. }
  34654. }
  34655. bool ImageButton::hitTest (int x, int y)
  34656. {
  34657. if (alphaThreshold == 0)
  34658. return true;
  34659. Image* const im = getCurrentImage();
  34660. return im == 0
  34661. || (imageW > 0 && imageH > 0
  34662. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34663. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34664. }
  34665. END_JUCE_NAMESPACE
  34666. /********* End of inlined file: juce_ImageButton.cpp *********/
  34667. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  34668. BEGIN_JUCE_NAMESPACE
  34669. ShapeButton::ShapeButton (const String& text,
  34670. const Colour& normalColour_,
  34671. const Colour& overColour_,
  34672. const Colour& downColour_)
  34673. : Button (text),
  34674. normalColour (normalColour_),
  34675. overColour (overColour_),
  34676. downColour (downColour_),
  34677. maintainShapeProportions (false),
  34678. outlineWidth (0.0f)
  34679. {
  34680. }
  34681. ShapeButton::~ShapeButton()
  34682. {
  34683. }
  34684. void ShapeButton::setColours (const Colour& newNormalColour,
  34685. const Colour& newOverColour,
  34686. const Colour& newDownColour)
  34687. {
  34688. normalColour = newNormalColour;
  34689. overColour = newOverColour;
  34690. downColour = newDownColour;
  34691. }
  34692. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34693. const float newOutlineWidth)
  34694. {
  34695. outlineColour = newOutlineColour;
  34696. outlineWidth = newOutlineWidth;
  34697. }
  34698. void ShapeButton::setShape (const Path& newShape,
  34699. const bool resizeNowToFitThisShape,
  34700. const bool maintainShapeProportions_,
  34701. const bool hasShadow)
  34702. {
  34703. shape = newShape;
  34704. maintainShapeProportions = maintainShapeProportions_;
  34705. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34706. setComponentEffect ((hasShadow) ? &shadow : 0);
  34707. if (resizeNowToFitThisShape)
  34708. {
  34709. float x, y, w, h;
  34710. shape.getBounds (x, y, w, h);
  34711. shape.applyTransform (AffineTransform::translation (-x, -y));
  34712. if (hasShadow)
  34713. {
  34714. w += 4.0f;
  34715. h += 4.0f;
  34716. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  34717. }
  34718. setSize (1 + (int) (w + outlineWidth),
  34719. 1 + (int) (h + outlineWidth));
  34720. }
  34721. }
  34722. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34723. {
  34724. if (! isEnabled())
  34725. {
  34726. isMouseOverButton = false;
  34727. isButtonDown = false;
  34728. }
  34729. g.setColour ((isButtonDown) ? downColour
  34730. : (isMouseOverButton) ? overColour
  34731. : normalColour);
  34732. int w = getWidth();
  34733. int h = getHeight();
  34734. if (getComponentEffect() != 0)
  34735. {
  34736. w -= 4;
  34737. h -= 4;
  34738. }
  34739. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34740. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34741. w - offset - outlineWidth,
  34742. h - offset - outlineWidth,
  34743. maintainShapeProportions));
  34744. g.fillPath (shape, trans);
  34745. if (outlineWidth > 0.0f)
  34746. {
  34747. g.setColour (outlineColour);
  34748. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34749. }
  34750. }
  34751. END_JUCE_NAMESPACE
  34752. /********* End of inlined file: juce_ShapeButton.cpp *********/
  34753. /********* Start of inlined file: juce_TextButton.cpp *********/
  34754. BEGIN_JUCE_NAMESPACE
  34755. TextButton::TextButton (const String& name,
  34756. const String& toolTip)
  34757. : Button (name)
  34758. {
  34759. setTooltip (toolTip);
  34760. }
  34761. TextButton::~TextButton()
  34762. {
  34763. }
  34764. void TextButton::paintButton (Graphics& g,
  34765. bool isMouseOverButton,
  34766. bool isButtonDown)
  34767. {
  34768. getLookAndFeel().drawButtonBackground (g, *this,
  34769. findColour (getToggleState() ? buttonOnColourId
  34770. : buttonColourId),
  34771. isMouseOverButton,
  34772. isButtonDown);
  34773. getLookAndFeel().drawButtonText (g, *this,
  34774. isMouseOverButton,
  34775. isButtonDown);
  34776. }
  34777. void TextButton::colourChanged()
  34778. {
  34779. repaint();
  34780. }
  34781. const Font TextButton::getFont()
  34782. {
  34783. return Font (jmin (15.0f, getHeight() * 0.6f));
  34784. }
  34785. void TextButton::changeWidthToFitText (const int newHeight)
  34786. {
  34787. if (newHeight >= 0)
  34788. setSize (jmax (1, getWidth()), newHeight);
  34789. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34790. getHeight());
  34791. }
  34792. END_JUCE_NAMESPACE
  34793. /********* End of inlined file: juce_TextButton.cpp *********/
  34794. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  34795. BEGIN_JUCE_NAMESPACE
  34796. ToggleButton::ToggleButton (const String& buttonText)
  34797. : Button (buttonText)
  34798. {
  34799. setClickingTogglesState (true);
  34800. }
  34801. ToggleButton::~ToggleButton()
  34802. {
  34803. }
  34804. void ToggleButton::paintButton (Graphics& g,
  34805. bool isMouseOverButton,
  34806. bool isButtonDown)
  34807. {
  34808. getLookAndFeel().drawToggleButton (g, *this,
  34809. isMouseOverButton,
  34810. isButtonDown);
  34811. }
  34812. void ToggleButton::changeWidthToFitText()
  34813. {
  34814. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34815. }
  34816. void ToggleButton::colourChanged()
  34817. {
  34818. repaint();
  34819. }
  34820. END_JUCE_NAMESPACE
  34821. /********* End of inlined file: juce_ToggleButton.cpp *********/
  34822. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  34823. BEGIN_JUCE_NAMESPACE
  34824. ToolbarButton::ToolbarButton (const int itemId_,
  34825. const String& buttonText,
  34826. Drawable* const normalImage_,
  34827. Drawable* const toggledOnImage_)
  34828. : ToolbarItemComponent (itemId_, buttonText, true),
  34829. normalImage (normalImage_),
  34830. toggledOnImage (toggledOnImage_)
  34831. {
  34832. }
  34833. ToolbarButton::~ToolbarButton()
  34834. {
  34835. delete normalImage;
  34836. delete toggledOnImage;
  34837. }
  34838. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34839. bool /*isToolbarVertical*/,
  34840. int& preferredSize,
  34841. int& minSize, int& maxSize)
  34842. {
  34843. preferredSize = minSize = maxSize = toolbarDepth;
  34844. return true;
  34845. }
  34846. void ToolbarButton::paintButtonArea (Graphics& g,
  34847. int width, int height,
  34848. bool /*isMouseOver*/,
  34849. bool /*isMouseDown*/)
  34850. {
  34851. Drawable* d = normalImage;
  34852. if (getToggleState() && toggledOnImage != 0)
  34853. d = toggledOnImage;
  34854. if (! isEnabled())
  34855. {
  34856. Image im (Image::ARGB, width, height, true);
  34857. Graphics g2 (im);
  34858. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  34859. im.desaturate();
  34860. g.drawImageAt (&im, 0, 0);
  34861. }
  34862. else
  34863. {
  34864. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  34865. }
  34866. }
  34867. void ToolbarButton::contentAreaChanged (const Rectangle&)
  34868. {
  34869. }
  34870. END_JUCE_NAMESPACE
  34871. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  34872. /********* Start of inlined file: juce_ComboBox.cpp *********/
  34873. BEGIN_JUCE_NAMESPACE
  34874. ComboBox::ComboBox (const String& name)
  34875. : Component (name),
  34876. items (4),
  34877. currentIndex (-1),
  34878. isButtonDown (false),
  34879. separatorPending (false),
  34880. menuActive (false),
  34881. listeners (2),
  34882. label (0)
  34883. {
  34884. noChoicesMessage = TRANS("(no choices)");
  34885. setRepaintsOnMouseActivity (true);
  34886. lookAndFeelChanged();
  34887. }
  34888. ComboBox::~ComboBox()
  34889. {
  34890. if (menuActive)
  34891. PopupMenu::dismissAllActiveMenus();
  34892. deleteAllChildren();
  34893. }
  34894. void ComboBox::setEditableText (const bool isEditable)
  34895. {
  34896. label->setEditable (isEditable, isEditable, false);
  34897. setWantsKeyboardFocus (! isEditable);
  34898. resized();
  34899. }
  34900. bool ComboBox::isTextEditable() const throw()
  34901. {
  34902. return label->isEditable();
  34903. }
  34904. void ComboBox::setJustificationType (const Justification& justification) throw()
  34905. {
  34906. label->setJustificationType (justification);
  34907. }
  34908. const Justification ComboBox::getJustificationType() const throw()
  34909. {
  34910. return label->getJustificationType();
  34911. }
  34912. void ComboBox::setTooltip (const String& newTooltip)
  34913. {
  34914. SettableTooltipClient::setTooltip (newTooltip);
  34915. label->setTooltip (newTooltip);
  34916. }
  34917. void ComboBox::addItem (const String& newItemText,
  34918. const int newItemId) throw()
  34919. {
  34920. // you can't add empty strings to the list..
  34921. jassert (newItemText.isNotEmpty());
  34922. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  34923. jassert (newItemId != 0);
  34924. // you shouldn't use duplicate item IDs!
  34925. jassert (getItemForId (newItemId) == 0);
  34926. if (newItemText.isNotEmpty() && newItemId != 0)
  34927. {
  34928. if (separatorPending)
  34929. {
  34930. separatorPending = false;
  34931. ItemInfo* const item = new ItemInfo();
  34932. item->itemId = 0;
  34933. item->isEnabled = false;
  34934. item->isHeading = false;
  34935. items.add (item);
  34936. }
  34937. ItemInfo* const item = new ItemInfo();
  34938. item->name = newItemText;
  34939. item->itemId = newItemId;
  34940. item->isEnabled = true;
  34941. item->isHeading = false;
  34942. items.add (item);
  34943. }
  34944. }
  34945. void ComboBox::addSeparator() throw()
  34946. {
  34947. separatorPending = (items.size() > 0);
  34948. }
  34949. void ComboBox::addSectionHeading (const String& headingName) throw()
  34950. {
  34951. // you can't add empty strings to the list..
  34952. jassert (headingName.isNotEmpty());
  34953. if (headingName.isNotEmpty())
  34954. {
  34955. if (separatorPending)
  34956. {
  34957. separatorPending = false;
  34958. ItemInfo* const item = new ItemInfo();
  34959. item->itemId = 0;
  34960. item->isEnabled = false;
  34961. item->isHeading = false;
  34962. items.add (item);
  34963. }
  34964. ItemInfo* const item = new ItemInfo();
  34965. item->name = headingName;
  34966. item->itemId = 0;
  34967. item->isEnabled = true;
  34968. item->isHeading = true;
  34969. items.add (item);
  34970. }
  34971. }
  34972. void ComboBox::setItemEnabled (const int itemId,
  34973. const bool isEnabled) throw()
  34974. {
  34975. ItemInfo* const item = getItemForId (itemId);
  34976. if (item != 0)
  34977. item->isEnabled = isEnabled;
  34978. }
  34979. void ComboBox::changeItemText (const int itemId,
  34980. const String& newText) throw()
  34981. {
  34982. ItemInfo* const item = getItemForId (itemId);
  34983. jassert (item != 0);
  34984. if (item != 0)
  34985. item->name = newText;
  34986. }
  34987. void ComboBox::clear (const bool dontSendChangeMessage)
  34988. {
  34989. items.clear();
  34990. separatorPending = false;
  34991. if (! label->isEditable())
  34992. setSelectedItemIndex (-1, dontSendChangeMessage);
  34993. }
  34994. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  34995. {
  34996. jassert (itemId != 0);
  34997. if (itemId != 0)
  34998. {
  34999. for (int i = items.size(); --i >= 0;)
  35000. if (items.getUnchecked(i)->itemId == itemId)
  35001. return items.getUnchecked(i);
  35002. }
  35003. return 0;
  35004. }
  35005. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  35006. {
  35007. int n = 0;
  35008. for (int i = 0; i < items.size(); ++i)
  35009. {
  35010. ItemInfo* const item = items.getUnchecked(i);
  35011. if (item->isRealItem())
  35012. {
  35013. if (n++ == index)
  35014. return item;
  35015. }
  35016. }
  35017. return 0;
  35018. }
  35019. int ComboBox::getNumItems() const throw()
  35020. {
  35021. int n = 0;
  35022. for (int i = items.size(); --i >= 0;)
  35023. {
  35024. ItemInfo* const item = items.getUnchecked(i);
  35025. if (item->isRealItem())
  35026. ++n;
  35027. }
  35028. return n;
  35029. }
  35030. const String ComboBox::getItemText (const int index) const throw()
  35031. {
  35032. ItemInfo* const item = getItemForIndex (index);
  35033. if (item != 0)
  35034. return item->name;
  35035. return String::empty;
  35036. }
  35037. int ComboBox::getItemId (const int index) const throw()
  35038. {
  35039. ItemInfo* const item = getItemForIndex (index);
  35040. return (item != 0) ? item->itemId : 0;
  35041. }
  35042. bool ComboBox::ItemInfo::isSeparator() const throw()
  35043. {
  35044. return name.isEmpty();
  35045. }
  35046. bool ComboBox::ItemInfo::isRealItem() const throw()
  35047. {
  35048. return ! (isHeading || name.isEmpty());
  35049. }
  35050. int ComboBox::getSelectedItemIndex() const throw()
  35051. {
  35052. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  35053. ? currentIndex
  35054. : -1;
  35055. }
  35056. void ComboBox::setSelectedItemIndex (const int index,
  35057. const bool dontSendChangeMessage) throw()
  35058. {
  35059. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  35060. {
  35061. if (((unsigned int) index) < (unsigned int) getNumItems())
  35062. currentIndex = index;
  35063. else
  35064. currentIndex = -1;
  35065. label->setText (getItemText (currentIndex), false);
  35066. if (! dontSendChangeMessage)
  35067. triggerAsyncUpdate();
  35068. }
  35069. }
  35070. void ComboBox::setSelectedId (const int newItemId,
  35071. const bool dontSendChangeMessage) throw()
  35072. {
  35073. for (int i = getNumItems(); --i >= 0;)
  35074. {
  35075. if (getItemId(i) == newItemId)
  35076. {
  35077. setSelectedItemIndex (i, dontSendChangeMessage);
  35078. break;
  35079. }
  35080. }
  35081. }
  35082. int ComboBox::getSelectedId() const throw()
  35083. {
  35084. const ItemInfo* const item = getItemForIndex (currentIndex);
  35085. return (item != 0 && getText() == item->name)
  35086. ? item->itemId
  35087. : 0;
  35088. }
  35089. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  35090. {
  35091. jassert (listener != 0);
  35092. if (listener != 0)
  35093. listeners.add (listener);
  35094. }
  35095. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  35096. {
  35097. listeners.removeValue (listener);
  35098. }
  35099. void ComboBox::handleAsyncUpdate()
  35100. {
  35101. for (int i = listeners.size(); --i >= 0;)
  35102. {
  35103. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  35104. i = jmin (i, listeners.size());
  35105. }
  35106. }
  35107. const String ComboBox::getText() const throw()
  35108. {
  35109. return label->getText();
  35110. }
  35111. void ComboBox::setText (const String& newText,
  35112. const bool dontSendChangeMessage) throw()
  35113. {
  35114. for (int i = items.size(); --i >= 0;)
  35115. {
  35116. ItemInfo* const item = items.getUnchecked(i);
  35117. if (item->isRealItem()
  35118. && item->name == newText)
  35119. {
  35120. setSelectedId (item->itemId, dontSendChangeMessage);
  35121. return;
  35122. }
  35123. }
  35124. currentIndex = -1;
  35125. if (label->getText() != newText)
  35126. {
  35127. label->setText (newText, false);
  35128. if (! dontSendChangeMessage)
  35129. triggerAsyncUpdate();
  35130. }
  35131. repaint();
  35132. }
  35133. void ComboBox::showEditor()
  35134. {
  35135. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  35136. label->showEditor();
  35137. }
  35138. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  35139. {
  35140. textWhenNothingSelected = newMessage;
  35141. repaint();
  35142. }
  35143. const String ComboBox::getTextWhenNothingSelected() const throw()
  35144. {
  35145. return textWhenNothingSelected;
  35146. }
  35147. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  35148. {
  35149. noChoicesMessage = newMessage;
  35150. }
  35151. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  35152. {
  35153. return noChoicesMessage;
  35154. }
  35155. void ComboBox::paint (Graphics& g)
  35156. {
  35157. getLookAndFeel().drawComboBox (g,
  35158. getWidth(),
  35159. getHeight(),
  35160. isButtonDown,
  35161. label->getRight(),
  35162. 0,
  35163. getWidth() - label->getRight(),
  35164. getHeight(),
  35165. *this);
  35166. if (textWhenNothingSelected.isNotEmpty()
  35167. && label->getText().isEmpty()
  35168. && ! label->isBeingEdited())
  35169. {
  35170. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  35171. g.setFont (label->getFont());
  35172. g.drawFittedText (textWhenNothingSelected,
  35173. label->getX() + 2, label->getY() + 1,
  35174. label->getWidth() - 4, label->getHeight() - 2,
  35175. label->getJustificationType(),
  35176. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  35177. }
  35178. }
  35179. void ComboBox::resized()
  35180. {
  35181. if (getHeight() > 0 && getWidth() > 0)
  35182. getLookAndFeel().positionComboBoxText (*this, *label);
  35183. }
  35184. void ComboBox::enablementChanged()
  35185. {
  35186. repaint();
  35187. }
  35188. void ComboBox::lookAndFeelChanged()
  35189. {
  35190. repaint();
  35191. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  35192. if (label != 0)
  35193. {
  35194. newLabel->setEditable (label->isEditable());
  35195. newLabel->setJustificationType (label->getJustificationType());
  35196. newLabel->setTooltip (label->getTooltip());
  35197. newLabel->setText (label->getText(), false);
  35198. }
  35199. delete label;
  35200. label = newLabel;
  35201. addAndMakeVisible (newLabel);
  35202. newLabel->addListener (this);
  35203. newLabel->addMouseListener (this, false);
  35204. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  35205. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  35206. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  35207. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35208. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  35209. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35210. resized();
  35211. }
  35212. void ComboBox::colourChanged()
  35213. {
  35214. lookAndFeelChanged();
  35215. }
  35216. bool ComboBox::keyPressed (const KeyPress& key)
  35217. {
  35218. bool used = false;
  35219. if (key.isKeyCode (KeyPress::upKey)
  35220. || key.isKeyCode (KeyPress::leftKey))
  35221. {
  35222. setSelectedItemIndex (jmax (0, currentIndex - 1));
  35223. used = true;
  35224. }
  35225. else if (key.isKeyCode (KeyPress::downKey)
  35226. || key.isKeyCode (KeyPress::rightKey))
  35227. {
  35228. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  35229. used = true;
  35230. }
  35231. else if (key.isKeyCode (KeyPress::returnKey))
  35232. {
  35233. showPopup();
  35234. used = true;
  35235. }
  35236. return used;
  35237. }
  35238. bool ComboBox::keyStateChanged (const bool isKeyDown)
  35239. {
  35240. // only forward key events that aren't used by this component
  35241. return isKeyDown
  35242. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  35243. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  35244. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  35245. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  35246. }
  35247. void ComboBox::focusGained (FocusChangeType)
  35248. {
  35249. repaint();
  35250. }
  35251. void ComboBox::focusLost (FocusChangeType)
  35252. {
  35253. repaint();
  35254. }
  35255. void ComboBox::labelTextChanged (Label*)
  35256. {
  35257. triggerAsyncUpdate();
  35258. }
  35259. void ComboBox::showPopup()
  35260. {
  35261. if (! menuActive)
  35262. {
  35263. const int currentId = getSelectedId();
  35264. ComponentDeletionWatcher deletionWatcher (this);
  35265. PopupMenu menu;
  35266. menu.setLookAndFeel (&getLookAndFeel());
  35267. for (int i = 0; i < items.size(); ++i)
  35268. {
  35269. const ItemInfo* const item = items.getUnchecked(i);
  35270. if (item->isSeparator())
  35271. menu.addSeparator();
  35272. else if (item->isHeading)
  35273. menu.addSectionHeader (item->name);
  35274. else
  35275. menu.addItem (item->itemId, item->name,
  35276. item->isEnabled, item->itemId == currentId);
  35277. }
  35278. if (items.size() == 0)
  35279. menu.addItem (1, noChoicesMessage, false);
  35280. const int itemHeight = jlimit (12, 24, getHeight());
  35281. menuActive = true;
  35282. const int resultId = menu.showAt (this, currentId,
  35283. getWidth(), 1, itemHeight);
  35284. if (deletionWatcher.hasBeenDeleted())
  35285. return;
  35286. menuActive = false;
  35287. if (resultId != 0)
  35288. setSelectedId (resultId);
  35289. }
  35290. }
  35291. void ComboBox::mouseDown (const MouseEvent& e)
  35292. {
  35293. beginDragAutoRepeat (300);
  35294. isButtonDown = isEnabled();
  35295. if (isButtonDown
  35296. && (e.eventComponent == this || ! label->isEditable()))
  35297. {
  35298. showPopup();
  35299. }
  35300. }
  35301. void ComboBox::mouseDrag (const MouseEvent& e)
  35302. {
  35303. beginDragAutoRepeat (50);
  35304. if (isButtonDown && ! e.mouseWasClicked())
  35305. showPopup();
  35306. }
  35307. void ComboBox::mouseUp (const MouseEvent& e2)
  35308. {
  35309. if (isButtonDown)
  35310. {
  35311. isButtonDown = false;
  35312. repaint();
  35313. const MouseEvent e (e2.getEventRelativeTo (this));
  35314. if (reallyContains (e.x, e.y, true)
  35315. && (e2.eventComponent == this || ! label->isEditable()))
  35316. {
  35317. showPopup();
  35318. }
  35319. }
  35320. }
  35321. END_JUCE_NAMESPACE
  35322. /********* End of inlined file: juce_ComboBox.cpp *********/
  35323. /********* Start of inlined file: juce_Label.cpp *********/
  35324. BEGIN_JUCE_NAMESPACE
  35325. Label::Label (const String& componentName,
  35326. const String& labelText)
  35327. : Component (componentName),
  35328. text (labelText),
  35329. font (15.0f),
  35330. justification (Justification::centredLeft),
  35331. editor (0),
  35332. listeners (2),
  35333. ownerComponent (0),
  35334. deletionWatcher (0),
  35335. horizontalBorderSize (3),
  35336. verticalBorderSize (1),
  35337. minimumHorizontalScale (0.7f),
  35338. editSingleClick (false),
  35339. editDoubleClick (false),
  35340. lossOfFocusDiscardsChanges (false)
  35341. {
  35342. setColour (TextEditor::textColourId, Colours::black);
  35343. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35344. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35345. }
  35346. Label::~Label()
  35347. {
  35348. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35349. ownerComponent->removeComponentListener (this);
  35350. deleteAndZero (deletionWatcher);
  35351. if (editor != 0)
  35352. delete editor;
  35353. }
  35354. void Label::setText (const String& newText,
  35355. const bool broadcastChangeMessage)
  35356. {
  35357. hideEditor (true);
  35358. if (text != newText)
  35359. {
  35360. text = newText;
  35361. repaint();
  35362. textWasChanged();
  35363. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35364. componentMovedOrResized (*ownerComponent, true, true);
  35365. if (broadcastChangeMessage)
  35366. callChangeListeners();
  35367. }
  35368. }
  35369. const String Label::getText (const bool returnActiveEditorContents) const throw()
  35370. {
  35371. return (returnActiveEditorContents && isBeingEdited())
  35372. ? editor->getText()
  35373. : text;
  35374. }
  35375. void Label::setFont (const Font& newFont) throw()
  35376. {
  35377. font = newFont;
  35378. repaint();
  35379. }
  35380. const Font& Label::getFont() const throw()
  35381. {
  35382. return font;
  35383. }
  35384. void Label::setEditable (const bool editOnSingleClick,
  35385. const bool editOnDoubleClick,
  35386. const bool lossOfFocusDiscardsChanges_) throw()
  35387. {
  35388. editSingleClick = editOnSingleClick;
  35389. editDoubleClick = editOnDoubleClick;
  35390. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  35391. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  35392. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  35393. }
  35394. void Label::setJustificationType (const Justification& justification_) throw()
  35395. {
  35396. justification = justification_;
  35397. repaint();
  35398. }
  35399. void Label::setBorderSize (int h, int v)
  35400. {
  35401. horizontalBorderSize = h;
  35402. verticalBorderSize = v;
  35403. repaint();
  35404. }
  35405. void Label::attachToComponent (Component* owner,
  35406. const bool onLeft)
  35407. {
  35408. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35409. ownerComponent->removeComponentListener (this);
  35410. deleteAndZero (deletionWatcher);
  35411. ownerComponent = owner;
  35412. leftOfOwnerComp = onLeft;
  35413. if (ownerComponent != 0)
  35414. {
  35415. deletionWatcher = new ComponentDeletionWatcher (owner);
  35416. setVisible (owner->isVisible());
  35417. ownerComponent->addComponentListener (this);
  35418. componentParentHierarchyChanged (*ownerComponent);
  35419. componentMovedOrResized (*ownerComponent, true, true);
  35420. }
  35421. }
  35422. void Label::componentMovedOrResized (Component& component,
  35423. bool /*wasMoved*/,
  35424. bool /*wasResized*/)
  35425. {
  35426. if (leftOfOwnerComp)
  35427. {
  35428. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  35429. component.getHeight());
  35430. setTopRightPosition (component.getX(), component.getY());
  35431. }
  35432. else
  35433. {
  35434. setSize (component.getWidth(),
  35435. 8 + roundFloatToInt (getFont().getHeight()));
  35436. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  35437. }
  35438. }
  35439. void Label::componentParentHierarchyChanged (Component& component)
  35440. {
  35441. if (component.getParentComponent() != 0)
  35442. component.getParentComponent()->addChildComponent (this);
  35443. }
  35444. void Label::componentVisibilityChanged (Component& component)
  35445. {
  35446. setVisible (component.isVisible());
  35447. }
  35448. void Label::textWasEdited()
  35449. {
  35450. }
  35451. void Label::textWasChanged()
  35452. {
  35453. }
  35454. void Label::showEditor()
  35455. {
  35456. if (editor == 0)
  35457. {
  35458. addAndMakeVisible (editor = createEditorComponent());
  35459. editor->setText (getText(), false);
  35460. editor->addListener (this);
  35461. editor->grabKeyboardFocus();
  35462. editor->setHighlightedRegion (0, text.length());
  35463. editor->addListener (this);
  35464. resized();
  35465. repaint();
  35466. editorShown (editor);
  35467. enterModalState();
  35468. editor->grabKeyboardFocus();
  35469. }
  35470. }
  35471. void Label::editorShown (TextEditor* editorComponent)
  35472. {
  35473. }
  35474. void Label::editorAboutToBeHidden (TextEditor* editorComponent)
  35475. {
  35476. }
  35477. bool Label::updateFromTextEditorContents()
  35478. {
  35479. jassert (editor != 0);
  35480. const String newText (editor->getText());
  35481. if (text != newText)
  35482. {
  35483. text = newText;
  35484. repaint();
  35485. textWasChanged();
  35486. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35487. componentMovedOrResized (*ownerComponent, true, true);
  35488. return true;
  35489. }
  35490. return false;
  35491. }
  35492. void Label::hideEditor (const bool discardCurrentEditorContents)
  35493. {
  35494. if (editor != 0)
  35495. {
  35496. editorAboutToBeHidden (editor);
  35497. const bool changed = (! discardCurrentEditorContents)
  35498. && updateFromTextEditorContents();
  35499. deleteAndZero (editor);
  35500. repaint();
  35501. if (changed)
  35502. textWasEdited();
  35503. exitModalState (0);
  35504. if (changed && isValidComponent())
  35505. callChangeListeners();
  35506. }
  35507. }
  35508. void Label::inputAttemptWhenModal()
  35509. {
  35510. if (editor != 0)
  35511. {
  35512. if (lossOfFocusDiscardsChanges)
  35513. textEditorEscapeKeyPressed (*editor);
  35514. else
  35515. textEditorReturnKeyPressed (*editor);
  35516. }
  35517. }
  35518. bool Label::isBeingEdited() const throw()
  35519. {
  35520. return editor != 0;
  35521. }
  35522. TextEditor* Label::createEditorComponent()
  35523. {
  35524. TextEditor* const ed = new TextEditor (getName());
  35525. ed->setFont (font);
  35526. // copy these colours from our own settings..
  35527. const int cols[] = { TextEditor::backgroundColourId,
  35528. TextEditor::textColourId,
  35529. TextEditor::highlightColourId,
  35530. TextEditor::highlightedTextColourId,
  35531. TextEditor::caretColourId,
  35532. TextEditor::outlineColourId,
  35533. TextEditor::focusedOutlineColourId,
  35534. TextEditor::shadowColourId };
  35535. for (int i = 0; i < numElementsInArray (cols); ++i)
  35536. ed->setColour (cols[i], findColour (cols[i]));
  35537. return ed;
  35538. }
  35539. void Label::paint (Graphics& g)
  35540. {
  35541. getLookAndFeel().drawLabel (g, *this);
  35542. }
  35543. void Label::mouseUp (const MouseEvent& e)
  35544. {
  35545. if (editSingleClick
  35546. && e.mouseWasClicked()
  35547. && contains (e.x, e.y)
  35548. && ! e.mods.isPopupMenu())
  35549. {
  35550. showEditor();
  35551. }
  35552. }
  35553. void Label::mouseDoubleClick (const MouseEvent& e)
  35554. {
  35555. if (editDoubleClick && ! e.mods.isPopupMenu())
  35556. showEditor();
  35557. }
  35558. void Label::resized()
  35559. {
  35560. if (editor != 0)
  35561. editor->setBoundsInset (BorderSize (0));
  35562. }
  35563. void Label::focusGained (FocusChangeType cause)
  35564. {
  35565. if (editSingleClick && cause == focusChangedByTabKey)
  35566. showEditor();
  35567. }
  35568. void Label::enablementChanged()
  35569. {
  35570. repaint();
  35571. }
  35572. void Label::colourChanged()
  35573. {
  35574. repaint();
  35575. }
  35576. void Label::setMinimumHorizontalScale (const float newScale)
  35577. {
  35578. if (minimumHorizontalScale != newScale)
  35579. {
  35580. minimumHorizontalScale = newScale;
  35581. repaint();
  35582. }
  35583. }
  35584. // We'll use a custom focus traverser here to make sure focus goes from the
  35585. // text editor to another component rather than back to the label itself.
  35586. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  35587. {
  35588. public:
  35589. LabelKeyboardFocusTraverser() {}
  35590. Component* getNextComponent (Component* current)
  35591. {
  35592. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  35593. ? current->getParentComponent() : current);
  35594. }
  35595. Component* getPreviousComponent (Component* current)
  35596. {
  35597. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  35598. ? current->getParentComponent() : current);
  35599. }
  35600. };
  35601. KeyboardFocusTraverser* Label::createFocusTraverser()
  35602. {
  35603. return new LabelKeyboardFocusTraverser();
  35604. }
  35605. void Label::addListener (LabelListener* const listener) throw()
  35606. {
  35607. jassert (listener != 0);
  35608. if (listener != 0)
  35609. listeners.add (listener);
  35610. }
  35611. void Label::removeListener (LabelListener* const listener) throw()
  35612. {
  35613. listeners.removeValue (listener);
  35614. }
  35615. void Label::callChangeListeners()
  35616. {
  35617. for (int i = listeners.size(); --i >= 0;)
  35618. {
  35619. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  35620. i = jmin (i, listeners.size());
  35621. }
  35622. }
  35623. void Label::textEditorTextChanged (TextEditor& ed)
  35624. {
  35625. if (editor != 0)
  35626. {
  35627. jassert (&ed == editor);
  35628. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  35629. {
  35630. if (lossOfFocusDiscardsChanges)
  35631. textEditorEscapeKeyPressed (ed);
  35632. else
  35633. textEditorReturnKeyPressed (ed);
  35634. }
  35635. }
  35636. }
  35637. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  35638. {
  35639. if (editor != 0)
  35640. {
  35641. jassert (&ed == editor);
  35642. (void) ed;
  35643. const bool changed = updateFromTextEditorContents();
  35644. hideEditor (true);
  35645. if (changed)
  35646. {
  35647. textWasEdited();
  35648. if (isValidComponent())
  35649. callChangeListeners();
  35650. }
  35651. }
  35652. }
  35653. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  35654. {
  35655. if (editor != 0)
  35656. {
  35657. jassert (&ed == editor);
  35658. (void) ed;
  35659. editor->setText (text, false);
  35660. hideEditor (true);
  35661. }
  35662. }
  35663. void Label::textEditorFocusLost (TextEditor& ed)
  35664. {
  35665. textEditorTextChanged (ed);
  35666. }
  35667. END_JUCE_NAMESPACE
  35668. /********* End of inlined file: juce_Label.cpp *********/
  35669. /********* Start of inlined file: juce_ListBox.cpp *********/
  35670. BEGIN_JUCE_NAMESPACE
  35671. class ListBoxRowComponent : public Component
  35672. {
  35673. public:
  35674. ListBoxRowComponent (ListBox& owner_)
  35675. : owner (owner_),
  35676. row (-1),
  35677. selected (false),
  35678. isDragging (false)
  35679. {
  35680. }
  35681. ~ListBoxRowComponent()
  35682. {
  35683. deleteAllChildren();
  35684. }
  35685. void paint (Graphics& g)
  35686. {
  35687. if (owner.getModel() != 0)
  35688. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  35689. }
  35690. void update (const int row_, const bool selected_)
  35691. {
  35692. if (row != row_ || selected != selected_)
  35693. {
  35694. repaint();
  35695. row = row_;
  35696. selected = selected_;
  35697. }
  35698. if (owner.getModel() != 0)
  35699. {
  35700. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  35701. if (customComp != 0)
  35702. {
  35703. addAndMakeVisible (customComp);
  35704. customComp->setBounds (0, 0, getWidth(), getHeight());
  35705. for (int i = getNumChildComponents(); --i >= 0;)
  35706. if (getChildComponent (i) != customComp)
  35707. delete getChildComponent (i);
  35708. }
  35709. else
  35710. {
  35711. deleteAllChildren();
  35712. }
  35713. }
  35714. }
  35715. void mouseDown (const MouseEvent& e)
  35716. {
  35717. isDragging = false;
  35718. selectRowOnMouseUp = false;
  35719. if (isEnabled())
  35720. {
  35721. if (! selected)
  35722. {
  35723. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35724. if (owner.getModel() != 0)
  35725. owner.getModel()->listBoxItemClicked (row, e);
  35726. }
  35727. else
  35728. {
  35729. selectRowOnMouseUp = true;
  35730. }
  35731. }
  35732. }
  35733. void mouseUp (const MouseEvent& e)
  35734. {
  35735. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  35736. {
  35737. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35738. if (owner.getModel() != 0)
  35739. owner.getModel()->listBoxItemClicked (row, e);
  35740. }
  35741. }
  35742. void mouseDoubleClick (const MouseEvent& e)
  35743. {
  35744. if (owner.getModel() != 0 && isEnabled())
  35745. owner.getModel()->listBoxItemDoubleClicked (row, e);
  35746. }
  35747. void mouseDrag (const MouseEvent& e)
  35748. {
  35749. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  35750. {
  35751. const SparseSet <int> selectedRows (owner.getSelectedRows());
  35752. if (selectedRows.size() > 0)
  35753. {
  35754. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  35755. if (dragDescription.isNotEmpty())
  35756. {
  35757. isDragging = true;
  35758. DragAndDropContainer* const dragContainer
  35759. = DragAndDropContainer::findParentDragContainerFor (this);
  35760. if (dragContainer != 0)
  35761. {
  35762. Image* dragImage = owner.createSnapshotOfSelectedRows();
  35763. dragImage->multiplyAllAlphas (0.6f);
  35764. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  35765. }
  35766. else
  35767. {
  35768. // to be able to do a drag-and-drop operation, the listbox needs to
  35769. // be inside a component which is also a DragAndDropContainer.
  35770. jassertfalse
  35771. }
  35772. }
  35773. }
  35774. }
  35775. }
  35776. void resized()
  35777. {
  35778. if (getNumChildComponents() > 0)
  35779. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  35780. }
  35781. juce_UseDebuggingNewOperator
  35782. bool neededFlag;
  35783. private:
  35784. ListBox& owner;
  35785. int row;
  35786. bool selected, isDragging, selectRowOnMouseUp;
  35787. ListBoxRowComponent (const ListBoxRowComponent&);
  35788. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  35789. };
  35790. class ListViewport : public Viewport
  35791. {
  35792. public:
  35793. int firstIndex, firstWholeIndex, lastWholeIndex;
  35794. bool hasUpdated;
  35795. ListViewport (ListBox& owner_)
  35796. : owner (owner_)
  35797. {
  35798. setWantsKeyboardFocus (false);
  35799. setViewedComponent (new Component());
  35800. getViewedComponent()->addMouseListener (this, false);
  35801. getViewedComponent()->setWantsKeyboardFocus (false);
  35802. }
  35803. ~ListViewport()
  35804. {
  35805. getViewedComponent()->removeMouseListener (this);
  35806. getViewedComponent()->deleteAllChildren();
  35807. }
  35808. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  35809. {
  35810. return (ListBoxRowComponent*) getViewedComponent()
  35811. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  35812. }
  35813. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  35814. {
  35815. const int index = getIndexOfChildComponent (rowComponent);
  35816. const int num = getViewedComponent()->getNumChildComponents();
  35817. for (int i = num; --i >= 0;)
  35818. if (((firstIndex + i) % jmax (1, num)) == index)
  35819. return firstIndex + i;
  35820. return -1;
  35821. }
  35822. Component* getComponentForRowIfOnscreen (const int row) const throw()
  35823. {
  35824. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  35825. ? getComponentForRow (row) : 0;
  35826. }
  35827. void visibleAreaChanged (int, int, int, int)
  35828. {
  35829. updateVisibleArea (true);
  35830. if (owner.getModel() != 0)
  35831. owner.getModel()->listWasScrolled();
  35832. }
  35833. void updateVisibleArea (const bool makeSureItUpdatesContent)
  35834. {
  35835. hasUpdated = false;
  35836. const int newX = getViewedComponent()->getX();
  35837. int newY = getViewedComponent()->getY();
  35838. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  35839. const int newH = owner.totalItems * owner.getRowHeight();
  35840. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  35841. newY = getMaximumVisibleHeight() - newH;
  35842. getViewedComponent()->setBounds (newX, newY, newW, newH);
  35843. if (makeSureItUpdatesContent && ! hasUpdated)
  35844. updateContents();
  35845. }
  35846. void updateContents()
  35847. {
  35848. hasUpdated = true;
  35849. const int rowHeight = owner.getRowHeight();
  35850. if (rowHeight > 0)
  35851. {
  35852. const int y = getViewPositionY();
  35853. const int w = getViewedComponent()->getWidth();
  35854. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  35855. while (numNeeded > getViewedComponent()->getNumChildComponents())
  35856. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  35857. jassert (numNeeded >= 0);
  35858. while (numNeeded < getViewedComponent()->getNumChildComponents())
  35859. {
  35860. Component* const rowToRemove
  35861. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  35862. delete rowToRemove;
  35863. }
  35864. firstIndex = y / rowHeight;
  35865. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  35866. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  35867. for (int i = 0; i < numNeeded; ++i)
  35868. {
  35869. const int row = i + firstIndex;
  35870. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  35871. if (rowComp != 0)
  35872. {
  35873. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  35874. rowComp->update (row, owner.isRowSelected (row));
  35875. }
  35876. }
  35877. }
  35878. if (owner.headerComponent != 0)
  35879. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  35880. owner.outlineThickness,
  35881. jmax (owner.getWidth() - owner.outlineThickness * 2,
  35882. getViewedComponent()->getWidth()),
  35883. owner.headerComponent->getHeight());
  35884. }
  35885. void paint (Graphics& g)
  35886. {
  35887. if (isOpaque())
  35888. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  35889. }
  35890. bool keyPressed (const KeyPress& key)
  35891. {
  35892. if (key.isKeyCode (KeyPress::upKey)
  35893. || key.isKeyCode (KeyPress::downKey)
  35894. || key.isKeyCode (KeyPress::pageUpKey)
  35895. || key.isKeyCode (KeyPress::pageDownKey)
  35896. || key.isKeyCode (KeyPress::homeKey)
  35897. || key.isKeyCode (KeyPress::endKey))
  35898. {
  35899. // we want to avoid these keypresses going to the viewport, and instead allow
  35900. // them to pass up to our listbox..
  35901. return false;
  35902. }
  35903. return Viewport::keyPressed (key);
  35904. }
  35905. juce_UseDebuggingNewOperator
  35906. private:
  35907. ListBox& owner;
  35908. ListViewport (const ListViewport&);
  35909. const ListViewport& operator= (const ListViewport&);
  35910. };
  35911. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  35912. : Component (name),
  35913. model (model_),
  35914. headerComponent (0),
  35915. totalItems (0),
  35916. rowHeight (22),
  35917. minimumRowWidth (0),
  35918. outlineThickness (0),
  35919. lastRowSelected (-1),
  35920. mouseMoveSelects (false),
  35921. multipleSelection (false),
  35922. hasDoneInitialUpdate (false)
  35923. {
  35924. addAndMakeVisible (viewport = new ListViewport (*this));
  35925. setWantsKeyboardFocus (true);
  35926. colourChanged();
  35927. }
  35928. ListBox::~ListBox()
  35929. {
  35930. deleteAllChildren();
  35931. }
  35932. void ListBox::setModel (ListBoxModel* const newModel)
  35933. {
  35934. if (model != newModel)
  35935. {
  35936. model = newModel;
  35937. updateContent();
  35938. }
  35939. }
  35940. void ListBox::setMultipleSelectionEnabled (bool b)
  35941. {
  35942. multipleSelection = b;
  35943. }
  35944. void ListBox::setMouseMoveSelectsRows (bool b)
  35945. {
  35946. mouseMoveSelects = b;
  35947. if (b)
  35948. addMouseListener (this, true);
  35949. }
  35950. void ListBox::paint (Graphics& g)
  35951. {
  35952. if (! hasDoneInitialUpdate)
  35953. updateContent();
  35954. g.fillAll (findColour (backgroundColourId));
  35955. }
  35956. void ListBox::paintOverChildren (Graphics& g)
  35957. {
  35958. if (outlineThickness > 0)
  35959. {
  35960. g.setColour (findColour (outlineColourId));
  35961. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  35962. }
  35963. }
  35964. void ListBox::resized()
  35965. {
  35966. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  35967. outlineThickness,
  35968. outlineThickness,
  35969. outlineThickness));
  35970. viewport->setSingleStepSizes (20, getRowHeight());
  35971. viewport->updateVisibleArea (false);
  35972. }
  35973. void ListBox::visibilityChanged()
  35974. {
  35975. viewport->updateVisibleArea (true);
  35976. }
  35977. Viewport* ListBox::getViewport() const throw()
  35978. {
  35979. return viewport;
  35980. }
  35981. void ListBox::updateContent()
  35982. {
  35983. hasDoneInitialUpdate = true;
  35984. totalItems = (model != 0) ? model->getNumRows() : 0;
  35985. bool selectionChanged = false;
  35986. if (selected [selected.size() - 1] >= totalItems)
  35987. {
  35988. selected.removeRange (totalItems, INT_MAX - totalItems);
  35989. lastRowSelected = getSelectedRow (0);
  35990. selectionChanged = true;
  35991. }
  35992. viewport->updateVisibleArea (isVisible());
  35993. viewport->resized();
  35994. if (selectionChanged && model != 0)
  35995. model->selectedRowsChanged (lastRowSelected);
  35996. }
  35997. void ListBox::selectRow (const int row,
  35998. bool dontScroll,
  35999. bool deselectOthersFirst)
  36000. {
  36001. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  36002. }
  36003. void ListBox::selectRowInternal (const int row,
  36004. bool dontScroll,
  36005. bool deselectOthersFirst,
  36006. bool isMouseClick)
  36007. {
  36008. if (! multipleSelection)
  36009. deselectOthersFirst = true;
  36010. if ((! isRowSelected (row))
  36011. || (deselectOthersFirst && getNumSelectedRows() > 1))
  36012. {
  36013. if (((unsigned int) row) < (unsigned int) totalItems)
  36014. {
  36015. if (deselectOthersFirst)
  36016. selected.clear();
  36017. selected.addRange (row, 1);
  36018. if (getHeight() == 0 || getWidth() == 0)
  36019. dontScroll = true;
  36020. viewport->hasUpdated = false;
  36021. if (row < viewport->firstWholeIndex && ! dontScroll)
  36022. {
  36023. viewport->setViewPosition (viewport->getViewPositionX(),
  36024. row * getRowHeight());
  36025. }
  36026. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  36027. {
  36028. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  36029. if (row >= lastRowSelected + rowsOnScreen
  36030. && rowsOnScreen < totalItems - 1
  36031. && ! isMouseClick)
  36032. {
  36033. viewport->setViewPosition (viewport->getViewPositionX(),
  36034. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  36035. * getRowHeight());
  36036. }
  36037. else
  36038. {
  36039. viewport->setViewPosition (viewport->getViewPositionX(),
  36040. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  36041. }
  36042. }
  36043. if (! viewport->hasUpdated)
  36044. viewport->updateContents();
  36045. lastRowSelected = row;
  36046. model->selectedRowsChanged (row);
  36047. }
  36048. else
  36049. {
  36050. if (deselectOthersFirst)
  36051. deselectAllRows();
  36052. }
  36053. }
  36054. }
  36055. void ListBox::deselectRow (const int row)
  36056. {
  36057. if (selected.contains (row))
  36058. {
  36059. selected.removeRange (row, 1);
  36060. if (row == lastRowSelected)
  36061. lastRowSelected = getSelectedRow (0);
  36062. viewport->updateContents();
  36063. model->selectedRowsChanged (lastRowSelected);
  36064. }
  36065. }
  36066. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  36067. const bool sendNotificationEventToModel)
  36068. {
  36069. selected = setOfRowsToBeSelected;
  36070. selected.removeRange (totalItems, INT_MAX - totalItems);
  36071. if (! isRowSelected (lastRowSelected))
  36072. lastRowSelected = getSelectedRow (0);
  36073. viewport->updateContents();
  36074. if ((model != 0) && sendNotificationEventToModel)
  36075. model->selectedRowsChanged (lastRowSelected);
  36076. }
  36077. const SparseSet<int> ListBox::getSelectedRows() const
  36078. {
  36079. return selected;
  36080. }
  36081. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  36082. {
  36083. if (multipleSelection && (firstRow != lastRow))
  36084. {
  36085. const int numRows = totalItems - 1;
  36086. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  36087. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  36088. selected.addRange (jmin (firstRow, lastRow),
  36089. abs (firstRow - lastRow) + 1);
  36090. selected.removeRange (lastRow, 1);
  36091. }
  36092. selectRowInternal (lastRow, false, false, true);
  36093. }
  36094. void ListBox::flipRowSelection (const int row)
  36095. {
  36096. if (isRowSelected (row))
  36097. deselectRow (row);
  36098. else
  36099. selectRowInternal (row, false, false, true);
  36100. }
  36101. void ListBox::deselectAllRows()
  36102. {
  36103. if (! selected.isEmpty())
  36104. {
  36105. selected.clear();
  36106. lastRowSelected = -1;
  36107. viewport->updateContents();
  36108. if (model != 0)
  36109. model->selectedRowsChanged (lastRowSelected);
  36110. }
  36111. }
  36112. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  36113. const ModifierKeys& mods)
  36114. {
  36115. if (multipleSelection && mods.isCommandDown())
  36116. {
  36117. flipRowSelection (row);
  36118. }
  36119. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  36120. {
  36121. selectRangeOfRows (lastRowSelected, row);
  36122. }
  36123. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  36124. {
  36125. selectRowInternal (row, false, true, true);
  36126. }
  36127. }
  36128. int ListBox::getNumSelectedRows() const
  36129. {
  36130. return selected.size();
  36131. }
  36132. int ListBox::getSelectedRow (const int index) const
  36133. {
  36134. return (((unsigned int) index) < (unsigned int) selected.size())
  36135. ? selected [index] : -1;
  36136. }
  36137. bool ListBox::isRowSelected (const int row) const
  36138. {
  36139. return selected.contains (row);
  36140. }
  36141. int ListBox::getLastRowSelected() const
  36142. {
  36143. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  36144. }
  36145. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  36146. {
  36147. if (((unsigned int) x) < (unsigned int) getWidth())
  36148. {
  36149. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  36150. if (((unsigned int) row) < (unsigned int) totalItems)
  36151. return row;
  36152. }
  36153. return -1;
  36154. }
  36155. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  36156. {
  36157. if (((unsigned int) x) < (unsigned int) getWidth())
  36158. {
  36159. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  36160. return jlimit (0, totalItems, row);
  36161. }
  36162. return -1;
  36163. }
  36164. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  36165. {
  36166. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  36167. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  36168. }
  36169. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  36170. {
  36171. return viewport->getRowNumberOfComponent (rowComponent);
  36172. }
  36173. const Rectangle ListBox::getRowPosition (const int rowNumber,
  36174. const bool relativeToComponentTopLeft) const throw()
  36175. {
  36176. const int rowHeight = getRowHeight();
  36177. int y = viewport->getY() + rowHeight * rowNumber;
  36178. if (relativeToComponentTopLeft)
  36179. y -= viewport->getViewPositionY();
  36180. return Rectangle (viewport->getX(), y,
  36181. viewport->getViewedComponent()->getWidth(), rowHeight);
  36182. }
  36183. void ListBox::setVerticalPosition (const double proportion)
  36184. {
  36185. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36186. viewport->setViewPosition (viewport->getViewPositionX(),
  36187. jmax (0, roundDoubleToInt (proportion * offscreen)));
  36188. }
  36189. double ListBox::getVerticalPosition() const
  36190. {
  36191. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36192. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  36193. : 0;
  36194. }
  36195. int ListBox::getVisibleRowWidth() const throw()
  36196. {
  36197. return viewport->getViewWidth();
  36198. }
  36199. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  36200. {
  36201. if (row < viewport->firstWholeIndex)
  36202. {
  36203. viewport->setViewPosition (viewport->getViewPositionX(),
  36204. row * getRowHeight());
  36205. }
  36206. else if (row >= viewport->lastWholeIndex)
  36207. {
  36208. viewport->setViewPosition (viewport->getViewPositionX(),
  36209. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  36210. }
  36211. }
  36212. bool ListBox::keyPressed (const KeyPress& key)
  36213. {
  36214. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  36215. const bool multiple = multipleSelection
  36216. && (lastRowSelected >= 0)
  36217. && (key.getModifiers().isShiftDown()
  36218. || key.getModifiers().isCtrlDown()
  36219. || key.getModifiers().isCommandDown());
  36220. if (key.isKeyCode (KeyPress::upKey))
  36221. {
  36222. if (multiple)
  36223. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  36224. else
  36225. selectRow (jmax (0, lastRowSelected - 1));
  36226. }
  36227. else if (key.isKeyCode (KeyPress::returnKey)
  36228. && isRowSelected (lastRowSelected))
  36229. {
  36230. if (model != 0)
  36231. model->returnKeyPressed (lastRowSelected);
  36232. }
  36233. else if (key.isKeyCode (KeyPress::pageUpKey))
  36234. {
  36235. if (multiple)
  36236. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  36237. else
  36238. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  36239. }
  36240. else if (key.isKeyCode (KeyPress::pageDownKey))
  36241. {
  36242. if (multiple)
  36243. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  36244. else
  36245. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  36246. }
  36247. else if (key.isKeyCode (KeyPress::homeKey))
  36248. {
  36249. if (multiple && key.getModifiers().isShiftDown())
  36250. selectRangeOfRows (lastRowSelected, 0);
  36251. else
  36252. selectRow (0);
  36253. }
  36254. else if (key.isKeyCode (KeyPress::endKey))
  36255. {
  36256. if (multiple && key.getModifiers().isShiftDown())
  36257. selectRangeOfRows (lastRowSelected, totalItems - 1);
  36258. else
  36259. selectRow (totalItems - 1);
  36260. }
  36261. else if (key.isKeyCode (KeyPress::downKey))
  36262. {
  36263. if (multiple)
  36264. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  36265. else
  36266. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  36267. }
  36268. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  36269. && isRowSelected (lastRowSelected))
  36270. {
  36271. if (model != 0)
  36272. model->deleteKeyPressed (lastRowSelected);
  36273. }
  36274. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  36275. {
  36276. selectRangeOfRows (0, INT_MAX);
  36277. }
  36278. else
  36279. {
  36280. return false;
  36281. }
  36282. return true;
  36283. }
  36284. bool ListBox::keyStateChanged (const bool isKeyDown)
  36285. {
  36286. return isKeyDown
  36287. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  36288. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  36289. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  36290. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  36291. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  36292. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  36293. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  36294. }
  36295. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36296. {
  36297. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  36298. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  36299. }
  36300. void ListBox::mouseMove (const MouseEvent& e)
  36301. {
  36302. if (mouseMoveSelects)
  36303. {
  36304. const MouseEvent e2 (e.getEventRelativeTo (this));
  36305. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  36306. lastMouseX = e2.x;
  36307. lastMouseY = e2.y;
  36308. }
  36309. }
  36310. void ListBox::mouseExit (const MouseEvent& e)
  36311. {
  36312. mouseMove (e);
  36313. }
  36314. void ListBox::mouseUp (const MouseEvent& e)
  36315. {
  36316. if (e.mouseWasClicked() && model != 0)
  36317. model->backgroundClicked();
  36318. }
  36319. void ListBox::setRowHeight (const int newHeight)
  36320. {
  36321. rowHeight = jmax (1, newHeight);
  36322. viewport->setSingleStepSizes (20, rowHeight);
  36323. updateContent();
  36324. }
  36325. int ListBox::getNumRowsOnScreen() const throw()
  36326. {
  36327. return viewport->getMaximumVisibleHeight() / rowHeight;
  36328. }
  36329. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  36330. {
  36331. minimumRowWidth = newMinimumWidth;
  36332. updateContent();
  36333. }
  36334. int ListBox::getVisibleContentWidth() const throw()
  36335. {
  36336. return viewport->getMaximumVisibleWidth();
  36337. }
  36338. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  36339. {
  36340. return viewport->getVerticalScrollBar();
  36341. }
  36342. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  36343. {
  36344. return viewport->getHorizontalScrollBar();
  36345. }
  36346. void ListBox::colourChanged()
  36347. {
  36348. setOpaque (findColour (backgroundColourId).isOpaque());
  36349. viewport->setOpaque (isOpaque());
  36350. repaint();
  36351. }
  36352. void ListBox::setOutlineThickness (const int outlineThickness_)
  36353. {
  36354. outlineThickness = outlineThickness_;
  36355. resized();
  36356. }
  36357. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  36358. {
  36359. if (headerComponent != newHeaderComponent)
  36360. {
  36361. if (headerComponent != 0)
  36362. delete headerComponent;
  36363. headerComponent = newHeaderComponent;
  36364. addAndMakeVisible (newHeaderComponent);
  36365. ListBox::resized();
  36366. }
  36367. }
  36368. void ListBox::repaintRow (const int rowNumber) throw()
  36369. {
  36370. const Rectangle r (getRowPosition (rowNumber, true));
  36371. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  36372. }
  36373. Image* ListBox::createSnapshotOfSelectedRows()
  36374. {
  36375. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  36376. Graphics g (*snapshot);
  36377. const int firstRow = getRowContainingPosition (0, 0);
  36378. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  36379. {
  36380. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  36381. if (rowComp != 0 && isRowSelected (firstRow + i))
  36382. {
  36383. g.saveState();
  36384. int x = 0, y = 0;
  36385. rowComp->relativePositionToOtherComponent (this, x, y);
  36386. g.setOrigin (x, y);
  36387. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  36388. rowComp->paintEntireComponent (g);
  36389. g.restoreState();
  36390. }
  36391. }
  36392. return snapshot;
  36393. }
  36394. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  36395. {
  36396. (void) existingComponentToUpdate;
  36397. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36398. return 0;
  36399. }
  36400. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  36401. {
  36402. }
  36403. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  36404. {
  36405. }
  36406. void ListBoxModel::backgroundClicked()
  36407. {
  36408. }
  36409. void ListBoxModel::selectedRowsChanged (int)
  36410. {
  36411. }
  36412. void ListBoxModel::deleteKeyPressed (int)
  36413. {
  36414. }
  36415. void ListBoxModel::returnKeyPressed (int)
  36416. {
  36417. }
  36418. void ListBoxModel::listWasScrolled()
  36419. {
  36420. }
  36421. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36422. {
  36423. return String::empty;
  36424. }
  36425. END_JUCE_NAMESPACE
  36426. /********* End of inlined file: juce_ListBox.cpp *********/
  36427. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  36428. BEGIN_JUCE_NAMESPACE
  36429. ProgressBar::ProgressBar (double& progress_)
  36430. : progress (progress_),
  36431. displayPercentage (true),
  36432. lastCallbackTime (0)
  36433. {
  36434. currentValue = jlimit (0.0, 1.0, progress);
  36435. }
  36436. ProgressBar::~ProgressBar()
  36437. {
  36438. }
  36439. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  36440. {
  36441. displayPercentage = shouldDisplayPercentage;
  36442. repaint();
  36443. }
  36444. void ProgressBar::setTextToDisplay (const String& text)
  36445. {
  36446. displayPercentage = false;
  36447. displayedMessage = text;
  36448. }
  36449. void ProgressBar::lookAndFeelChanged()
  36450. {
  36451. setOpaque (findColour (backgroundColourId).isOpaque());
  36452. }
  36453. void ProgressBar::colourChanged()
  36454. {
  36455. lookAndFeelChanged();
  36456. }
  36457. void ProgressBar::paint (Graphics& g)
  36458. {
  36459. String text;
  36460. if (displayPercentage)
  36461. {
  36462. if (currentValue >= 0 && currentValue <= 1.0)
  36463. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  36464. }
  36465. else
  36466. {
  36467. text = displayedMessage;
  36468. }
  36469. getLookAndFeel().drawProgressBar (g, *this,
  36470. getWidth(), getHeight(),
  36471. currentValue, text);
  36472. }
  36473. void ProgressBar::visibilityChanged()
  36474. {
  36475. if (isVisible())
  36476. startTimer (30);
  36477. else
  36478. stopTimer();
  36479. }
  36480. void ProgressBar::timerCallback()
  36481. {
  36482. double newProgress = progress;
  36483. if (currentValue != newProgress
  36484. || newProgress < 0 || newProgress >= 1.0
  36485. || currentMessage != displayedMessage)
  36486. {
  36487. if (currentValue < newProgress
  36488. && newProgress >= 0 && newProgress < 1.0
  36489. && currentValue >= 0 && currentValue < 1.0)
  36490. {
  36491. const uint32 now = Time::getMillisecondCounter();
  36492. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  36493. lastCallbackTime = now;
  36494. newProgress = jmin (currentValue + 0.00018 * timeSinceLastCallback,
  36495. newProgress);
  36496. }
  36497. currentValue = newProgress;
  36498. currentMessage = displayedMessage;
  36499. repaint();
  36500. }
  36501. }
  36502. END_JUCE_NAMESPACE
  36503. /********* End of inlined file: juce_ProgressBar.cpp *********/
  36504. /********* Start of inlined file: juce_Slider.cpp *********/
  36505. BEGIN_JUCE_NAMESPACE
  36506. class SliderPopupDisplayComponent : public BubbleComponent
  36507. {
  36508. public:
  36509. SliderPopupDisplayComponent (Slider* const owner_)
  36510. : owner (owner_),
  36511. font (15.0f, Font::bold)
  36512. {
  36513. setAlwaysOnTop (true);
  36514. }
  36515. ~SliderPopupDisplayComponent()
  36516. {
  36517. }
  36518. void paintContent (Graphics& g, int w, int h)
  36519. {
  36520. g.setFont (font);
  36521. g.setColour (Colours::black);
  36522. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  36523. }
  36524. void getContentSize (int& w, int& h)
  36525. {
  36526. w = font.getStringWidth (text) + 18;
  36527. h = (int) (font.getHeight() * 1.6f);
  36528. }
  36529. void updatePosition (const String& newText)
  36530. {
  36531. if (text != newText)
  36532. {
  36533. text = newText;
  36534. repaint();
  36535. }
  36536. BubbleComponent::setPosition (owner);
  36537. }
  36538. juce_UseDebuggingNewOperator
  36539. private:
  36540. Slider* owner;
  36541. Font font;
  36542. String text;
  36543. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  36544. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  36545. };
  36546. Slider::Slider (const String& name)
  36547. : Component (name),
  36548. listeners (2),
  36549. currentValue (0.0),
  36550. valueMin (0.0),
  36551. valueMax (0.0),
  36552. minimum (0),
  36553. maximum (10),
  36554. interval (0),
  36555. skewFactor (1.0),
  36556. velocityModeSensitivity (1.0),
  36557. velocityModeOffset (0.0),
  36558. velocityModeThreshold (1),
  36559. rotaryStart (float_Pi * 1.2f),
  36560. rotaryEnd (float_Pi * 2.8f),
  36561. numDecimalPlaces (7),
  36562. sliderRegionStart (0),
  36563. sliderRegionSize (1),
  36564. sliderBeingDragged (-1),
  36565. pixelsForFullDragExtent (250),
  36566. style (LinearHorizontal),
  36567. textBoxPos (TextBoxLeft),
  36568. textBoxWidth (80),
  36569. textBoxHeight (20),
  36570. incDecButtonMode (incDecButtonsNotDraggable),
  36571. editableText (true),
  36572. doubleClickToValue (false),
  36573. isVelocityBased (false),
  36574. userKeyOverridesVelocity (true),
  36575. rotaryStop (true),
  36576. incDecButtonsSideBySide (false),
  36577. sendChangeOnlyOnRelease (false),
  36578. popupDisplayEnabled (false),
  36579. menuEnabled (false),
  36580. menuShown (false),
  36581. scrollWheelEnabled (true),
  36582. snapsToMousePos (true),
  36583. valueBox (0),
  36584. incButton (0),
  36585. decButton (0),
  36586. popupDisplay (0),
  36587. parentForPopupDisplay (0)
  36588. {
  36589. setWantsKeyboardFocus (false);
  36590. setRepaintsOnMouseActivity (true);
  36591. lookAndFeelChanged();
  36592. updateText();
  36593. }
  36594. Slider::~Slider()
  36595. {
  36596. deleteAndZero (popupDisplay);
  36597. deleteAllChildren();
  36598. }
  36599. void Slider::handleAsyncUpdate()
  36600. {
  36601. cancelPendingUpdate();
  36602. for (int i = listeners.size(); --i >= 0;)
  36603. {
  36604. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  36605. i = jmin (i, listeners.size());
  36606. }
  36607. }
  36608. void Slider::sendDragStart()
  36609. {
  36610. startedDragging();
  36611. for (int i = listeners.size(); --i >= 0;)
  36612. {
  36613. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  36614. i = jmin (i, listeners.size());
  36615. }
  36616. }
  36617. void Slider::sendDragEnd()
  36618. {
  36619. stoppedDragging();
  36620. sliderBeingDragged = -1;
  36621. for (int i = listeners.size(); --i >= 0;)
  36622. {
  36623. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  36624. i = jmin (i, listeners.size());
  36625. }
  36626. }
  36627. void Slider::addListener (SliderListener* const listener) throw()
  36628. {
  36629. jassert (listener != 0);
  36630. if (listener != 0)
  36631. listeners.add (listener);
  36632. }
  36633. void Slider::removeListener (SliderListener* const listener) throw()
  36634. {
  36635. listeners.removeValue (listener);
  36636. }
  36637. void Slider::setSliderStyle (const SliderStyle newStyle)
  36638. {
  36639. if (style != newStyle)
  36640. {
  36641. style = newStyle;
  36642. repaint();
  36643. lookAndFeelChanged();
  36644. }
  36645. }
  36646. void Slider::setRotaryParameters (const float startAngleRadians,
  36647. const float endAngleRadians,
  36648. const bool stopAtEnd)
  36649. {
  36650. // make sure the values are sensible..
  36651. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  36652. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  36653. jassert (rotaryStart < rotaryEnd);
  36654. rotaryStart = startAngleRadians;
  36655. rotaryEnd = endAngleRadians;
  36656. rotaryStop = stopAtEnd;
  36657. }
  36658. void Slider::setVelocityBasedMode (const bool velBased) throw()
  36659. {
  36660. isVelocityBased = velBased;
  36661. }
  36662. void Slider::setVelocityModeParameters (const double sensitivity,
  36663. const int threshold,
  36664. const double offset,
  36665. const bool userCanPressKeyToSwapMode) throw()
  36666. {
  36667. jassert (threshold >= 0);
  36668. jassert (sensitivity > 0);
  36669. jassert (offset >= 0);
  36670. velocityModeSensitivity = sensitivity;
  36671. velocityModeOffset = offset;
  36672. velocityModeThreshold = threshold;
  36673. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  36674. }
  36675. void Slider::setSkewFactor (const double factor) throw()
  36676. {
  36677. skewFactor = factor;
  36678. }
  36679. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  36680. {
  36681. if (maximum > minimum)
  36682. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  36683. / (maximum - minimum));
  36684. }
  36685. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  36686. {
  36687. jassert (distanceForFullScaleDrag > 0);
  36688. pixelsForFullDragExtent = distanceForFullScaleDrag;
  36689. }
  36690. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  36691. {
  36692. if (incDecButtonMode != mode)
  36693. {
  36694. incDecButtonMode = mode;
  36695. lookAndFeelChanged();
  36696. }
  36697. }
  36698. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  36699. const bool isReadOnly,
  36700. const int textEntryBoxWidth,
  36701. const int textEntryBoxHeight)
  36702. {
  36703. textBoxPos = newPosition;
  36704. editableText = ! isReadOnly;
  36705. textBoxWidth = textEntryBoxWidth;
  36706. textBoxHeight = textEntryBoxHeight;
  36707. repaint();
  36708. lookAndFeelChanged();
  36709. }
  36710. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  36711. {
  36712. editableText = shouldBeEditable;
  36713. if (valueBox != 0)
  36714. valueBox->setEditable (shouldBeEditable && isEnabled());
  36715. }
  36716. void Slider::showTextBox()
  36717. {
  36718. jassert (editableText); // this should probably be avoided in read-only sliders.
  36719. if (valueBox != 0)
  36720. valueBox->showEditor();
  36721. }
  36722. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  36723. {
  36724. if (valueBox != 0)
  36725. {
  36726. valueBox->hideEditor (discardCurrentEditorContents);
  36727. if (discardCurrentEditorContents)
  36728. updateText();
  36729. }
  36730. }
  36731. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  36732. {
  36733. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  36734. }
  36735. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  36736. {
  36737. snapsToMousePos = shouldSnapToMouse;
  36738. }
  36739. void Slider::setPopupDisplayEnabled (const bool enabled,
  36740. Component* const parentComponentToUse) throw()
  36741. {
  36742. popupDisplayEnabled = enabled;
  36743. parentForPopupDisplay = parentComponentToUse;
  36744. }
  36745. void Slider::colourChanged()
  36746. {
  36747. lookAndFeelChanged();
  36748. }
  36749. void Slider::lookAndFeelChanged()
  36750. {
  36751. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  36752. : getTextFromValue (currentValue));
  36753. deleteAllChildren();
  36754. valueBox = 0;
  36755. LookAndFeel& lf = getLookAndFeel();
  36756. if (textBoxPos != NoTextBox)
  36757. {
  36758. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  36759. valueBox->setWantsKeyboardFocus (false);
  36760. valueBox->setText (previousTextBoxContent, false);
  36761. valueBox->setEditable (editableText && isEnabled());
  36762. valueBox->addListener (this);
  36763. if (style == LinearBar)
  36764. valueBox->addMouseListener (this, false);
  36765. valueBox->setTooltip (getTooltip());
  36766. }
  36767. if (style == IncDecButtons)
  36768. {
  36769. addAndMakeVisible (incButton = lf.createSliderButton (true));
  36770. incButton->addButtonListener (this);
  36771. addAndMakeVisible (decButton = lf.createSliderButton (false));
  36772. decButton->addButtonListener (this);
  36773. if (incDecButtonMode != incDecButtonsNotDraggable)
  36774. {
  36775. incButton->addMouseListener (this, false);
  36776. decButton->addMouseListener (this, false);
  36777. }
  36778. else
  36779. {
  36780. incButton->setRepeatSpeed (300, 100, 20);
  36781. incButton->addMouseListener (decButton, false);
  36782. decButton->setRepeatSpeed (300, 100, 20);
  36783. decButton->addMouseListener (incButton, false);
  36784. }
  36785. incButton->setTooltip (getTooltip());
  36786. decButton->setTooltip (getTooltip());
  36787. }
  36788. setComponentEffect (lf.getSliderEffect());
  36789. resized();
  36790. repaint();
  36791. }
  36792. void Slider::setRange (const double newMin,
  36793. const double newMax,
  36794. const double newInt)
  36795. {
  36796. if (minimum != newMin
  36797. || maximum != newMax
  36798. || interval != newInt)
  36799. {
  36800. minimum = newMin;
  36801. maximum = newMax;
  36802. interval = newInt;
  36803. // figure out the number of DPs needed to display all values at this
  36804. // interval setting.
  36805. numDecimalPlaces = 7;
  36806. if (newInt != 0)
  36807. {
  36808. int v = abs ((int) (newInt * 10000000));
  36809. while ((v % 10) == 0)
  36810. {
  36811. --numDecimalPlaces;
  36812. v /= 10;
  36813. }
  36814. }
  36815. // keep the current values inside the new range..
  36816. if (style != TwoValueHorizontal && style != TwoValueVertical)
  36817. {
  36818. setValue (currentValue, false, false);
  36819. }
  36820. else
  36821. {
  36822. setMinValue (getMinValue(), false, false);
  36823. setMaxValue (getMaxValue(), false, false);
  36824. }
  36825. updateText();
  36826. }
  36827. }
  36828. void Slider::triggerChangeMessage (const bool synchronous)
  36829. {
  36830. if (synchronous)
  36831. handleAsyncUpdate();
  36832. else
  36833. triggerAsyncUpdate();
  36834. valueChanged();
  36835. }
  36836. double Slider::getValue() const throw()
  36837. {
  36838. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  36839. // methods to get the two values.
  36840. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36841. return currentValue;
  36842. }
  36843. void Slider::setValue (double newValue,
  36844. const bool sendUpdateMessage,
  36845. const bool sendMessageSynchronously)
  36846. {
  36847. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  36848. // methods to set the two values.
  36849. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36850. newValue = constrainedValue (newValue);
  36851. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  36852. {
  36853. jassert (valueMin <= valueMax);
  36854. newValue = jlimit (valueMin, valueMax, newValue);
  36855. }
  36856. if (currentValue != newValue)
  36857. {
  36858. if (valueBox != 0)
  36859. valueBox->hideEditor (true);
  36860. currentValue = newValue;
  36861. updateText();
  36862. repaint();
  36863. if (popupDisplay != 0)
  36864. {
  36865. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  36866. popupDisplay->repaint();
  36867. }
  36868. if (sendUpdateMessage)
  36869. triggerChangeMessage (sendMessageSynchronously);
  36870. }
  36871. }
  36872. double Slider::getMinValue() const throw()
  36873. {
  36874. // The minimum value only applies to sliders that are in two- or three-value mode.
  36875. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36876. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36877. return valueMin;
  36878. }
  36879. double Slider::getMaxValue() const throw()
  36880. {
  36881. // The maximum value only applies to sliders that are in two- or three-value mode.
  36882. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36883. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36884. return valueMax;
  36885. }
  36886. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36887. {
  36888. // The minimum value only applies to sliders that are in two- or three-value mode.
  36889. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36890. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36891. newValue = constrainedValue (newValue);
  36892. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36893. {
  36894. if (allowNudgingOfOtherValues && newValue > valueMax)
  36895. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36896. newValue = jmin (valueMax, newValue);
  36897. }
  36898. else
  36899. {
  36900. if (allowNudgingOfOtherValues && newValue > currentValue)
  36901. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36902. newValue = jmin (currentValue, newValue);
  36903. }
  36904. if (valueMin != newValue)
  36905. {
  36906. valueMin = newValue;
  36907. repaint();
  36908. if (popupDisplay != 0)
  36909. {
  36910. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  36911. popupDisplay->repaint();
  36912. }
  36913. if (sendUpdateMessage)
  36914. triggerChangeMessage (sendMessageSynchronously);
  36915. }
  36916. }
  36917. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36918. {
  36919. // The maximum value only applies to sliders that are in two- or three-value mode.
  36920. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36921. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36922. newValue = constrainedValue (newValue);
  36923. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36924. {
  36925. if (allowNudgingOfOtherValues && newValue < valueMin)
  36926. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36927. newValue = jmax (valueMin, newValue);
  36928. }
  36929. else
  36930. {
  36931. if (allowNudgingOfOtherValues && newValue < currentValue)
  36932. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36933. newValue = jmax (currentValue, newValue);
  36934. }
  36935. if (valueMax != newValue)
  36936. {
  36937. valueMax = newValue;
  36938. repaint();
  36939. if (popupDisplay != 0)
  36940. {
  36941. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  36942. popupDisplay->repaint();
  36943. }
  36944. if (sendUpdateMessage)
  36945. triggerChangeMessage (sendMessageSynchronously);
  36946. }
  36947. }
  36948. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  36949. const double valueToSetOnDoubleClick) throw()
  36950. {
  36951. doubleClickToValue = isDoubleClickEnabled;
  36952. doubleClickReturnValue = valueToSetOnDoubleClick;
  36953. }
  36954. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  36955. {
  36956. isEnabled_ = doubleClickToValue;
  36957. return doubleClickReturnValue;
  36958. }
  36959. void Slider::updateText()
  36960. {
  36961. if (valueBox != 0)
  36962. valueBox->setText (getTextFromValue (currentValue), false);
  36963. }
  36964. void Slider::setTextValueSuffix (const String& suffix)
  36965. {
  36966. if (textSuffix != suffix)
  36967. {
  36968. textSuffix = suffix;
  36969. updateText();
  36970. }
  36971. }
  36972. const String Slider::getTextFromValue (double v)
  36973. {
  36974. if (numDecimalPlaces > 0)
  36975. return String (v, numDecimalPlaces) + textSuffix;
  36976. else
  36977. return String (roundDoubleToInt (v)) + textSuffix;
  36978. }
  36979. double Slider::getValueFromText (const String& text)
  36980. {
  36981. String t (text.trimStart());
  36982. if (t.endsWith (textSuffix))
  36983. t = t.substring (0, t.length() - textSuffix.length());
  36984. while (t.startsWithChar (T('+')))
  36985. t = t.substring (1).trimStart();
  36986. return t.initialSectionContainingOnly (T("0123456789.,-"))
  36987. .getDoubleValue();
  36988. }
  36989. double Slider::proportionOfLengthToValue (double proportion)
  36990. {
  36991. if (skewFactor != 1.0 && proportion > 0.0)
  36992. proportion = exp (log (proportion) / skewFactor);
  36993. return minimum + (maximum - minimum) * proportion;
  36994. }
  36995. double Slider::valueToProportionOfLength (double value)
  36996. {
  36997. const double n = (value - minimum) / (maximum - minimum);
  36998. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  36999. }
  37000. double Slider::snapValue (double attemptedValue, const bool)
  37001. {
  37002. return attemptedValue;
  37003. }
  37004. void Slider::startedDragging()
  37005. {
  37006. }
  37007. void Slider::stoppedDragging()
  37008. {
  37009. }
  37010. void Slider::valueChanged()
  37011. {
  37012. }
  37013. void Slider::enablementChanged()
  37014. {
  37015. repaint();
  37016. }
  37017. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  37018. {
  37019. menuEnabled = menuEnabled_;
  37020. }
  37021. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  37022. {
  37023. scrollWheelEnabled = enabled;
  37024. }
  37025. void Slider::labelTextChanged (Label* label)
  37026. {
  37027. const double newValue = snapValue (getValueFromText (label->getText()), false);
  37028. if (getValue() != newValue)
  37029. {
  37030. sendDragStart();
  37031. setValue (newValue, true, true);
  37032. sendDragEnd();
  37033. }
  37034. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  37035. }
  37036. void Slider::buttonClicked (Button* button)
  37037. {
  37038. if (style == IncDecButtons)
  37039. {
  37040. sendDragStart();
  37041. if (button == incButton)
  37042. setValue (snapValue (getValue() + interval, false), true, true);
  37043. else if (button == decButton)
  37044. setValue (snapValue (getValue() - interval, false), true, true);
  37045. sendDragEnd();
  37046. }
  37047. }
  37048. double Slider::constrainedValue (double value) const throw()
  37049. {
  37050. if (interval > 0)
  37051. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  37052. if (value <= minimum || maximum <= minimum)
  37053. value = minimum;
  37054. else if (value >= maximum)
  37055. value = maximum;
  37056. return value;
  37057. }
  37058. float Slider::getLinearSliderPos (const double value)
  37059. {
  37060. double sliderPosProportional;
  37061. if (maximum > minimum)
  37062. {
  37063. if (value < minimum)
  37064. {
  37065. sliderPosProportional = 0.0;
  37066. }
  37067. else if (value > maximum)
  37068. {
  37069. sliderPosProportional = 1.0;
  37070. }
  37071. else
  37072. {
  37073. sliderPosProportional = valueToProportionOfLength (value);
  37074. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  37075. }
  37076. }
  37077. else
  37078. {
  37079. sliderPosProportional = 0.5;
  37080. }
  37081. if (isVertical() || style == IncDecButtons)
  37082. sliderPosProportional = 1.0 - sliderPosProportional;
  37083. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  37084. }
  37085. bool Slider::isHorizontal() const throw()
  37086. {
  37087. return style == LinearHorizontal
  37088. || style == LinearBar
  37089. || style == TwoValueHorizontal
  37090. || style == ThreeValueHorizontal;
  37091. }
  37092. bool Slider::isVertical() const throw()
  37093. {
  37094. return style == LinearVertical
  37095. || style == TwoValueVertical
  37096. || style == ThreeValueVertical;
  37097. }
  37098. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  37099. {
  37100. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  37101. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  37102. }
  37103. float Slider::getPositionOfValue (const double value)
  37104. {
  37105. if (isHorizontal() || isVertical())
  37106. {
  37107. return getLinearSliderPos (value);
  37108. }
  37109. else
  37110. {
  37111. jassertfalse // not a valid call on a slider that doesn't work linearly!
  37112. return 0.0f;
  37113. }
  37114. }
  37115. void Slider::paint (Graphics& g)
  37116. {
  37117. if (style != IncDecButtons)
  37118. {
  37119. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37120. {
  37121. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  37122. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  37123. getLookAndFeel().drawRotarySlider (g,
  37124. sliderRect.getX(),
  37125. sliderRect.getY(),
  37126. sliderRect.getWidth(),
  37127. sliderRect.getHeight(),
  37128. sliderPos,
  37129. rotaryStart, rotaryEnd,
  37130. *this);
  37131. }
  37132. else
  37133. {
  37134. getLookAndFeel().drawLinearSlider (g,
  37135. sliderRect.getX(),
  37136. sliderRect.getY(),
  37137. sliderRect.getWidth(),
  37138. sliderRect.getHeight(),
  37139. getLinearSliderPos (currentValue),
  37140. getLinearSliderPos (valueMin),
  37141. getLinearSliderPos (valueMax),
  37142. style,
  37143. *this);
  37144. }
  37145. if (style == LinearBar && valueBox == 0)
  37146. {
  37147. g.setColour (findColour (Slider::textBoxOutlineColourId));
  37148. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  37149. }
  37150. }
  37151. }
  37152. void Slider::resized()
  37153. {
  37154. int minXSpace = 0;
  37155. int minYSpace = 0;
  37156. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37157. minXSpace = 30;
  37158. else
  37159. minYSpace = 15;
  37160. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  37161. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  37162. if (style == LinearBar)
  37163. {
  37164. if (valueBox != 0)
  37165. valueBox->setBounds (0, 0, getWidth(), getHeight());
  37166. }
  37167. else
  37168. {
  37169. if (textBoxPos == NoTextBox)
  37170. {
  37171. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  37172. }
  37173. else if (textBoxPos == TextBoxLeft)
  37174. {
  37175. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  37176. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  37177. }
  37178. else if (textBoxPos == TextBoxRight)
  37179. {
  37180. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  37181. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  37182. }
  37183. else if (textBoxPos == TextBoxAbove)
  37184. {
  37185. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  37186. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  37187. }
  37188. else if (textBoxPos == TextBoxBelow)
  37189. {
  37190. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  37191. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  37192. }
  37193. }
  37194. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  37195. if (style == LinearBar)
  37196. {
  37197. const int barIndent = 1;
  37198. sliderRegionStart = barIndent;
  37199. sliderRegionSize = getWidth() - barIndent * 2;
  37200. sliderRect.setBounds (sliderRegionStart, barIndent,
  37201. sliderRegionSize, getHeight() - barIndent * 2);
  37202. }
  37203. else if (isHorizontal())
  37204. {
  37205. sliderRegionStart = sliderRect.getX() + indent;
  37206. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  37207. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  37208. sliderRegionSize, sliderRect.getHeight());
  37209. }
  37210. else if (isVertical())
  37211. {
  37212. sliderRegionStart = sliderRect.getY() + indent;
  37213. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  37214. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  37215. sliderRect.getWidth(), sliderRegionSize);
  37216. }
  37217. else
  37218. {
  37219. sliderRegionStart = 0;
  37220. sliderRegionSize = 100;
  37221. }
  37222. if (style == IncDecButtons)
  37223. {
  37224. Rectangle buttonRect (sliderRect);
  37225. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37226. buttonRect.expand (-2, 0);
  37227. else
  37228. buttonRect.expand (0, -2);
  37229. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  37230. if (incDecButtonsSideBySide)
  37231. {
  37232. decButton->setBounds (buttonRect.getX(),
  37233. buttonRect.getY(),
  37234. buttonRect.getWidth() / 2,
  37235. buttonRect.getHeight());
  37236. decButton->setConnectedEdges (Button::ConnectedOnRight);
  37237. incButton->setBounds (buttonRect.getCentreX(),
  37238. buttonRect.getY(),
  37239. buttonRect.getWidth() / 2,
  37240. buttonRect.getHeight());
  37241. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  37242. }
  37243. else
  37244. {
  37245. incButton->setBounds (buttonRect.getX(),
  37246. buttonRect.getY(),
  37247. buttonRect.getWidth(),
  37248. buttonRect.getHeight() / 2);
  37249. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  37250. decButton->setBounds (buttonRect.getX(),
  37251. buttonRect.getCentreY(),
  37252. buttonRect.getWidth(),
  37253. buttonRect.getHeight() / 2);
  37254. decButton->setConnectedEdges (Button::ConnectedOnTop);
  37255. }
  37256. }
  37257. }
  37258. void Slider::focusOfChildComponentChanged (FocusChangeType)
  37259. {
  37260. repaint();
  37261. }
  37262. void Slider::mouseDown (const MouseEvent& e)
  37263. {
  37264. mouseWasHidden = false;
  37265. incDecDragged = false;
  37266. mouseXWhenLastDragged = e.x;
  37267. mouseYWhenLastDragged = e.y;
  37268. mouseDragStartX = e.getMouseDownX();
  37269. mouseDragStartY = e.getMouseDownY();
  37270. if (isEnabled())
  37271. {
  37272. if (e.mods.isPopupMenu() && menuEnabled)
  37273. {
  37274. menuShown = true;
  37275. PopupMenu m;
  37276. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  37277. m.addSeparator();
  37278. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37279. {
  37280. PopupMenu rotaryMenu;
  37281. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  37282. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  37283. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  37284. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  37285. }
  37286. const int r = m.show();
  37287. if (r == 1)
  37288. {
  37289. setVelocityBasedMode (! isVelocityBased);
  37290. }
  37291. else if (r == 2)
  37292. {
  37293. setSliderStyle (Rotary);
  37294. }
  37295. else if (r == 3)
  37296. {
  37297. setSliderStyle (RotaryHorizontalDrag);
  37298. }
  37299. else if (r == 4)
  37300. {
  37301. setSliderStyle (RotaryVerticalDrag);
  37302. }
  37303. }
  37304. else if (maximum > minimum)
  37305. {
  37306. menuShown = false;
  37307. if (valueBox != 0)
  37308. valueBox->hideEditor (true);
  37309. sliderBeingDragged = 0;
  37310. if (style == TwoValueHorizontal
  37311. || style == TwoValueVertical
  37312. || style == ThreeValueHorizontal
  37313. || style == ThreeValueVertical)
  37314. {
  37315. const float mousePos = (float) (isVertical() ? e.y : e.x);
  37316. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  37317. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  37318. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  37319. if (style == TwoValueHorizontal || style == TwoValueVertical)
  37320. {
  37321. if (maxPosDistance <= minPosDistance)
  37322. sliderBeingDragged = 2;
  37323. else
  37324. sliderBeingDragged = 1;
  37325. }
  37326. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  37327. {
  37328. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  37329. sliderBeingDragged = 1;
  37330. else if (normalPosDistance >= maxPosDistance)
  37331. sliderBeingDragged = 2;
  37332. }
  37333. }
  37334. minMaxDiff = valueMax - valueMin;
  37335. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  37336. * valueToProportionOfLength (currentValue);
  37337. if (sliderBeingDragged == 2)
  37338. valueWhenLastDragged = valueMax;
  37339. else if (sliderBeingDragged == 1)
  37340. valueWhenLastDragged = valueMin;
  37341. else
  37342. valueWhenLastDragged = currentValue;
  37343. valueOnMouseDown = valueWhenLastDragged;
  37344. if (popupDisplayEnabled)
  37345. {
  37346. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  37347. popupDisplay = popup;
  37348. if (parentForPopupDisplay != 0)
  37349. {
  37350. parentForPopupDisplay->addChildComponent (popup);
  37351. }
  37352. else
  37353. {
  37354. popup->addToDesktop (0);
  37355. }
  37356. popup->setVisible (true);
  37357. }
  37358. sendDragStart();
  37359. mouseDrag (e);
  37360. }
  37361. }
  37362. }
  37363. void Slider::mouseUp (const MouseEvent&)
  37364. {
  37365. if (isEnabled()
  37366. && (! menuShown)
  37367. && (maximum > minimum)
  37368. && (style != IncDecButtons || incDecDragged))
  37369. {
  37370. restoreMouseIfHidden();
  37371. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  37372. triggerChangeMessage (false);
  37373. sendDragEnd();
  37374. deleteAndZero (popupDisplay);
  37375. if (style == IncDecButtons)
  37376. {
  37377. incButton->setState (Button::buttonNormal);
  37378. decButton->setState (Button::buttonNormal);
  37379. }
  37380. }
  37381. }
  37382. void Slider::restoreMouseIfHidden()
  37383. {
  37384. if (mouseWasHidden)
  37385. {
  37386. mouseWasHidden = false;
  37387. Component* c = Component::getComponentUnderMouse();
  37388. if (c == 0)
  37389. c = this;
  37390. c->enableUnboundedMouseMovement (false);
  37391. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  37392. : ((sliderBeingDragged == 1) ? getMinValue()
  37393. : currentValue);
  37394. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37395. {
  37396. int x, y, downX, downY;
  37397. Desktop::getMousePosition (x, y);
  37398. Desktop::getLastMouseDownPosition (downX, downY);
  37399. if (style == RotaryHorizontalDrag)
  37400. {
  37401. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  37402. x = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downX);
  37403. y = downY;
  37404. }
  37405. else
  37406. {
  37407. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  37408. x = downX;
  37409. y = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downY);
  37410. }
  37411. Desktop::setMousePosition (x, y);
  37412. }
  37413. else
  37414. {
  37415. const int pixelPos = (int) getLinearSliderPos (pos);
  37416. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  37417. int y = isVertical() ? pixelPos : (getHeight() / 2);
  37418. relativePositionToGlobal (x, y);
  37419. Desktop::setMousePosition (x, y);
  37420. }
  37421. }
  37422. }
  37423. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  37424. {
  37425. if (isEnabled()
  37426. && style != IncDecButtons
  37427. && style != Rotary
  37428. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  37429. {
  37430. restoreMouseIfHidden();
  37431. }
  37432. }
  37433. static double smallestAngleBetween (double a1, double a2)
  37434. {
  37435. return jmin (fabs (a1 - a2),
  37436. fabs (a1 + double_Pi * 2.0 - a2),
  37437. fabs (a2 + double_Pi * 2.0 - a1));
  37438. }
  37439. void Slider::mouseDrag (const MouseEvent& e)
  37440. {
  37441. if (isEnabled()
  37442. && (! menuShown)
  37443. && (maximum > minimum))
  37444. {
  37445. if (style == Rotary)
  37446. {
  37447. int dx = e.x - sliderRect.getCentreX();
  37448. int dy = e.y - sliderRect.getCentreY();
  37449. if (dx * dx + dy * dy > 25)
  37450. {
  37451. double angle = atan2 ((double) dx, (double) -dy);
  37452. while (angle < 0.0)
  37453. angle += double_Pi * 2.0;
  37454. if (rotaryStop && ! e.mouseWasClicked())
  37455. {
  37456. if (fabs (angle - lastAngle) > double_Pi)
  37457. {
  37458. if (angle >= lastAngle)
  37459. angle -= double_Pi * 2.0;
  37460. else
  37461. angle += double_Pi * 2.0;
  37462. }
  37463. if (angle >= lastAngle)
  37464. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  37465. else
  37466. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  37467. }
  37468. else
  37469. {
  37470. while (angle < rotaryStart)
  37471. angle += double_Pi * 2.0;
  37472. if (angle > rotaryEnd)
  37473. {
  37474. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  37475. angle = rotaryStart;
  37476. else
  37477. angle = rotaryEnd;
  37478. }
  37479. }
  37480. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  37481. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  37482. lastAngle = angle;
  37483. }
  37484. }
  37485. else
  37486. {
  37487. if (style == LinearBar && e.mouseWasClicked()
  37488. && valueBox != 0 && valueBox->isEditable())
  37489. return;
  37490. if (style == IncDecButtons && ! incDecDragged)
  37491. {
  37492. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  37493. return;
  37494. incDecDragged = true;
  37495. mouseDragStartX = e.x;
  37496. mouseDragStartY = e.y;
  37497. }
  37498. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  37499. : false))
  37500. || ((maximum - minimum) / sliderRegionSize < interval))
  37501. {
  37502. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  37503. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  37504. if (style == RotaryHorizontalDrag
  37505. || style == RotaryVerticalDrag
  37506. || style == IncDecButtons
  37507. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  37508. && ! snapsToMousePos))
  37509. {
  37510. const int mouseDiff = (style == RotaryHorizontalDrag
  37511. || style == LinearHorizontal
  37512. || style == LinearBar
  37513. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37514. ? e.x - mouseDragStartX
  37515. : mouseDragStartY - e.y;
  37516. double newPos = valueToProportionOfLength (valueOnMouseDown)
  37517. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  37518. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  37519. if (style == IncDecButtons)
  37520. {
  37521. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  37522. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  37523. }
  37524. }
  37525. else
  37526. {
  37527. if (isVertical())
  37528. scaledMousePos = 1.0 - scaledMousePos;
  37529. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  37530. }
  37531. }
  37532. else
  37533. {
  37534. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  37535. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37536. ? e.x - mouseXWhenLastDragged
  37537. : e.y - mouseYWhenLastDragged;
  37538. const double maxSpeed = jmax (200, sliderRegionSize);
  37539. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  37540. if (speed != 0)
  37541. {
  37542. speed = 0.2 * velocityModeSensitivity
  37543. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  37544. + jmax (0.0, (double) (speed - velocityModeThreshold))
  37545. / maxSpeed))));
  37546. if (mouseDiff < 0)
  37547. speed = -speed;
  37548. if (isVertical() || style == RotaryVerticalDrag
  37549. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  37550. speed = -speed;
  37551. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  37552. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  37553. e.originalComponent->enableUnboundedMouseMovement (true, false);
  37554. mouseWasHidden = true;
  37555. }
  37556. }
  37557. }
  37558. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  37559. if (sliderBeingDragged == 0)
  37560. {
  37561. setValue (snapValue (valueWhenLastDragged, true),
  37562. ! sendChangeOnlyOnRelease, true);
  37563. }
  37564. else if (sliderBeingDragged == 1)
  37565. {
  37566. setMinValue (snapValue (valueWhenLastDragged, true),
  37567. ! sendChangeOnlyOnRelease, false, true);
  37568. if (e.mods.isShiftDown())
  37569. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  37570. else
  37571. minMaxDiff = valueMax - valueMin;
  37572. }
  37573. else
  37574. {
  37575. jassert (sliderBeingDragged == 2);
  37576. setMaxValue (snapValue (valueWhenLastDragged, true),
  37577. ! sendChangeOnlyOnRelease, false, true);
  37578. if (e.mods.isShiftDown())
  37579. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  37580. else
  37581. minMaxDiff = valueMax - valueMin;
  37582. }
  37583. mouseXWhenLastDragged = e.x;
  37584. mouseYWhenLastDragged = e.y;
  37585. }
  37586. }
  37587. void Slider::mouseDoubleClick (const MouseEvent&)
  37588. {
  37589. if (doubleClickToValue
  37590. && isEnabled()
  37591. && style != IncDecButtons
  37592. && minimum <= doubleClickReturnValue
  37593. && maximum >= doubleClickReturnValue)
  37594. {
  37595. sendDragStart();
  37596. setValue (doubleClickReturnValue, true, true);
  37597. sendDragEnd();
  37598. }
  37599. }
  37600. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37601. {
  37602. if (scrollWheelEnabled && isEnabled()
  37603. && style != TwoValueHorizontal
  37604. && style != TwoValueVertical)
  37605. {
  37606. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  37607. {
  37608. if (valueBox != 0)
  37609. valueBox->hideEditor (false);
  37610. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  37611. const double currentPos = valueToProportionOfLength (currentValue);
  37612. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  37613. double delta = (newValue != currentValue)
  37614. ? jmax (fabs (newValue - currentValue), interval) : 0;
  37615. if (currentValue > newValue)
  37616. delta = -delta;
  37617. sendDragStart();
  37618. setValue (snapValue (currentValue + delta, false), true, true);
  37619. sendDragEnd();
  37620. }
  37621. }
  37622. else
  37623. {
  37624. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37625. }
  37626. }
  37627. void SliderListener::sliderDragStarted (Slider*)
  37628. {
  37629. }
  37630. void SliderListener::sliderDragEnded (Slider*)
  37631. {
  37632. }
  37633. END_JUCE_NAMESPACE
  37634. /********* End of inlined file: juce_Slider.cpp *********/
  37635. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  37636. BEGIN_JUCE_NAMESPACE
  37637. class DragOverlayComp : public Component
  37638. {
  37639. public:
  37640. DragOverlayComp (Image* const image_)
  37641. : image (image_)
  37642. {
  37643. image->multiplyAllAlphas (0.8f);
  37644. setAlwaysOnTop (true);
  37645. }
  37646. ~DragOverlayComp()
  37647. {
  37648. delete image;
  37649. }
  37650. void paint (Graphics& g)
  37651. {
  37652. g.drawImageAt (image, 0, 0);
  37653. }
  37654. private:
  37655. Image* image;
  37656. DragOverlayComp (const DragOverlayComp&);
  37657. const DragOverlayComp& operator= (const DragOverlayComp&);
  37658. };
  37659. TableHeaderComponent::TableHeaderComponent()
  37660. : listeners (2),
  37661. dragOverlayComp (0),
  37662. columnsChanged (false),
  37663. columnsResized (false),
  37664. sortChanged (false),
  37665. menuActive (true),
  37666. stretchToFit (false),
  37667. columnIdBeingResized (0),
  37668. columnIdBeingDragged (0),
  37669. columnIdUnderMouse (0),
  37670. lastDeliberateWidth (0)
  37671. {
  37672. }
  37673. TableHeaderComponent::~TableHeaderComponent()
  37674. {
  37675. delete dragOverlayComp;
  37676. }
  37677. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  37678. {
  37679. menuActive = hasMenu;
  37680. }
  37681. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  37682. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  37683. {
  37684. if (onlyCountVisibleColumns)
  37685. {
  37686. int num = 0;
  37687. for (int i = columns.size(); --i >= 0;)
  37688. if (columns.getUnchecked(i)->isVisible())
  37689. ++num;
  37690. return num;
  37691. }
  37692. else
  37693. {
  37694. return columns.size();
  37695. }
  37696. }
  37697. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  37698. {
  37699. const ColumnInfo* const ci = getInfoForId (columnId);
  37700. return ci != 0 ? ci->name : String::empty;
  37701. }
  37702. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  37703. {
  37704. ColumnInfo* const ci = getInfoForId (columnId);
  37705. if (ci != 0 && ci->name != newName)
  37706. {
  37707. ci->name = newName;
  37708. sendColumnsChanged();
  37709. }
  37710. }
  37711. void TableHeaderComponent::addColumn (const String& columnName,
  37712. const int columnId,
  37713. const int width,
  37714. const int minimumWidth,
  37715. const int maximumWidth,
  37716. const int propertyFlags,
  37717. const int insertIndex)
  37718. {
  37719. // can't have a duplicate or null ID!
  37720. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  37721. jassert (width > 0);
  37722. ColumnInfo* const ci = new ColumnInfo();
  37723. ci->name = columnName;
  37724. ci->id = columnId;
  37725. ci->width = width;
  37726. ci->lastDeliberateWidth = width;
  37727. ci->minimumWidth = minimumWidth;
  37728. ci->maximumWidth = maximumWidth;
  37729. if (ci->maximumWidth < 0)
  37730. ci->maximumWidth = INT_MAX;
  37731. jassert (ci->maximumWidth >= ci->minimumWidth);
  37732. ci->propertyFlags = propertyFlags;
  37733. columns.insert (insertIndex, ci);
  37734. sendColumnsChanged();
  37735. }
  37736. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  37737. {
  37738. const int index = getIndexOfColumnId (columnIdToRemove, false);
  37739. if (index >= 0)
  37740. {
  37741. columns.remove (index);
  37742. sortChanged = true;
  37743. sendColumnsChanged();
  37744. }
  37745. }
  37746. void TableHeaderComponent::removeAllColumns()
  37747. {
  37748. if (columns.size() > 0)
  37749. {
  37750. columns.clear();
  37751. sendColumnsChanged();
  37752. }
  37753. }
  37754. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  37755. {
  37756. const int currentIndex = getIndexOfColumnId (columnId, false);
  37757. newIndex = visibleIndexToTotalIndex (newIndex);
  37758. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  37759. {
  37760. columns.move (currentIndex, newIndex);
  37761. sendColumnsChanged();
  37762. }
  37763. }
  37764. int TableHeaderComponent::getColumnWidth (const int columnId) const throw()
  37765. {
  37766. const ColumnInfo* const ci = getInfoForId (columnId);
  37767. return ci != 0 ? ci->width : 0;
  37768. }
  37769. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  37770. {
  37771. ColumnInfo* const ci = getInfoForId (columnId);
  37772. if (ci != 0 && ci->width != newWidth)
  37773. {
  37774. const int numColumns = getNumColumns (true);
  37775. ci->lastDeliberateWidth = ci->width
  37776. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  37777. if (stretchToFit)
  37778. {
  37779. const int index = getIndexOfColumnId (columnId, true) + 1;
  37780. if (((unsigned int) index) < (unsigned int) numColumns)
  37781. {
  37782. const int x = getColumnPosition (index).getX();
  37783. if (lastDeliberateWidth == 0)
  37784. lastDeliberateWidth = getTotalWidth();
  37785. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  37786. }
  37787. }
  37788. repaint();
  37789. columnsResized = true;
  37790. triggerAsyncUpdate();
  37791. }
  37792. }
  37793. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  37794. {
  37795. int n = 0;
  37796. for (int i = 0; i < columns.size(); ++i)
  37797. {
  37798. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  37799. {
  37800. if (columns.getUnchecked(i)->id == columnId)
  37801. return n;
  37802. ++n;
  37803. }
  37804. }
  37805. return -1;
  37806. }
  37807. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  37808. {
  37809. if (onlyCountVisibleColumns)
  37810. index = visibleIndexToTotalIndex (index);
  37811. const ColumnInfo* const ci = columns [index];
  37812. return (ci != 0) ? ci->id : 0;
  37813. }
  37814. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  37815. {
  37816. int x = 0, width = 0, n = 0;
  37817. for (int i = 0; i < columns.size(); ++i)
  37818. {
  37819. x += width;
  37820. if (columns.getUnchecked(i)->isVisible())
  37821. {
  37822. width = columns.getUnchecked(i)->width;
  37823. if (n++ == index)
  37824. break;
  37825. }
  37826. else
  37827. {
  37828. width = 0;
  37829. }
  37830. }
  37831. return Rectangle (x, 0, width, getHeight());
  37832. }
  37833. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  37834. {
  37835. if (xToFind >= 0)
  37836. {
  37837. int x = 0;
  37838. for (int i = 0; i < columns.size(); ++i)
  37839. {
  37840. const ColumnInfo* const ci = columns.getUnchecked(i);
  37841. if (ci->isVisible())
  37842. {
  37843. x += ci->width;
  37844. if (xToFind < x)
  37845. return ci->id;
  37846. }
  37847. }
  37848. }
  37849. return 0;
  37850. }
  37851. int TableHeaderComponent::getTotalWidth() const throw()
  37852. {
  37853. int w = 0;
  37854. for (int i = columns.size(); --i >= 0;)
  37855. if (columns.getUnchecked(i)->isVisible())
  37856. w += columns.getUnchecked(i)->width;
  37857. return w;
  37858. }
  37859. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  37860. {
  37861. stretchToFit = shouldStretchToFit;
  37862. lastDeliberateWidth = getTotalWidth();
  37863. resized();
  37864. }
  37865. bool TableHeaderComponent::isStretchToFitActive() const throw()
  37866. {
  37867. return stretchToFit;
  37868. }
  37869. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  37870. {
  37871. if (stretchToFit && getWidth() > 0
  37872. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  37873. {
  37874. lastDeliberateWidth = targetTotalWidth;
  37875. resizeColumnsToFit (0, targetTotalWidth);
  37876. }
  37877. }
  37878. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  37879. {
  37880. targetTotalWidth = jmax (targetTotalWidth, 0);
  37881. StretchableObjectResizer sor;
  37882. int i;
  37883. for (i = firstColumnIndex; i < columns.size(); ++i)
  37884. {
  37885. ColumnInfo* const ci = columns.getUnchecked(i);
  37886. if (ci->isVisible())
  37887. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  37888. }
  37889. sor.resizeToFit (targetTotalWidth);
  37890. int visIndex = 0;
  37891. for (i = firstColumnIndex; i < columns.size(); ++i)
  37892. {
  37893. ColumnInfo* const ci = columns.getUnchecked(i);
  37894. if (ci->isVisible())
  37895. {
  37896. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  37897. (int) floor (sor.getItemSize (visIndex++)));
  37898. if (newWidth != ci->width)
  37899. {
  37900. ci->width = newWidth;
  37901. repaint();
  37902. columnsResized = true;
  37903. triggerAsyncUpdate();
  37904. }
  37905. }
  37906. }
  37907. }
  37908. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  37909. {
  37910. ColumnInfo* const ci = getInfoForId (columnId);
  37911. if (ci != 0 && shouldBeVisible != ci->isVisible())
  37912. {
  37913. if (shouldBeVisible)
  37914. ci->propertyFlags |= visible;
  37915. else
  37916. ci->propertyFlags &= ~visible;
  37917. sendColumnsChanged();
  37918. resized();
  37919. }
  37920. }
  37921. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  37922. {
  37923. const ColumnInfo* const ci = getInfoForId (columnId);
  37924. return ci != 0 && ci->isVisible();
  37925. }
  37926. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  37927. {
  37928. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  37929. {
  37930. for (int i = columns.size(); --i >= 0;)
  37931. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  37932. ColumnInfo* const ci = getInfoForId (columnId);
  37933. if (ci != 0)
  37934. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  37935. reSortTable();
  37936. }
  37937. }
  37938. int TableHeaderComponent::getSortColumnId() const throw()
  37939. {
  37940. for (int i = columns.size(); --i >= 0;)
  37941. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37942. return columns.getUnchecked(i)->id;
  37943. return 0;
  37944. }
  37945. bool TableHeaderComponent::isSortedForwards() const throw()
  37946. {
  37947. for (int i = columns.size(); --i >= 0;)
  37948. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37949. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  37950. return true;
  37951. }
  37952. void TableHeaderComponent::reSortTable()
  37953. {
  37954. sortChanged = true;
  37955. repaint();
  37956. triggerAsyncUpdate();
  37957. }
  37958. const String TableHeaderComponent::toString() const
  37959. {
  37960. String s;
  37961. XmlElement doc (T("TABLELAYOUT"));
  37962. doc.setAttribute (T("sortedCol"), getSortColumnId());
  37963. doc.setAttribute (T("sortForwards"), isSortedForwards());
  37964. for (int i = 0; i < columns.size(); ++i)
  37965. {
  37966. const ColumnInfo* const ci = columns.getUnchecked (i);
  37967. XmlElement* const e = new XmlElement (T("COLUMN"));
  37968. doc.addChildElement (e);
  37969. e->setAttribute (T("id"), ci->id);
  37970. e->setAttribute (T("visible"), ci->isVisible());
  37971. e->setAttribute (T("width"), ci->width);
  37972. }
  37973. return doc.createDocument (String::empty, true, false);
  37974. }
  37975. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  37976. {
  37977. XmlDocument doc (storedVersion);
  37978. XmlElement* const storedXml = doc.getDocumentElement();
  37979. int index = 0;
  37980. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  37981. {
  37982. forEachXmlChildElement (*storedXml, col)
  37983. {
  37984. const int tabId = col->getIntAttribute (T("id"));
  37985. ColumnInfo* const ci = getInfoForId (tabId);
  37986. if (ci != 0)
  37987. {
  37988. columns.move (columns.indexOf (ci), index);
  37989. ci->width = col->getIntAttribute (T("width"));
  37990. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  37991. }
  37992. ++index;
  37993. }
  37994. columnsResized = true;
  37995. sendColumnsChanged();
  37996. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  37997. storedXml->getBoolAttribute (T("sortForwards"), true));
  37998. }
  37999. delete storedXml;
  38000. }
  38001. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  38002. {
  38003. listeners.addIfNotAlreadyThere (newListener);
  38004. }
  38005. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  38006. {
  38007. listeners.removeValue (listenerToRemove);
  38008. }
  38009. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  38010. {
  38011. const ColumnInfo* const ci = getInfoForId (columnId);
  38012. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  38013. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  38014. }
  38015. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  38016. {
  38017. for (int i = 0; i < columns.size(); ++i)
  38018. {
  38019. const ColumnInfo* const ci = columns.getUnchecked(i);
  38020. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  38021. menu.addItem (ci->id, ci->name,
  38022. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  38023. isColumnVisible (ci->id));
  38024. }
  38025. }
  38026. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  38027. {
  38028. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  38029. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  38030. }
  38031. void TableHeaderComponent::paint (Graphics& g)
  38032. {
  38033. LookAndFeel& lf = getLookAndFeel();
  38034. lf.drawTableHeaderBackground (g, *this);
  38035. const Rectangle clip (g.getClipBounds());
  38036. int x = 0;
  38037. for (int i = 0; i < columns.size(); ++i)
  38038. {
  38039. const ColumnInfo* const ci = columns.getUnchecked(i);
  38040. if (ci->isVisible())
  38041. {
  38042. if (x + ci->width > clip.getX()
  38043. && (ci->id != columnIdBeingDragged
  38044. || dragOverlayComp == 0
  38045. || ! dragOverlayComp->isVisible()))
  38046. {
  38047. g.saveState();
  38048. g.setOrigin (x, 0);
  38049. g.reduceClipRegion (0, 0, ci->width, getHeight());
  38050. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  38051. ci->id == columnIdUnderMouse,
  38052. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  38053. ci->propertyFlags);
  38054. g.restoreState();
  38055. }
  38056. x += ci->width;
  38057. if (x >= clip.getRight())
  38058. break;
  38059. }
  38060. }
  38061. }
  38062. void TableHeaderComponent::resized()
  38063. {
  38064. }
  38065. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  38066. {
  38067. updateColumnUnderMouse (e.x, e.y);
  38068. }
  38069. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  38070. {
  38071. updateColumnUnderMouse (e.x, e.y);
  38072. }
  38073. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  38074. {
  38075. updateColumnUnderMouse (e.x, e.y);
  38076. }
  38077. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  38078. {
  38079. repaint();
  38080. columnIdBeingResized = 0;
  38081. columnIdBeingDragged = 0;
  38082. if (columnIdUnderMouse != 0)
  38083. {
  38084. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  38085. if (e.mods.isPopupMenu())
  38086. columnClicked (columnIdUnderMouse, e.mods);
  38087. }
  38088. if (menuActive && e.mods.isPopupMenu())
  38089. showColumnChooserMenu (columnIdUnderMouse);
  38090. }
  38091. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  38092. {
  38093. if (columnIdBeingResized == 0
  38094. && columnIdBeingDragged == 0
  38095. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  38096. {
  38097. deleteAndZero (dragOverlayComp);
  38098. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  38099. if (columnIdBeingResized != 0)
  38100. {
  38101. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  38102. initialColumnWidth = ci->width;
  38103. }
  38104. else
  38105. {
  38106. beginDrag (e);
  38107. }
  38108. }
  38109. if (columnIdBeingResized != 0)
  38110. {
  38111. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  38112. if (ci != 0)
  38113. {
  38114. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  38115. initialColumnWidth + e.getDistanceFromDragStartX());
  38116. if (stretchToFit)
  38117. {
  38118. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  38119. int minWidthOnRight = 0;
  38120. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  38121. if (columns.getUnchecked (i)->isVisible())
  38122. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  38123. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  38124. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  38125. }
  38126. setColumnWidth (columnIdBeingResized, w);
  38127. }
  38128. }
  38129. else if (columnIdBeingDragged != 0)
  38130. {
  38131. if (e.y >= -50 && e.y < getHeight() + 50)
  38132. {
  38133. if (dragOverlayComp != 0)
  38134. {
  38135. dragOverlayComp->setVisible (true);
  38136. dragOverlayComp->setBounds (jlimit (0,
  38137. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  38138. e.x - draggingColumnOffset),
  38139. 0,
  38140. dragOverlayComp->getWidth(),
  38141. getHeight());
  38142. for (int i = columns.size(); --i >= 0;)
  38143. {
  38144. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  38145. int newIndex = currentIndex;
  38146. if (newIndex > 0)
  38147. {
  38148. // if the previous column isn't draggable, we can't move our column
  38149. // past it, because that'd change the undraggable column's position..
  38150. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  38151. if ((previous->propertyFlags & draggable) != 0)
  38152. {
  38153. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  38154. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  38155. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  38156. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  38157. {
  38158. --newIndex;
  38159. }
  38160. }
  38161. }
  38162. if (newIndex < columns.size() - 1)
  38163. {
  38164. // if the next column isn't draggable, we can't move our column
  38165. // past it, because that'd change the undraggable column's position..
  38166. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  38167. if ((nextCol->propertyFlags & draggable) != 0)
  38168. {
  38169. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  38170. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  38171. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  38172. > abs (dragOverlayComp->getRight() - rightOfNext))
  38173. {
  38174. ++newIndex;
  38175. }
  38176. }
  38177. }
  38178. if (newIndex != currentIndex)
  38179. moveColumn (columnIdBeingDragged, newIndex);
  38180. else
  38181. break;
  38182. }
  38183. }
  38184. }
  38185. else
  38186. {
  38187. endDrag (draggingColumnOriginalIndex);
  38188. }
  38189. }
  38190. }
  38191. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  38192. {
  38193. if (columnIdBeingDragged == 0)
  38194. {
  38195. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  38196. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  38197. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  38198. {
  38199. columnIdBeingDragged = 0;
  38200. }
  38201. else
  38202. {
  38203. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  38204. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  38205. const int temp = columnIdBeingDragged;
  38206. columnIdBeingDragged = 0;
  38207. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  38208. columnIdBeingDragged = temp;
  38209. dragOverlayComp->setBounds (columnRect);
  38210. for (int i = listeners.size(); --i >= 0;)
  38211. {
  38212. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  38213. i = jmin (i, listeners.size() - 1);
  38214. }
  38215. }
  38216. }
  38217. }
  38218. void TableHeaderComponent::endDrag (const int finalIndex)
  38219. {
  38220. if (columnIdBeingDragged != 0)
  38221. {
  38222. moveColumn (columnIdBeingDragged, finalIndex);
  38223. columnIdBeingDragged = 0;
  38224. repaint();
  38225. for (int i = listeners.size(); --i >= 0;)
  38226. {
  38227. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  38228. i = jmin (i, listeners.size() - 1);
  38229. }
  38230. }
  38231. }
  38232. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  38233. {
  38234. mouseDrag (e);
  38235. for (int i = columns.size(); --i >= 0;)
  38236. if (columns.getUnchecked (i)->isVisible())
  38237. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  38238. columnIdBeingResized = 0;
  38239. repaint();
  38240. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  38241. updateColumnUnderMouse (e.x, e.y);
  38242. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  38243. columnClicked (columnIdUnderMouse, e.mods);
  38244. deleteAndZero (dragOverlayComp);
  38245. }
  38246. const MouseCursor TableHeaderComponent::getMouseCursor()
  38247. {
  38248. int x, y;
  38249. getMouseXYRelative (x, y);
  38250. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  38251. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  38252. return Component::getMouseCursor();
  38253. }
  38254. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  38255. {
  38256. return (propertyFlags & TableHeaderComponent::visible) != 0;
  38257. }
  38258. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  38259. {
  38260. for (int i = columns.size(); --i >= 0;)
  38261. if (columns.getUnchecked(i)->id == id)
  38262. return columns.getUnchecked(i);
  38263. return 0;
  38264. }
  38265. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  38266. {
  38267. int n = 0;
  38268. for (int i = 0; i < columns.size(); ++i)
  38269. {
  38270. if (columns.getUnchecked(i)->isVisible())
  38271. {
  38272. if (n == visibleIndex)
  38273. return i;
  38274. ++n;
  38275. }
  38276. }
  38277. return -1;
  38278. }
  38279. void TableHeaderComponent::sendColumnsChanged()
  38280. {
  38281. if (stretchToFit && lastDeliberateWidth > 0)
  38282. resizeAllColumnsToFit (lastDeliberateWidth);
  38283. repaint();
  38284. columnsChanged = true;
  38285. triggerAsyncUpdate();
  38286. }
  38287. void TableHeaderComponent::handleAsyncUpdate()
  38288. {
  38289. const bool changed = columnsChanged || sortChanged;
  38290. const bool sized = columnsResized || changed;
  38291. const bool sorted = sortChanged;
  38292. columnsChanged = false;
  38293. columnsResized = false;
  38294. sortChanged = false;
  38295. if (sorted)
  38296. {
  38297. for (int i = listeners.size(); --i >= 0;)
  38298. {
  38299. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  38300. i = jmin (i, listeners.size() - 1);
  38301. }
  38302. }
  38303. if (changed)
  38304. {
  38305. for (int i = listeners.size(); --i >= 0;)
  38306. {
  38307. listeners.getUnchecked(i)->tableColumnsChanged (this);
  38308. i = jmin (i, listeners.size() - 1);
  38309. }
  38310. }
  38311. if (sized)
  38312. {
  38313. for (int i = listeners.size(); --i >= 0;)
  38314. {
  38315. listeners.getUnchecked(i)->tableColumnsResized (this);
  38316. i = jmin (i, listeners.size() - 1);
  38317. }
  38318. }
  38319. }
  38320. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  38321. {
  38322. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  38323. {
  38324. const int draggableDistance = 3;
  38325. int x = 0;
  38326. for (int i = 0; i < columns.size(); ++i)
  38327. {
  38328. const ColumnInfo* const ci = columns.getUnchecked(i);
  38329. if (ci->isVisible())
  38330. {
  38331. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  38332. && (ci->propertyFlags & resizable) != 0)
  38333. return ci->id;
  38334. x += ci->width;
  38335. }
  38336. }
  38337. }
  38338. return 0;
  38339. }
  38340. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  38341. {
  38342. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  38343. ? getColumnIdAtX (x) : 0;
  38344. if (newCol != columnIdUnderMouse)
  38345. {
  38346. columnIdUnderMouse = newCol;
  38347. repaint();
  38348. }
  38349. }
  38350. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  38351. {
  38352. PopupMenu m;
  38353. addMenuItems (m, columnIdClicked);
  38354. if (m.getNumItems() > 0)
  38355. {
  38356. const int result = m.show();
  38357. if (result != 0)
  38358. reactToMenuItem (result, columnIdClicked);
  38359. }
  38360. }
  38361. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  38362. {
  38363. }
  38364. END_JUCE_NAMESPACE
  38365. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  38366. /********* Start of inlined file: juce_TableListBox.cpp *********/
  38367. BEGIN_JUCE_NAMESPACE
  38368. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  38369. class TableListRowComp : public Component,
  38370. public TooltipClient
  38371. {
  38372. public:
  38373. TableListRowComp (TableListBox& owner_)
  38374. : owner (owner_),
  38375. row (-1),
  38376. isSelected (false)
  38377. {
  38378. }
  38379. ~TableListRowComp()
  38380. {
  38381. deleteAllChildren();
  38382. }
  38383. void paint (Graphics& g)
  38384. {
  38385. TableListBoxModel* const model = owner.getModel();
  38386. if (model != 0)
  38387. {
  38388. const TableHeaderComponent* const header = owner.getHeader();
  38389. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  38390. const int numColumns = header->getNumColumns (true);
  38391. for (int i = 0; i < numColumns; ++i)
  38392. {
  38393. if (! columnsWithComponents [i])
  38394. {
  38395. const int columnId = header->getColumnIdOfIndex (i, true);
  38396. Rectangle columnRect (header->getColumnPosition (i));
  38397. columnRect.setSize (columnRect.getWidth(), getHeight());
  38398. g.saveState();
  38399. g.reduceClipRegion (columnRect);
  38400. g.setOrigin (columnRect.getX(), 0);
  38401. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  38402. g.restoreState();
  38403. }
  38404. }
  38405. }
  38406. }
  38407. void update (const int newRow, const bool isNowSelected)
  38408. {
  38409. if (newRow != row || isNowSelected != isSelected)
  38410. {
  38411. row = newRow;
  38412. isSelected = isNowSelected;
  38413. repaint();
  38414. }
  38415. if (row < owner.getNumRows())
  38416. {
  38417. jassert (row >= 0);
  38418. const tchar* const tagPropertyName = T("_tableLastUseNum");
  38419. const int newTag = Random::getSystemRandom().nextInt();
  38420. const TableHeaderComponent* const header = owner.getHeader();
  38421. const int numColumns = header->getNumColumns (true);
  38422. int i;
  38423. columnsWithComponents.clear();
  38424. if (owner.getModel() != 0)
  38425. {
  38426. for (i = 0; i < numColumns; ++i)
  38427. {
  38428. const int columnId = header->getColumnIdOfIndex (i, true);
  38429. Component* const newComp
  38430. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  38431. findChildComponentForColumn (columnId));
  38432. if (newComp != 0)
  38433. {
  38434. addAndMakeVisible (newComp);
  38435. newComp->setComponentProperty (tagPropertyName, newTag);
  38436. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  38437. const Rectangle columnRect (header->getColumnPosition (i));
  38438. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38439. columnsWithComponents.setBit (i);
  38440. }
  38441. }
  38442. }
  38443. for (i = getNumChildComponents(); --i >= 0;)
  38444. {
  38445. Component* const c = getChildComponent (i);
  38446. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  38447. delete c;
  38448. }
  38449. }
  38450. else
  38451. {
  38452. columnsWithComponents.clear();
  38453. deleteAllChildren();
  38454. }
  38455. }
  38456. void resized()
  38457. {
  38458. for (int i = getNumChildComponents(); --i >= 0;)
  38459. {
  38460. Component* const c = getChildComponent (i);
  38461. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  38462. if (columnId != 0)
  38463. {
  38464. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  38465. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38466. }
  38467. }
  38468. }
  38469. void mouseDown (const MouseEvent& e)
  38470. {
  38471. isDragging = false;
  38472. selectRowOnMouseUp = false;
  38473. if (isEnabled())
  38474. {
  38475. if (! isSelected)
  38476. {
  38477. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38478. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38479. if (columnId != 0 && owner.getModel() != 0)
  38480. owner.getModel()->cellClicked (row, columnId, e);
  38481. }
  38482. else
  38483. {
  38484. selectRowOnMouseUp = true;
  38485. }
  38486. }
  38487. }
  38488. void mouseDrag (const MouseEvent& e)
  38489. {
  38490. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38491. {
  38492. const SparseSet <int> selectedRows (owner.getSelectedRows());
  38493. if (selectedRows.size() > 0)
  38494. {
  38495. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38496. if (dragDescription.isNotEmpty())
  38497. {
  38498. isDragging = true;
  38499. DragAndDropContainer* const dragContainer
  38500. = DragAndDropContainer::findParentDragContainerFor (this);
  38501. if (dragContainer != 0)
  38502. {
  38503. Image* dragImage = owner.createSnapshotOfSelectedRows();
  38504. dragImage->multiplyAllAlphas (0.6f);
  38505. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  38506. }
  38507. else
  38508. {
  38509. // to be able to do a drag-and-drop operation, the listbox needs to
  38510. // be inside a component which is also a DragAndDropContainer.
  38511. jassertfalse
  38512. }
  38513. }
  38514. }
  38515. }
  38516. }
  38517. void mouseUp (const MouseEvent& e)
  38518. {
  38519. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  38520. {
  38521. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38522. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38523. if (columnId != 0 && owner.getModel() != 0)
  38524. owner.getModel()->cellClicked (row, columnId, e);
  38525. }
  38526. }
  38527. void mouseDoubleClick (const MouseEvent& e)
  38528. {
  38529. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38530. if (columnId != 0 && owner.getModel() != 0)
  38531. owner.getModel()->cellDoubleClicked (row, columnId, e);
  38532. }
  38533. const String getTooltip()
  38534. {
  38535. int x, y;
  38536. getMouseXYRelative (x, y);
  38537. const int columnId = owner.getHeader()->getColumnIdAtX (x);
  38538. if (columnId != 0 && owner.getModel() != 0)
  38539. return owner.getModel()->getCellTooltip (row, columnId);
  38540. return String::empty;
  38541. }
  38542. juce_UseDebuggingNewOperator
  38543. private:
  38544. TableListBox& owner;
  38545. int row;
  38546. bool isSelected, isDragging, selectRowOnMouseUp;
  38547. BitArray columnsWithComponents;
  38548. Component* findChildComponentForColumn (const int columnId) const
  38549. {
  38550. for (int i = getNumChildComponents(); --i >= 0;)
  38551. {
  38552. Component* const c = getChildComponent (i);
  38553. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  38554. return c;
  38555. }
  38556. return 0;
  38557. }
  38558. TableListRowComp (const TableListRowComp&);
  38559. const TableListRowComp& operator= (const TableListRowComp&);
  38560. };
  38561. class TableListBoxHeader : public TableHeaderComponent
  38562. {
  38563. public:
  38564. TableListBoxHeader (TableListBox& owner_)
  38565. : owner (owner_)
  38566. {
  38567. }
  38568. ~TableListBoxHeader()
  38569. {
  38570. }
  38571. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  38572. {
  38573. if (owner.isAutoSizeMenuOptionShown())
  38574. {
  38575. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  38576. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  38577. menu.addSeparator();
  38578. }
  38579. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  38580. }
  38581. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  38582. {
  38583. if (menuReturnId == 0xf836743)
  38584. {
  38585. owner.autoSizeColumn (columnIdClicked);
  38586. }
  38587. else if (menuReturnId == 0xf836744)
  38588. {
  38589. owner.autoSizeAllColumns();
  38590. }
  38591. else
  38592. {
  38593. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  38594. }
  38595. }
  38596. juce_UseDebuggingNewOperator
  38597. private:
  38598. TableListBox& owner;
  38599. TableListBoxHeader (const TableListBoxHeader&);
  38600. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  38601. };
  38602. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  38603. : ListBox (name, 0),
  38604. model (model_),
  38605. autoSizeOptionsShown (true)
  38606. {
  38607. ListBox::model = this;
  38608. header = new TableListBoxHeader (*this);
  38609. header->setSize (100, 28);
  38610. header->addListener (this);
  38611. setHeaderComponent (header);
  38612. }
  38613. TableListBox::~TableListBox()
  38614. {
  38615. deleteAllChildren();
  38616. }
  38617. void TableListBox::setModel (TableListBoxModel* const newModel)
  38618. {
  38619. if (model != newModel)
  38620. {
  38621. model = newModel;
  38622. updateContent();
  38623. }
  38624. }
  38625. int TableListBox::getHeaderHeight() const throw()
  38626. {
  38627. return header->getHeight();
  38628. }
  38629. void TableListBox::setHeaderHeight (const int newHeight)
  38630. {
  38631. header->setSize (header->getWidth(), newHeight);
  38632. resized();
  38633. }
  38634. void TableListBox::autoSizeColumn (const int columnId)
  38635. {
  38636. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  38637. if (width > 0)
  38638. header->setColumnWidth (columnId, width);
  38639. }
  38640. void TableListBox::autoSizeAllColumns()
  38641. {
  38642. for (int i = 0; i < header->getNumColumns (true); ++i)
  38643. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  38644. }
  38645. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  38646. {
  38647. autoSizeOptionsShown = shouldBeShown;
  38648. }
  38649. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  38650. {
  38651. return autoSizeOptionsShown;
  38652. }
  38653. const Rectangle TableListBox::getCellPosition (const int columnId,
  38654. const int rowNumber,
  38655. const bool relativeToComponentTopLeft) const
  38656. {
  38657. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38658. if (relativeToComponentTopLeft)
  38659. headerCell.translate (header->getX(), 0);
  38660. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  38661. return Rectangle (headerCell.getX(), row.getY(),
  38662. headerCell.getWidth(), row.getHeight());
  38663. }
  38664. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  38665. {
  38666. ScrollBar* const scrollbar = getHorizontalScrollBar();
  38667. if (scrollbar != 0)
  38668. {
  38669. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38670. double x = scrollbar->getCurrentRangeStart();
  38671. const double w = scrollbar->getCurrentRangeSize();
  38672. if (pos.getX() < x)
  38673. x = pos.getX();
  38674. else if (pos.getRight() > x + w)
  38675. x += jmax (0.0, pos.getRight() - (x + w));
  38676. scrollbar->setCurrentRangeStart (x);
  38677. }
  38678. }
  38679. int TableListBox::getNumRows()
  38680. {
  38681. return model != 0 ? model->getNumRows() : 0;
  38682. }
  38683. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  38684. {
  38685. }
  38686. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  38687. {
  38688. if (existingComponentToUpdate == 0)
  38689. existingComponentToUpdate = new TableListRowComp (*this);
  38690. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  38691. return existingComponentToUpdate;
  38692. }
  38693. void TableListBox::selectedRowsChanged (int row)
  38694. {
  38695. if (model != 0)
  38696. model->selectedRowsChanged (row);
  38697. }
  38698. void TableListBox::deleteKeyPressed (int row)
  38699. {
  38700. if (model != 0)
  38701. model->deleteKeyPressed (row);
  38702. }
  38703. void TableListBox::returnKeyPressed (int row)
  38704. {
  38705. if (model != 0)
  38706. model->returnKeyPressed (row);
  38707. }
  38708. void TableListBox::backgroundClicked()
  38709. {
  38710. if (model != 0)
  38711. model->backgroundClicked();
  38712. }
  38713. void TableListBox::listWasScrolled()
  38714. {
  38715. if (model != 0)
  38716. model->listWasScrolled();
  38717. }
  38718. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  38719. {
  38720. setMinimumContentWidth (header->getTotalWidth());
  38721. repaint();
  38722. updateColumnComponents();
  38723. }
  38724. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  38725. {
  38726. setMinimumContentWidth (header->getTotalWidth());
  38727. repaint();
  38728. updateColumnComponents();
  38729. }
  38730. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  38731. {
  38732. if (model != 0)
  38733. model->sortOrderChanged (header->getSortColumnId(),
  38734. header->isSortedForwards());
  38735. }
  38736. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  38737. {
  38738. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  38739. repaint();
  38740. }
  38741. void TableListBox::resized()
  38742. {
  38743. ListBox::resized();
  38744. header->resizeAllColumnsToFit (getVisibleContentWidth());
  38745. setMinimumContentWidth (header->getTotalWidth());
  38746. }
  38747. void TableListBox::updateColumnComponents() const
  38748. {
  38749. const int firstRow = getRowContainingPosition (0, 0);
  38750. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  38751. {
  38752. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  38753. if (rowComp != 0)
  38754. rowComp->resized();
  38755. }
  38756. }
  38757. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  38758. {
  38759. }
  38760. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  38761. {
  38762. }
  38763. void TableListBoxModel::backgroundClicked()
  38764. {
  38765. }
  38766. void TableListBoxModel::sortOrderChanged (int, const bool)
  38767. {
  38768. }
  38769. int TableListBoxModel::getColumnAutoSizeWidth (int)
  38770. {
  38771. return 0;
  38772. }
  38773. void TableListBoxModel::selectedRowsChanged (int)
  38774. {
  38775. }
  38776. void TableListBoxModel::deleteKeyPressed (int)
  38777. {
  38778. }
  38779. void TableListBoxModel::returnKeyPressed (int)
  38780. {
  38781. }
  38782. void TableListBoxModel::listWasScrolled()
  38783. {
  38784. }
  38785. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  38786. {
  38787. return String::empty;
  38788. }
  38789. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38790. {
  38791. return String::empty;
  38792. }
  38793. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  38794. {
  38795. (void) existingComponentToUpdate;
  38796. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38797. return 0;
  38798. }
  38799. END_JUCE_NAMESPACE
  38800. /********* End of inlined file: juce_TableListBox.cpp *********/
  38801. /********* Start of inlined file: juce_TextEditor.cpp *********/
  38802. BEGIN_JUCE_NAMESPACE
  38803. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  38804. // a word or space that can't be broken down any further
  38805. struct TextAtom
  38806. {
  38807. String atomText;
  38808. float width;
  38809. uint16 numChars;
  38810. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  38811. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  38812. const String getText (const tchar passwordCharacter) const throw()
  38813. {
  38814. if (passwordCharacter == 0)
  38815. return atomText;
  38816. else
  38817. return String::repeatedString (String::charToString (passwordCharacter),
  38818. atomText.length());
  38819. }
  38820. const String getTrimmedText (const tchar passwordCharacter) const throw()
  38821. {
  38822. if (passwordCharacter == 0)
  38823. return atomText.substring (0, numChars);
  38824. else if (isNewLine())
  38825. return String::empty;
  38826. else
  38827. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  38828. }
  38829. };
  38830. // a run of text with a single font and colour
  38831. class UniformTextSection
  38832. {
  38833. public:
  38834. UniformTextSection (const String& text,
  38835. const Font& font_,
  38836. const Colour& colour_,
  38837. const tchar passwordCharacter) throw()
  38838. : font (font_),
  38839. colour (colour_),
  38840. atoms (64)
  38841. {
  38842. initialiseAtoms (text, passwordCharacter);
  38843. }
  38844. UniformTextSection (const UniformTextSection& other) throw()
  38845. : font (other.font),
  38846. colour (other.colour),
  38847. atoms (64)
  38848. {
  38849. for (int i = 0; i < other.atoms.size(); ++i)
  38850. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  38851. }
  38852. ~UniformTextSection() throw()
  38853. {
  38854. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  38855. }
  38856. void clear() throw()
  38857. {
  38858. for (int i = atoms.size(); --i >= 0;)
  38859. {
  38860. TextAtom* const atom = getAtom(i);
  38861. delete atom;
  38862. }
  38863. atoms.clear();
  38864. }
  38865. int getNumAtoms() const throw()
  38866. {
  38867. return atoms.size();
  38868. }
  38869. TextAtom* getAtom (const int index) const throw()
  38870. {
  38871. return (TextAtom*) atoms.getUnchecked (index);
  38872. }
  38873. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  38874. {
  38875. if (other.atoms.size() > 0)
  38876. {
  38877. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  38878. int i = 0;
  38879. if (lastAtom != 0)
  38880. {
  38881. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  38882. {
  38883. TextAtom* const first = other.getAtom(0);
  38884. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  38885. {
  38886. lastAtom->atomText += first->atomText;
  38887. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  38888. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  38889. delete first;
  38890. ++i;
  38891. }
  38892. }
  38893. }
  38894. while (i < other.atoms.size())
  38895. {
  38896. atoms.add (other.getAtom(i));
  38897. ++i;
  38898. }
  38899. }
  38900. }
  38901. UniformTextSection* split (const int indexToBreakAt,
  38902. const tchar passwordCharacter) throw()
  38903. {
  38904. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  38905. font, colour,
  38906. passwordCharacter);
  38907. int index = 0;
  38908. for (int i = 0; i < atoms.size(); ++i)
  38909. {
  38910. TextAtom* const atom = getAtom(i);
  38911. const int nextIndex = index + atom->numChars;
  38912. if (index == indexToBreakAt)
  38913. {
  38914. int j;
  38915. for (j = i; j < atoms.size(); ++j)
  38916. section2->atoms.add (getAtom (j));
  38917. for (j = atoms.size(); --j >= i;)
  38918. atoms.remove (j);
  38919. break;
  38920. }
  38921. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  38922. {
  38923. TextAtom* const secondAtom = new TextAtom();
  38924. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  38925. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  38926. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  38927. section2->atoms.add (secondAtom);
  38928. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  38929. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38930. atom->numChars = (uint16) (indexToBreakAt - index);
  38931. int j;
  38932. for (j = i + 1; j < atoms.size(); ++j)
  38933. section2->atoms.add (getAtom (j));
  38934. for (j = atoms.size(); --j > i;)
  38935. atoms.remove (j);
  38936. break;
  38937. }
  38938. index = nextIndex;
  38939. }
  38940. return section2;
  38941. }
  38942. const String getAllText() const throw()
  38943. {
  38944. String s;
  38945. s.preallocateStorage (getTotalLength());
  38946. tchar* endOfString = (tchar*) &(s[0]);
  38947. for (int i = 0; i < atoms.size(); ++i)
  38948. {
  38949. const TextAtom* const atom = getAtom(i);
  38950. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  38951. endOfString += atom->numChars;
  38952. }
  38953. *endOfString = 0;
  38954. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  38955. return s;
  38956. }
  38957. const String getTextSubstring (const int startCharacter,
  38958. const int endCharacter) const throw()
  38959. {
  38960. int index = 0;
  38961. int totalLen = 0;
  38962. int i;
  38963. for (i = 0; i < atoms.size(); ++i)
  38964. {
  38965. const TextAtom* const atom = getAtom (i);
  38966. const int nextIndex = index + atom->numChars;
  38967. if (startCharacter < nextIndex)
  38968. {
  38969. if (endCharacter <= index)
  38970. break;
  38971. const int start = jmax (0, startCharacter - index);
  38972. const int end = jmin (endCharacter - index, atom->numChars);
  38973. jassert (end >= start);
  38974. totalLen += end - start;
  38975. }
  38976. index = nextIndex;
  38977. }
  38978. String s;
  38979. s.preallocateStorage (totalLen + 1);
  38980. tchar* psz = (tchar*) (const tchar*) s;
  38981. index = 0;
  38982. for (i = 0; i < atoms.size(); ++i)
  38983. {
  38984. const TextAtom* const atom = getAtom (i);
  38985. const int nextIndex = index + atom->numChars;
  38986. if (startCharacter < nextIndex)
  38987. {
  38988. if (endCharacter <= index)
  38989. break;
  38990. const int start = jmax (0, startCharacter - index);
  38991. const int len = jmin (endCharacter - index, atom->numChars) - start;
  38992. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  38993. psz += len;
  38994. *psz = 0;
  38995. }
  38996. index = nextIndex;
  38997. }
  38998. return s;
  38999. }
  39000. int getTotalLength() const throw()
  39001. {
  39002. int c = 0;
  39003. for (int i = atoms.size(); --i >= 0;)
  39004. c += getAtom(i)->numChars;
  39005. return c;
  39006. }
  39007. void setFont (const Font& newFont,
  39008. const tchar passwordCharacter) throw()
  39009. {
  39010. if (font != newFont)
  39011. {
  39012. font = newFont;
  39013. for (int i = atoms.size(); --i >= 0;)
  39014. {
  39015. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  39016. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  39017. }
  39018. }
  39019. }
  39020. juce_UseDebuggingNewOperator
  39021. Font font;
  39022. Colour colour;
  39023. private:
  39024. VoidArray atoms;
  39025. void initialiseAtoms (const String& textToParse,
  39026. const tchar passwordCharacter) throw()
  39027. {
  39028. int i = 0;
  39029. const int len = textToParse.length();
  39030. const tchar* const text = (const tchar*) textToParse;
  39031. while (i < len)
  39032. {
  39033. int start = i;
  39034. // create a whitespace atom unless it starts with non-ws
  39035. if (CharacterFunctions::isWhitespace (text[i])
  39036. && text[i] != T('\r')
  39037. && text[i] != T('\n'))
  39038. {
  39039. while (i < len
  39040. && CharacterFunctions::isWhitespace (text[i])
  39041. && text[i] != T('\r')
  39042. && text[i] != T('\n'))
  39043. {
  39044. ++i;
  39045. }
  39046. }
  39047. else
  39048. {
  39049. if (text[i] == T('\r'))
  39050. {
  39051. ++i;
  39052. if ((i < len) && (text[i] == T('\n')))
  39053. {
  39054. ++start;
  39055. ++i;
  39056. }
  39057. }
  39058. else if (text[i] == T('\n'))
  39059. {
  39060. ++i;
  39061. }
  39062. else
  39063. {
  39064. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  39065. ++i;
  39066. }
  39067. }
  39068. TextAtom* const atom = new TextAtom();
  39069. atom->atomText = String (text + start, i - start);
  39070. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  39071. atom->numChars = (uint16) (i - start);
  39072. atoms.add (atom);
  39073. }
  39074. }
  39075. const UniformTextSection& operator= (const UniformTextSection& other);
  39076. };
  39077. class TextEditorIterator
  39078. {
  39079. public:
  39080. TextEditorIterator (const VoidArray& sections_,
  39081. const float wordWrapWidth_,
  39082. const tchar passwordCharacter_) throw()
  39083. : indexInText (0),
  39084. lineY (0),
  39085. lineHeight (0),
  39086. maxDescent (0),
  39087. atomX (0),
  39088. atomRight (0),
  39089. atom (0),
  39090. currentSection (0),
  39091. sections (sections_),
  39092. sectionIndex (0),
  39093. atomIndex (0),
  39094. wordWrapWidth (wordWrapWidth_),
  39095. passwordCharacter (passwordCharacter_)
  39096. {
  39097. jassert (wordWrapWidth_ > 0);
  39098. if (sections.size() > 0)
  39099. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  39100. if (currentSection != 0)
  39101. {
  39102. lineHeight = currentSection->font.getHeight();
  39103. maxDescent = currentSection->font.getDescent();
  39104. }
  39105. }
  39106. TextEditorIterator (const TextEditorIterator& other) throw()
  39107. : indexInText (other.indexInText),
  39108. lineY (other.lineY),
  39109. lineHeight (other.lineHeight),
  39110. maxDescent (other.maxDescent),
  39111. atomX (other.atomX),
  39112. atomRight (other.atomRight),
  39113. atom (other.atom),
  39114. currentSection (other.currentSection),
  39115. sections (other.sections),
  39116. sectionIndex (other.sectionIndex),
  39117. atomIndex (other.atomIndex),
  39118. wordWrapWidth (other.wordWrapWidth),
  39119. passwordCharacter (other.passwordCharacter),
  39120. tempAtom (other.tempAtom)
  39121. {
  39122. }
  39123. ~TextEditorIterator() throw()
  39124. {
  39125. }
  39126. bool next() throw()
  39127. {
  39128. if (atom == &tempAtom)
  39129. {
  39130. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  39131. if (numRemaining > 0)
  39132. {
  39133. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  39134. atomX = 0;
  39135. if (tempAtom.numChars > 0)
  39136. lineY += lineHeight;
  39137. indexInText += tempAtom.numChars;
  39138. GlyphArrangement g;
  39139. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  39140. int split;
  39141. for (split = 0; split < g.getNumGlyphs(); ++split)
  39142. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  39143. break;
  39144. if (split > 0 && split <= numRemaining)
  39145. {
  39146. tempAtom.numChars = (uint16) split;
  39147. tempAtom.width = g.getGlyph (split - 1).getRight();
  39148. atomRight = atomX + tempAtom.width;
  39149. return true;
  39150. }
  39151. }
  39152. }
  39153. bool forceNewLine = false;
  39154. if (sectionIndex >= sections.size())
  39155. {
  39156. moveToEndOfLastAtom();
  39157. return false;
  39158. }
  39159. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  39160. {
  39161. if (atomIndex >= currentSection->getNumAtoms())
  39162. {
  39163. if (++sectionIndex >= sections.size())
  39164. {
  39165. moveToEndOfLastAtom();
  39166. return false;
  39167. }
  39168. atomIndex = 0;
  39169. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  39170. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39171. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39172. }
  39173. else
  39174. {
  39175. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  39176. if (! lastAtom->isWhitespace())
  39177. {
  39178. // handle the case where the last atom in a section is actually part of the same
  39179. // word as the first atom of the next section...
  39180. float right = atomRight + lastAtom->width;
  39181. float lineHeight2 = lineHeight;
  39182. float maxDescent2 = maxDescent;
  39183. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  39184. {
  39185. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  39186. if (s->getNumAtoms() == 0)
  39187. break;
  39188. const TextAtom* const nextAtom = s->getAtom (0);
  39189. if (nextAtom->isWhitespace())
  39190. break;
  39191. right += nextAtom->width;
  39192. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  39193. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  39194. if (SHOULD_WRAP (right, wordWrapWidth))
  39195. {
  39196. lineHeight = lineHeight2;
  39197. maxDescent = maxDescent2;
  39198. forceNewLine = true;
  39199. break;
  39200. }
  39201. if (s->getNumAtoms() > 1)
  39202. break;
  39203. }
  39204. }
  39205. }
  39206. }
  39207. if (atom != 0)
  39208. {
  39209. atomX = atomRight;
  39210. indexInText += atom->numChars;
  39211. if (atom->isNewLine())
  39212. {
  39213. atomX = 0;
  39214. lineY += lineHeight;
  39215. }
  39216. }
  39217. atom = currentSection->getAtom (atomIndex);
  39218. atomRight = atomX + atom->width;
  39219. ++atomIndex;
  39220. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  39221. {
  39222. if (atom->isWhitespace())
  39223. {
  39224. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  39225. atomRight = jmin (atomRight, wordWrapWidth);
  39226. }
  39227. else
  39228. {
  39229. return wrapCurrentAtom();
  39230. }
  39231. }
  39232. return true;
  39233. }
  39234. bool wrapCurrentAtom() throw()
  39235. {
  39236. atomRight = atom->width;
  39237. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  39238. {
  39239. tempAtom = *atom;
  39240. tempAtom.width = 0;
  39241. tempAtom.numChars = 0;
  39242. atom = &tempAtom;
  39243. if (atomX > 0)
  39244. {
  39245. atomX = 0;
  39246. lineY += lineHeight;
  39247. }
  39248. return next();
  39249. }
  39250. atomX = 0;
  39251. lineY += lineHeight;
  39252. return true;
  39253. }
  39254. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  39255. {
  39256. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39257. {
  39258. if (lastSection != currentSection)
  39259. {
  39260. lastSection = currentSection;
  39261. g.setColour (currentSection->colour);
  39262. g.setFont (currentSection->font);
  39263. }
  39264. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  39265. GlyphArrangement ga;
  39266. ga.addLineOfText (currentSection->font,
  39267. atom->getTrimmedText (passwordCharacter),
  39268. atomX,
  39269. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39270. ga.draw (g);
  39271. }
  39272. }
  39273. void drawSelection (Graphics& g,
  39274. const int selectionStart,
  39275. const int selectionEnd) const throw()
  39276. {
  39277. const int startX = roundFloatToInt (indexToX (selectionStart));
  39278. const int endX = roundFloatToInt (indexToX (selectionEnd));
  39279. const int y = roundFloatToInt (lineY);
  39280. const int nextY = roundFloatToInt (lineY + lineHeight);
  39281. g.fillRect (startX, y, endX - startX, nextY - y);
  39282. }
  39283. void drawSelectedText (Graphics& g,
  39284. const int selectionStart,
  39285. const int selectionEnd,
  39286. const Colour& selectedTextColour) const throw()
  39287. {
  39288. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39289. {
  39290. GlyphArrangement ga;
  39291. ga.addLineOfText (currentSection->font,
  39292. atom->getTrimmedText (passwordCharacter),
  39293. atomX,
  39294. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39295. if (selectionEnd < indexInText + atom->numChars)
  39296. {
  39297. GlyphArrangement ga2 (ga);
  39298. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  39299. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  39300. g.setColour (currentSection->colour);
  39301. ga2.draw (g);
  39302. }
  39303. if (selectionStart > indexInText)
  39304. {
  39305. GlyphArrangement ga2 (ga);
  39306. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  39307. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  39308. g.setColour (currentSection->colour);
  39309. ga2.draw (g);
  39310. }
  39311. g.setColour (selectedTextColour);
  39312. ga.draw (g);
  39313. }
  39314. }
  39315. float indexToX (const int indexToFind) const throw()
  39316. {
  39317. if (indexToFind <= indexInText)
  39318. return atomX;
  39319. if (indexToFind >= indexInText + atom->numChars)
  39320. return atomRight;
  39321. GlyphArrangement g;
  39322. g.addLineOfText (currentSection->font,
  39323. atom->getText (passwordCharacter),
  39324. atomX, 0.0f);
  39325. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  39326. }
  39327. int xToIndex (const float xToFind) const throw()
  39328. {
  39329. if (xToFind <= atomX || atom->isNewLine())
  39330. return indexInText;
  39331. if (xToFind >= atomRight)
  39332. return indexInText + atom->numChars;
  39333. GlyphArrangement g;
  39334. g.addLineOfText (currentSection->font,
  39335. atom->getText (passwordCharacter),
  39336. atomX, 0.0f);
  39337. int j;
  39338. for (j = 0; j < atom->numChars; ++j)
  39339. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  39340. break;
  39341. return indexInText + j;
  39342. }
  39343. void updateLineHeight() throw()
  39344. {
  39345. float x = atomRight;
  39346. int tempSectionIndex = sectionIndex;
  39347. int tempAtomIndex = atomIndex;
  39348. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39349. while (! SHOULD_WRAP (x, wordWrapWidth))
  39350. {
  39351. if (tempSectionIndex >= sections.size())
  39352. break;
  39353. bool checkSize = false;
  39354. if (tempAtomIndex >= currentSection->getNumAtoms())
  39355. {
  39356. if (++tempSectionIndex >= sections.size())
  39357. break;
  39358. tempAtomIndex = 0;
  39359. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39360. checkSize = true;
  39361. }
  39362. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  39363. if (atom == 0)
  39364. break;
  39365. x += atom->width;
  39366. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  39367. break;
  39368. if (checkSize)
  39369. {
  39370. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39371. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39372. }
  39373. ++tempAtomIndex;
  39374. }
  39375. }
  39376. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  39377. {
  39378. while (next())
  39379. {
  39380. if (indexInText + atom->numChars >= index)
  39381. {
  39382. updateLineHeight();
  39383. if (indexInText + atom->numChars > index)
  39384. {
  39385. cx = indexToX (index);
  39386. cy = lineY;
  39387. lineHeight_ = lineHeight;
  39388. return true;
  39389. }
  39390. }
  39391. }
  39392. cx = atomX;
  39393. cy = lineY;
  39394. lineHeight_ = lineHeight;
  39395. return false;
  39396. }
  39397. juce_UseDebuggingNewOperator
  39398. int indexInText;
  39399. float lineY, lineHeight, maxDescent;
  39400. float atomX, atomRight;
  39401. const TextAtom* atom;
  39402. const UniformTextSection* currentSection;
  39403. private:
  39404. const VoidArray& sections;
  39405. int sectionIndex, atomIndex;
  39406. const float wordWrapWidth;
  39407. const tchar passwordCharacter;
  39408. TextAtom tempAtom;
  39409. const TextEditorIterator& operator= (const TextEditorIterator&);
  39410. void moveToEndOfLastAtom() throw()
  39411. {
  39412. if (atom != 0)
  39413. {
  39414. atomX = atomRight;
  39415. if (atom->isNewLine())
  39416. {
  39417. atomX = 0.0f;
  39418. lineY += lineHeight;
  39419. }
  39420. }
  39421. }
  39422. };
  39423. class TextEditorInsertAction : public UndoableAction
  39424. {
  39425. TextEditor& owner;
  39426. const String text;
  39427. const int insertIndex, oldCaretPos, newCaretPos;
  39428. const Font font;
  39429. const Colour colour;
  39430. TextEditorInsertAction (const TextEditorInsertAction&);
  39431. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  39432. public:
  39433. TextEditorInsertAction (TextEditor& owner_,
  39434. const String& text_,
  39435. const int insertIndex_,
  39436. const Font& font_,
  39437. const Colour& colour_,
  39438. const int oldCaretPos_,
  39439. const int newCaretPos_) throw()
  39440. : owner (owner_),
  39441. text (text_),
  39442. insertIndex (insertIndex_),
  39443. oldCaretPos (oldCaretPos_),
  39444. newCaretPos (newCaretPos_),
  39445. font (font_),
  39446. colour (colour_)
  39447. {
  39448. }
  39449. ~TextEditorInsertAction()
  39450. {
  39451. }
  39452. bool perform()
  39453. {
  39454. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  39455. return true;
  39456. }
  39457. bool undo()
  39458. {
  39459. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  39460. return true;
  39461. }
  39462. int getSizeInUnits()
  39463. {
  39464. return text.length() + 16;
  39465. }
  39466. };
  39467. class TextEditorRemoveAction : public UndoableAction
  39468. {
  39469. TextEditor& owner;
  39470. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  39471. VoidArray removedSections;
  39472. TextEditorRemoveAction (const TextEditorRemoveAction&);
  39473. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  39474. public:
  39475. TextEditorRemoveAction (TextEditor& owner_,
  39476. const int startIndex_,
  39477. const int endIndex_,
  39478. const int oldCaretPos_,
  39479. const int newCaretPos_,
  39480. const VoidArray& removedSections_) throw()
  39481. : owner (owner_),
  39482. startIndex (startIndex_),
  39483. endIndex (endIndex_),
  39484. oldCaretPos (oldCaretPos_),
  39485. newCaretPos (newCaretPos_),
  39486. removedSections (removedSections_)
  39487. {
  39488. }
  39489. ~TextEditorRemoveAction()
  39490. {
  39491. for (int i = removedSections.size(); --i >= 0;)
  39492. {
  39493. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39494. section->clear();
  39495. delete section;
  39496. }
  39497. }
  39498. bool perform()
  39499. {
  39500. owner.remove (startIndex, endIndex, 0, newCaretPos);
  39501. return true;
  39502. }
  39503. bool undo()
  39504. {
  39505. owner.reinsert (startIndex, removedSections);
  39506. owner.moveCursorTo (oldCaretPos, false);
  39507. return true;
  39508. }
  39509. int getSizeInUnits()
  39510. {
  39511. int n = 0;
  39512. for (int i = removedSections.size(); --i >= 0;)
  39513. {
  39514. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39515. n += section->getTotalLength();
  39516. }
  39517. return n + 16;
  39518. }
  39519. };
  39520. class TextHolderComponent : public Component,
  39521. public Timer
  39522. {
  39523. TextEditor* const owner;
  39524. TextHolderComponent (const TextHolderComponent&);
  39525. const TextHolderComponent& operator= (const TextHolderComponent&);
  39526. public:
  39527. TextHolderComponent (TextEditor* const owner_)
  39528. : owner (owner_)
  39529. {
  39530. setWantsKeyboardFocus (false);
  39531. setInterceptsMouseClicks (false, true);
  39532. }
  39533. ~TextHolderComponent()
  39534. {
  39535. }
  39536. void paint (Graphics& g)
  39537. {
  39538. owner->drawContent (g);
  39539. }
  39540. void timerCallback()
  39541. {
  39542. owner->timerCallbackInt();
  39543. }
  39544. const MouseCursor getMouseCursor()
  39545. {
  39546. return owner->getMouseCursor();
  39547. }
  39548. };
  39549. class TextEditorViewport : public Viewport
  39550. {
  39551. TextEditor* const owner;
  39552. float lastWordWrapWidth;
  39553. TextEditorViewport (const TextEditorViewport&);
  39554. const TextEditorViewport& operator= (const TextEditorViewport&);
  39555. public:
  39556. TextEditorViewport (TextEditor* const owner_)
  39557. : owner (owner_),
  39558. lastWordWrapWidth (0)
  39559. {
  39560. }
  39561. ~TextEditorViewport()
  39562. {
  39563. }
  39564. void visibleAreaChanged (int, int, int, int)
  39565. {
  39566. const float wordWrapWidth = owner->getWordWrapWidth();
  39567. if (wordWrapWidth != lastWordWrapWidth)
  39568. {
  39569. lastWordWrapWidth = wordWrapWidth;
  39570. owner->updateTextHolderSize();
  39571. }
  39572. }
  39573. };
  39574. const int flashSpeedIntervalMs = 380;
  39575. const int textChangeMessageId = 0x10003001;
  39576. const int returnKeyMessageId = 0x10003002;
  39577. const int escapeKeyMessageId = 0x10003003;
  39578. const int focusLossMessageId = 0x10003004;
  39579. TextEditor::TextEditor (const String& name,
  39580. const tchar passwordCharacter_)
  39581. : Component (name),
  39582. borderSize (1, 1, 1, 3),
  39583. readOnly (false),
  39584. multiline (false),
  39585. wordWrap (false),
  39586. returnKeyStartsNewLine (false),
  39587. caretVisible (true),
  39588. popupMenuEnabled (true),
  39589. selectAllTextWhenFocused (false),
  39590. scrollbarVisible (true),
  39591. wasFocused (false),
  39592. caretFlashState (true),
  39593. keepCursorOnScreen (true),
  39594. tabKeyUsed (false),
  39595. menuActive (false),
  39596. cursorX (0),
  39597. cursorY (0),
  39598. cursorHeight (0),
  39599. maxTextLength (0),
  39600. selectionStart (0),
  39601. selectionEnd (0),
  39602. leftIndent (4),
  39603. topIndent (4),
  39604. lastTransactionTime (0),
  39605. currentFont (14.0f),
  39606. totalNumChars (0),
  39607. caretPosition (0),
  39608. sections (8),
  39609. passwordCharacter (passwordCharacter_),
  39610. dragType (notDragging),
  39611. listeners (2)
  39612. {
  39613. setOpaque (true);
  39614. addAndMakeVisible (viewport = new TextEditorViewport (this));
  39615. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  39616. viewport->setWantsKeyboardFocus (false);
  39617. viewport->setScrollBarsShown (false, false);
  39618. setMouseCursor (MouseCursor::IBeamCursor);
  39619. setWantsKeyboardFocus (true);
  39620. }
  39621. TextEditor::~TextEditor()
  39622. {
  39623. clearInternal (0);
  39624. delete viewport;
  39625. }
  39626. void TextEditor::newTransaction() throw()
  39627. {
  39628. lastTransactionTime = Time::getApproximateMillisecondCounter();
  39629. undoManager.beginNewTransaction();
  39630. }
  39631. void TextEditor::doUndoRedo (const bool isRedo)
  39632. {
  39633. if (! isReadOnly())
  39634. {
  39635. if ((isRedo) ? undoManager.redo()
  39636. : undoManager.undo())
  39637. {
  39638. scrollToMakeSureCursorIsVisible();
  39639. repaint();
  39640. textChanged();
  39641. }
  39642. }
  39643. }
  39644. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  39645. const bool shouldWordWrap)
  39646. {
  39647. multiline = shouldBeMultiLine;
  39648. wordWrap = shouldWordWrap && shouldBeMultiLine;
  39649. setScrollbarsShown (scrollbarVisible);
  39650. viewport->setViewPosition (0, 0);
  39651. resized();
  39652. scrollToMakeSureCursorIsVisible();
  39653. }
  39654. bool TextEditor::isMultiLine() const throw()
  39655. {
  39656. return multiline;
  39657. }
  39658. void TextEditor::setScrollbarsShown (bool enabled) throw()
  39659. {
  39660. scrollbarVisible = enabled;
  39661. enabled = enabled && isMultiLine();
  39662. viewport->setScrollBarsShown (enabled, enabled);
  39663. }
  39664. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  39665. {
  39666. readOnly = shouldBeReadOnly;
  39667. enablementChanged();
  39668. }
  39669. bool TextEditor::isReadOnly() const throw()
  39670. {
  39671. return readOnly || ! isEnabled();
  39672. }
  39673. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  39674. {
  39675. returnKeyStartsNewLine = shouldStartNewLine;
  39676. }
  39677. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  39678. {
  39679. tabKeyUsed = shouldTabKeyBeUsed;
  39680. }
  39681. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  39682. {
  39683. popupMenuEnabled = b;
  39684. }
  39685. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  39686. {
  39687. selectAllTextWhenFocused = b;
  39688. }
  39689. const Font TextEditor::getFont() const throw()
  39690. {
  39691. return currentFont;
  39692. }
  39693. void TextEditor::setFont (const Font& newFont) throw()
  39694. {
  39695. currentFont = newFont;
  39696. scrollToMakeSureCursorIsVisible();
  39697. }
  39698. void TextEditor::applyFontToAllText (const Font& newFont)
  39699. {
  39700. currentFont = newFont;
  39701. const Colour overallColour (findColour (textColourId));
  39702. for (int i = sections.size(); --i >= 0;)
  39703. {
  39704. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  39705. uts->setFont (newFont, passwordCharacter);
  39706. uts->colour = overallColour;
  39707. }
  39708. coalesceSimilarSections();
  39709. updateTextHolderSize();
  39710. scrollToMakeSureCursorIsVisible();
  39711. repaint();
  39712. }
  39713. void TextEditor::colourChanged()
  39714. {
  39715. setOpaque (findColour (backgroundColourId).isOpaque());
  39716. repaint();
  39717. }
  39718. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  39719. {
  39720. caretVisible = shouldCaretBeVisible;
  39721. if (shouldCaretBeVisible)
  39722. textHolder->startTimer (flashSpeedIntervalMs);
  39723. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  39724. : MouseCursor::NormalCursor);
  39725. }
  39726. void TextEditor::setInputRestrictions (const int maxLen,
  39727. const String& chars) throw()
  39728. {
  39729. maxTextLength = jmax (0, maxLen);
  39730. allowedCharacters = chars;
  39731. }
  39732. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  39733. {
  39734. textToShowWhenEmpty = text;
  39735. colourForTextWhenEmpty = colourToUse;
  39736. }
  39737. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  39738. {
  39739. if (passwordCharacter != newPasswordCharacter)
  39740. {
  39741. passwordCharacter = newPasswordCharacter;
  39742. resized();
  39743. repaint();
  39744. }
  39745. }
  39746. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  39747. {
  39748. viewport->setScrollBarThickness (newThicknessPixels);
  39749. }
  39750. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  39751. {
  39752. viewport->setScrollBarButtonVisibility (buttonsVisible);
  39753. }
  39754. void TextEditor::clear()
  39755. {
  39756. clearInternal (0);
  39757. updateTextHolderSize();
  39758. undoManager.clearUndoHistory();
  39759. }
  39760. void TextEditor::setText (const String& newText,
  39761. const bool sendTextChangeMessage)
  39762. {
  39763. const int newLength = newText.length();
  39764. if (newLength != getTotalNumChars() || getText() != newText)
  39765. {
  39766. const int oldCursorPos = caretPosition;
  39767. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  39768. clearInternal (0);
  39769. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  39770. // if you're adding text with line-feeds to a single-line text editor, it
  39771. // ain't gonna look right!
  39772. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  39773. if (cursorWasAtEnd && ! isMultiLine())
  39774. moveCursorTo (getTotalNumChars(), false);
  39775. else
  39776. moveCursorTo (oldCursorPos, false);
  39777. if (sendTextChangeMessage)
  39778. textChanged();
  39779. repaint();
  39780. }
  39781. updateTextHolderSize();
  39782. scrollToMakeSureCursorIsVisible();
  39783. undoManager.clearUndoHistory();
  39784. }
  39785. void TextEditor::textChanged() throw()
  39786. {
  39787. updateTextHolderSize();
  39788. postCommandMessage (textChangeMessageId);
  39789. }
  39790. void TextEditor::returnPressed()
  39791. {
  39792. postCommandMessage (returnKeyMessageId);
  39793. }
  39794. void TextEditor::escapePressed()
  39795. {
  39796. postCommandMessage (escapeKeyMessageId);
  39797. }
  39798. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  39799. {
  39800. jassert (newListener != 0)
  39801. if (newListener != 0)
  39802. listeners.add (newListener);
  39803. }
  39804. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  39805. {
  39806. listeners.removeValue (listenerToRemove);
  39807. }
  39808. void TextEditor::timerCallbackInt()
  39809. {
  39810. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  39811. if (caretFlashState != newState)
  39812. {
  39813. caretFlashState = newState;
  39814. if (caretFlashState)
  39815. wasFocused = true;
  39816. if (caretVisible
  39817. && hasKeyboardFocus (false)
  39818. && ! isReadOnly())
  39819. {
  39820. repaintCaret();
  39821. }
  39822. }
  39823. const unsigned int now = Time::getApproximateMillisecondCounter();
  39824. if (now > lastTransactionTime + 200)
  39825. newTransaction();
  39826. }
  39827. void TextEditor::repaintCaret()
  39828. {
  39829. if (! findColour (caretColourId).isTransparent())
  39830. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  39831. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  39832. 4,
  39833. roundFloatToInt (cursorHeight) + 2);
  39834. }
  39835. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  39836. {
  39837. if (textStartIndex > textEndIndex && textEndIndex > 0)
  39838. swapVariables (textStartIndex, textEndIndex);
  39839. float x = 0, y = 0, lh = currentFont.getHeight();
  39840. const float wordWrapWidth = getWordWrapWidth();
  39841. if (wordWrapWidth > 0)
  39842. {
  39843. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39844. i.getCharPosition (textStartIndex, x, y, lh);
  39845. const int y1 = (int) y;
  39846. int y2;
  39847. if (textEndIndex >= 0)
  39848. {
  39849. i.getCharPosition (textEndIndex, x, y, lh);
  39850. y2 = (int) (y + lh * 2.0f);
  39851. }
  39852. else
  39853. {
  39854. y2 = textHolder->getHeight();
  39855. }
  39856. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  39857. }
  39858. }
  39859. void TextEditor::moveCaret (int newCaretPos) throw()
  39860. {
  39861. if (newCaretPos < 0)
  39862. newCaretPos = 0;
  39863. else if (newCaretPos > getTotalNumChars())
  39864. newCaretPos = getTotalNumChars();
  39865. if (newCaretPos != getCaretPosition())
  39866. {
  39867. repaintCaret();
  39868. caretFlashState = true;
  39869. caretPosition = newCaretPos;
  39870. textHolder->startTimer (flashSpeedIntervalMs);
  39871. scrollToMakeSureCursorIsVisible();
  39872. repaintCaret();
  39873. }
  39874. }
  39875. void TextEditor::setCaretPosition (const int newIndex) throw()
  39876. {
  39877. moveCursorTo (newIndex, false);
  39878. }
  39879. int TextEditor::getCaretPosition() const throw()
  39880. {
  39881. return caretPosition;
  39882. }
  39883. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  39884. const int desiredCaretY) throw()
  39885. {
  39886. updateCaretPosition();
  39887. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  39888. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  39889. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  39890. {
  39891. vx += desiredCaretX - proportionOfWidth (0.2f);
  39892. }
  39893. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39894. {
  39895. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39896. }
  39897. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  39898. if (! isMultiLine())
  39899. {
  39900. vy = viewport->getViewPositionY();
  39901. }
  39902. else
  39903. {
  39904. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  39905. const int curH = roundFloatToInt (cursorHeight);
  39906. if (desiredCaretY < 0)
  39907. {
  39908. vy = jmax (0, desiredCaretY + vy);
  39909. }
  39910. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39911. {
  39912. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39913. }
  39914. }
  39915. viewport->setViewPosition (vx, vy);
  39916. }
  39917. const Rectangle TextEditor::getCaretRectangle() throw()
  39918. {
  39919. updateCaretPosition();
  39920. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  39921. roundFloatToInt (cursorY) - viewport->getY(),
  39922. 1, roundFloatToInt (cursorHeight));
  39923. }
  39924. float TextEditor::getWordWrapWidth() const throw()
  39925. {
  39926. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  39927. : 1.0e10f;
  39928. }
  39929. void TextEditor::updateTextHolderSize() throw()
  39930. {
  39931. const float wordWrapWidth = getWordWrapWidth();
  39932. if (wordWrapWidth > 0)
  39933. {
  39934. float maxWidth = 0.0f;
  39935. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39936. while (i.next())
  39937. maxWidth = jmax (maxWidth, i.atomRight);
  39938. const int w = leftIndent + roundFloatToInt (maxWidth);
  39939. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  39940. currentFont.getHeight()));
  39941. textHolder->setSize (w + 1, h + 1);
  39942. }
  39943. }
  39944. int TextEditor::getTextWidth() const throw()
  39945. {
  39946. return textHolder->getWidth();
  39947. }
  39948. int TextEditor::getTextHeight() const throw()
  39949. {
  39950. return textHolder->getHeight();
  39951. }
  39952. void TextEditor::setIndents (const int newLeftIndent,
  39953. const int newTopIndent) throw()
  39954. {
  39955. leftIndent = newLeftIndent;
  39956. topIndent = newTopIndent;
  39957. }
  39958. void TextEditor::setBorder (const BorderSize& border) throw()
  39959. {
  39960. borderSize = border;
  39961. resized();
  39962. }
  39963. const BorderSize TextEditor::getBorder() const throw()
  39964. {
  39965. return borderSize;
  39966. }
  39967. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  39968. {
  39969. keepCursorOnScreen = shouldScrollToShowCursor;
  39970. }
  39971. void TextEditor::updateCaretPosition() throw()
  39972. {
  39973. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  39974. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  39975. }
  39976. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  39977. {
  39978. updateCaretPosition();
  39979. if (keepCursorOnScreen)
  39980. {
  39981. int x = viewport->getViewPositionX();
  39982. int y = viewport->getViewPositionY();
  39983. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  39984. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  39985. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  39986. {
  39987. x += relativeCursorX - proportionOfWidth (0.2f);
  39988. }
  39989. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39990. {
  39991. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39992. }
  39993. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  39994. if (! isMultiLine())
  39995. {
  39996. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  39997. }
  39998. else
  39999. {
  40000. const int curH = roundFloatToInt (cursorHeight);
  40001. if (relativeCursorY < 0)
  40002. {
  40003. y = jmax (0, relativeCursorY + y);
  40004. }
  40005. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  40006. {
  40007. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  40008. }
  40009. }
  40010. viewport->setViewPosition (x, y);
  40011. }
  40012. }
  40013. void TextEditor::moveCursorTo (const int newPosition,
  40014. const bool isSelecting) throw()
  40015. {
  40016. if (isSelecting)
  40017. {
  40018. moveCaret (newPosition);
  40019. const int oldSelStart = selectionStart;
  40020. const int oldSelEnd = selectionEnd;
  40021. if (dragType == notDragging)
  40022. {
  40023. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  40024. dragType = draggingSelectionStart;
  40025. else
  40026. dragType = draggingSelectionEnd;
  40027. }
  40028. if (dragType == draggingSelectionStart)
  40029. {
  40030. selectionStart = getCaretPosition();
  40031. if (selectionEnd < selectionStart)
  40032. {
  40033. swapVariables (selectionStart, selectionEnd);
  40034. dragType = draggingSelectionEnd;
  40035. }
  40036. }
  40037. else
  40038. {
  40039. selectionEnd = getCaretPosition();
  40040. if (selectionEnd < selectionStart)
  40041. {
  40042. swapVariables (selectionStart, selectionEnd);
  40043. dragType = draggingSelectionStart;
  40044. }
  40045. }
  40046. jassert (selectionStart <= selectionEnd);
  40047. jassert (oldSelStart <= oldSelEnd);
  40048. repaintText (jmin (oldSelStart, selectionStart),
  40049. jmax (oldSelEnd, selectionEnd));
  40050. }
  40051. else
  40052. {
  40053. dragType = notDragging;
  40054. if (selectionEnd > selectionStart)
  40055. repaintText (selectionStart, selectionEnd);
  40056. moveCaret (newPosition);
  40057. selectionStart = getCaretPosition();
  40058. selectionEnd = getCaretPosition();
  40059. }
  40060. }
  40061. int TextEditor::getTextIndexAt (const int x,
  40062. const int y) throw()
  40063. {
  40064. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  40065. (float) (y + viewport->getViewPositionY() - topIndent));
  40066. }
  40067. void TextEditor::insertTextAtCursor (String newText)
  40068. {
  40069. if (allowedCharacters.isNotEmpty())
  40070. newText = newText.retainCharacters (allowedCharacters);
  40071. if (! isMultiLine())
  40072. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  40073. else
  40074. newText = newText.replace (T("\r\n"), T("\n"));
  40075. const int newCaretPos = selectionStart + newText.length();
  40076. const int insertIndex = selectionStart;
  40077. remove (selectionStart, selectionEnd,
  40078. &undoManager,
  40079. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  40080. if (maxTextLength > 0)
  40081. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  40082. if (newText.isNotEmpty())
  40083. insert (newText,
  40084. insertIndex,
  40085. currentFont,
  40086. findColour (textColourId),
  40087. &undoManager,
  40088. newCaretPos);
  40089. textChanged();
  40090. }
  40091. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  40092. {
  40093. moveCursorTo (startPos, false);
  40094. moveCursorTo (startPos + numChars, true);
  40095. }
  40096. void TextEditor::copy()
  40097. {
  40098. if (passwordCharacter == 0)
  40099. {
  40100. const String selection (getTextSubstring (selectionStart, selectionEnd));
  40101. if (selection.isNotEmpty())
  40102. SystemClipboard::copyTextToClipboard (selection);
  40103. }
  40104. }
  40105. void TextEditor::paste()
  40106. {
  40107. if (! isReadOnly())
  40108. {
  40109. const String clip (SystemClipboard::getTextFromClipboard());
  40110. if (clip.isNotEmpty())
  40111. insertTextAtCursor (clip);
  40112. }
  40113. }
  40114. void TextEditor::cut()
  40115. {
  40116. if (! isReadOnly())
  40117. {
  40118. moveCaret (selectionEnd);
  40119. insertTextAtCursor (String::empty);
  40120. }
  40121. }
  40122. void TextEditor::drawContent (Graphics& g)
  40123. {
  40124. const float wordWrapWidth = getWordWrapWidth();
  40125. if (wordWrapWidth > 0)
  40126. {
  40127. g.setOrigin (leftIndent, topIndent);
  40128. const Rectangle clip (g.getClipBounds());
  40129. Colour selectedTextColour;
  40130. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40131. while (i.lineY + 200.0 < clip.getY() && i.next())
  40132. {}
  40133. if (selectionStart < selectionEnd)
  40134. {
  40135. g.setColour (findColour (highlightColourId)
  40136. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  40137. selectedTextColour = findColour (highlightedTextColourId);
  40138. TextEditorIterator i2 (i);
  40139. while (i2.next() && i2.lineY < clip.getBottom())
  40140. {
  40141. i2.updateLineHeight();
  40142. if (i2.lineY + i2.lineHeight >= clip.getY()
  40143. && selectionEnd >= i2.indexInText
  40144. && selectionStart <= i2.indexInText + i2.atom->numChars)
  40145. {
  40146. i2.drawSelection (g, selectionStart, selectionEnd);
  40147. }
  40148. }
  40149. }
  40150. const UniformTextSection* lastSection = 0;
  40151. while (i.next() && i.lineY < clip.getBottom())
  40152. {
  40153. i.updateLineHeight();
  40154. if (i.lineY + i.lineHeight >= clip.getY())
  40155. {
  40156. if (selectionEnd >= i.indexInText
  40157. && selectionStart <= i.indexInText + i.atom->numChars)
  40158. {
  40159. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  40160. lastSection = 0;
  40161. }
  40162. else
  40163. {
  40164. i.draw (g, lastSection);
  40165. }
  40166. }
  40167. }
  40168. }
  40169. }
  40170. void TextEditor::paint (Graphics& g)
  40171. {
  40172. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  40173. }
  40174. void TextEditor::paintOverChildren (Graphics& g)
  40175. {
  40176. if (caretFlashState
  40177. && hasKeyboardFocus (false)
  40178. && caretVisible
  40179. && ! isReadOnly())
  40180. {
  40181. g.setColour (findColour (caretColourId));
  40182. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  40183. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  40184. 2.0f, cursorHeight);
  40185. }
  40186. if (textToShowWhenEmpty.isNotEmpty()
  40187. && (! hasKeyboardFocus (false))
  40188. && getTotalNumChars() == 0)
  40189. {
  40190. g.setColour (colourForTextWhenEmpty);
  40191. g.setFont (getFont());
  40192. if (isMultiLine())
  40193. {
  40194. g.drawText (textToShowWhenEmpty,
  40195. 0, 0, getWidth(), getHeight(),
  40196. Justification::centred, true);
  40197. }
  40198. else
  40199. {
  40200. g.drawText (textToShowWhenEmpty,
  40201. leftIndent, topIndent,
  40202. viewport->getWidth() - leftIndent,
  40203. viewport->getHeight() - topIndent,
  40204. Justification::centredLeft, true);
  40205. }
  40206. }
  40207. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  40208. }
  40209. void TextEditor::mouseDown (const MouseEvent& e)
  40210. {
  40211. beginDragAutoRepeat (100);
  40212. newTransaction();
  40213. if (wasFocused || ! selectAllTextWhenFocused)
  40214. {
  40215. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40216. {
  40217. moveCursorTo (getTextIndexAt (e.x, e.y),
  40218. e.mods.isShiftDown());
  40219. }
  40220. else
  40221. {
  40222. PopupMenu m;
  40223. addPopupMenuItems (m, &e);
  40224. menuActive = true;
  40225. const int result = m.show();
  40226. menuActive = false;
  40227. if (result != 0)
  40228. performPopupMenuAction (result);
  40229. }
  40230. }
  40231. }
  40232. void TextEditor::mouseDrag (const MouseEvent& e)
  40233. {
  40234. if (wasFocused || ! selectAllTextWhenFocused)
  40235. {
  40236. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40237. {
  40238. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  40239. }
  40240. }
  40241. }
  40242. void TextEditor::mouseUp (const MouseEvent& e)
  40243. {
  40244. newTransaction();
  40245. textHolder->startTimer (flashSpeedIntervalMs);
  40246. if (wasFocused || ! selectAllTextWhenFocused)
  40247. {
  40248. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40249. {
  40250. moveCaret (getTextIndexAt (e.x, e.y));
  40251. }
  40252. }
  40253. wasFocused = true;
  40254. }
  40255. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  40256. {
  40257. int tokenEnd = getTextIndexAt (e.x, e.y);
  40258. int tokenStart = tokenEnd;
  40259. if (e.getNumberOfClicks() > 3)
  40260. {
  40261. tokenStart = 0;
  40262. tokenEnd = getTotalNumChars();
  40263. }
  40264. else
  40265. {
  40266. const String t (getText());
  40267. const int totalLength = getTotalNumChars();
  40268. while (tokenEnd < totalLength)
  40269. {
  40270. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  40271. ++tokenEnd;
  40272. else
  40273. break;
  40274. }
  40275. tokenStart = tokenEnd;
  40276. while (tokenStart > 0)
  40277. {
  40278. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  40279. --tokenStart;
  40280. else
  40281. break;
  40282. }
  40283. if (e.getNumberOfClicks() > 2)
  40284. {
  40285. while (tokenEnd < totalLength)
  40286. {
  40287. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  40288. ++tokenEnd;
  40289. else
  40290. break;
  40291. }
  40292. while (tokenStart > 0)
  40293. {
  40294. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  40295. --tokenStart;
  40296. else
  40297. break;
  40298. }
  40299. }
  40300. }
  40301. moveCursorTo (tokenEnd, false);
  40302. moveCursorTo (tokenStart, true);
  40303. }
  40304. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40305. {
  40306. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  40307. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40308. }
  40309. bool TextEditor::keyPressed (const KeyPress& key)
  40310. {
  40311. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  40312. return false;
  40313. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  40314. if (key.isKeyCode (KeyPress::leftKey)
  40315. || key.isKeyCode (KeyPress::upKey))
  40316. {
  40317. newTransaction();
  40318. int newPos;
  40319. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  40320. newPos = indexAtPosition (cursorX, cursorY - 1);
  40321. else if (moveInWholeWordSteps)
  40322. newPos = findWordBreakBefore (getCaretPosition());
  40323. else
  40324. newPos = getCaretPosition() - 1;
  40325. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40326. }
  40327. else if (key.isKeyCode (KeyPress::rightKey)
  40328. || key.isKeyCode (KeyPress::downKey))
  40329. {
  40330. newTransaction();
  40331. int newPos;
  40332. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  40333. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  40334. else if (moveInWholeWordSteps)
  40335. newPos = findWordBreakAfter (getCaretPosition());
  40336. else
  40337. newPos = getCaretPosition() + 1;
  40338. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40339. }
  40340. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  40341. {
  40342. newTransaction();
  40343. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  40344. key.getModifiers().isShiftDown());
  40345. }
  40346. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  40347. {
  40348. newTransaction();
  40349. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  40350. key.getModifiers().isShiftDown());
  40351. }
  40352. else if (key.isKeyCode (KeyPress::homeKey))
  40353. {
  40354. newTransaction();
  40355. if (isMultiLine() && ! moveInWholeWordSteps)
  40356. moveCursorTo (indexAtPosition (0.0f, cursorY),
  40357. key.getModifiers().isShiftDown());
  40358. else
  40359. moveCursorTo (0, key.getModifiers().isShiftDown());
  40360. }
  40361. else if (key.isKeyCode (KeyPress::endKey))
  40362. {
  40363. newTransaction();
  40364. if (isMultiLine() && ! moveInWholeWordSteps)
  40365. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  40366. key.getModifiers().isShiftDown());
  40367. else
  40368. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  40369. }
  40370. else if (key.isKeyCode (KeyPress::backspaceKey))
  40371. {
  40372. if (moveInWholeWordSteps)
  40373. {
  40374. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  40375. }
  40376. else
  40377. {
  40378. if (selectionStart == selectionEnd && selectionStart > 0)
  40379. --selectionStart;
  40380. }
  40381. cut();
  40382. }
  40383. else if (key.isKeyCode (KeyPress::deleteKey))
  40384. {
  40385. if (key.getModifiers().isShiftDown())
  40386. copy();
  40387. if (selectionStart == selectionEnd
  40388. && selectionEnd < getTotalNumChars())
  40389. {
  40390. ++selectionEnd;
  40391. }
  40392. cut();
  40393. }
  40394. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  40395. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  40396. {
  40397. newTransaction();
  40398. copy();
  40399. }
  40400. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  40401. {
  40402. newTransaction();
  40403. copy();
  40404. cut();
  40405. }
  40406. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  40407. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  40408. {
  40409. newTransaction();
  40410. paste();
  40411. }
  40412. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  40413. {
  40414. newTransaction();
  40415. doUndoRedo (false);
  40416. }
  40417. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  40418. {
  40419. newTransaction();
  40420. doUndoRedo (true);
  40421. }
  40422. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  40423. {
  40424. newTransaction();
  40425. moveCursorTo (getTotalNumChars(), false);
  40426. moveCursorTo (0, true);
  40427. }
  40428. else if (key == KeyPress::returnKey)
  40429. {
  40430. newTransaction();
  40431. if (returnKeyStartsNewLine)
  40432. insertTextAtCursor (T("\n"));
  40433. else
  40434. returnPressed();
  40435. }
  40436. else if (key.isKeyCode (KeyPress::escapeKey))
  40437. {
  40438. newTransaction();
  40439. moveCursorTo (getCaretPosition(), false);
  40440. escapePressed();
  40441. }
  40442. else if (key.getTextCharacter() >= ' '
  40443. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  40444. {
  40445. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  40446. lastTransactionTime = Time::getApproximateMillisecondCounter();
  40447. }
  40448. else
  40449. {
  40450. return false;
  40451. }
  40452. return true;
  40453. }
  40454. bool TextEditor::keyStateChanged (const bool isKeyDown)
  40455. {
  40456. if (! isKeyDown)
  40457. return false;
  40458. #if JUCE_WIN32
  40459. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  40460. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  40461. #endif
  40462. // (overridden to avoid forwarding key events to the parent)
  40463. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  40464. }
  40465. const int baseMenuItemID = 0x7fff0000;
  40466. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  40467. {
  40468. const bool writable = ! isReadOnly();
  40469. if (passwordCharacter == 0)
  40470. {
  40471. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  40472. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  40473. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  40474. }
  40475. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  40476. m.addSeparator();
  40477. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  40478. m.addSeparator();
  40479. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  40480. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  40481. }
  40482. void TextEditor::performPopupMenuAction (const int menuItemID)
  40483. {
  40484. switch (menuItemID)
  40485. {
  40486. case baseMenuItemID + 1:
  40487. copy();
  40488. cut();
  40489. break;
  40490. case baseMenuItemID + 2:
  40491. copy();
  40492. break;
  40493. case baseMenuItemID + 3:
  40494. paste();
  40495. break;
  40496. case baseMenuItemID + 4:
  40497. cut();
  40498. break;
  40499. case baseMenuItemID + 5:
  40500. moveCursorTo (getTotalNumChars(), false);
  40501. moveCursorTo (0, true);
  40502. break;
  40503. case baseMenuItemID + 6:
  40504. doUndoRedo (false);
  40505. break;
  40506. case baseMenuItemID + 7:
  40507. doUndoRedo (true);
  40508. break;
  40509. default:
  40510. break;
  40511. }
  40512. }
  40513. void TextEditor::focusGained (FocusChangeType)
  40514. {
  40515. newTransaction();
  40516. caretFlashState = true;
  40517. if (selectAllTextWhenFocused)
  40518. {
  40519. moveCursorTo (0, false);
  40520. moveCursorTo (getTotalNumChars(), true);
  40521. }
  40522. repaint();
  40523. if (caretVisible)
  40524. textHolder->startTimer (flashSpeedIntervalMs);
  40525. ComponentPeer* const peer = getPeer();
  40526. if (peer != 0 && ! isReadOnly())
  40527. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  40528. getScreenY() - peer->getScreenY());
  40529. }
  40530. void TextEditor::focusLost (FocusChangeType)
  40531. {
  40532. newTransaction();
  40533. wasFocused = false;
  40534. textHolder->stopTimer();
  40535. caretFlashState = false;
  40536. postCommandMessage (focusLossMessageId);
  40537. repaint();
  40538. }
  40539. void TextEditor::resized()
  40540. {
  40541. viewport->setBoundsInset (borderSize);
  40542. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  40543. updateTextHolderSize();
  40544. if (! isMultiLine())
  40545. {
  40546. scrollToMakeSureCursorIsVisible();
  40547. }
  40548. else
  40549. {
  40550. updateCaretPosition();
  40551. }
  40552. }
  40553. void TextEditor::handleCommandMessage (const int commandId)
  40554. {
  40555. const ComponentDeletionWatcher deletionChecker (this);
  40556. for (int i = listeners.size(); --i >= 0;)
  40557. {
  40558. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  40559. if (tl != 0)
  40560. {
  40561. switch (commandId)
  40562. {
  40563. case textChangeMessageId:
  40564. tl->textEditorTextChanged (*this);
  40565. break;
  40566. case returnKeyMessageId:
  40567. tl->textEditorReturnKeyPressed (*this);
  40568. break;
  40569. case escapeKeyMessageId:
  40570. tl->textEditorEscapeKeyPressed (*this);
  40571. break;
  40572. case focusLossMessageId:
  40573. tl->textEditorFocusLost (*this);
  40574. break;
  40575. default:
  40576. jassertfalse
  40577. break;
  40578. }
  40579. if (i > 0 && deletionChecker.hasBeenDeleted())
  40580. return;
  40581. }
  40582. }
  40583. }
  40584. void TextEditor::enablementChanged()
  40585. {
  40586. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  40587. : MouseCursor::IBeamCursor));
  40588. repaint();
  40589. }
  40590. void TextEditor::clearInternal (UndoManager* const um) throw()
  40591. {
  40592. remove (0, getTotalNumChars(), um, caretPosition);
  40593. }
  40594. void TextEditor::insert (const String& text,
  40595. const int insertIndex,
  40596. const Font& font,
  40597. const Colour& colour,
  40598. UndoManager* const um,
  40599. const int caretPositionToMoveTo) throw()
  40600. {
  40601. if (text.isNotEmpty())
  40602. {
  40603. if (um != 0)
  40604. {
  40605. um->perform (new TextEditorInsertAction (*this,
  40606. text,
  40607. insertIndex,
  40608. font,
  40609. colour,
  40610. caretPosition,
  40611. caretPositionToMoveTo));
  40612. }
  40613. else
  40614. {
  40615. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  40616. // a line gets moved due to word wrap
  40617. int index = 0;
  40618. int nextIndex = 0;
  40619. for (int i = 0; i < sections.size(); ++i)
  40620. {
  40621. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40622. if (insertIndex == index)
  40623. {
  40624. sections.insert (i, new UniformTextSection (text,
  40625. font, colour,
  40626. passwordCharacter));
  40627. break;
  40628. }
  40629. else if (insertIndex > index && insertIndex < nextIndex)
  40630. {
  40631. splitSection (i, insertIndex - index);
  40632. sections.insert (i + 1, new UniformTextSection (text,
  40633. font, colour,
  40634. passwordCharacter));
  40635. break;
  40636. }
  40637. index = nextIndex;
  40638. }
  40639. if (nextIndex == insertIndex)
  40640. sections.add (new UniformTextSection (text,
  40641. font, colour,
  40642. passwordCharacter));
  40643. coalesceSimilarSections();
  40644. totalNumChars = -1;
  40645. moveCursorTo (caretPositionToMoveTo, false);
  40646. repaintText (insertIndex, -1);
  40647. }
  40648. }
  40649. }
  40650. void TextEditor::reinsert (const int insertIndex,
  40651. const VoidArray& sectionsToInsert) throw()
  40652. {
  40653. int index = 0;
  40654. int nextIndex = 0;
  40655. for (int i = 0; i < sections.size(); ++i)
  40656. {
  40657. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40658. if (insertIndex == index)
  40659. {
  40660. for (int j = sectionsToInsert.size(); --j >= 0;)
  40661. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40662. break;
  40663. }
  40664. else if (insertIndex > index && insertIndex < nextIndex)
  40665. {
  40666. splitSection (i, insertIndex - index);
  40667. for (int j = sectionsToInsert.size(); --j >= 0;)
  40668. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40669. break;
  40670. }
  40671. index = nextIndex;
  40672. }
  40673. if (nextIndex == insertIndex)
  40674. {
  40675. for (int j = 0; j < sectionsToInsert.size(); ++j)
  40676. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40677. }
  40678. coalesceSimilarSections();
  40679. totalNumChars = -1;
  40680. }
  40681. void TextEditor::remove (const int startIndex,
  40682. int endIndex,
  40683. UndoManager* const um,
  40684. const int caretPositionToMoveTo) throw()
  40685. {
  40686. if (endIndex > startIndex)
  40687. {
  40688. int index = 0;
  40689. for (int i = 0; i < sections.size(); ++i)
  40690. {
  40691. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  40692. if (startIndex > index && startIndex < nextIndex)
  40693. {
  40694. splitSection (i, startIndex - index);
  40695. --i;
  40696. }
  40697. else if (endIndex > index && endIndex < nextIndex)
  40698. {
  40699. splitSection (i, endIndex - index);
  40700. --i;
  40701. }
  40702. else
  40703. {
  40704. index = nextIndex;
  40705. if (index > endIndex)
  40706. break;
  40707. }
  40708. }
  40709. index = 0;
  40710. if (um != 0)
  40711. {
  40712. VoidArray removedSections;
  40713. for (int i = 0; i < sections.size(); ++i)
  40714. {
  40715. if (endIndex <= startIndex)
  40716. break;
  40717. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40718. const int nextIndex = index + section->getTotalLength();
  40719. if (startIndex <= index && endIndex >= nextIndex)
  40720. removedSections.add (new UniformTextSection (*section));
  40721. index = nextIndex;
  40722. }
  40723. um->perform (new TextEditorRemoveAction (*this,
  40724. startIndex,
  40725. endIndex,
  40726. caretPosition,
  40727. caretPositionToMoveTo,
  40728. removedSections));
  40729. }
  40730. else
  40731. {
  40732. for (int i = 0; i < sections.size(); ++i)
  40733. {
  40734. if (endIndex <= startIndex)
  40735. break;
  40736. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40737. const int nextIndex = index + section->getTotalLength();
  40738. if (startIndex <= index && endIndex >= nextIndex)
  40739. {
  40740. sections.remove(i);
  40741. endIndex -= (nextIndex - index);
  40742. section->clear();
  40743. delete section;
  40744. --i;
  40745. }
  40746. else
  40747. {
  40748. index = nextIndex;
  40749. }
  40750. }
  40751. coalesceSimilarSections();
  40752. totalNumChars = -1;
  40753. moveCursorTo (caretPositionToMoveTo, false);
  40754. repaintText (startIndex, -1);
  40755. }
  40756. }
  40757. }
  40758. const String TextEditor::getText() const throw()
  40759. {
  40760. String t;
  40761. for (int i = 0; i < sections.size(); ++i)
  40762. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  40763. return t;
  40764. }
  40765. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  40766. {
  40767. String t;
  40768. int index = 0;
  40769. for (int i = 0; i < sections.size(); ++i)
  40770. {
  40771. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  40772. const int nextIndex = index + s->getTotalLength();
  40773. if (startCharacter < nextIndex)
  40774. {
  40775. if (endCharacter <= index)
  40776. break;
  40777. const int start = jmax (index, startCharacter);
  40778. t += s->getTextSubstring (start - index, endCharacter - index);
  40779. }
  40780. index = nextIndex;
  40781. }
  40782. return t;
  40783. }
  40784. const String TextEditor::getHighlightedText() const throw()
  40785. {
  40786. return getTextSubstring (getHighlightedRegionStart(),
  40787. getHighlightedRegionStart() + getHighlightedRegionLength());
  40788. }
  40789. int TextEditor::getTotalNumChars() throw()
  40790. {
  40791. if (totalNumChars < 0)
  40792. {
  40793. totalNumChars = 0;
  40794. for (int i = sections.size(); --i >= 0;)
  40795. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40796. }
  40797. return totalNumChars;
  40798. }
  40799. bool TextEditor::isEmpty() const throw()
  40800. {
  40801. if (totalNumChars != 0)
  40802. {
  40803. for (int i = sections.size(); --i >= 0;)
  40804. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  40805. return false;
  40806. }
  40807. return true;
  40808. }
  40809. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  40810. {
  40811. const float wordWrapWidth = getWordWrapWidth();
  40812. if (wordWrapWidth > 0 && sections.size() > 0)
  40813. {
  40814. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40815. i.getCharPosition (index, cx, cy, lineHeight);
  40816. }
  40817. else
  40818. {
  40819. cx = cy = 0;
  40820. lineHeight = currentFont.getHeight();
  40821. }
  40822. }
  40823. int TextEditor::indexAtPosition (const float x, const float y) throw()
  40824. {
  40825. const float wordWrapWidth = getWordWrapWidth();
  40826. if (wordWrapWidth > 0)
  40827. {
  40828. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40829. while (i.next())
  40830. {
  40831. if (i.lineY + getHeight() > y)
  40832. i.updateLineHeight();
  40833. if (i.lineY + i.lineHeight > y)
  40834. {
  40835. if (i.lineY > y)
  40836. return jmax (0, i.indexInText - 1);
  40837. if (i.atomX >= x)
  40838. return i.indexInText;
  40839. if (x < i.atomRight)
  40840. return i.xToIndex (x);
  40841. }
  40842. }
  40843. }
  40844. return getTotalNumChars();
  40845. }
  40846. static int getCharacterCategory (const tchar character) throw()
  40847. {
  40848. return CharacterFunctions::isLetterOrDigit (character)
  40849. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  40850. }
  40851. int TextEditor::findWordBreakAfter (const int position) const throw()
  40852. {
  40853. const String t (getTextSubstring (position, position + 512));
  40854. const int totalLength = t.length();
  40855. int i = 0;
  40856. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40857. ++i;
  40858. const int type = getCharacterCategory (t[i]);
  40859. while (i < totalLength && type == getCharacterCategory (t[i]))
  40860. ++i;
  40861. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40862. ++i;
  40863. return position + i;
  40864. }
  40865. int TextEditor::findWordBreakBefore (const int position) const throw()
  40866. {
  40867. if (position <= 0)
  40868. return 0;
  40869. const int startOfBuffer = jmax (0, position - 512);
  40870. const String t (getTextSubstring (startOfBuffer, position));
  40871. int i = position - startOfBuffer;
  40872. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  40873. --i;
  40874. if (i > 0)
  40875. {
  40876. const int type = getCharacterCategory (t [i - 1]);
  40877. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  40878. --i;
  40879. }
  40880. jassert (startOfBuffer + i >= 0);
  40881. return startOfBuffer + i;
  40882. }
  40883. void TextEditor::splitSection (const int sectionIndex,
  40884. const int charToSplitAt) throw()
  40885. {
  40886. jassert (sections[sectionIndex] != 0);
  40887. sections.insert (sectionIndex + 1,
  40888. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  40889. ->split (charToSplitAt, passwordCharacter));
  40890. }
  40891. void TextEditor::coalesceSimilarSections() throw()
  40892. {
  40893. for (int i = 0; i < sections.size() - 1; ++i)
  40894. {
  40895. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  40896. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  40897. if (s1->font == s2->font
  40898. && s1->colour == s2->colour)
  40899. {
  40900. s1->append (*s2, passwordCharacter);
  40901. sections.remove (i + 1);
  40902. delete s2;
  40903. --i;
  40904. }
  40905. }
  40906. }
  40907. END_JUCE_NAMESPACE
  40908. /********* End of inlined file: juce_TextEditor.cpp *********/
  40909. /********* Start of inlined file: juce_Toolbar.cpp *********/
  40910. BEGIN_JUCE_NAMESPACE
  40911. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  40912. class ToolbarSpacerComp : public ToolbarItemComponent
  40913. {
  40914. public:
  40915. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  40916. : ToolbarItemComponent (itemId, String::empty, false),
  40917. fixedSize (fixedSize_),
  40918. drawBar (drawBar_)
  40919. {
  40920. }
  40921. ~ToolbarSpacerComp()
  40922. {
  40923. }
  40924. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  40925. int& preferredSize, int& minSize, int& maxSize)
  40926. {
  40927. if (fixedSize <= 0)
  40928. {
  40929. preferredSize = toolbarThickness * 2;
  40930. minSize = 4;
  40931. maxSize = 32768;
  40932. }
  40933. else
  40934. {
  40935. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  40936. minSize = drawBar ? maxSize : jmin (4, maxSize);
  40937. preferredSize = maxSize;
  40938. if (getEditingMode() == editableOnPalette)
  40939. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  40940. }
  40941. return true;
  40942. }
  40943. void paintButtonArea (Graphics&, int, int, bool, bool)
  40944. {
  40945. }
  40946. void contentAreaChanged (const Rectangle&)
  40947. {
  40948. }
  40949. int getResizeOrder() const throw()
  40950. {
  40951. return fixedSize <= 0 ? 0 : 1;
  40952. }
  40953. void paint (Graphics& g)
  40954. {
  40955. const int w = getWidth();
  40956. const int h = getHeight();
  40957. if (drawBar)
  40958. {
  40959. g.setColour (findColour (Toolbar::separatorColourId, true));
  40960. const float thickness = 0.2f;
  40961. if (isToolbarVertical())
  40962. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  40963. else
  40964. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  40965. }
  40966. if (getEditingMode() != normalMode && ! drawBar)
  40967. {
  40968. g.setColour (findColour (Toolbar::separatorColourId, true));
  40969. const int indentX = jmin (2, (w - 3) / 2);
  40970. const int indentY = jmin (2, (h - 3) / 2);
  40971. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  40972. if (fixedSize <= 0)
  40973. {
  40974. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  40975. if (isToolbarVertical())
  40976. {
  40977. x1 = w * 0.5f;
  40978. y1 = h * 0.4f;
  40979. x2 = x1;
  40980. y2 = indentX * 2.0f;
  40981. x3 = x1;
  40982. y3 = h * 0.6f;
  40983. x4 = x1;
  40984. y4 = h - y2;
  40985. hw = w * 0.15f;
  40986. hl = w * 0.2f;
  40987. }
  40988. else
  40989. {
  40990. x1 = w * 0.4f;
  40991. y1 = h * 0.5f;
  40992. x2 = indentX * 2.0f;
  40993. y2 = y1;
  40994. x3 = w * 0.6f;
  40995. y3 = y1;
  40996. x4 = w - x2;
  40997. y4 = y1;
  40998. hw = h * 0.15f;
  40999. hl = h * 0.2f;
  41000. }
  41001. Path p;
  41002. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  41003. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  41004. g.fillPath (p);
  41005. }
  41006. }
  41007. }
  41008. juce_UseDebuggingNewOperator
  41009. private:
  41010. const float fixedSize;
  41011. const bool drawBar;
  41012. ToolbarSpacerComp (const ToolbarSpacerComp&);
  41013. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  41014. };
  41015. class MissingItemsComponent : public PopupMenuCustomComponent
  41016. {
  41017. public:
  41018. MissingItemsComponent (Toolbar& owner_, const int height_)
  41019. : PopupMenuCustomComponent (true),
  41020. owner (owner_),
  41021. height (height_)
  41022. {
  41023. for (int i = owner_.items.size(); --i >= 0;)
  41024. {
  41025. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  41026. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  41027. {
  41028. oldIndexes.insert (0, i);
  41029. addAndMakeVisible (tc, 0);
  41030. }
  41031. }
  41032. layout (400);
  41033. }
  41034. ~MissingItemsComponent()
  41035. {
  41036. // deleting the toolbar while its menu it open??
  41037. jassert (owner.isValidComponent());
  41038. for (int i = 0; i < getNumChildComponents(); ++i)
  41039. {
  41040. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  41041. if (tc != 0)
  41042. {
  41043. tc->setVisible (false);
  41044. const int index = oldIndexes.remove (i);
  41045. owner.addChildComponent (tc, index);
  41046. --i;
  41047. }
  41048. }
  41049. owner.resized();
  41050. }
  41051. void layout (const int preferredWidth)
  41052. {
  41053. const int indent = 8;
  41054. int x = indent;
  41055. int y = indent;
  41056. int maxX = 0;
  41057. for (int i = 0; i < getNumChildComponents(); ++i)
  41058. {
  41059. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  41060. if (tc != 0)
  41061. {
  41062. int preferredSize = 1, minSize = 1, maxSize = 1;
  41063. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41064. {
  41065. if (x + preferredSize > preferredWidth && x > indent)
  41066. {
  41067. x = indent;
  41068. y += height;
  41069. }
  41070. tc->setBounds (x, y, preferredSize, height);
  41071. x += preferredSize;
  41072. maxX = jmax (maxX, x);
  41073. }
  41074. }
  41075. }
  41076. setSize (maxX + 8, y + height + 8);
  41077. }
  41078. void getIdealSize (int& idealWidth, int& idealHeight)
  41079. {
  41080. idealWidth = getWidth();
  41081. idealHeight = getHeight();
  41082. }
  41083. juce_UseDebuggingNewOperator
  41084. private:
  41085. Toolbar& owner;
  41086. const int height;
  41087. Array <int> oldIndexes;
  41088. MissingItemsComponent (const MissingItemsComponent&);
  41089. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  41090. };
  41091. Toolbar::Toolbar()
  41092. : vertical (false),
  41093. isEditingActive (false),
  41094. toolbarStyle (Toolbar::iconsOnly)
  41095. {
  41096. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  41097. missingItemsButton->setAlwaysOnTop (true);
  41098. missingItemsButton->addButtonListener (this);
  41099. }
  41100. Toolbar::~Toolbar()
  41101. {
  41102. animator.cancelAllAnimations (true);
  41103. deleteAllChildren();
  41104. }
  41105. void Toolbar::setVertical (const bool shouldBeVertical)
  41106. {
  41107. if (vertical != shouldBeVertical)
  41108. {
  41109. vertical = shouldBeVertical;
  41110. resized();
  41111. }
  41112. }
  41113. void Toolbar::clear()
  41114. {
  41115. for (int i = items.size(); --i >= 0;)
  41116. {
  41117. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41118. items.remove (i);
  41119. delete tc;
  41120. }
  41121. resized();
  41122. }
  41123. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  41124. {
  41125. if (itemId == ToolbarItemFactory::separatorBarId)
  41126. return new ToolbarSpacerComp (itemId, 0.1f, true);
  41127. else if (itemId == ToolbarItemFactory::spacerId)
  41128. return new ToolbarSpacerComp (itemId, 0.5f, false);
  41129. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  41130. return new ToolbarSpacerComp (itemId, 0, false);
  41131. return factory.createItem (itemId);
  41132. }
  41133. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  41134. const int itemId,
  41135. const int insertIndex)
  41136. {
  41137. // An ID can't be zero - this might indicate a mistake somewhere?
  41138. jassert (itemId != 0);
  41139. ToolbarItemComponent* const tc = createItem (factory, itemId);
  41140. if (tc != 0)
  41141. {
  41142. #ifdef JUCE_DEBUG
  41143. Array <int> allowedIds;
  41144. factory.getAllToolbarItemIds (allowedIds);
  41145. // If your factory can create an item for a given ID, it must also return
  41146. // that ID from its getAllToolbarItemIds() method!
  41147. jassert (allowedIds.contains (itemId));
  41148. #endif
  41149. items.insert (insertIndex, tc);
  41150. addAndMakeVisible (tc, insertIndex);
  41151. }
  41152. }
  41153. void Toolbar::addItem (ToolbarItemFactory& factory,
  41154. const int itemId,
  41155. const int insertIndex)
  41156. {
  41157. addItemInternal (factory, itemId, insertIndex);
  41158. resized();
  41159. }
  41160. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  41161. {
  41162. Array <int> ids;
  41163. factoryToUse.getDefaultItemSet (ids);
  41164. clear();
  41165. for (int i = 0; i < ids.size(); ++i)
  41166. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  41167. resized();
  41168. }
  41169. void Toolbar::removeToolbarItem (const int itemIndex)
  41170. {
  41171. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41172. if (tc != 0)
  41173. {
  41174. items.removeValue (tc);
  41175. delete tc;
  41176. resized();
  41177. }
  41178. }
  41179. int Toolbar::getNumItems() const throw()
  41180. {
  41181. return items.size();
  41182. }
  41183. int Toolbar::getItemId (const int itemIndex) const throw()
  41184. {
  41185. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41186. return tc != 0 ? tc->getItemId() : 0;
  41187. }
  41188. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  41189. {
  41190. return items [itemIndex];
  41191. }
  41192. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  41193. {
  41194. for (;;)
  41195. {
  41196. index += delta;
  41197. ToolbarItemComponent* const tc = getItemComponent (index);
  41198. if (tc == 0)
  41199. break;
  41200. if (tc->isActive)
  41201. return tc;
  41202. }
  41203. return 0;
  41204. }
  41205. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  41206. {
  41207. if (toolbarStyle != newStyle)
  41208. {
  41209. toolbarStyle = newStyle;
  41210. updateAllItemPositions (false);
  41211. }
  41212. }
  41213. const String Toolbar::toString() const
  41214. {
  41215. String s (T("TB:"));
  41216. for (int i = 0; i < getNumItems(); ++i)
  41217. s << getItemId(i) << T(' ');
  41218. return s.trimEnd();
  41219. }
  41220. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  41221. const String& savedVersion)
  41222. {
  41223. if (! savedVersion.startsWith (T("TB:")))
  41224. return false;
  41225. StringArray tokens;
  41226. tokens.addTokens (savedVersion.substring (3), false);
  41227. clear();
  41228. for (int i = 0; i < tokens.size(); ++i)
  41229. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  41230. resized();
  41231. return true;
  41232. }
  41233. void Toolbar::paint (Graphics& g)
  41234. {
  41235. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  41236. }
  41237. int Toolbar::getThickness() const throw()
  41238. {
  41239. return vertical ? getWidth() : getHeight();
  41240. }
  41241. int Toolbar::getLength() const throw()
  41242. {
  41243. return vertical ? getHeight() : getWidth();
  41244. }
  41245. void Toolbar::setEditingActive (const bool active)
  41246. {
  41247. if (isEditingActive != active)
  41248. {
  41249. isEditingActive = active;
  41250. updateAllItemPositions (false);
  41251. }
  41252. }
  41253. void Toolbar::resized()
  41254. {
  41255. updateAllItemPositions (false);
  41256. }
  41257. void Toolbar::updateAllItemPositions (const bool animate)
  41258. {
  41259. if (getWidth() > 0 && getHeight() > 0)
  41260. {
  41261. StretchableObjectResizer resizer;
  41262. int i;
  41263. for (i = 0; i < items.size(); ++i)
  41264. {
  41265. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41266. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  41267. : ToolbarItemComponent::normalMode);
  41268. tc->setStyle (toolbarStyle);
  41269. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  41270. int preferredSize = 1, minSize = 1, maxSize = 1;
  41271. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  41272. preferredSize, minSize, maxSize))
  41273. {
  41274. tc->isActive = true;
  41275. resizer.addItem (preferredSize, minSize, maxSize,
  41276. spacer != 0 ? spacer->getResizeOrder() : 2);
  41277. }
  41278. else
  41279. {
  41280. tc->isActive = false;
  41281. tc->setVisible (false);
  41282. }
  41283. }
  41284. resizer.resizeToFit (getLength());
  41285. int totalLength = 0;
  41286. for (i = 0; i < resizer.getNumItems(); ++i)
  41287. totalLength += (int) resizer.getItemSize (i);
  41288. const bool itemsOffTheEnd = totalLength > getLength();
  41289. const int extrasButtonSize = getThickness() / 2;
  41290. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  41291. missingItemsButton->setVisible (itemsOffTheEnd);
  41292. missingItemsButton->setEnabled (! isEditingActive);
  41293. if (vertical)
  41294. missingItemsButton->setCentrePosition (getWidth() / 2,
  41295. getHeight() - 4 - extrasButtonSize / 2);
  41296. else
  41297. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  41298. getHeight() / 2);
  41299. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  41300. : missingItemsButton->getX()) - 4
  41301. : getLength();
  41302. int pos = 0, activeIndex = 0;
  41303. for (i = 0; i < items.size(); ++i)
  41304. {
  41305. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41306. if (tc->isActive)
  41307. {
  41308. const int size = (int) resizer.getItemSize (activeIndex++);
  41309. Rectangle newBounds;
  41310. if (vertical)
  41311. newBounds.setBounds (0, pos, getWidth(), size);
  41312. else
  41313. newBounds.setBounds (pos, 0, size, getHeight());
  41314. if (animate)
  41315. {
  41316. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  41317. }
  41318. else
  41319. {
  41320. animator.cancelAnimation (tc, false);
  41321. tc->setBounds (newBounds);
  41322. }
  41323. pos += size;
  41324. tc->setVisible (pos <= maxLength
  41325. && ((! tc->isBeingDragged)
  41326. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  41327. }
  41328. }
  41329. }
  41330. }
  41331. void Toolbar::buttonClicked (Button*)
  41332. {
  41333. jassert (missingItemsButton->isShowing());
  41334. if (missingItemsButton->isShowing())
  41335. {
  41336. PopupMenu m;
  41337. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  41338. m.showAt (missingItemsButton);
  41339. }
  41340. }
  41341. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  41342. Component* /*sourceComponent*/)
  41343. {
  41344. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  41345. }
  41346. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  41347. {
  41348. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41349. if (tc != 0)
  41350. {
  41351. if (getNumItems() == 0)
  41352. {
  41353. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41354. {
  41355. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41356. if (palette != 0)
  41357. palette->replaceComponent (tc);
  41358. }
  41359. else
  41360. {
  41361. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41362. }
  41363. items.add (tc);
  41364. addChildComponent (tc);
  41365. updateAllItemPositions (false);
  41366. }
  41367. else
  41368. {
  41369. for (int i = getNumItems(); --i >= 0;)
  41370. {
  41371. int currentIndex = getIndexOfChildComponent (tc);
  41372. if (currentIndex < 0)
  41373. {
  41374. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41375. {
  41376. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41377. if (palette != 0)
  41378. palette->replaceComponent (tc);
  41379. }
  41380. else
  41381. {
  41382. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41383. }
  41384. items.add (tc);
  41385. addChildComponent (tc);
  41386. currentIndex = getIndexOfChildComponent (tc);
  41387. updateAllItemPositions (true);
  41388. }
  41389. int newIndex = currentIndex;
  41390. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  41391. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  41392. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  41393. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  41394. if (prev != 0)
  41395. {
  41396. const Rectangle previousPos (animator.getComponentDestination (prev));
  41397. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  41398. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  41399. {
  41400. newIndex = getIndexOfChildComponent (prev);
  41401. }
  41402. }
  41403. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  41404. if (next != 0)
  41405. {
  41406. const Rectangle nextPos (animator.getComponentDestination (next));
  41407. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  41408. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  41409. {
  41410. newIndex = getIndexOfChildComponent (next) + 1;
  41411. }
  41412. }
  41413. if (newIndex != currentIndex)
  41414. {
  41415. items.removeValue (tc);
  41416. removeChildComponent (tc);
  41417. addChildComponent (tc, newIndex);
  41418. items.insert (newIndex, tc);
  41419. updateAllItemPositions (true);
  41420. }
  41421. else
  41422. {
  41423. break;
  41424. }
  41425. }
  41426. }
  41427. }
  41428. }
  41429. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  41430. {
  41431. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41432. if (tc != 0)
  41433. {
  41434. if (isParentOf (tc))
  41435. {
  41436. items.removeValue (tc);
  41437. removeChildComponent (tc);
  41438. updateAllItemPositions (true);
  41439. }
  41440. }
  41441. }
  41442. void Toolbar::itemDropped (const String&, Component*, int, int)
  41443. {
  41444. }
  41445. void Toolbar::mouseDown (const MouseEvent& e)
  41446. {
  41447. if (e.mods.isPopupMenu())
  41448. {
  41449. }
  41450. }
  41451. class ToolbarCustomisationDialog : public DialogWindow
  41452. {
  41453. public:
  41454. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  41455. Toolbar* const toolbar_,
  41456. const int optionFlags)
  41457. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  41458. toolbar (toolbar_)
  41459. {
  41460. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  41461. setResizable (true, true);
  41462. setResizeLimits (400, 300, 1500, 1000);
  41463. positionNearBar();
  41464. }
  41465. ~ToolbarCustomisationDialog()
  41466. {
  41467. setContentComponent (0, true);
  41468. }
  41469. void closeButtonPressed()
  41470. {
  41471. setVisible (false);
  41472. }
  41473. bool canModalEventBeSentToComponent (const Component* comp)
  41474. {
  41475. return toolbar->isParentOf (comp);
  41476. }
  41477. void positionNearBar()
  41478. {
  41479. const Rectangle screenSize (toolbar->getParentMonitorArea());
  41480. const int tbx = toolbar->getScreenX();
  41481. const int tby = toolbar->getScreenY();
  41482. const int gap = 8;
  41483. int x, y;
  41484. if (toolbar->isVertical())
  41485. {
  41486. y = tby;
  41487. if (tbx > screenSize.getCentreX())
  41488. x = tbx - getWidth() - gap;
  41489. else
  41490. x = tbx + toolbar->getWidth() + gap;
  41491. }
  41492. else
  41493. {
  41494. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  41495. if (tby > screenSize.getCentreY())
  41496. y = tby - getHeight() - gap;
  41497. else
  41498. y = tby + toolbar->getHeight() + gap;
  41499. }
  41500. setTopLeftPosition (x, y);
  41501. }
  41502. private:
  41503. Toolbar* const toolbar;
  41504. class CustomiserPanel : public Component,
  41505. private ComboBoxListener,
  41506. private ButtonListener
  41507. {
  41508. public:
  41509. CustomiserPanel (ToolbarItemFactory& factory_,
  41510. Toolbar* const toolbar_,
  41511. const int optionFlags)
  41512. : factory (factory_),
  41513. toolbar (toolbar_),
  41514. styleBox (0),
  41515. defaultButton (0)
  41516. {
  41517. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  41518. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  41519. | Toolbar::allowIconsWithTextChoice
  41520. | Toolbar::allowTextOnlyChoice)) != 0)
  41521. {
  41522. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  41523. styleBox->setEditableText (false);
  41524. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  41525. styleBox->addItem (TRANS("Show icons only"), 1);
  41526. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  41527. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  41528. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  41529. styleBox->addItem (TRANS("Show descriptions only"), 3);
  41530. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  41531. styleBox->setSelectedId (1);
  41532. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  41533. styleBox->setSelectedId (2);
  41534. else if (toolbar_->getStyle() == Toolbar::textOnly)
  41535. styleBox->setSelectedId (3);
  41536. styleBox->addListener (this);
  41537. }
  41538. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  41539. {
  41540. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  41541. defaultButton->addButtonListener (this);
  41542. }
  41543. addAndMakeVisible (instructions = new Label (String::empty,
  41544. 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.")));
  41545. instructions->setFont (Font (13.0f));
  41546. setSize (500, 300);
  41547. }
  41548. ~CustomiserPanel()
  41549. {
  41550. deleteAllChildren();
  41551. }
  41552. void comboBoxChanged (ComboBox*)
  41553. {
  41554. if (styleBox->getSelectedId() == 1)
  41555. toolbar->setStyle (Toolbar::iconsOnly);
  41556. else if (styleBox->getSelectedId() == 2)
  41557. toolbar->setStyle (Toolbar::iconsWithText);
  41558. else if (styleBox->getSelectedId() == 3)
  41559. toolbar->setStyle (Toolbar::textOnly);
  41560. palette->resized(); // to make it update the styles
  41561. }
  41562. void buttonClicked (Button*)
  41563. {
  41564. toolbar->addDefaultItems (factory);
  41565. }
  41566. void paint (Graphics& g)
  41567. {
  41568. Colour background;
  41569. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  41570. if (dw != 0)
  41571. background = dw->getBackgroundColour();
  41572. g.setColour (background.contrasting().withAlpha (0.3f));
  41573. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  41574. }
  41575. void resized()
  41576. {
  41577. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  41578. if (styleBox != 0)
  41579. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  41580. if (defaultButton != 0)
  41581. {
  41582. defaultButton->changeWidthToFitText (22);
  41583. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  41584. }
  41585. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  41586. }
  41587. private:
  41588. ToolbarItemFactory& factory;
  41589. Toolbar* const toolbar;
  41590. Label* instructions;
  41591. ToolbarItemPalette* palette;
  41592. ComboBox* styleBox;
  41593. TextButton* defaultButton;
  41594. };
  41595. };
  41596. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  41597. {
  41598. setEditingActive (true);
  41599. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  41600. dw.runModalLoop();
  41601. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  41602. setEditingActive (false);
  41603. }
  41604. END_JUCE_NAMESPACE
  41605. /********* End of inlined file: juce_Toolbar.cpp *********/
  41606. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  41607. BEGIN_JUCE_NAMESPACE
  41608. ToolbarItemFactory::ToolbarItemFactory()
  41609. {
  41610. }
  41611. ToolbarItemFactory::~ToolbarItemFactory()
  41612. {
  41613. }
  41614. class ItemDragAndDropOverlayComponent : public Component
  41615. {
  41616. public:
  41617. ItemDragAndDropOverlayComponent()
  41618. : isDragging (false)
  41619. {
  41620. setAlwaysOnTop (true);
  41621. setRepaintsOnMouseActivity (true);
  41622. setMouseCursor (MouseCursor::DraggingHandCursor);
  41623. }
  41624. ~ItemDragAndDropOverlayComponent()
  41625. {
  41626. }
  41627. void paint (Graphics& g)
  41628. {
  41629. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41630. if (isMouseOverOrDragging()
  41631. && tc != 0
  41632. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41633. {
  41634. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  41635. g.drawRect (0, 0, getWidth(), getHeight(),
  41636. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  41637. }
  41638. }
  41639. void mouseDown (const MouseEvent& e)
  41640. {
  41641. isDragging = false;
  41642. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41643. if (tc != 0)
  41644. {
  41645. tc->dragOffsetX = e.x;
  41646. tc->dragOffsetY = e.y;
  41647. }
  41648. }
  41649. void mouseDrag (const MouseEvent& e)
  41650. {
  41651. if (! (isDragging || e.mouseWasClicked()))
  41652. {
  41653. isDragging = true;
  41654. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  41655. if (dnd != 0)
  41656. {
  41657. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  41658. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41659. if (tc != 0)
  41660. {
  41661. tc->isBeingDragged = true;
  41662. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41663. tc->setVisible (false);
  41664. }
  41665. }
  41666. }
  41667. }
  41668. void mouseUp (const MouseEvent&)
  41669. {
  41670. isDragging = false;
  41671. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41672. if (tc != 0)
  41673. {
  41674. tc->isBeingDragged = false;
  41675. Toolbar* const tb = tc->getToolbar();
  41676. if (tb != 0)
  41677. tb->updateAllItemPositions (true);
  41678. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41679. delete tc;
  41680. }
  41681. }
  41682. void parentSizeChanged()
  41683. {
  41684. setBounds (0, 0, getParentWidth(), getParentHeight());
  41685. }
  41686. juce_UseDebuggingNewOperator
  41687. private:
  41688. bool isDragging;
  41689. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  41690. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  41691. };
  41692. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  41693. const String& labelText,
  41694. const bool isBeingUsedAsAButton_)
  41695. : Button (labelText),
  41696. itemId (itemId_),
  41697. mode (normalMode),
  41698. toolbarStyle (Toolbar::iconsOnly),
  41699. overlayComp (0),
  41700. dragOffsetX (0),
  41701. dragOffsetY (0),
  41702. isActive (true),
  41703. isBeingDragged (false),
  41704. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  41705. {
  41706. // Your item ID can't be 0!
  41707. jassert (itemId_ != 0);
  41708. }
  41709. ToolbarItemComponent::~ToolbarItemComponent()
  41710. {
  41711. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41712. delete overlayComp;
  41713. }
  41714. Toolbar* ToolbarItemComponent::getToolbar() const
  41715. {
  41716. return dynamic_cast <Toolbar*> (getParentComponent());
  41717. }
  41718. bool ToolbarItemComponent::isToolbarVertical() const
  41719. {
  41720. const Toolbar* const t = getToolbar();
  41721. return t != 0 && t->isVertical();
  41722. }
  41723. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  41724. {
  41725. if (toolbarStyle != newStyle)
  41726. {
  41727. toolbarStyle = newStyle;
  41728. repaint();
  41729. resized();
  41730. }
  41731. }
  41732. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  41733. {
  41734. if (isBeingUsedAsAButton)
  41735. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  41736. isMouseOver, isMouseDown, *this);
  41737. if (toolbarStyle != Toolbar::iconsOnly)
  41738. {
  41739. const int indent = contentArea.getX();
  41740. int y = indent;
  41741. int h = getHeight() - indent * 2;
  41742. if (toolbarStyle == Toolbar::iconsWithText)
  41743. {
  41744. y = contentArea.getBottom() + indent / 2;
  41745. h -= contentArea.getHeight();
  41746. }
  41747. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  41748. getButtonText(), *this);
  41749. }
  41750. if (! contentArea.isEmpty())
  41751. {
  41752. g.saveState();
  41753. g.setOrigin (contentArea.getX(), contentArea.getY());
  41754. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  41755. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  41756. g.restoreState();
  41757. }
  41758. }
  41759. void ToolbarItemComponent::resized()
  41760. {
  41761. if (toolbarStyle != Toolbar::textOnly)
  41762. {
  41763. const int indent = jmin (proportionOfWidth (0.08f),
  41764. proportionOfHeight (0.08f));
  41765. contentArea = Rectangle (indent, indent,
  41766. getWidth() - indent * 2,
  41767. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  41768. : (getHeight() - indent * 2));
  41769. }
  41770. else
  41771. {
  41772. contentArea = Rectangle();
  41773. }
  41774. contentAreaChanged (contentArea);
  41775. }
  41776. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  41777. {
  41778. if (mode != newMode)
  41779. {
  41780. mode = newMode;
  41781. repaint();
  41782. if (mode == normalMode)
  41783. {
  41784. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41785. delete overlayComp;
  41786. overlayComp = 0;
  41787. }
  41788. else if (overlayComp == 0)
  41789. {
  41790. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  41791. overlayComp->parentSizeChanged();
  41792. }
  41793. resized();
  41794. }
  41795. }
  41796. END_JUCE_NAMESPACE
  41797. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  41798. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  41799. BEGIN_JUCE_NAMESPACE
  41800. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  41801. Toolbar* const toolbar_)
  41802. : factory (factory_),
  41803. toolbar (toolbar_)
  41804. {
  41805. Component* const itemHolder = new Component();
  41806. Array <int> allIds;
  41807. factory_.getAllToolbarItemIds (allIds);
  41808. for (int i = 0; i < allIds.size(); ++i)
  41809. {
  41810. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  41811. jassert (tc != 0);
  41812. if (tc != 0)
  41813. {
  41814. itemHolder->addAndMakeVisible (tc);
  41815. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  41816. }
  41817. }
  41818. viewport = new Viewport();
  41819. viewport->setViewedComponent (itemHolder);
  41820. addAndMakeVisible (viewport);
  41821. }
  41822. ToolbarItemPalette::~ToolbarItemPalette()
  41823. {
  41824. viewport->getViewedComponent()->deleteAllChildren();
  41825. deleteAllChildren();
  41826. }
  41827. void ToolbarItemPalette::resized()
  41828. {
  41829. viewport->setBoundsInset (BorderSize (1));
  41830. Component* const itemHolder = viewport->getViewedComponent();
  41831. const int indent = 8;
  41832. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  41833. const int height = toolbar->getThickness();
  41834. int x = indent;
  41835. int y = indent;
  41836. int maxX = 0;
  41837. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  41838. {
  41839. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  41840. if (tc != 0)
  41841. {
  41842. tc->setStyle (toolbar->getStyle());
  41843. int preferredSize = 1, minSize = 1, maxSize = 1;
  41844. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41845. {
  41846. if (x + preferredSize > preferredWidth && x > indent)
  41847. {
  41848. x = indent;
  41849. y += height;
  41850. }
  41851. tc->setBounds (x, y, preferredSize, height);
  41852. x += preferredSize + 8;
  41853. maxX = jmax (maxX, x);
  41854. }
  41855. }
  41856. }
  41857. itemHolder->setSize (maxX, y + height + 8);
  41858. }
  41859. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  41860. {
  41861. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  41862. jassert (tc != 0);
  41863. if (tc != 0)
  41864. {
  41865. tc->setBounds (comp->getBounds());
  41866. tc->setStyle (toolbar->getStyle());
  41867. tc->setEditingMode (comp->getEditingMode());
  41868. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  41869. }
  41870. }
  41871. END_JUCE_NAMESPACE
  41872. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  41873. /********* Start of inlined file: juce_TreeView.cpp *********/
  41874. BEGIN_JUCE_NAMESPACE
  41875. class TreeViewContentComponent : public Component,
  41876. public TooltipClient
  41877. {
  41878. public:
  41879. TreeViewContentComponent (TreeView* const owner_)
  41880. : owner (owner_),
  41881. buttonUnderMouse (0),
  41882. isDragging (false)
  41883. {
  41884. }
  41885. ~TreeViewContentComponent()
  41886. {
  41887. deleteAllChildren();
  41888. }
  41889. void mouseDown (const MouseEvent& e)
  41890. {
  41891. updateButtonUnderMouse (e);
  41892. isDragging = false;
  41893. needSelectionOnMouseUp = false;
  41894. Rectangle pos;
  41895. TreeViewItem* const item = findItemAt (e.y, pos);
  41896. if (item == 0)
  41897. return;
  41898. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  41899. // as selection clicks)
  41900. if (e.x < pos.getX() && owner->openCloseButtonsVisible)
  41901. {
  41902. if (e.x >= pos.getX() - owner->getIndentSize())
  41903. item->setOpen (! item->isOpen());
  41904. // (clicks to the left of an open/close button are ignored)
  41905. }
  41906. else
  41907. {
  41908. // mouse-down inside the body of the item..
  41909. if (! owner->isMultiSelectEnabled())
  41910. item->setSelected (true, true);
  41911. else if (item->isSelected())
  41912. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  41913. else
  41914. selectBasedOnModifiers (item, e.mods);
  41915. MouseEvent e2 (e);
  41916. e2.x -= pos.getX();
  41917. e2.y -= pos.getY();
  41918. if (e2.x >= 0)
  41919. item->itemClicked (e2);
  41920. }
  41921. }
  41922. void mouseUp (const MouseEvent& e)
  41923. {
  41924. updateButtonUnderMouse (e);
  41925. if (needSelectionOnMouseUp && e.mouseWasClicked())
  41926. {
  41927. Rectangle pos;
  41928. TreeViewItem* const item = findItemAt (e.y, pos);
  41929. if (item != 0)
  41930. selectBasedOnModifiers (item, e.mods);
  41931. }
  41932. }
  41933. void mouseDoubleClick (const MouseEvent& e)
  41934. {
  41935. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  41936. {
  41937. Rectangle pos;
  41938. TreeViewItem* const item = findItemAt (e.y, pos);
  41939. if (item != 0 && (e.x >= pos.getX() || ! owner->openCloseButtonsVisible))
  41940. {
  41941. MouseEvent e2 (e);
  41942. e2.x -= pos.getX();
  41943. e2.y -= pos.getY();
  41944. item->itemDoubleClicked (e2);
  41945. }
  41946. }
  41947. }
  41948. void mouseDrag (const MouseEvent& e)
  41949. {
  41950. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  41951. {
  41952. isDragging = true;
  41953. Rectangle pos;
  41954. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  41955. if (item != 0 && e.getMouseDownX() >= pos.getX())
  41956. {
  41957. const String dragDescription (item->getDragSourceDescription());
  41958. if (dragDescription.isNotEmpty())
  41959. {
  41960. DragAndDropContainer* const dragContainer
  41961. = DragAndDropContainer::findParentDragContainerFor (this);
  41962. if (dragContainer != 0)
  41963. {
  41964. pos.setSize (pos.getWidth(), item->itemHeight);
  41965. Image* dragImage = Component::createComponentSnapshot (pos, true);
  41966. dragImage->multiplyAllAlphas (0.6f);
  41967. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  41968. }
  41969. else
  41970. {
  41971. // to be able to do a drag-and-drop operation, the treeview needs to
  41972. // be inside a component which is also a DragAndDropContainer.
  41973. jassertfalse
  41974. }
  41975. }
  41976. }
  41977. }
  41978. }
  41979. void mouseMove (const MouseEvent& e)
  41980. {
  41981. updateButtonUnderMouse (e);
  41982. }
  41983. void mouseExit (const MouseEvent& e)
  41984. {
  41985. updateButtonUnderMouse (e);
  41986. }
  41987. void paint (Graphics& g);
  41988. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  41989. void updateComponents()
  41990. {
  41991. const int visibleTop = -getY();
  41992. const int visibleBottom = visibleTop + getParentHeight();
  41993. BitArray itemsToKeep;
  41994. TreeViewItem* item = owner->rootItem;
  41995. int y = (item != 0 && !owner->rootItemVisible) ? -item->itemHeight : 0;
  41996. while (item != 0 && y < visibleBottom)
  41997. {
  41998. y += item->itemHeight;
  41999. if (y >= visibleTop)
  42000. {
  42001. const int index = rowComponentIds.indexOf (item->uid);
  42002. if (index < 0)
  42003. {
  42004. Component* const comp = item->createItemComponent();
  42005. if (comp != 0)
  42006. {
  42007. addAndMakeVisible (comp);
  42008. itemsToKeep.setBit (rowComponentItems.size());
  42009. rowComponentItems.add (item);
  42010. rowComponentIds.add (item->uid);
  42011. rowComponents.add (comp);
  42012. }
  42013. }
  42014. else
  42015. {
  42016. itemsToKeep.setBit (index);
  42017. }
  42018. }
  42019. item = item->getNextVisibleItem (true);
  42020. }
  42021. for (int i = rowComponentItems.size(); --i >= 0;)
  42022. {
  42023. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  42024. bool keep = false;
  42025. if (isParentOf (comp))
  42026. {
  42027. if (itemsToKeep[i])
  42028. {
  42029. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  42030. Rectangle pos (item->getItemPosition (false));
  42031. pos.setSize (pos.getWidth(), item->itemHeight);
  42032. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  42033. {
  42034. keep = true;
  42035. comp->setBounds (pos);
  42036. }
  42037. }
  42038. if ((! keep)
  42039. && Component::isMouseButtonDownAnywhere()
  42040. && (comp == Component::getComponentUnderMouse()
  42041. || comp->isParentOf (Component::getComponentUnderMouse())))
  42042. {
  42043. keep = true;
  42044. comp->setSize (0, 0);
  42045. }
  42046. }
  42047. if (! keep)
  42048. {
  42049. delete comp;
  42050. rowComponents.remove (i);
  42051. rowComponentIds.remove (i);
  42052. rowComponentItems.remove (i);
  42053. }
  42054. }
  42055. }
  42056. void updateButtonUnderMouse (const MouseEvent& e)
  42057. {
  42058. TreeViewItem* newItem = 0;
  42059. if (owner->openCloseButtonsVisible)
  42060. {
  42061. Rectangle pos;
  42062. TreeViewItem* item = findItemAt (e.y, pos);
  42063. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner->getIndentSize())
  42064. {
  42065. newItem = item;
  42066. if (! newItem->mightContainSubItems())
  42067. newItem = 0;
  42068. }
  42069. }
  42070. if (buttonUnderMouse != newItem)
  42071. {
  42072. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  42073. {
  42074. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  42075. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  42076. }
  42077. buttonUnderMouse = newItem;
  42078. if (buttonUnderMouse != 0)
  42079. {
  42080. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  42081. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  42082. }
  42083. }
  42084. }
  42085. bool isMouseOverButton (TreeViewItem* item) const throw()
  42086. {
  42087. return item == buttonUnderMouse;
  42088. }
  42089. void resized()
  42090. {
  42091. owner->itemsChanged();
  42092. }
  42093. const String getTooltip()
  42094. {
  42095. int x, y;
  42096. getMouseXYRelative (x, y);
  42097. Rectangle pos;
  42098. TreeViewItem* const item = findItemAt (y, pos);
  42099. if (item != 0)
  42100. return item->getTooltip();
  42101. return owner->getTooltip();
  42102. }
  42103. juce_UseDebuggingNewOperator
  42104. private:
  42105. TreeView* const owner;
  42106. VoidArray rowComponentItems;
  42107. Array <int> rowComponentIds;
  42108. VoidArray rowComponents;
  42109. TreeViewItem* buttonUnderMouse;
  42110. bool isDragging, needSelectionOnMouseUp;
  42111. TreeViewContentComponent (const TreeViewContentComponent&);
  42112. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  42113. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  42114. {
  42115. TreeViewItem* firstSelected = 0;
  42116. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  42117. {
  42118. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  42119. jassert (lastSelected != 0);
  42120. int rowStart = firstSelected->getRowNumberInTree();
  42121. int rowEnd = lastSelected->getRowNumberInTree();
  42122. if (rowStart > rowEnd)
  42123. swapVariables (rowStart, rowEnd);
  42124. int ourRow = item->getRowNumberInTree();
  42125. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  42126. if (ourRow > otherEnd)
  42127. swapVariables (ourRow, otherEnd);
  42128. for (int i = ourRow; i <= otherEnd; ++i)
  42129. owner->getItemOnRow (i)->setSelected (true, false);
  42130. }
  42131. else
  42132. {
  42133. const bool cmd = modifiers.isCommandDown();
  42134. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  42135. }
  42136. }
  42137. bool containsItem (TreeViewItem* const item) const
  42138. {
  42139. for (int i = rowComponentItems.size(); --i >= 0;)
  42140. if ((TreeViewItem*) rowComponentItems.getUnchecked (i) == item)
  42141. return true;
  42142. return false;
  42143. }
  42144. };
  42145. class TreeViewport : public Viewport
  42146. {
  42147. public:
  42148. TreeViewport() throw() {}
  42149. ~TreeViewport() throw() {}
  42150. void updateComponents()
  42151. {
  42152. if (getViewedComponent() != 0)
  42153. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  42154. repaint();
  42155. }
  42156. void visibleAreaChanged (int, int, int, int)
  42157. {
  42158. updateComponents();
  42159. }
  42160. juce_UseDebuggingNewOperator
  42161. private:
  42162. TreeViewport (const TreeViewport&);
  42163. const TreeViewport& operator= (const TreeViewport&);
  42164. };
  42165. TreeView::TreeView (const String& componentName)
  42166. : Component (componentName),
  42167. rootItem (0),
  42168. indentSize (24),
  42169. defaultOpenness (false),
  42170. needsRecalculating (true),
  42171. rootItemVisible (true),
  42172. multiSelectEnabled (false),
  42173. openCloseButtonsVisible (true)
  42174. {
  42175. addAndMakeVisible (viewport = new TreeViewport());
  42176. viewport->setViewedComponent (new TreeViewContentComponent (this));
  42177. viewport->setWantsKeyboardFocus (false);
  42178. setWantsKeyboardFocus (true);
  42179. }
  42180. TreeView::~TreeView()
  42181. {
  42182. if (rootItem != 0)
  42183. rootItem->setOwnerView (0);
  42184. deleteAllChildren();
  42185. }
  42186. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  42187. {
  42188. if (rootItem != newRootItem)
  42189. {
  42190. if (newRootItem != 0)
  42191. {
  42192. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  42193. if (newRootItem->ownerView != 0)
  42194. newRootItem->ownerView->setRootItem (0);
  42195. }
  42196. if (rootItem != 0)
  42197. rootItem->setOwnerView (0);
  42198. rootItem = newRootItem;
  42199. if (newRootItem != 0)
  42200. newRootItem->setOwnerView (this);
  42201. needsRecalculating = true;
  42202. handleAsyncUpdate();
  42203. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42204. {
  42205. rootItem->setOpen (false); // force a re-open
  42206. rootItem->setOpen (true);
  42207. }
  42208. }
  42209. }
  42210. void TreeView::deleteRootItem()
  42211. {
  42212. TreeViewItem* const oldItem = rootItem;
  42213. setRootItem (0);
  42214. delete oldItem;
  42215. }
  42216. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  42217. {
  42218. rootItemVisible = shouldBeVisible;
  42219. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42220. {
  42221. rootItem->setOpen (false); // force a re-open
  42222. rootItem->setOpen (true);
  42223. }
  42224. itemsChanged();
  42225. }
  42226. void TreeView::colourChanged()
  42227. {
  42228. setOpaque (findColour (backgroundColourId).isOpaque());
  42229. repaint();
  42230. }
  42231. void TreeView::setIndentSize (const int newIndentSize)
  42232. {
  42233. if (indentSize != newIndentSize)
  42234. {
  42235. indentSize = newIndentSize;
  42236. resized();
  42237. }
  42238. }
  42239. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  42240. {
  42241. if (defaultOpenness != isOpenByDefault)
  42242. {
  42243. defaultOpenness = isOpenByDefault;
  42244. itemsChanged();
  42245. }
  42246. }
  42247. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  42248. {
  42249. multiSelectEnabled = canMultiSelect;
  42250. }
  42251. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  42252. {
  42253. if (openCloseButtonsVisible != shouldBeVisible)
  42254. {
  42255. openCloseButtonsVisible = shouldBeVisible;
  42256. itemsChanged();
  42257. }
  42258. }
  42259. void TreeView::clearSelectedItems()
  42260. {
  42261. if (rootItem != 0)
  42262. rootItem->deselectAllRecursively();
  42263. }
  42264. int TreeView::getNumSelectedItems() const throw()
  42265. {
  42266. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  42267. }
  42268. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  42269. {
  42270. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  42271. }
  42272. int TreeView::getNumRowsInTree() const
  42273. {
  42274. if (rootItem != 0)
  42275. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  42276. return 0;
  42277. }
  42278. TreeViewItem* TreeView::getItemOnRow (int index) const
  42279. {
  42280. if (! rootItemVisible)
  42281. ++index;
  42282. if (rootItem != 0 && index >= 0)
  42283. return rootItem->getItemOnRow (index);
  42284. return 0;
  42285. }
  42286. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  42287. {
  42288. XmlElement* e = 0;
  42289. if (rootItem != 0)
  42290. {
  42291. e = rootItem->createXmlOpenness();
  42292. if (e != 0 && alsoIncludeScrollPosition)
  42293. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  42294. }
  42295. return e;
  42296. }
  42297. void TreeView::restoreOpennessState (const XmlElement& newState)
  42298. {
  42299. if (rootItem != 0)
  42300. {
  42301. rootItem->restoreFromXml (newState);
  42302. if (newState.hasAttribute (T("scrollPos")))
  42303. viewport->setViewPosition (viewport->getViewPositionX(),
  42304. newState.getIntAttribute (T("scrollPos")));
  42305. }
  42306. }
  42307. void TreeView::paint (Graphics& g)
  42308. {
  42309. g.fillAll (findColour (backgroundColourId));
  42310. }
  42311. void TreeView::resized()
  42312. {
  42313. viewport->setBounds (0, 0, getWidth(), getHeight());
  42314. itemsChanged();
  42315. handleAsyncUpdate();
  42316. }
  42317. void TreeView::enablementChanged()
  42318. {
  42319. repaint();
  42320. }
  42321. void TreeView::moveSelectedRow (int delta)
  42322. {
  42323. if (delta == 0)
  42324. return;
  42325. int rowSelected = 0;
  42326. TreeViewItem* const firstSelected = getSelectedItem (0);
  42327. if (firstSelected != 0)
  42328. rowSelected = firstSelected->getRowNumberInTree();
  42329. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  42330. for (;;)
  42331. {
  42332. TreeViewItem* item = getItemOnRow (rowSelected);
  42333. if (item != 0)
  42334. {
  42335. if (! item->canBeSelected())
  42336. {
  42337. // if the row we want to highlight doesn't allow it, try skipping
  42338. // to the next item..
  42339. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  42340. rowSelected + (delta < 0 ? -1 : 1));
  42341. if (rowSelected != nextRowToTry)
  42342. {
  42343. rowSelected = nextRowToTry;
  42344. continue;
  42345. }
  42346. else
  42347. {
  42348. break;
  42349. }
  42350. }
  42351. item->setSelected (true, true);
  42352. scrollToKeepItemVisible (item);
  42353. }
  42354. break;
  42355. }
  42356. }
  42357. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  42358. {
  42359. if (item != 0 && item->ownerView == this)
  42360. {
  42361. handleAsyncUpdate();
  42362. item = item->getDeepestOpenParentItem();
  42363. int y = item->y;
  42364. int viewTop = viewport->getViewPositionY();
  42365. if (y < viewTop)
  42366. {
  42367. viewport->setViewPosition (viewport->getViewPositionX(), y);
  42368. }
  42369. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  42370. {
  42371. viewport->setViewPosition (viewport->getViewPositionX(),
  42372. (y + item->itemHeight) - viewport->getViewHeight());
  42373. }
  42374. }
  42375. }
  42376. bool TreeView::keyPressed (const KeyPress& key)
  42377. {
  42378. if (key.isKeyCode (KeyPress::upKey))
  42379. {
  42380. moveSelectedRow (-1);
  42381. }
  42382. else if (key.isKeyCode (KeyPress::downKey))
  42383. {
  42384. moveSelectedRow (1);
  42385. }
  42386. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  42387. {
  42388. if (rootItem != 0)
  42389. {
  42390. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  42391. if (key.isKeyCode (KeyPress::pageUpKey))
  42392. rowsOnScreen = -rowsOnScreen;
  42393. moveSelectedRow (rowsOnScreen);
  42394. }
  42395. }
  42396. else if (key.isKeyCode (KeyPress::homeKey))
  42397. {
  42398. moveSelectedRow (-0x3fffffff);
  42399. }
  42400. else if (key.isKeyCode (KeyPress::endKey))
  42401. {
  42402. moveSelectedRow (0x3fffffff);
  42403. }
  42404. else if (key.isKeyCode (KeyPress::returnKey))
  42405. {
  42406. TreeViewItem* const firstSelected = getSelectedItem (0);
  42407. if (firstSelected != 0)
  42408. firstSelected->setOpen (! firstSelected->isOpen());
  42409. }
  42410. else if (key.isKeyCode (KeyPress::leftKey))
  42411. {
  42412. TreeViewItem* const firstSelected = getSelectedItem (0);
  42413. if (firstSelected != 0)
  42414. {
  42415. if (firstSelected->isOpen())
  42416. {
  42417. firstSelected->setOpen (false);
  42418. }
  42419. else
  42420. {
  42421. TreeViewItem* parent = firstSelected->parentItem;
  42422. if ((! rootItemVisible) && parent == rootItem)
  42423. parent = 0;
  42424. if (parent != 0)
  42425. {
  42426. parent->setSelected (true, true);
  42427. scrollToKeepItemVisible (parent);
  42428. }
  42429. }
  42430. }
  42431. }
  42432. else if (key.isKeyCode (KeyPress::rightKey))
  42433. {
  42434. TreeViewItem* const firstSelected = getSelectedItem (0);
  42435. if (firstSelected != 0)
  42436. {
  42437. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  42438. moveSelectedRow (1);
  42439. else
  42440. firstSelected->setOpen (true);
  42441. }
  42442. }
  42443. else
  42444. {
  42445. return false;
  42446. }
  42447. return true;
  42448. }
  42449. void TreeView::itemsChanged() throw()
  42450. {
  42451. needsRecalculating = true;
  42452. repaint();
  42453. triggerAsyncUpdate();
  42454. }
  42455. void TreeView::handleAsyncUpdate()
  42456. {
  42457. if (needsRecalculating)
  42458. {
  42459. needsRecalculating = false;
  42460. const ScopedLock sl (nodeAlterationLock);
  42461. if (rootItem != 0)
  42462. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  42463. ((TreeViewport*) viewport)->updateComponents();
  42464. if (rootItem != 0)
  42465. {
  42466. viewport->getViewedComponent()
  42467. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  42468. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  42469. }
  42470. else
  42471. {
  42472. viewport->getViewedComponent()->setSize (0, 0);
  42473. }
  42474. }
  42475. }
  42476. void TreeViewContentComponent::paint (Graphics& g)
  42477. {
  42478. if (owner->rootItem != 0)
  42479. {
  42480. owner->handleAsyncUpdate();
  42481. if (! owner->rootItemVisible)
  42482. g.setOrigin (0, -owner->rootItem->itemHeight);
  42483. owner->rootItem->paintRecursively (g, getWidth());
  42484. }
  42485. }
  42486. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  42487. {
  42488. if (owner->rootItem != 0)
  42489. {
  42490. owner->handleAsyncUpdate();
  42491. if (! owner->rootItemVisible)
  42492. y += owner->rootItem->itemHeight;
  42493. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  42494. if (ti != 0)
  42495. itemPosition = ti->getItemPosition (false);
  42496. return ti;
  42497. }
  42498. return 0;
  42499. }
  42500. #define opennessDefault 0
  42501. #define opennessClosed 1
  42502. #define opennessOpen 2
  42503. TreeViewItem::TreeViewItem()
  42504. : ownerView (0),
  42505. parentItem (0),
  42506. subItems (8),
  42507. y (0),
  42508. itemHeight (0),
  42509. totalHeight (0),
  42510. selected (false),
  42511. redrawNeeded (true),
  42512. drawLinesInside (true),
  42513. drawsInLeftMargin (false),
  42514. openness (opennessDefault)
  42515. {
  42516. static int nextUID = 0;
  42517. uid = nextUID++;
  42518. }
  42519. TreeViewItem::~TreeViewItem()
  42520. {
  42521. }
  42522. const String TreeViewItem::getUniqueName() const
  42523. {
  42524. return String::empty;
  42525. }
  42526. void TreeViewItem::itemOpennessChanged (bool)
  42527. {
  42528. }
  42529. int TreeViewItem::getNumSubItems() const throw()
  42530. {
  42531. return subItems.size();
  42532. }
  42533. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  42534. {
  42535. return subItems [index];
  42536. }
  42537. void TreeViewItem::clearSubItems()
  42538. {
  42539. if (subItems.size() > 0)
  42540. {
  42541. if (ownerView != 0)
  42542. {
  42543. const ScopedLock sl (ownerView->nodeAlterationLock);
  42544. subItems.clear();
  42545. treeHasChanged();
  42546. }
  42547. else
  42548. {
  42549. subItems.clear();
  42550. }
  42551. }
  42552. }
  42553. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  42554. {
  42555. if (newItem != 0)
  42556. {
  42557. newItem->parentItem = this;
  42558. newItem->setOwnerView (ownerView);
  42559. newItem->y = 0;
  42560. newItem->itemHeight = newItem->getItemHeight();
  42561. newItem->totalHeight = 0;
  42562. newItem->itemWidth = newItem->getItemWidth();
  42563. newItem->totalWidth = 0;
  42564. if (ownerView != 0)
  42565. {
  42566. const ScopedLock sl (ownerView->nodeAlterationLock);
  42567. subItems.insert (insertPosition, newItem);
  42568. treeHasChanged();
  42569. if (newItem->isOpen())
  42570. newItem->itemOpennessChanged (true);
  42571. }
  42572. else
  42573. {
  42574. subItems.insert (insertPosition, newItem);
  42575. if (newItem->isOpen())
  42576. newItem->itemOpennessChanged (true);
  42577. }
  42578. }
  42579. }
  42580. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  42581. {
  42582. if (ownerView != 0)
  42583. ownerView->nodeAlterationLock.enter();
  42584. if (((unsigned int) index) < (unsigned int) subItems.size())
  42585. {
  42586. subItems.remove (index, deleteItem);
  42587. treeHasChanged();
  42588. }
  42589. if (ownerView != 0)
  42590. ownerView->nodeAlterationLock.exit();
  42591. }
  42592. bool TreeViewItem::isOpen() const throw()
  42593. {
  42594. if (openness == opennessDefault)
  42595. return ownerView != 0 && ownerView->defaultOpenness;
  42596. else
  42597. return openness == opennessOpen;
  42598. }
  42599. void TreeViewItem::setOpen (const bool shouldBeOpen)
  42600. {
  42601. if (isOpen() != shouldBeOpen)
  42602. {
  42603. openness = shouldBeOpen ? opennessOpen
  42604. : opennessClosed;
  42605. treeHasChanged();
  42606. itemOpennessChanged (isOpen());
  42607. }
  42608. }
  42609. bool TreeViewItem::isSelected() const throw()
  42610. {
  42611. return selected;
  42612. }
  42613. void TreeViewItem::deselectAllRecursively()
  42614. {
  42615. setSelected (false, false);
  42616. for (int i = 0; i < subItems.size(); ++i)
  42617. subItems.getUnchecked(i)->deselectAllRecursively();
  42618. }
  42619. void TreeViewItem::setSelected (const bool shouldBeSelected,
  42620. const bool deselectOtherItemsFirst)
  42621. {
  42622. if (shouldBeSelected && ! canBeSelected())
  42623. return;
  42624. if (deselectOtherItemsFirst)
  42625. getTopLevelItem()->deselectAllRecursively();
  42626. if (shouldBeSelected != selected)
  42627. {
  42628. selected = shouldBeSelected;
  42629. if (ownerView != 0)
  42630. ownerView->repaint();
  42631. itemSelectionChanged (shouldBeSelected);
  42632. }
  42633. }
  42634. void TreeViewItem::paintItem (Graphics&, int, int)
  42635. {
  42636. }
  42637. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  42638. {
  42639. ownerView->getLookAndFeel()
  42640. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  42641. }
  42642. void TreeViewItem::itemClicked (const MouseEvent&)
  42643. {
  42644. }
  42645. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  42646. {
  42647. if (mightContainSubItems())
  42648. setOpen (! isOpen());
  42649. }
  42650. void TreeViewItem::itemSelectionChanged (bool)
  42651. {
  42652. }
  42653. const String TreeViewItem::getTooltip()
  42654. {
  42655. return String::empty;
  42656. }
  42657. const String TreeViewItem::getDragSourceDescription()
  42658. {
  42659. return String::empty;
  42660. }
  42661. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  42662. {
  42663. const int indentX = getIndentX();
  42664. int width = itemWidth;
  42665. if (ownerView != 0 && width < 0)
  42666. width = ownerView->viewport->getViewWidth() - indentX;
  42667. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  42668. if (relativeToTreeViewTopLeft)
  42669. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  42670. r.getY() - ownerView->viewport->getViewPositionY());
  42671. return r;
  42672. }
  42673. void TreeViewItem::treeHasChanged() const throw()
  42674. {
  42675. if (ownerView != 0)
  42676. ownerView->itemsChanged();
  42677. }
  42678. void TreeViewItem::repaintItem() const
  42679. {
  42680. if (ownerView != 0 && areAllParentsOpen())
  42681. {
  42682. const Rectangle r (getItemPosition (true));
  42683. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  42684. }
  42685. }
  42686. bool TreeViewItem::areAllParentsOpen() const throw()
  42687. {
  42688. return parentItem == 0
  42689. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  42690. }
  42691. void TreeViewItem::updatePositions (int newY)
  42692. {
  42693. y = newY;
  42694. itemHeight = getItemHeight();
  42695. totalHeight = itemHeight;
  42696. itemWidth = getItemWidth();
  42697. totalWidth = jmax (itemWidth, 0) + getIndentX();
  42698. if (isOpen())
  42699. {
  42700. newY += totalHeight;
  42701. for (int i = 0; i < subItems.size(); ++i)
  42702. {
  42703. TreeViewItem* const ti = subItems.getUnchecked(i);
  42704. ti->updatePositions (newY);
  42705. newY += ti->totalHeight;
  42706. totalHeight += ti->totalHeight;
  42707. totalWidth = jmax (totalWidth, ti->totalWidth);
  42708. }
  42709. }
  42710. }
  42711. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  42712. {
  42713. TreeViewItem* result = this;
  42714. TreeViewItem* item = this;
  42715. while (item->parentItem != 0)
  42716. {
  42717. item = item->parentItem;
  42718. if (! item->isOpen())
  42719. result = item;
  42720. }
  42721. return result;
  42722. }
  42723. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  42724. {
  42725. ownerView = newOwner;
  42726. for (int i = subItems.size(); --i >= 0;)
  42727. subItems.getUnchecked(i)->setOwnerView (newOwner);
  42728. }
  42729. int TreeViewItem::getIndentX() const throw()
  42730. {
  42731. const int indentWidth = ownerView->getIndentSize();
  42732. int x = ownerView->rootItemVisible ? indentWidth : 0;
  42733. if (! ownerView->openCloseButtonsVisible)
  42734. x -= indentWidth;
  42735. TreeViewItem* p = parentItem;
  42736. while (p != 0)
  42737. {
  42738. x += indentWidth;
  42739. p = p->parentItem;
  42740. }
  42741. return x;
  42742. }
  42743. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  42744. {
  42745. drawsInLeftMargin = canDrawInLeftMargin;
  42746. }
  42747. void TreeViewItem::paintRecursively (Graphics& g, int width)
  42748. {
  42749. jassert (ownerView != 0);
  42750. if (ownerView == 0)
  42751. return;
  42752. const int indent = getIndentX();
  42753. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  42754. g.setColour (ownerView->findColour (TreeView::linesColourId));
  42755. const float halfH = itemHeight * 0.5f;
  42756. int depth = 0;
  42757. TreeViewItem* p = parentItem;
  42758. while (p != 0)
  42759. {
  42760. ++depth;
  42761. p = p->parentItem;
  42762. }
  42763. if (! ownerView->rootItemVisible)
  42764. --depth;
  42765. const int indentWidth = ownerView->getIndentSize();
  42766. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  42767. {
  42768. float x = (depth + 0.5f) * indentWidth;
  42769. if (depth >= 0)
  42770. {
  42771. if (parentItem != 0 && parentItem->drawLinesInside)
  42772. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  42773. if ((parentItem != 0 && parentItem->drawLinesInside)
  42774. || (parentItem == 0 && drawLinesInside))
  42775. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  42776. }
  42777. p = parentItem;
  42778. int d = depth;
  42779. while (p != 0 && --d >= 0)
  42780. {
  42781. x -= (float) indentWidth;
  42782. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  42783. && ! p->isLastOfSiblings())
  42784. {
  42785. g.drawLine (x, 0, x, (float) itemHeight);
  42786. }
  42787. p = p->parentItem;
  42788. }
  42789. if (mightContainSubItems())
  42790. {
  42791. g.saveState();
  42792. g.setOrigin (depth * indentWidth, 0);
  42793. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  42794. paintOpenCloseButton (g, indentWidth, itemHeight,
  42795. ((TreeViewContentComponent*) ownerView->viewport->getViewedComponent())
  42796. ->isMouseOverButton (this));
  42797. g.restoreState();
  42798. }
  42799. }
  42800. {
  42801. g.saveState();
  42802. g.setOrigin (indent, 0);
  42803. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  42804. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  42805. paintItem (g, itemW, itemHeight);
  42806. g.restoreState();
  42807. }
  42808. if (isOpen())
  42809. {
  42810. const Rectangle clip (g.getClipBounds());
  42811. for (int i = 0; i < subItems.size(); ++i)
  42812. {
  42813. TreeViewItem* const ti = subItems.getUnchecked(i);
  42814. const int relY = ti->y - y;
  42815. if (relY >= clip.getBottom())
  42816. break;
  42817. if (relY + ti->totalHeight >= clip.getY())
  42818. {
  42819. g.saveState();
  42820. g.setOrigin (0, relY);
  42821. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  42822. ti->paintRecursively (g, width);
  42823. g.restoreState();
  42824. }
  42825. }
  42826. }
  42827. }
  42828. bool TreeViewItem::isLastOfSiblings() const throw()
  42829. {
  42830. return parentItem == 0
  42831. || parentItem->subItems.getLast() == this;
  42832. }
  42833. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  42834. {
  42835. return (parentItem == 0) ? this
  42836. : parentItem->getTopLevelItem();
  42837. }
  42838. int TreeViewItem::getNumRows() const throw()
  42839. {
  42840. int num = 1;
  42841. if (isOpen())
  42842. {
  42843. for (int i = subItems.size(); --i >= 0;)
  42844. num += subItems.getUnchecked(i)->getNumRows();
  42845. }
  42846. return num;
  42847. }
  42848. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  42849. {
  42850. if (index == 0)
  42851. return this;
  42852. if (index > 0 && isOpen())
  42853. {
  42854. --index;
  42855. for (int i = 0; i < subItems.size(); ++i)
  42856. {
  42857. TreeViewItem* const item = subItems.getUnchecked(i);
  42858. if (index == 0)
  42859. return item;
  42860. const int numRows = item->getNumRows();
  42861. if (numRows > index)
  42862. return item->getItemOnRow (index);
  42863. index -= numRows;
  42864. }
  42865. }
  42866. return 0;
  42867. }
  42868. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  42869. {
  42870. if (((unsigned int) y) < (unsigned int) totalHeight)
  42871. {
  42872. const int h = itemHeight;
  42873. if (y < h)
  42874. return this;
  42875. if (isOpen())
  42876. {
  42877. y -= h;
  42878. for (int i = 0; i < subItems.size(); ++i)
  42879. {
  42880. TreeViewItem* const ti = subItems.getUnchecked(i);
  42881. if (ti->totalHeight >= y)
  42882. return ti->findItemRecursively (y);
  42883. y -= ti->totalHeight;
  42884. }
  42885. }
  42886. }
  42887. return 0;
  42888. }
  42889. int TreeViewItem::countSelectedItemsRecursively() const throw()
  42890. {
  42891. int total = 0;
  42892. if (isSelected())
  42893. ++total;
  42894. for (int i = subItems.size(); --i >= 0;)
  42895. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  42896. return total;
  42897. }
  42898. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  42899. {
  42900. if (isSelected())
  42901. {
  42902. if (index == 0)
  42903. return this;
  42904. --index;
  42905. }
  42906. if (index >= 0)
  42907. {
  42908. for (int i = 0; i < subItems.size(); ++i)
  42909. {
  42910. TreeViewItem* const item = subItems.getUnchecked(i);
  42911. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  42912. if (found != 0)
  42913. return found;
  42914. index -= item->countSelectedItemsRecursively();
  42915. }
  42916. }
  42917. return 0;
  42918. }
  42919. int TreeViewItem::getRowNumberInTree() const throw()
  42920. {
  42921. if (parentItem != 0 && ownerView != 0)
  42922. {
  42923. int n = 1 + parentItem->getRowNumberInTree();
  42924. int ourIndex = parentItem->subItems.indexOf (this);
  42925. jassert (ourIndex >= 0);
  42926. while (--ourIndex >= 0)
  42927. n += parentItem->subItems [ourIndex]->getNumRows();
  42928. if (parentItem->parentItem == 0
  42929. && ! ownerView->rootItemVisible)
  42930. --n;
  42931. return n;
  42932. }
  42933. else
  42934. {
  42935. return 0;
  42936. }
  42937. }
  42938. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  42939. {
  42940. drawLinesInside = drawLines;
  42941. }
  42942. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  42943. {
  42944. if (recurse && isOpen() && subItems.size() > 0)
  42945. return subItems [0];
  42946. if (parentItem != 0)
  42947. {
  42948. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  42949. if (nextIndex >= parentItem->subItems.size())
  42950. return parentItem->getNextVisibleItem (false);
  42951. return parentItem->subItems [nextIndex];
  42952. }
  42953. return 0;
  42954. }
  42955. void TreeViewItem::restoreFromXml (const XmlElement& e)
  42956. {
  42957. if (e.hasTagName (T("CLOSED")))
  42958. {
  42959. setOpen (false);
  42960. }
  42961. else if (e.hasTagName (T("OPEN")))
  42962. {
  42963. setOpen (true);
  42964. forEachXmlChildElement (e, n)
  42965. {
  42966. const String id (n->getStringAttribute (T("id")));
  42967. for (int i = 0; i < subItems.size(); ++i)
  42968. {
  42969. TreeViewItem* const ti = subItems.getUnchecked(i);
  42970. if (ti->getUniqueName() == id)
  42971. {
  42972. ti->restoreFromXml (*n);
  42973. break;
  42974. }
  42975. }
  42976. }
  42977. }
  42978. }
  42979. XmlElement* TreeViewItem::createXmlOpenness() const
  42980. {
  42981. if (openness != opennessDefault)
  42982. {
  42983. const String name (getUniqueName());
  42984. if (name.isNotEmpty())
  42985. {
  42986. XmlElement* e;
  42987. if (isOpen())
  42988. {
  42989. e = new XmlElement (T("OPEN"));
  42990. for (int i = 0; i < subItems.size(); ++i)
  42991. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  42992. }
  42993. else
  42994. {
  42995. e = new XmlElement (T("CLOSED"));
  42996. }
  42997. e->setAttribute (T("id"), name);
  42998. return e;
  42999. }
  43000. else
  43001. {
  43002. // trying to save the openness for an element that has no name - this won't
  43003. // work because it needs the names to identify what to open.
  43004. jassertfalse
  43005. }
  43006. }
  43007. return 0;
  43008. }
  43009. END_JUCE_NAMESPACE
  43010. /********* End of inlined file: juce_TreeView.cpp *********/
  43011. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  43012. BEGIN_JUCE_NAMESPACE
  43013. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  43014. : fileList (listToShow),
  43015. listeners (2)
  43016. {
  43017. }
  43018. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  43019. {
  43020. }
  43021. FileBrowserListener::~FileBrowserListener()
  43022. {
  43023. }
  43024. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  43025. {
  43026. jassert (listener != 0);
  43027. if (listener != 0)
  43028. listeners.add (listener);
  43029. }
  43030. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  43031. {
  43032. listeners.removeValue (listener);
  43033. }
  43034. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  43035. {
  43036. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  43037. for (int i = listeners.size(); --i >= 0;)
  43038. {
  43039. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43040. if (deletionWatcher.hasBeenDeleted())
  43041. return;
  43042. i = jmin (i, listeners.size() - 1);
  43043. }
  43044. }
  43045. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  43046. {
  43047. if (fileList.getDirectory().exists())
  43048. {
  43049. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  43050. for (int i = listeners.size(); --i >= 0;)
  43051. {
  43052. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  43053. if (deletionWatcher.hasBeenDeleted())
  43054. return;
  43055. i = jmin (i, listeners.size() - 1);
  43056. }
  43057. }
  43058. }
  43059. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  43060. {
  43061. if (fileList.getDirectory().exists())
  43062. {
  43063. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  43064. for (int i = listeners.size(); --i >= 0;)
  43065. {
  43066. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  43067. if (deletionWatcher.hasBeenDeleted())
  43068. return;
  43069. i = jmin (i, listeners.size() - 1);
  43070. }
  43071. }
  43072. }
  43073. END_JUCE_NAMESPACE
  43074. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  43075. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  43076. BEGIN_JUCE_NAMESPACE
  43077. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  43078. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  43079. Time* creationTime, bool* isReadOnly) throw();
  43080. bool juce_findFileNext (void* handle, String& resultFile,
  43081. bool* isDirectory, bool* isHidden, int64* fileSize,
  43082. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  43083. void juce_findFileClose (void* handle) throw();
  43084. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  43085. TimeSliceThread& thread_)
  43086. : fileFilter (fileFilter_),
  43087. thread (thread_),
  43088. includeDirectories (false),
  43089. includeFiles (false),
  43090. ignoreHiddenFiles (true),
  43091. fileFindHandle (0),
  43092. shouldStop (true)
  43093. {
  43094. }
  43095. DirectoryContentsList::~DirectoryContentsList()
  43096. {
  43097. clear();
  43098. }
  43099. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  43100. {
  43101. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  43102. }
  43103. const File& DirectoryContentsList::getDirectory() const throw()
  43104. {
  43105. return root;
  43106. }
  43107. void DirectoryContentsList::setDirectory (const File& directory,
  43108. const bool includeDirectories_,
  43109. const bool includeFiles_)
  43110. {
  43111. if (directory != root
  43112. || includeDirectories != includeDirectories_
  43113. || includeFiles != includeFiles_)
  43114. {
  43115. clear();
  43116. root = directory;
  43117. includeDirectories = includeDirectories_;
  43118. includeFiles = includeFiles_;
  43119. refresh();
  43120. }
  43121. }
  43122. void DirectoryContentsList::clear()
  43123. {
  43124. shouldStop = true;
  43125. thread.removeTimeSliceClient (this);
  43126. if (fileFindHandle != 0)
  43127. {
  43128. juce_findFileClose (fileFindHandle);
  43129. fileFindHandle = 0;
  43130. }
  43131. if (files.size() > 0)
  43132. {
  43133. files.clear();
  43134. changed();
  43135. }
  43136. }
  43137. void DirectoryContentsList::refresh()
  43138. {
  43139. clear();
  43140. if (root.isDirectory())
  43141. {
  43142. String fileFound;
  43143. bool fileFoundIsDir, isHidden, isReadOnly;
  43144. int64 fileSize;
  43145. Time modTime, creationTime;
  43146. String path (root.getFullPathName());
  43147. if (! path.endsWithChar (File::separator))
  43148. path += File::separator;
  43149. jassert (fileFindHandle == 0);
  43150. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  43151. &fileFoundIsDir,
  43152. &isHidden,
  43153. &fileSize,
  43154. &modTime,
  43155. &creationTime,
  43156. &isReadOnly);
  43157. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  43158. {
  43159. if (addFile (fileFound, fileFoundIsDir, isHidden,
  43160. fileSize, modTime, creationTime, isReadOnly))
  43161. {
  43162. changed();
  43163. }
  43164. }
  43165. shouldStop = false;
  43166. thread.addTimeSliceClient (this);
  43167. }
  43168. }
  43169. int DirectoryContentsList::getNumFiles() const
  43170. {
  43171. return files.size();
  43172. }
  43173. bool DirectoryContentsList::getFileInfo (const int index,
  43174. FileInfo& result) const
  43175. {
  43176. const ScopedLock sl (fileListLock);
  43177. const FileInfo* const info = files [index];
  43178. if (info != 0)
  43179. {
  43180. result = *info;
  43181. return true;
  43182. }
  43183. return false;
  43184. }
  43185. const File DirectoryContentsList::getFile (const int index) const
  43186. {
  43187. const ScopedLock sl (fileListLock);
  43188. const FileInfo* const info = files [index];
  43189. if (info != 0)
  43190. return root.getChildFile (info->filename);
  43191. return File::nonexistent;
  43192. }
  43193. bool DirectoryContentsList::isStillLoading() const
  43194. {
  43195. return fileFindHandle != 0;
  43196. }
  43197. void DirectoryContentsList::changed()
  43198. {
  43199. sendChangeMessage (this);
  43200. }
  43201. bool DirectoryContentsList::useTimeSlice()
  43202. {
  43203. const uint32 startTime = Time::getApproximateMillisecondCounter();
  43204. bool hasChanged = false;
  43205. for (int i = 100; --i >= 0;)
  43206. {
  43207. if (! checkNextFile (hasChanged))
  43208. {
  43209. if (hasChanged)
  43210. changed();
  43211. return false;
  43212. }
  43213. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  43214. break;
  43215. }
  43216. if (hasChanged)
  43217. changed();
  43218. return true;
  43219. }
  43220. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  43221. {
  43222. if (fileFindHandle != 0)
  43223. {
  43224. String fileFound;
  43225. bool fileFoundIsDir, isHidden, isReadOnly;
  43226. int64 fileSize;
  43227. Time modTime, creationTime;
  43228. if (juce_findFileNext (fileFindHandle, fileFound,
  43229. &fileFoundIsDir, &isHidden,
  43230. &fileSize,
  43231. &modTime,
  43232. &creationTime,
  43233. &isReadOnly))
  43234. {
  43235. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  43236. modTime, creationTime, isReadOnly))
  43237. {
  43238. hasChanged = true;
  43239. }
  43240. return true;
  43241. }
  43242. else
  43243. {
  43244. juce_findFileClose (fileFindHandle);
  43245. fileFindHandle = 0;
  43246. }
  43247. }
  43248. return false;
  43249. }
  43250. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  43251. const DirectoryContentsList::FileInfo* const second) throw()
  43252. {
  43253. #if JUCE_WINDOWS
  43254. if (first->isDirectory != second->isDirectory)
  43255. return first->isDirectory ? -1 : 1;
  43256. #endif
  43257. return first->filename.compareIgnoreCase (second->filename);
  43258. }
  43259. bool DirectoryContentsList::addFile (const String& filename,
  43260. const bool isDir,
  43261. const bool isHidden,
  43262. const int64 fileSize,
  43263. const Time& modTime,
  43264. const Time& creationTime,
  43265. const bool isReadOnly)
  43266. {
  43267. if (filename == T("..")
  43268. || filename == T(".")
  43269. || (ignoreHiddenFiles && isHidden))
  43270. return false;
  43271. const File file (root.getChildFile (filename));
  43272. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  43273. && (fileFilter == 0
  43274. || ((! isDir) && fileFilter->isFileSuitable (file))
  43275. || (isDir && fileFilter->isDirectorySuitable (file))))
  43276. {
  43277. FileInfo* const info = new FileInfo();
  43278. info->filename = filename;
  43279. info->fileSize = fileSize;
  43280. info->modificationTime = modTime;
  43281. info->creationTime = creationTime;
  43282. info->isDirectory = isDir;
  43283. info->isReadOnly = isReadOnly;
  43284. const ScopedLock sl (fileListLock);
  43285. for (int i = files.size(); --i >= 0;)
  43286. {
  43287. if (files.getUnchecked(i)->filename == info->filename)
  43288. {
  43289. delete info;
  43290. return false;
  43291. }
  43292. }
  43293. files.addSorted (*this, info);
  43294. return true;
  43295. }
  43296. return false;
  43297. }
  43298. END_JUCE_NAMESPACE
  43299. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  43300. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  43301. BEGIN_JUCE_NAMESPACE
  43302. class DirectoriesOnlyFilter : public FileFilter
  43303. {
  43304. public:
  43305. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  43306. bool isFileSuitable (const File&) const { return false; }
  43307. bool isDirectorySuitable (const File&) const { return true; }
  43308. };
  43309. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  43310. const File& initialFileOrDirectory,
  43311. const FileFilter* fileFilter,
  43312. FilePreviewComponent* previewComp_,
  43313. const bool useTreeView,
  43314. const bool filenameTextBoxIsReadOnly)
  43315. : directoriesOnlyFilter (0),
  43316. mode (mode_),
  43317. listeners (2),
  43318. previewComp (previewComp_),
  43319. thread ("Juce FileBrowser")
  43320. {
  43321. String filename;
  43322. if (initialFileOrDirectory == File::nonexistent)
  43323. {
  43324. currentRoot = File::getCurrentWorkingDirectory();
  43325. }
  43326. else if (initialFileOrDirectory.isDirectory())
  43327. {
  43328. currentRoot = initialFileOrDirectory;
  43329. }
  43330. else
  43331. {
  43332. currentRoot = initialFileOrDirectory.getParentDirectory();
  43333. filename = initialFileOrDirectory.getFileName();
  43334. }
  43335. if (mode_ == chooseDirectoryMode)
  43336. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  43337. fileList = new DirectoryContentsList (fileFilter, thread);
  43338. if (useTreeView)
  43339. {
  43340. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  43341. addAndMakeVisible (tree);
  43342. fileListComponent = tree;
  43343. }
  43344. else
  43345. {
  43346. FileListComponent* const list = new FileListComponent (*fileList);
  43347. list->setOutlineThickness (1);
  43348. addAndMakeVisible (list);
  43349. fileListComponent = list;
  43350. }
  43351. fileListComponent->addListener (this);
  43352. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  43353. currentPathBox->setEditableText (true);
  43354. StringArray rootNames, rootPaths;
  43355. const BitArray separators (getRoots (rootNames, rootPaths));
  43356. for (int i = 0; i < rootNames.size(); ++i)
  43357. {
  43358. if (separators [i])
  43359. currentPathBox->addSeparator();
  43360. currentPathBox->addItem (rootNames[i], i + 1);
  43361. }
  43362. currentPathBox->addSeparator();
  43363. currentPathBox->addListener (this);
  43364. addAndMakeVisible (filenameBox = new TextEditor());
  43365. filenameBox->setMultiLine (false);
  43366. filenameBox->setSelectAllWhenFocused (true);
  43367. filenameBox->setText (filename, false);
  43368. filenameBox->addListener (this);
  43369. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  43370. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  43371. : TRANS("file:"));
  43372. addAndMakeVisible (label);
  43373. label->attachToComponent (filenameBox, true);
  43374. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  43375. goUpButton->addButtonListener (this);
  43376. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  43377. if (previewComp != 0)
  43378. addAndMakeVisible (previewComp);
  43379. setRoot (currentRoot);
  43380. thread.startThread (4);
  43381. }
  43382. FileBrowserComponent::~FileBrowserComponent()
  43383. {
  43384. if (previewComp != 0)
  43385. removeChildComponent (previewComp);
  43386. deleteAllChildren();
  43387. deleteAndZero (fileList);
  43388. delete directoriesOnlyFilter;
  43389. thread.stopThread (10000);
  43390. }
  43391. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  43392. {
  43393. jassert (newListener != 0)
  43394. if (newListener != 0)
  43395. listeners.add (newListener);
  43396. }
  43397. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  43398. {
  43399. listeners.removeValue (listener);
  43400. }
  43401. const File FileBrowserComponent::getCurrentFile() const throw()
  43402. {
  43403. return currentRoot.getChildFile (filenameBox->getText());
  43404. }
  43405. bool FileBrowserComponent::currentFileIsValid() const
  43406. {
  43407. if (mode == saveFileMode)
  43408. return ! getCurrentFile().isDirectory();
  43409. else if (mode == loadFileMode)
  43410. return getCurrentFile().existsAsFile();
  43411. else if (mode == chooseDirectoryMode)
  43412. return getCurrentFile().isDirectory();
  43413. jassertfalse
  43414. return false;
  43415. }
  43416. const File FileBrowserComponent::getRoot() const
  43417. {
  43418. return currentRoot;
  43419. }
  43420. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  43421. {
  43422. if (currentRoot != newRootDirectory)
  43423. {
  43424. fileListComponent->scrollToTop();
  43425. if (mode == chooseDirectoryMode)
  43426. filenameBox->setText (String::empty, false);
  43427. String path (newRootDirectory.getFullPathName());
  43428. if (path.isEmpty())
  43429. path += File::separator;
  43430. StringArray rootNames, rootPaths;
  43431. getRoots (rootNames, rootPaths);
  43432. if (! rootPaths.contains (path, true))
  43433. {
  43434. bool alreadyListed = false;
  43435. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  43436. {
  43437. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  43438. {
  43439. alreadyListed = true;
  43440. break;
  43441. }
  43442. }
  43443. if (! alreadyListed)
  43444. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  43445. }
  43446. }
  43447. currentRoot = newRootDirectory;
  43448. fileList->setDirectory (currentRoot, true, true);
  43449. String currentRootName (currentRoot.getFullPathName());
  43450. if (currentRootName.isEmpty())
  43451. currentRootName += File::separator;
  43452. currentPathBox->setText (currentRootName, true);
  43453. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  43454. && currentRoot.getParentDirectory() != currentRoot);
  43455. }
  43456. void FileBrowserComponent::goUp()
  43457. {
  43458. setRoot (getRoot().getParentDirectory());
  43459. }
  43460. void FileBrowserComponent::refresh()
  43461. {
  43462. fileList->refresh();
  43463. }
  43464. const String FileBrowserComponent::getActionVerb() const
  43465. {
  43466. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  43467. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  43468. }
  43469. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  43470. {
  43471. return previewComp;
  43472. }
  43473. void FileBrowserComponent::resized()
  43474. {
  43475. getLookAndFeel()
  43476. .layoutFileBrowserComponent (*this, fileListComponent,
  43477. previewComp, currentPathBox,
  43478. filenameBox, goUpButton);
  43479. }
  43480. void FileBrowserComponent::sendListenerChangeMessage()
  43481. {
  43482. ComponentDeletionWatcher deletionWatcher (this);
  43483. if (previewComp != 0)
  43484. previewComp->selectedFileChanged (getCurrentFile());
  43485. jassert (! deletionWatcher.hasBeenDeleted());
  43486. for (int i = listeners.size(); --i >= 0;)
  43487. {
  43488. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43489. if (deletionWatcher.hasBeenDeleted())
  43490. return;
  43491. i = jmin (i, listeners.size() - 1);
  43492. }
  43493. }
  43494. void FileBrowserComponent::selectionChanged()
  43495. {
  43496. const File selected (fileListComponent->getSelectedFile());
  43497. if ((mode == chooseDirectoryMode && selected.isDirectory())
  43498. || selected.existsAsFile())
  43499. {
  43500. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  43501. }
  43502. sendListenerChangeMessage();
  43503. }
  43504. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  43505. {
  43506. ComponentDeletionWatcher deletionWatcher (this);
  43507. for (int i = listeners.size(); --i >= 0;)
  43508. {
  43509. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  43510. if (deletionWatcher.hasBeenDeleted())
  43511. return;
  43512. i = jmin (i, listeners.size() - 1);
  43513. }
  43514. }
  43515. void FileBrowserComponent::fileDoubleClicked (const File& f)
  43516. {
  43517. if (f.isDirectory())
  43518. {
  43519. setRoot (f);
  43520. }
  43521. else
  43522. {
  43523. ComponentDeletionWatcher deletionWatcher (this);
  43524. for (int i = listeners.size(); --i >= 0;)
  43525. {
  43526. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  43527. if (deletionWatcher.hasBeenDeleted())
  43528. return;
  43529. i = jmin (i, listeners.size() - 1);
  43530. }
  43531. }
  43532. }
  43533. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  43534. {
  43535. #if JUCE_LINUX || JUCE_WINDOWS
  43536. if (key.getModifiers().isCommandDown()
  43537. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  43538. {
  43539. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  43540. fileList->refresh();
  43541. return true;
  43542. }
  43543. #endif
  43544. return false;
  43545. }
  43546. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  43547. {
  43548. sendListenerChangeMessage();
  43549. }
  43550. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  43551. {
  43552. if (filenameBox->getText().containsChar (File::separator))
  43553. {
  43554. const File f (currentRoot.getChildFile (filenameBox->getText()));
  43555. if (f.isDirectory())
  43556. {
  43557. setRoot (f);
  43558. filenameBox->setText (String::empty);
  43559. }
  43560. else
  43561. {
  43562. setRoot (f.getParentDirectory());
  43563. filenameBox->setText (f.getFileName());
  43564. }
  43565. }
  43566. else
  43567. {
  43568. fileDoubleClicked (getCurrentFile());
  43569. }
  43570. }
  43571. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  43572. {
  43573. }
  43574. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  43575. {
  43576. if (mode != saveFileMode)
  43577. selectionChanged();
  43578. }
  43579. void FileBrowserComponent::buttonClicked (Button*)
  43580. {
  43581. goUp();
  43582. }
  43583. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  43584. {
  43585. const String newText (currentPathBox->getText().trim().unquoted());
  43586. if (newText.isNotEmpty())
  43587. {
  43588. const int index = currentPathBox->getSelectedId() - 1;
  43589. StringArray rootNames, rootPaths;
  43590. getRoots (rootNames, rootPaths);
  43591. if (rootPaths [index].isNotEmpty())
  43592. {
  43593. setRoot (File (rootPaths [index]));
  43594. }
  43595. else
  43596. {
  43597. File f (newText);
  43598. for (;;)
  43599. {
  43600. if (f.isDirectory())
  43601. {
  43602. setRoot (f);
  43603. break;
  43604. }
  43605. if (f.getParentDirectory() == f)
  43606. break;
  43607. f = f.getParentDirectory();
  43608. }
  43609. }
  43610. }
  43611. }
  43612. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  43613. {
  43614. BitArray separators;
  43615. #if JUCE_WINDOWS
  43616. OwnedArray<File> roots;
  43617. File::findFileSystemRoots (roots);
  43618. rootPaths.clear();
  43619. for (int i = 0; i < roots.size(); ++i)
  43620. {
  43621. const File* const drive = roots.getUnchecked(i);
  43622. String name (drive->getFullPathName());
  43623. rootPaths.add (name);
  43624. if (drive->isOnHardDisk())
  43625. {
  43626. String volume (drive->getVolumeLabel());
  43627. if (volume.isEmpty())
  43628. volume = TRANS("Hard Drive");
  43629. name << " [" << drive->getVolumeLabel() << ']';
  43630. }
  43631. else if (drive->isOnCDRomDrive())
  43632. {
  43633. name << TRANS(" [CD/DVD drive]");
  43634. }
  43635. rootNames.add (name);
  43636. }
  43637. separators.setBit (rootPaths.size());
  43638. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43639. rootNames.add ("Documents");
  43640. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43641. rootNames.add ("Desktop");
  43642. #endif
  43643. #if JUCE_MAC
  43644. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43645. rootNames.add ("Home folder");
  43646. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43647. rootNames.add ("Documents");
  43648. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43649. rootNames.add ("Desktop");
  43650. separators.setBit (rootPaths.size());
  43651. OwnedArray <File> volumes;
  43652. File vol ("/Volumes");
  43653. vol.findChildFiles (volumes, File::findDirectories, false);
  43654. for (int i = 0; i < volumes.size(); ++i)
  43655. {
  43656. const File* const volume = volumes.getUnchecked(i);
  43657. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  43658. {
  43659. rootPaths.add (volume->getFullPathName());
  43660. rootNames.add (volume->getFileName());
  43661. }
  43662. }
  43663. #endif
  43664. #if JUCE_LINUX
  43665. rootPaths.add ("/");
  43666. rootNames.add ("/");
  43667. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43668. rootNames.add ("Home folder");
  43669. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43670. rootNames.add ("Desktop");
  43671. #endif
  43672. return separators;
  43673. }
  43674. END_JUCE_NAMESPACE
  43675. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  43676. /********* Start of inlined file: juce_FileChooser.cpp *********/
  43677. BEGIN_JUCE_NAMESPACE
  43678. FileChooser::FileChooser (const String& chooserBoxTitle,
  43679. const File& currentFileOrDirectory,
  43680. const String& fileFilters,
  43681. const bool useNativeDialogBox_)
  43682. : title (chooserBoxTitle),
  43683. filters (fileFilters),
  43684. startingFile (currentFileOrDirectory),
  43685. useNativeDialogBox (useNativeDialogBox_)
  43686. {
  43687. #if JUCE_LINUX
  43688. useNativeDialogBox = false;
  43689. #endif
  43690. if (! fileFilters.containsNonWhitespaceChars())
  43691. filters = T("*");
  43692. }
  43693. FileChooser::~FileChooser()
  43694. {
  43695. }
  43696. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  43697. {
  43698. return showDialog (false, false, false, false, previewComponent);
  43699. }
  43700. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  43701. {
  43702. return showDialog (false, false, false, true, previewComponent);
  43703. }
  43704. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  43705. {
  43706. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  43707. }
  43708. bool FileChooser::browseForDirectory()
  43709. {
  43710. return showDialog (true, false, false, false, 0);
  43711. }
  43712. const File FileChooser::getResult() const
  43713. {
  43714. // if you've used a multiple-file select, you should use the getResults() method
  43715. // to retrieve all the files that were chosen.
  43716. jassert (results.size() <= 1);
  43717. const File* const f = results.getFirst();
  43718. if (f != 0)
  43719. return *f;
  43720. return File::nonexistent;
  43721. }
  43722. const OwnedArray <File>& FileChooser::getResults() const
  43723. {
  43724. return results;
  43725. }
  43726. bool FileChooser::showDialog (const bool isDirectory,
  43727. const bool isSave,
  43728. const bool warnAboutOverwritingExistingFiles,
  43729. const bool selectMultipleFiles,
  43730. FilePreviewComponent* const previewComponent)
  43731. {
  43732. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  43733. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  43734. if (currentlyFocused != 0)
  43735. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  43736. results.clear();
  43737. // the preview component needs to be the right size before you pass it in here..
  43738. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  43739. && previewComponent->getHeight() > 10));
  43740. #if JUCE_WINDOWS
  43741. if (useNativeDialogBox)
  43742. #else
  43743. if (useNativeDialogBox && (previewComponent == 0))
  43744. #endif
  43745. {
  43746. showPlatformDialog (results, title, startingFile, filters,
  43747. isDirectory, isSave,
  43748. warnAboutOverwritingExistingFiles,
  43749. selectMultipleFiles,
  43750. previewComponent);
  43751. }
  43752. else
  43753. {
  43754. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  43755. WildcardFileFilter wildcard (filters, String::empty);
  43756. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  43757. : (isSave ? FileBrowserComponent::saveFileMode
  43758. : FileBrowserComponent::loadFileMode),
  43759. startingFile, &wildcard, previewComponent);
  43760. FileChooserDialogBox box (title, String::empty,
  43761. browserComponent,
  43762. warnAboutOverwritingExistingFiles,
  43763. browserComponent.findColour (AlertWindow::backgroundColourId));
  43764. if (box.show())
  43765. results.add (new File (browserComponent.getCurrentFile()));
  43766. }
  43767. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  43768. currentlyFocused->grabKeyboardFocus();
  43769. delete currentlyFocusedChecker;
  43770. return results.size() > 0;
  43771. }
  43772. FilePreviewComponent::FilePreviewComponent()
  43773. {
  43774. }
  43775. FilePreviewComponent::~FilePreviewComponent()
  43776. {
  43777. }
  43778. END_JUCE_NAMESPACE
  43779. /********* End of inlined file: juce_FileChooser.cpp *********/
  43780. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  43781. BEGIN_JUCE_NAMESPACE
  43782. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  43783. const String& instructions,
  43784. FileBrowserComponent& chooserComponent,
  43785. const bool warnAboutOverwritingExistingFiles_,
  43786. const Colour& backgroundColour)
  43787. : ResizableWindow (name, backgroundColour, true),
  43788. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  43789. {
  43790. content = new ContentComponent();
  43791. content->setName (name);
  43792. content->instructions = instructions;
  43793. content->chooserComponent = &chooserComponent;
  43794. content->addAndMakeVisible (&chooserComponent);
  43795. content->okButton = new TextButton (chooserComponent.getActionVerb());
  43796. content->addAndMakeVisible (content->okButton);
  43797. content->okButton->addButtonListener (this);
  43798. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  43799. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  43800. content->cancelButton = new TextButton (TRANS("Cancel"));
  43801. content->addAndMakeVisible (content->cancelButton);
  43802. content->cancelButton->addButtonListener (this);
  43803. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  43804. setContentComponent (content);
  43805. setResizable (true, true);
  43806. setResizeLimits (300, 300, 1200, 1000);
  43807. content->chooserComponent->addListener (this);
  43808. }
  43809. FileChooserDialogBox::~FileChooserDialogBox()
  43810. {
  43811. content->chooserComponent->removeListener (this);
  43812. }
  43813. bool FileChooserDialogBox::show (int w, int h)
  43814. {
  43815. if (w <= 0)
  43816. {
  43817. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  43818. if (previewComp != 0)
  43819. w = 400 + previewComp->getWidth();
  43820. else
  43821. w = 600;
  43822. }
  43823. if (h <= 0)
  43824. h = 500;
  43825. centreWithSize (w, h);
  43826. const bool ok = (runModalLoop() != 0);
  43827. setVisible (false);
  43828. return ok;
  43829. }
  43830. void FileChooserDialogBox::buttonClicked (Button* button)
  43831. {
  43832. if (button == content->okButton)
  43833. {
  43834. if (warnAboutOverwritingExistingFiles
  43835. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  43836. && content->chooserComponent->getCurrentFile().exists())
  43837. {
  43838. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  43839. TRANS("File already exists"),
  43840. TRANS("There's already a file called:\n\n")
  43841. + content->chooserComponent->getCurrentFile().getFullPathName()
  43842. + T("\n\nAre you sure you want to overwrite it?"),
  43843. TRANS("overwrite"),
  43844. TRANS("cancel")))
  43845. {
  43846. return;
  43847. }
  43848. }
  43849. exitModalState (1);
  43850. }
  43851. else if (button == content->cancelButton)
  43852. closeButtonPressed();
  43853. }
  43854. void FileChooserDialogBox::closeButtonPressed()
  43855. {
  43856. setVisible (false);
  43857. }
  43858. void FileChooserDialogBox::selectionChanged()
  43859. {
  43860. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  43861. }
  43862. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  43863. {
  43864. }
  43865. void FileChooserDialogBox::fileDoubleClicked (const File&)
  43866. {
  43867. selectionChanged();
  43868. content->okButton->triggerClick();
  43869. }
  43870. FileChooserDialogBox::ContentComponent::ContentComponent()
  43871. {
  43872. setInterceptsMouseClicks (false, true);
  43873. }
  43874. FileChooserDialogBox::ContentComponent::~ContentComponent()
  43875. {
  43876. delete okButton;
  43877. delete cancelButton;
  43878. }
  43879. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  43880. {
  43881. g.setColour (Colours::black);
  43882. text.draw (g);
  43883. }
  43884. void FileChooserDialogBox::ContentComponent::resized()
  43885. {
  43886. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  43887. float left, top, right, bottom;
  43888. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  43889. const int y = roundFloatToInt (bottom) + 10;
  43890. const int buttonHeight = 26;
  43891. const int buttonY = getHeight() - buttonHeight - 8;
  43892. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  43893. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  43894. proportionOfWidth (0.2f), buttonHeight);
  43895. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  43896. proportionOfWidth (0.2f), buttonHeight);
  43897. }
  43898. END_JUCE_NAMESPACE
  43899. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  43900. /********* Start of inlined file: juce_FileFilter.cpp *********/
  43901. BEGIN_JUCE_NAMESPACE
  43902. FileFilter::FileFilter (const String& filterDescription)
  43903. : description (filterDescription)
  43904. {
  43905. }
  43906. FileFilter::~FileFilter()
  43907. {
  43908. }
  43909. const String& FileFilter::getDescription() const throw()
  43910. {
  43911. return description;
  43912. }
  43913. END_JUCE_NAMESPACE
  43914. /********* End of inlined file: juce_FileFilter.cpp *********/
  43915. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  43916. BEGIN_JUCE_NAMESPACE
  43917. Image* juce_createIconForFile (const File& file);
  43918. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  43919. : ListBox (String::empty, 0),
  43920. DirectoryContentsDisplayComponent (listToShow)
  43921. {
  43922. setModel (this);
  43923. fileList.addChangeListener (this);
  43924. }
  43925. FileListComponent::~FileListComponent()
  43926. {
  43927. fileList.removeChangeListener (this);
  43928. deleteAllChildren();
  43929. }
  43930. const File FileListComponent::getSelectedFile() const
  43931. {
  43932. return fileList.getFile (getSelectedRow());
  43933. }
  43934. void FileListComponent::scrollToTop()
  43935. {
  43936. getVerticalScrollBar()->setCurrentRangeStart (0);
  43937. }
  43938. void FileListComponent::changeListenerCallback (void*)
  43939. {
  43940. updateContent();
  43941. if (lastDirectory != fileList.getDirectory())
  43942. {
  43943. lastDirectory = fileList.getDirectory();
  43944. deselectAllRows();
  43945. }
  43946. }
  43947. class FileListItemComponent : public Component,
  43948. public TimeSliceClient,
  43949. public AsyncUpdater
  43950. {
  43951. public:
  43952. FileListItemComponent (FileListComponent& owner_,
  43953. TimeSliceThread& thread_) throw()
  43954. : owner (owner_),
  43955. thread (thread_),
  43956. icon (0)
  43957. {
  43958. }
  43959. ~FileListItemComponent() throw()
  43960. {
  43961. thread.removeTimeSliceClient (this);
  43962. clearIcon();
  43963. }
  43964. void paint (Graphics& g)
  43965. {
  43966. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  43967. file.getFileName(),
  43968. icon,
  43969. fileSize, modTime,
  43970. isDirectory, highlighted,
  43971. index);
  43972. }
  43973. void mouseDown (const MouseEvent& e)
  43974. {
  43975. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  43976. owner.sendMouseClickMessage (file, e);
  43977. }
  43978. void mouseDoubleClick (const MouseEvent&)
  43979. {
  43980. owner.sendDoubleClickMessage (file);
  43981. }
  43982. void update (const File& root,
  43983. const DirectoryContentsList::FileInfo* const fileInfo,
  43984. const int index_,
  43985. const bool highlighted_) throw()
  43986. {
  43987. thread.removeTimeSliceClient (this);
  43988. if (highlighted_ != highlighted
  43989. || index_ != index)
  43990. {
  43991. index = index_;
  43992. highlighted = highlighted_;
  43993. repaint();
  43994. }
  43995. File newFile;
  43996. String newFileSize;
  43997. String newModTime;
  43998. if (fileInfo != 0)
  43999. {
  44000. newFile = root.getChildFile (fileInfo->filename);
  44001. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  44002. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  44003. }
  44004. if (newFile != file
  44005. || fileSize != newFileSize
  44006. || modTime != newModTime)
  44007. {
  44008. file = newFile;
  44009. fileSize = newFileSize;
  44010. modTime = newModTime;
  44011. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  44012. repaint();
  44013. clearIcon();
  44014. }
  44015. if (file != File::nonexistent
  44016. && icon == 0 && ! isDirectory)
  44017. {
  44018. updateIcon (true);
  44019. if (icon == 0)
  44020. thread.addTimeSliceClient (this);
  44021. }
  44022. }
  44023. bool useTimeSlice()
  44024. {
  44025. updateIcon (false);
  44026. return false;
  44027. }
  44028. void handleAsyncUpdate()
  44029. {
  44030. repaint();
  44031. }
  44032. juce_UseDebuggingNewOperator
  44033. private:
  44034. FileListComponent& owner;
  44035. TimeSliceThread& thread;
  44036. bool highlighted;
  44037. int index;
  44038. File file;
  44039. String fileSize;
  44040. String modTime;
  44041. Image* icon;
  44042. bool isDirectory;
  44043. void clearIcon() throw()
  44044. {
  44045. ImageCache::release (icon);
  44046. icon = 0;
  44047. }
  44048. void updateIcon (const bool onlyUpdateIfCached) throw()
  44049. {
  44050. if (icon == 0)
  44051. {
  44052. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44053. Image* im = ImageCache::getFromHashCode (hashCode);
  44054. if (im == 0 && ! onlyUpdateIfCached)
  44055. {
  44056. im = juce_createIconForFile (file);
  44057. if (im != 0)
  44058. ImageCache::addImageToCache (im, hashCode);
  44059. }
  44060. if (im != 0)
  44061. {
  44062. icon = im;
  44063. triggerAsyncUpdate();
  44064. }
  44065. }
  44066. }
  44067. };
  44068. int FileListComponent::getNumRows()
  44069. {
  44070. return fileList.getNumFiles();
  44071. }
  44072. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  44073. {
  44074. }
  44075. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  44076. {
  44077. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  44078. if (comp == 0)
  44079. {
  44080. delete existingComponentToUpdate;
  44081. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  44082. }
  44083. DirectoryContentsList::FileInfo fileInfo;
  44084. if (fileList.getFileInfo (row, fileInfo))
  44085. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  44086. else
  44087. comp->update (fileList.getDirectory(), 0, row, isSelected);
  44088. return comp;
  44089. }
  44090. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  44091. {
  44092. sendSelectionChangeMessage();
  44093. }
  44094. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  44095. {
  44096. }
  44097. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  44098. {
  44099. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  44100. }
  44101. END_JUCE_NAMESPACE
  44102. /********* End of inlined file: juce_FileListComponent.cpp *********/
  44103. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  44104. BEGIN_JUCE_NAMESPACE
  44105. FilenameComponent::FilenameComponent (const String& name,
  44106. const File& currentFile,
  44107. const bool canEditFilename,
  44108. const bool isDirectory,
  44109. const bool isForSaving,
  44110. const String& fileBrowserWildcard,
  44111. const String& enforcedSuffix_,
  44112. const String& textWhenNothingSelected)
  44113. : Component (name),
  44114. maxRecentFiles (30),
  44115. isDir (isDirectory),
  44116. isSaving (isForSaving),
  44117. isFileDragOver (false),
  44118. wildcard (fileBrowserWildcard),
  44119. enforcedSuffix (enforcedSuffix_)
  44120. {
  44121. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  44122. filenameBox->setEditableText (canEditFilename);
  44123. filenameBox->addListener (this);
  44124. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  44125. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  44126. browseButton = 0;
  44127. setBrowseButtonText (T("..."));
  44128. setCurrentFile (currentFile, true);
  44129. }
  44130. FilenameComponent::~FilenameComponent()
  44131. {
  44132. deleteAllChildren();
  44133. }
  44134. void FilenameComponent::paintOverChildren (Graphics& g)
  44135. {
  44136. if (isFileDragOver)
  44137. {
  44138. g.setColour (Colours::red.withAlpha (0.2f));
  44139. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  44140. }
  44141. }
  44142. void FilenameComponent::resized()
  44143. {
  44144. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  44145. }
  44146. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  44147. {
  44148. browseButtonText = newBrowseButtonText;
  44149. lookAndFeelChanged();
  44150. }
  44151. void FilenameComponent::lookAndFeelChanged()
  44152. {
  44153. deleteAndZero (browseButton);
  44154. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  44155. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  44156. resized();
  44157. browseButton->addButtonListener (this);
  44158. }
  44159. void FilenameComponent::setTooltip (const String& newTooltip)
  44160. {
  44161. SettableTooltipClient::setTooltip (newTooltip);
  44162. filenameBox->setTooltip (newTooltip);
  44163. }
  44164. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44165. {
  44166. defaultBrowseFile = newDefaultDirectory;
  44167. }
  44168. void FilenameComponent::buttonClicked (Button*)
  44169. {
  44170. FileChooser fc (TRANS("Choose a new file"),
  44171. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  44172. : getCurrentFile(),
  44173. wildcard);
  44174. if (isDir ? fc.browseForDirectory()
  44175. : (isSaving ? fc.browseForFileToSave (false)
  44176. : fc.browseForFileToOpen()))
  44177. {
  44178. setCurrentFile (fc.getResult(), true);
  44179. }
  44180. }
  44181. void FilenameComponent::comboBoxChanged (ComboBox*)
  44182. {
  44183. setCurrentFile (getCurrentFile(), true);
  44184. }
  44185. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  44186. {
  44187. return true;
  44188. }
  44189. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  44190. {
  44191. isFileDragOver = false;
  44192. repaint();
  44193. const File f (filenames[0]);
  44194. if (f.exists() && (f.isDirectory() == isDir))
  44195. setCurrentFile (f, true);
  44196. }
  44197. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  44198. {
  44199. isFileDragOver = true;
  44200. repaint();
  44201. }
  44202. void FilenameComponent::fileDragExit (const StringArray&)
  44203. {
  44204. isFileDragOver = false;
  44205. repaint();
  44206. }
  44207. const File FilenameComponent::getCurrentFile() const
  44208. {
  44209. File f (filenameBox->getText());
  44210. if (enforcedSuffix.isNotEmpty())
  44211. f = f.withFileExtension (enforcedSuffix);
  44212. return f;
  44213. }
  44214. void FilenameComponent::setCurrentFile (File newFile,
  44215. const bool addToRecentlyUsedList,
  44216. const bool sendChangeNotification)
  44217. {
  44218. if (enforcedSuffix.isNotEmpty())
  44219. newFile = newFile.withFileExtension (enforcedSuffix);
  44220. if (newFile.getFullPathName() != lastFilename)
  44221. {
  44222. lastFilename = newFile.getFullPathName();
  44223. if (addToRecentlyUsedList)
  44224. addRecentlyUsedFile (newFile);
  44225. filenameBox->setText (lastFilename, true);
  44226. if (sendChangeNotification)
  44227. triggerAsyncUpdate();
  44228. }
  44229. }
  44230. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  44231. {
  44232. filenameBox->setEditableText (shouldBeEditable);
  44233. }
  44234. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  44235. {
  44236. StringArray names;
  44237. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  44238. names.add (filenameBox->getItemText (i));
  44239. return names;
  44240. }
  44241. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  44242. {
  44243. if (filenames != getRecentlyUsedFilenames())
  44244. {
  44245. filenameBox->clear();
  44246. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  44247. filenameBox->addItem (filenames[i], i + 1);
  44248. }
  44249. }
  44250. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  44251. {
  44252. maxRecentFiles = jmax (1, newMaximum);
  44253. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  44254. }
  44255. void FilenameComponent::addRecentlyUsedFile (const File& file)
  44256. {
  44257. StringArray files (getRecentlyUsedFilenames());
  44258. if (file.getFullPathName().isNotEmpty())
  44259. {
  44260. files.removeString (file.getFullPathName(), true);
  44261. files.insert (0, file.getFullPathName());
  44262. setRecentlyUsedFilenames (files);
  44263. }
  44264. }
  44265. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  44266. {
  44267. jassert (listener != 0);
  44268. if (listener != 0)
  44269. listeners.add (listener);
  44270. }
  44271. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  44272. {
  44273. listeners.removeValue (listener);
  44274. }
  44275. void FilenameComponent::handleAsyncUpdate()
  44276. {
  44277. for (int i = listeners.size(); --i >= 0;)
  44278. {
  44279. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  44280. i = jmin (i, listeners.size());
  44281. }
  44282. }
  44283. END_JUCE_NAMESPACE
  44284. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  44285. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44286. BEGIN_JUCE_NAMESPACE
  44287. FileSearchPathListComponent::FileSearchPathListComponent()
  44288. {
  44289. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  44290. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  44291. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  44292. listBox->setOutlineThickness (1);
  44293. addAndMakeVisible (addButton = new TextButton ("+"));
  44294. addButton->addButtonListener (this);
  44295. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44296. addAndMakeVisible (removeButton = new TextButton ("-"));
  44297. removeButton->addButtonListener (this);
  44298. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44299. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  44300. changeButton->addButtonListener (this);
  44301. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44302. upButton->addButtonListener (this);
  44303. {
  44304. Path arrowPath;
  44305. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  44306. DrawablePath arrowImage;
  44307. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44308. arrowImage.setPath (arrowPath);
  44309. ((DrawableButton*) upButton)->setImages (&arrowImage);
  44310. }
  44311. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44312. downButton->addButtonListener (this);
  44313. {
  44314. Path arrowPath;
  44315. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  44316. DrawablePath arrowImage;
  44317. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44318. arrowImage.setPath (arrowPath);
  44319. ((DrawableButton*) downButton)->setImages (&arrowImage);
  44320. }
  44321. updateButtons();
  44322. }
  44323. FileSearchPathListComponent::~FileSearchPathListComponent()
  44324. {
  44325. deleteAllChildren();
  44326. }
  44327. void FileSearchPathListComponent::updateButtons() throw()
  44328. {
  44329. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  44330. removeButton->setEnabled (anythingSelected);
  44331. changeButton->setEnabled (anythingSelected);
  44332. upButton->setEnabled (anythingSelected);
  44333. downButton->setEnabled (anythingSelected);
  44334. }
  44335. void FileSearchPathListComponent::changed() throw()
  44336. {
  44337. listBox->updateContent();
  44338. listBox->repaint();
  44339. updateButtons();
  44340. }
  44341. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  44342. {
  44343. if (newPath.toString() != path.toString())
  44344. {
  44345. path = newPath;
  44346. changed();
  44347. }
  44348. }
  44349. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44350. {
  44351. defaultBrowseTarget = newDefaultDirectory;
  44352. }
  44353. int FileSearchPathListComponent::getNumRows()
  44354. {
  44355. return path.getNumPaths();
  44356. }
  44357. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  44358. {
  44359. if (rowIsSelected)
  44360. g.fillAll (findColour (TextEditor::highlightColourId));
  44361. g.setColour (findColour (ListBox::textColourId));
  44362. Font f (height * 0.7f);
  44363. f.setHorizontalScale (0.9f);
  44364. g.setFont (f);
  44365. g.drawText (path [rowNumber].getFullPathName(),
  44366. 4, 0, width - 6, height,
  44367. Justification::centredLeft, true);
  44368. }
  44369. void FileSearchPathListComponent::deleteKeyPressed (int row)
  44370. {
  44371. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  44372. {
  44373. path.remove (row);
  44374. changed();
  44375. }
  44376. }
  44377. void FileSearchPathListComponent::returnKeyPressed (int row)
  44378. {
  44379. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  44380. if (chooser.browseForDirectory())
  44381. {
  44382. path.remove (row);
  44383. path.add (chooser.getResult(), row);
  44384. changed();
  44385. }
  44386. }
  44387. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  44388. {
  44389. returnKeyPressed (row);
  44390. }
  44391. void FileSearchPathListComponent::selectedRowsChanged (int)
  44392. {
  44393. updateButtons();
  44394. }
  44395. void FileSearchPathListComponent::paint (Graphics& g)
  44396. {
  44397. g.fillAll (findColour (backgroundColourId));
  44398. }
  44399. void FileSearchPathListComponent::resized()
  44400. {
  44401. const int buttonH = 22;
  44402. const int buttonY = getHeight() - buttonH - 4;
  44403. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  44404. addButton->setBounds (2, buttonY, buttonH, buttonH);
  44405. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  44406. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  44407. downButton->setSize (buttonH * 2, buttonH);
  44408. upButton->setSize (buttonH * 2, buttonH);
  44409. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  44410. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  44411. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  44412. }
  44413. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  44414. {
  44415. return true;
  44416. }
  44417. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  44418. {
  44419. for (int i = filenames.size(); --i >= 0;)
  44420. {
  44421. const File f (filenames[i]);
  44422. if (f.isDirectory())
  44423. {
  44424. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  44425. path.add (f, row);
  44426. changed();
  44427. }
  44428. }
  44429. }
  44430. void FileSearchPathListComponent::buttonClicked (Button* button)
  44431. {
  44432. const int currentRow = listBox->getSelectedRow();
  44433. if (button == removeButton)
  44434. {
  44435. deleteKeyPressed (currentRow);
  44436. }
  44437. else if (button == addButton)
  44438. {
  44439. File start (defaultBrowseTarget);
  44440. if (start == File::nonexistent)
  44441. start = path [0];
  44442. if (start == File::nonexistent)
  44443. start = File::getCurrentWorkingDirectory();
  44444. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  44445. if (chooser.browseForDirectory())
  44446. {
  44447. path.add (chooser.getResult(), currentRow);
  44448. }
  44449. }
  44450. else if (button == changeButton)
  44451. {
  44452. returnKeyPressed (currentRow);
  44453. }
  44454. else if (button == upButton)
  44455. {
  44456. if (currentRow > 0 && currentRow < path.getNumPaths())
  44457. {
  44458. const File f (path[currentRow]);
  44459. path.remove (currentRow);
  44460. path.add (f, currentRow - 1);
  44461. listBox->selectRow (currentRow - 1);
  44462. }
  44463. }
  44464. else if (button == downButton)
  44465. {
  44466. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  44467. {
  44468. const File f (path[currentRow]);
  44469. path.remove (currentRow);
  44470. path.add (f, currentRow + 1);
  44471. listBox->selectRow (currentRow + 1);
  44472. }
  44473. }
  44474. changed();
  44475. }
  44476. END_JUCE_NAMESPACE
  44477. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44478. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  44479. BEGIN_JUCE_NAMESPACE
  44480. Image* juce_createIconForFile (const File& file);
  44481. class FileListTreeItem : public TreeViewItem,
  44482. public TimeSliceClient,
  44483. public AsyncUpdater,
  44484. public ChangeListener
  44485. {
  44486. public:
  44487. FileListTreeItem (FileTreeComponent& owner_,
  44488. DirectoryContentsList* const parentContentsList_,
  44489. const int indexInContentsList_,
  44490. const File& file_,
  44491. TimeSliceThread& thread_) throw()
  44492. : file (file_),
  44493. owner (owner_),
  44494. parentContentsList (parentContentsList_),
  44495. indexInContentsList (indexInContentsList_),
  44496. subContentsList (0),
  44497. canDeleteSubContentsList (false),
  44498. thread (thread_),
  44499. icon (0)
  44500. {
  44501. DirectoryContentsList::FileInfo fileInfo;
  44502. if (parentContentsList_ != 0
  44503. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  44504. {
  44505. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  44506. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  44507. isDirectory = fileInfo.isDirectory;
  44508. }
  44509. else
  44510. {
  44511. isDirectory = true;
  44512. }
  44513. }
  44514. ~FileListTreeItem() throw()
  44515. {
  44516. thread.removeTimeSliceClient (this);
  44517. clearSubItems();
  44518. ImageCache::release (icon);
  44519. if (canDeleteSubContentsList)
  44520. delete subContentsList;
  44521. }
  44522. bool mightContainSubItems() { return isDirectory; }
  44523. const String getUniqueName() const { return file.getFullPathName(); }
  44524. int getItemHeight() const { return 22; }
  44525. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  44526. void itemOpennessChanged (bool isNowOpen)
  44527. {
  44528. if (isNowOpen)
  44529. {
  44530. clearSubItems();
  44531. isDirectory = file.isDirectory();
  44532. if (isDirectory)
  44533. {
  44534. if (subContentsList == 0)
  44535. {
  44536. jassert (parentContentsList != 0);
  44537. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  44538. l->setDirectory (file, true, true);
  44539. setSubContentsList (l);
  44540. canDeleteSubContentsList = true;
  44541. }
  44542. changeListenerCallback (0);
  44543. }
  44544. }
  44545. }
  44546. void setSubContentsList (DirectoryContentsList* newList) throw()
  44547. {
  44548. jassert (subContentsList == 0);
  44549. subContentsList = newList;
  44550. newList->addChangeListener (this);
  44551. }
  44552. void changeListenerCallback (void*)
  44553. {
  44554. clearSubItems();
  44555. if (isOpen() && subContentsList != 0)
  44556. {
  44557. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  44558. {
  44559. FileListTreeItem* const item
  44560. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  44561. addSubItem (item);
  44562. }
  44563. }
  44564. }
  44565. void paintItem (Graphics& g, int width, int height)
  44566. {
  44567. if (file != File::nonexistent)
  44568. {
  44569. updateIcon (true);
  44570. if (icon == 0)
  44571. thread.addTimeSliceClient (this);
  44572. }
  44573. owner.getLookAndFeel()
  44574. .drawFileBrowserRow (g, width, height,
  44575. file.getFileName(),
  44576. icon,
  44577. fileSize, modTime,
  44578. isDirectory, isSelected(),
  44579. indexInContentsList);
  44580. }
  44581. void itemClicked (const MouseEvent& e)
  44582. {
  44583. owner.sendMouseClickMessage (file, e);
  44584. }
  44585. void itemDoubleClicked (const MouseEvent& e)
  44586. {
  44587. TreeViewItem::itemDoubleClicked (e);
  44588. owner.sendDoubleClickMessage (file);
  44589. }
  44590. void itemSelectionChanged (bool)
  44591. {
  44592. owner.sendSelectionChangeMessage();
  44593. }
  44594. bool useTimeSlice()
  44595. {
  44596. updateIcon (false);
  44597. thread.removeTimeSliceClient (this);
  44598. return false;
  44599. }
  44600. void handleAsyncUpdate()
  44601. {
  44602. owner.repaint();
  44603. }
  44604. const File file;
  44605. juce_UseDebuggingNewOperator
  44606. private:
  44607. FileTreeComponent& owner;
  44608. DirectoryContentsList* parentContentsList;
  44609. int indexInContentsList;
  44610. DirectoryContentsList* subContentsList;
  44611. bool isDirectory, canDeleteSubContentsList;
  44612. TimeSliceThread& thread;
  44613. Image* icon;
  44614. String fileSize;
  44615. String modTime;
  44616. void updateIcon (const bool onlyUpdateIfCached) throw()
  44617. {
  44618. if (icon == 0)
  44619. {
  44620. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44621. Image* im = ImageCache::getFromHashCode (hashCode);
  44622. if (im == 0 && ! onlyUpdateIfCached)
  44623. {
  44624. im = juce_createIconForFile (file);
  44625. if (im != 0)
  44626. ImageCache::addImageToCache (im, hashCode);
  44627. }
  44628. if (im != 0)
  44629. {
  44630. icon = im;
  44631. triggerAsyncUpdate();
  44632. }
  44633. }
  44634. }
  44635. };
  44636. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  44637. : DirectoryContentsDisplayComponent (listToShow)
  44638. {
  44639. FileListTreeItem* const root
  44640. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  44641. listToShow.getTimeSliceThread());
  44642. root->setSubContentsList (&listToShow);
  44643. setRootItemVisible (false);
  44644. setRootItem (root);
  44645. }
  44646. FileTreeComponent::~FileTreeComponent()
  44647. {
  44648. TreeViewItem* const root = getRootItem();
  44649. setRootItem (0);
  44650. delete root;
  44651. }
  44652. const File FileTreeComponent::getSelectedFile() const
  44653. {
  44654. return getSelectedFile (0);
  44655. }
  44656. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  44657. {
  44658. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  44659. if (item != 0)
  44660. return item->file;
  44661. return File::nonexistent;
  44662. }
  44663. void FileTreeComponent::scrollToTop()
  44664. {
  44665. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  44666. }
  44667. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  44668. {
  44669. dragAndDropDescription = description;
  44670. }
  44671. END_JUCE_NAMESPACE
  44672. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  44673. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  44674. BEGIN_JUCE_NAMESPACE
  44675. ImagePreviewComponent::ImagePreviewComponent()
  44676. : currentThumbnail (0)
  44677. {
  44678. }
  44679. ImagePreviewComponent::~ImagePreviewComponent()
  44680. {
  44681. delete currentThumbnail;
  44682. }
  44683. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  44684. {
  44685. const int availableW = proportionOfWidth (0.97f);
  44686. const int availableH = getHeight() - 13 * 4;
  44687. const double scale = jmin (1.0,
  44688. availableW / (double) w,
  44689. availableH / (double) h);
  44690. w = roundDoubleToInt (scale * w);
  44691. h = roundDoubleToInt (scale * h);
  44692. }
  44693. void ImagePreviewComponent::selectedFileChanged (const File& file)
  44694. {
  44695. if (fileToLoad != file)
  44696. {
  44697. fileToLoad = file;
  44698. startTimer (100);
  44699. }
  44700. }
  44701. void ImagePreviewComponent::timerCallback()
  44702. {
  44703. stopTimer();
  44704. deleteAndZero (currentThumbnail);
  44705. currentDetails = String::empty;
  44706. repaint();
  44707. FileInputStream* const in = fileToLoad.createInputStream();
  44708. if (in != 0)
  44709. {
  44710. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  44711. if (format != 0)
  44712. {
  44713. currentThumbnail = format->decodeImage (*in);
  44714. if (currentThumbnail != 0)
  44715. {
  44716. int w = currentThumbnail->getWidth();
  44717. int h = currentThumbnail->getHeight();
  44718. currentDetails
  44719. << fileToLoad.getFileName() << "\n"
  44720. << format->getFormatName() << "\n"
  44721. << w << " x " << h << " pixels\n"
  44722. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  44723. getThumbSize (w, h);
  44724. Image* const reduced = currentThumbnail->createCopy (w, h);
  44725. delete currentThumbnail;
  44726. currentThumbnail = reduced;
  44727. }
  44728. }
  44729. delete in;
  44730. }
  44731. }
  44732. void ImagePreviewComponent::paint (Graphics& g)
  44733. {
  44734. if (currentThumbnail != 0)
  44735. {
  44736. g.setFont (13.0f);
  44737. int w = currentThumbnail->getWidth();
  44738. int h = currentThumbnail->getHeight();
  44739. getThumbSize (w, h);
  44740. const int numLines = 4;
  44741. const int totalH = 13 * numLines + h + 4;
  44742. const int y = (getHeight() - totalH) / 2;
  44743. g.drawImageWithin (currentThumbnail,
  44744. (getWidth() - w) / 2, y, w, h,
  44745. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  44746. false);
  44747. g.drawFittedText (currentDetails,
  44748. 0, y + h + 4, getWidth(), 100,
  44749. Justification::centredTop, numLines);
  44750. }
  44751. }
  44752. END_JUCE_NAMESPACE
  44753. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  44754. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  44755. BEGIN_JUCE_NAMESPACE
  44756. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  44757. const String& description)
  44758. : FileFilter (description.isEmpty() ? wildcardPatterns
  44759. : (description + T(" (") + wildcardPatterns + T(")")))
  44760. {
  44761. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  44762. wildcards.trim();
  44763. wildcards.removeEmptyStrings();
  44764. // special case for *.*, because people use it to mean "any file", but it
  44765. // would actually ignore files with no extension.
  44766. for (int i = wildcards.size(); --i >= 0;)
  44767. if (wildcards[i] == T("*.*"))
  44768. wildcards.set (i, T("*"));
  44769. }
  44770. WildcardFileFilter::~WildcardFileFilter()
  44771. {
  44772. }
  44773. bool WildcardFileFilter::isFileSuitable (const File& file) const
  44774. {
  44775. const String filename (file.getFileName());
  44776. for (int i = wildcards.size(); --i >= 0;)
  44777. if (filename.matchesWildcard (wildcards[i], true))
  44778. return true;
  44779. return false;
  44780. }
  44781. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  44782. {
  44783. return true;
  44784. }
  44785. END_JUCE_NAMESPACE
  44786. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  44787. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44788. BEGIN_JUCE_NAMESPACE
  44789. KeyboardFocusTraverser::KeyboardFocusTraverser()
  44790. {
  44791. }
  44792. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  44793. {
  44794. }
  44795. // This will sort a set of components, so that they are ordered in terms of
  44796. // left-to-right and then top-to-bottom.
  44797. class ScreenPositionComparator
  44798. {
  44799. public:
  44800. ScreenPositionComparator() {}
  44801. static int compareElements (const Component* const first, const Component* const second) throw()
  44802. {
  44803. int explicitOrder1 = first->getExplicitFocusOrder();
  44804. if (explicitOrder1 <= 0)
  44805. explicitOrder1 = INT_MAX / 2;
  44806. int explicitOrder2 = second->getExplicitFocusOrder();
  44807. if (explicitOrder2 <= 0)
  44808. explicitOrder2 = INT_MAX / 2;
  44809. if (explicitOrder1 != explicitOrder2)
  44810. return explicitOrder1 - explicitOrder2;
  44811. const int diff = first->getY() - second->getY();
  44812. return (diff == 0) ? first->getX() - second->getX()
  44813. : diff;
  44814. }
  44815. };
  44816. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  44817. {
  44818. if (parent->getNumChildComponents() > 0)
  44819. {
  44820. Array <Component*> localComps;
  44821. ScreenPositionComparator comparator;
  44822. int i;
  44823. for (i = parent->getNumChildComponents(); --i >= 0;)
  44824. {
  44825. Component* const c = parent->getChildComponent (i);
  44826. if (c->isVisible() && c->isEnabled())
  44827. localComps.addSorted (comparator, c);
  44828. }
  44829. for (i = 0; i < localComps.size(); ++i)
  44830. {
  44831. Component* const c = localComps.getUnchecked (i);
  44832. if (c->getWantsKeyboardFocus())
  44833. comps.add (c);
  44834. if (! c->isFocusContainer())
  44835. findAllFocusableComponents (c, comps);
  44836. }
  44837. }
  44838. }
  44839. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  44840. {
  44841. Component* focusContainer = current->getParentComponent();
  44842. if (focusContainer != 0)
  44843. {
  44844. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  44845. focusContainer = focusContainer->getParentComponent();
  44846. if (focusContainer != 0)
  44847. {
  44848. Array <Component*> comps;
  44849. findAllFocusableComponents (focusContainer, comps);
  44850. if (comps.size() > 0)
  44851. {
  44852. const int index = comps.indexOf (current);
  44853. return comps [(index + comps.size() + delta) % comps.size()];
  44854. }
  44855. }
  44856. }
  44857. return 0;
  44858. }
  44859. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  44860. {
  44861. return getIncrementedComponent (current, 1);
  44862. }
  44863. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  44864. {
  44865. return getIncrementedComponent (current, -1);
  44866. }
  44867. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  44868. {
  44869. Array <Component*> comps;
  44870. if (parentComponent != 0)
  44871. findAllFocusableComponents (parentComponent, comps);
  44872. return comps.getFirst();
  44873. }
  44874. END_JUCE_NAMESPACE
  44875. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44876. /********* Start of inlined file: juce_KeyListener.cpp *********/
  44877. BEGIN_JUCE_NAMESPACE
  44878. bool KeyListener::keyStateChanged (const bool, Component*)
  44879. {
  44880. return false;
  44881. }
  44882. END_JUCE_NAMESPACE
  44883. /********* End of inlined file: juce_KeyListener.cpp *********/
  44884. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  44885. BEGIN_JUCE_NAMESPACE
  44886. // N.B. these two includes are put here deliberately to avoid problems with
  44887. // old GCCs failing on long include paths
  44888. const int maxKeys = 3;
  44889. class KeyMappingChangeButton : public Button
  44890. {
  44891. public:
  44892. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  44893. const CommandID commandID_,
  44894. const String& keyName,
  44895. const int keyNum_)
  44896. : Button (keyName),
  44897. owner (owner_),
  44898. commandID (commandID_),
  44899. keyNum (keyNum_)
  44900. {
  44901. setWantsKeyboardFocus (false);
  44902. setTriggeredOnMouseDown (keyNum >= 0);
  44903. if (keyNum_ < 0)
  44904. setTooltip (TRANS("adds a new key-mapping"));
  44905. else
  44906. setTooltip (TRANS("click to change this key-mapping"));
  44907. }
  44908. ~KeyMappingChangeButton()
  44909. {
  44910. }
  44911. void paintButton (Graphics& g, bool isOver, bool isDown)
  44912. {
  44913. if (keyNum >= 0)
  44914. {
  44915. if (isEnabled())
  44916. {
  44917. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  44918. g.fillAll (owner->textColour.withAlpha (alpha));
  44919. g.setOpacity (0.3f);
  44920. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  44921. }
  44922. g.setColour (owner->textColour);
  44923. g.setFont (getHeight() * 0.6f);
  44924. g.drawFittedText (getName(),
  44925. 3, 0, getWidth() - 6, getHeight(),
  44926. Justification::centred, 1);
  44927. }
  44928. else
  44929. {
  44930. const float thickness = 7.0f;
  44931. const float indent = 22.0f;
  44932. Path p;
  44933. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  44934. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  44935. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  44936. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  44937. p.setUsingNonZeroWinding (false);
  44938. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  44939. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  44940. }
  44941. if (hasKeyboardFocus (false))
  44942. {
  44943. g.setColour (owner->textColour.withAlpha (0.4f));
  44944. g.drawRect (0, 0, getWidth(), getHeight());
  44945. }
  44946. }
  44947. void clicked()
  44948. {
  44949. if (keyNum >= 0)
  44950. {
  44951. // existing key clicked..
  44952. PopupMenu m;
  44953. m.addItem (1, TRANS("change this key-mapping"));
  44954. m.addSeparator();
  44955. m.addItem (2, TRANS("remove this key-mapping"));
  44956. const int res = m.show();
  44957. if (res == 1)
  44958. {
  44959. owner->assignNewKey (commandID, keyNum);
  44960. }
  44961. else if (res == 2)
  44962. {
  44963. owner->getMappings()->removeKeyPress (commandID, keyNum);
  44964. }
  44965. }
  44966. else
  44967. {
  44968. // + button pressed..
  44969. owner->assignNewKey (commandID, -1);
  44970. }
  44971. }
  44972. void fitToContent (const int h) throw()
  44973. {
  44974. if (keyNum < 0)
  44975. {
  44976. setSize (h, h);
  44977. }
  44978. else
  44979. {
  44980. Font f (h * 0.6f);
  44981. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  44982. }
  44983. }
  44984. juce_UseDebuggingNewOperator
  44985. private:
  44986. KeyMappingEditorComponent* const owner;
  44987. const CommandID commandID;
  44988. const int keyNum;
  44989. KeyMappingChangeButton (const KeyMappingChangeButton&);
  44990. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  44991. };
  44992. class KeyMappingItemComponent : public Component
  44993. {
  44994. public:
  44995. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  44996. const CommandID commandID_)
  44997. : owner (owner_),
  44998. commandID (commandID_)
  44999. {
  45000. setInterceptsMouseClicks (false, true);
  45001. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  45002. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  45003. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  45004. {
  45005. KeyMappingChangeButton* const kb
  45006. = new KeyMappingChangeButton (owner_, commandID,
  45007. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  45008. kb->setEnabled (! isReadOnly);
  45009. addAndMakeVisible (kb);
  45010. }
  45011. KeyMappingChangeButton* const kb
  45012. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  45013. addChildComponent (kb);
  45014. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  45015. }
  45016. ~KeyMappingItemComponent()
  45017. {
  45018. deleteAllChildren();
  45019. }
  45020. void paint (Graphics& g)
  45021. {
  45022. g.setFont (getHeight() * 0.7f);
  45023. g.setColour (owner->textColour);
  45024. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  45025. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  45026. Justification::centredLeft, true);
  45027. }
  45028. void resized()
  45029. {
  45030. int x = getWidth() - 4;
  45031. for (int i = getNumChildComponents(); --i >= 0;)
  45032. {
  45033. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  45034. kb->fitToContent (getHeight() - 2);
  45035. kb->setTopRightPosition (x, 1);
  45036. x -= kb->getWidth() + 5;
  45037. }
  45038. }
  45039. juce_UseDebuggingNewOperator
  45040. private:
  45041. KeyMappingEditorComponent* const owner;
  45042. const CommandID commandID;
  45043. KeyMappingItemComponent (const KeyMappingItemComponent&);
  45044. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  45045. };
  45046. class KeyMappingTreeViewItem : public TreeViewItem
  45047. {
  45048. public:
  45049. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  45050. const CommandID commandID_)
  45051. : owner (owner_),
  45052. commandID (commandID_)
  45053. {
  45054. }
  45055. ~KeyMappingTreeViewItem()
  45056. {
  45057. }
  45058. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  45059. bool mightContainSubItems() { return false; }
  45060. int getItemHeight() const { return 20; }
  45061. Component* createItemComponent()
  45062. {
  45063. return new KeyMappingItemComponent (owner, commandID);
  45064. }
  45065. juce_UseDebuggingNewOperator
  45066. private:
  45067. KeyMappingEditorComponent* const owner;
  45068. const CommandID commandID;
  45069. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  45070. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  45071. };
  45072. class KeyCategoryTreeViewItem : public TreeViewItem
  45073. {
  45074. public:
  45075. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  45076. const String& name)
  45077. : owner (owner_),
  45078. categoryName (name)
  45079. {
  45080. }
  45081. ~KeyCategoryTreeViewItem()
  45082. {
  45083. }
  45084. const String getUniqueName() const { return categoryName + "_cat"; }
  45085. bool mightContainSubItems() { return true; }
  45086. int getItemHeight() const { return 28; }
  45087. void paintItem (Graphics& g, int width, int height)
  45088. {
  45089. g.setFont (height * 0.6f, Font::bold);
  45090. g.setColour (owner->textColour);
  45091. g.drawText (categoryName,
  45092. 2, 0, width - 2, height,
  45093. Justification::centredLeft, true);
  45094. }
  45095. void itemOpennessChanged (bool isNowOpen)
  45096. {
  45097. if (isNowOpen)
  45098. {
  45099. if (getNumSubItems() == 0)
  45100. {
  45101. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  45102. for (int i = 0; i < commands.size(); ++i)
  45103. {
  45104. if (owner->shouldCommandBeIncluded (commands[i]))
  45105. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  45106. }
  45107. }
  45108. }
  45109. else
  45110. {
  45111. clearSubItems();
  45112. }
  45113. }
  45114. juce_UseDebuggingNewOperator
  45115. private:
  45116. KeyMappingEditorComponent* owner;
  45117. String categoryName;
  45118. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  45119. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  45120. };
  45121. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  45122. const bool showResetToDefaultButton)
  45123. : mappings (mappingManager),
  45124. textColour (Colours::black)
  45125. {
  45126. jassert (mappingManager != 0); // can't be null!
  45127. mappingManager->addChangeListener (this);
  45128. setLinesDrawnForSubItems (false);
  45129. resetButton = 0;
  45130. if (showResetToDefaultButton)
  45131. {
  45132. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  45133. resetButton->addButtonListener (this);
  45134. }
  45135. addAndMakeVisible (tree = new TreeView());
  45136. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  45137. tree->setRootItemVisible (false);
  45138. tree->setDefaultOpenness (true);
  45139. tree->setRootItem (this);
  45140. }
  45141. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  45142. {
  45143. mappings->removeChangeListener (this);
  45144. deleteAllChildren();
  45145. }
  45146. bool KeyMappingEditorComponent::mightContainSubItems()
  45147. {
  45148. return true;
  45149. }
  45150. const String KeyMappingEditorComponent::getUniqueName() const
  45151. {
  45152. return T("keys");
  45153. }
  45154. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  45155. const Colour& textColour_)
  45156. {
  45157. backgroundColour = mainBackground;
  45158. textColour = textColour_;
  45159. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  45160. }
  45161. void KeyMappingEditorComponent::parentHierarchyChanged()
  45162. {
  45163. changeListenerCallback (0);
  45164. }
  45165. void KeyMappingEditorComponent::resized()
  45166. {
  45167. int h = getHeight();
  45168. if (resetButton != 0)
  45169. {
  45170. const int buttonHeight = 20;
  45171. h -= buttonHeight + 8;
  45172. int x = getWidth() - 8;
  45173. const int y = h + 6;
  45174. resetButton->changeWidthToFitText (buttonHeight);
  45175. resetButton->setTopRightPosition (x, y);
  45176. }
  45177. tree->setBounds (0, 0, getWidth(), h);
  45178. }
  45179. void KeyMappingEditorComponent::buttonClicked (Button* button)
  45180. {
  45181. if (button == resetButton)
  45182. {
  45183. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  45184. TRANS("Reset to defaults"),
  45185. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  45186. TRANS("Reset")))
  45187. {
  45188. mappings->resetToDefaultMappings();
  45189. }
  45190. }
  45191. }
  45192. void KeyMappingEditorComponent::changeListenerCallback (void*)
  45193. {
  45194. XmlElement* openness = tree->getOpennessState (true);
  45195. clearSubItems();
  45196. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  45197. for (int i = 0; i < categories.size(); ++i)
  45198. {
  45199. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  45200. int count = 0;
  45201. for (int j = 0; j < commands.size(); ++j)
  45202. if (shouldCommandBeIncluded (commands[j]))
  45203. ++count;
  45204. if (count > 0)
  45205. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  45206. }
  45207. if (openness != 0)
  45208. {
  45209. tree->restoreOpennessState (*openness);
  45210. delete openness;
  45211. }
  45212. }
  45213. class KeyEntryWindow : public AlertWindow
  45214. {
  45215. public:
  45216. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  45217. : AlertWindow (TRANS("New key-mapping"),
  45218. TRANS("Please press a key combination now..."),
  45219. AlertWindow::NoIcon),
  45220. owner (owner_)
  45221. {
  45222. addButton (TRANS("ok"), 1);
  45223. addButton (TRANS("cancel"), 0);
  45224. // (avoid return + escape keys getting processed by the buttons..)
  45225. for (int i = getNumChildComponents(); --i >= 0;)
  45226. getChildComponent (i)->setWantsKeyboardFocus (false);
  45227. setWantsKeyboardFocus (true);
  45228. grabKeyboardFocus();
  45229. }
  45230. ~KeyEntryWindow()
  45231. {
  45232. }
  45233. bool keyPressed (const KeyPress& key)
  45234. {
  45235. lastPress = key;
  45236. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  45237. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  45238. if (previousCommand != 0)
  45239. {
  45240. message << "\n\n"
  45241. << TRANS("(Currently assigned to \"")
  45242. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  45243. << "\")";
  45244. }
  45245. setMessage (message);
  45246. return true;
  45247. }
  45248. bool keyStateChanged (const bool)
  45249. {
  45250. return true;
  45251. }
  45252. KeyPress lastPress;
  45253. juce_UseDebuggingNewOperator
  45254. private:
  45255. KeyMappingEditorComponent* owner;
  45256. KeyEntryWindow (const KeyEntryWindow&);
  45257. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  45258. };
  45259. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  45260. {
  45261. KeyEntryWindow entryWindow (this);
  45262. if (entryWindow.runModalLoop() != 0)
  45263. {
  45264. entryWindow.setVisible (false);
  45265. if (entryWindow.lastPress.isValid())
  45266. {
  45267. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  45268. if (previousCommand != 0)
  45269. {
  45270. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  45271. TRANS("Change key-mapping"),
  45272. TRANS("This key is already assigned to the command \"")
  45273. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  45274. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  45275. TRANS("re-assign"),
  45276. TRANS("cancel")))
  45277. {
  45278. return;
  45279. }
  45280. }
  45281. mappings->removeKeyPress (entryWindow.lastPress);
  45282. if (index >= 0)
  45283. mappings->removeKeyPress (commandID, index);
  45284. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  45285. }
  45286. }
  45287. }
  45288. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  45289. {
  45290. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45291. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  45292. }
  45293. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  45294. {
  45295. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45296. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  45297. }
  45298. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  45299. {
  45300. return key.getTextDescription();
  45301. }
  45302. END_JUCE_NAMESPACE
  45303. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  45304. /********* Start of inlined file: juce_KeyPress.cpp *********/
  45305. BEGIN_JUCE_NAMESPACE
  45306. KeyPress::KeyPress() throw()
  45307. : keyCode (0),
  45308. mods (0),
  45309. textCharacter (0)
  45310. {
  45311. }
  45312. KeyPress::KeyPress (const int keyCode_,
  45313. const ModifierKeys& mods_,
  45314. const juce_wchar textCharacter_) throw()
  45315. : keyCode (keyCode_),
  45316. mods (mods_),
  45317. textCharacter (textCharacter_)
  45318. {
  45319. }
  45320. KeyPress::KeyPress (const int keyCode_) throw()
  45321. : keyCode (keyCode_),
  45322. textCharacter (0)
  45323. {
  45324. }
  45325. KeyPress::KeyPress (const KeyPress& other) throw()
  45326. : keyCode (other.keyCode),
  45327. mods (other.mods),
  45328. textCharacter (other.textCharacter)
  45329. {
  45330. }
  45331. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  45332. {
  45333. keyCode = other.keyCode;
  45334. mods = other.mods;
  45335. textCharacter = other.textCharacter;
  45336. return *this;
  45337. }
  45338. bool KeyPress::operator== (const KeyPress& other) const throw()
  45339. {
  45340. return mods.getRawFlags() == other.mods.getRawFlags()
  45341. && (textCharacter == other.textCharacter
  45342. || textCharacter == 0
  45343. || other.textCharacter == 0)
  45344. && (keyCode == other.keyCode
  45345. || (keyCode < 256
  45346. && other.keyCode < 256
  45347. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  45348. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  45349. }
  45350. bool KeyPress::operator!= (const KeyPress& other) const throw()
  45351. {
  45352. return ! operator== (other);
  45353. }
  45354. bool KeyPress::isCurrentlyDown() const throw()
  45355. {
  45356. return isKeyCurrentlyDown (keyCode)
  45357. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  45358. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  45359. }
  45360. struct KeyNameAndCode
  45361. {
  45362. const char* name;
  45363. int code;
  45364. };
  45365. static const KeyNameAndCode keyNameTranslations[] =
  45366. {
  45367. { "spacebar", KeyPress::spaceKey },
  45368. { "return", KeyPress::returnKey },
  45369. { "escape", KeyPress::escapeKey },
  45370. { "backspace", KeyPress::backspaceKey },
  45371. { "cursor left", KeyPress::leftKey },
  45372. { "cursor right", KeyPress::rightKey },
  45373. { "cursor up", KeyPress::upKey },
  45374. { "cursor down", KeyPress::downKey },
  45375. { "page up", KeyPress::pageUpKey },
  45376. { "page down", KeyPress::pageDownKey },
  45377. { "home", KeyPress::homeKey },
  45378. { "end", KeyPress::endKey },
  45379. { "delete", KeyPress::deleteKey },
  45380. { "insert", KeyPress::insertKey },
  45381. { "tab", KeyPress::tabKey },
  45382. { "play", KeyPress::playKey },
  45383. { "stop", KeyPress::stopKey },
  45384. { "fast forward", KeyPress::fastForwardKey },
  45385. { "rewind", KeyPress::rewindKey }
  45386. };
  45387. static const tchar* const numberPadPrefix = T("numpad ");
  45388. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  45389. {
  45390. int modifiers = 0;
  45391. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  45392. || desc.containsWholeWordIgnoreCase (T("control"))
  45393. || desc.containsWholeWordIgnoreCase (T("ctl")))
  45394. modifiers |= ModifierKeys::ctrlModifier;
  45395. if (desc.containsWholeWordIgnoreCase (T("shift"))
  45396. || desc.containsWholeWordIgnoreCase (T("shft")))
  45397. modifiers |= ModifierKeys::shiftModifier;
  45398. if (desc.containsWholeWordIgnoreCase (T("alt"))
  45399. || desc.containsWholeWordIgnoreCase (T("option")))
  45400. modifiers |= ModifierKeys::altModifier;
  45401. if (desc.containsWholeWordIgnoreCase (T("command"))
  45402. || desc.containsWholeWordIgnoreCase (T("cmd")))
  45403. modifiers |= ModifierKeys::commandModifier;
  45404. int key = 0;
  45405. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45406. {
  45407. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  45408. {
  45409. key = keyNameTranslations[i].code;
  45410. break;
  45411. }
  45412. }
  45413. if (key == 0)
  45414. {
  45415. // see if it's a numpad key..
  45416. if (desc.containsIgnoreCase (numberPadPrefix))
  45417. {
  45418. const tchar lastChar = desc.trimEnd().getLastCharacter();
  45419. if (lastChar >= T('0') && lastChar <= T('9'))
  45420. key = numberPad0 + lastChar - T('0');
  45421. else if (lastChar == T('+'))
  45422. key = numberPadAdd;
  45423. else if (lastChar == T('-'))
  45424. key = numberPadSubtract;
  45425. else if (lastChar == T('*'))
  45426. key = numberPadMultiply;
  45427. else if (lastChar == T('/'))
  45428. key = numberPadDivide;
  45429. else if (lastChar == T('.'))
  45430. key = numberPadDecimalPoint;
  45431. else if (lastChar == T('='))
  45432. key = numberPadEquals;
  45433. else if (desc.endsWith (T("separator")))
  45434. key = numberPadSeparator;
  45435. else if (desc.endsWith (T("delete")))
  45436. key = numberPadDelete;
  45437. }
  45438. if (key == 0)
  45439. {
  45440. // see if it's a function key..
  45441. for (int i = 1; i <= 12; ++i)
  45442. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  45443. key = F1Key + i - 1;
  45444. if (key == 0)
  45445. {
  45446. // give up and use the hex code..
  45447. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  45448. .toLowerCase()
  45449. .retainCharacters (T("0123456789abcdef"))
  45450. .getHexValue32();
  45451. if (hexCode > 0)
  45452. key = hexCode;
  45453. else
  45454. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  45455. }
  45456. }
  45457. }
  45458. return KeyPress (key, ModifierKeys (modifiers), 0);
  45459. }
  45460. const String KeyPress::getTextDescription() const throw()
  45461. {
  45462. String desc;
  45463. if (keyCode > 0)
  45464. {
  45465. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  45466. // want to store it as being a slash, not shift+whatever.
  45467. if (textCharacter == T('/'))
  45468. return "/";
  45469. if (mods.isCtrlDown())
  45470. desc << "ctrl + ";
  45471. if (mods.isShiftDown())
  45472. desc << "shift + ";
  45473. #if JUCE_MAC
  45474. // only do this on the mac, because on Windows ctrl and command are the same,
  45475. // and this would get confusing
  45476. if (mods.isCommandDown())
  45477. desc << "command + ";
  45478. if (mods.isAltDown())
  45479. desc << "option + ";
  45480. #else
  45481. if (mods.isAltDown())
  45482. desc << "alt + ";
  45483. #endif
  45484. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45485. if (keyCode == keyNameTranslations[i].code)
  45486. return desc + keyNameTranslations[i].name;
  45487. if (keyCode >= F1Key && keyCode <= F16Key)
  45488. desc << 'F' << (1 + keyCode - F1Key);
  45489. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  45490. desc << numberPadPrefix << (keyCode - numberPad0);
  45491. else if (keyCode >= 33 && keyCode < 176)
  45492. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  45493. else if (keyCode == numberPadAdd)
  45494. desc << numberPadPrefix << '+';
  45495. else if (keyCode == numberPadSubtract)
  45496. desc << numberPadPrefix << '-';
  45497. else if (keyCode == numberPadMultiply)
  45498. desc << numberPadPrefix << '*';
  45499. else if (keyCode == numberPadDivide)
  45500. desc << numberPadPrefix << '/';
  45501. else if (keyCode == numberPadSeparator)
  45502. desc << numberPadPrefix << "separator";
  45503. else if (keyCode == numberPadDecimalPoint)
  45504. desc << numberPadPrefix << '.';
  45505. else if (keyCode == numberPadDelete)
  45506. desc << numberPadPrefix << "delete";
  45507. else
  45508. desc << '#' << String::toHexString (keyCode);
  45509. }
  45510. return desc;
  45511. }
  45512. END_JUCE_NAMESPACE
  45513. /********* End of inlined file: juce_KeyPress.cpp *********/
  45514. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  45515. BEGIN_JUCE_NAMESPACE
  45516. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  45517. : commandManager (commandManager_)
  45518. {
  45519. // A manager is needed to get the descriptions of commands, and will be called when
  45520. // a command is invoked. So you can't leave this null..
  45521. jassert (commandManager_ != 0);
  45522. Desktop::getInstance().addFocusChangeListener (this);
  45523. }
  45524. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  45525. : commandManager (other.commandManager)
  45526. {
  45527. Desktop::getInstance().addFocusChangeListener (this);
  45528. }
  45529. KeyPressMappingSet::~KeyPressMappingSet()
  45530. {
  45531. Desktop::getInstance().removeFocusChangeListener (this);
  45532. }
  45533. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  45534. {
  45535. for (int i = 0; i < mappings.size(); ++i)
  45536. if (mappings.getUnchecked(i)->commandID == commandID)
  45537. return mappings.getUnchecked (i)->keypresses;
  45538. return Array <KeyPress> ();
  45539. }
  45540. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  45541. const KeyPress& newKeyPress,
  45542. int insertIndex) throw()
  45543. {
  45544. if (findCommandForKeyPress (newKeyPress) != commandID)
  45545. {
  45546. removeKeyPress (newKeyPress);
  45547. if (newKeyPress.isValid())
  45548. {
  45549. for (int i = mappings.size(); --i >= 0;)
  45550. {
  45551. if (mappings.getUnchecked(i)->commandID == commandID)
  45552. {
  45553. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  45554. sendChangeMessage (this);
  45555. return;
  45556. }
  45557. }
  45558. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45559. if (ci != 0)
  45560. {
  45561. CommandMapping* const cm = new CommandMapping();
  45562. cm->commandID = commandID;
  45563. cm->keypresses.add (newKeyPress);
  45564. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  45565. mappings.add (cm);
  45566. sendChangeMessage (this);
  45567. }
  45568. }
  45569. }
  45570. }
  45571. void KeyPressMappingSet::resetToDefaultMappings() throw()
  45572. {
  45573. mappings.clear();
  45574. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  45575. {
  45576. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  45577. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45578. {
  45579. addKeyPress (ci->commandID,
  45580. ci->defaultKeypresses.getReference (j));
  45581. }
  45582. }
  45583. sendChangeMessage (this);
  45584. }
  45585. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  45586. {
  45587. clearAllKeyPresses (commandID);
  45588. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45589. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45590. {
  45591. addKeyPress (ci->commandID,
  45592. ci->defaultKeypresses.getReference (j));
  45593. }
  45594. }
  45595. void KeyPressMappingSet::clearAllKeyPresses() throw()
  45596. {
  45597. if (mappings.size() > 0)
  45598. {
  45599. sendChangeMessage (this);
  45600. mappings.clear();
  45601. }
  45602. }
  45603. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  45604. {
  45605. for (int i = mappings.size(); --i >= 0;)
  45606. {
  45607. if (mappings.getUnchecked(i)->commandID == commandID)
  45608. {
  45609. mappings.remove (i);
  45610. sendChangeMessage (this);
  45611. }
  45612. }
  45613. }
  45614. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  45615. {
  45616. if (keypress.isValid())
  45617. {
  45618. for (int i = mappings.size(); --i >= 0;)
  45619. {
  45620. CommandMapping* const cm = mappings.getUnchecked(i);
  45621. for (int j = cm->keypresses.size(); --j >= 0;)
  45622. {
  45623. if (keypress == cm->keypresses [j])
  45624. {
  45625. cm->keypresses.remove (j);
  45626. sendChangeMessage (this);
  45627. }
  45628. }
  45629. }
  45630. }
  45631. }
  45632. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  45633. const int keyPressIndex) throw()
  45634. {
  45635. for (int i = mappings.size(); --i >= 0;)
  45636. {
  45637. if (mappings.getUnchecked(i)->commandID == commandID)
  45638. {
  45639. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  45640. sendChangeMessage (this);
  45641. break;
  45642. }
  45643. }
  45644. }
  45645. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  45646. {
  45647. for (int i = 0; i < mappings.size(); ++i)
  45648. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  45649. return mappings.getUnchecked(i)->commandID;
  45650. return 0;
  45651. }
  45652. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  45653. const KeyPress& keyPress) const throw()
  45654. {
  45655. for (int i = mappings.size(); --i >= 0;)
  45656. if (mappings.getUnchecked(i)->commandID == commandID)
  45657. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  45658. return false;
  45659. }
  45660. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  45661. const KeyPress& key,
  45662. const bool isKeyDown,
  45663. const int millisecsSinceKeyPressed,
  45664. Component* const originatingComponent) const
  45665. {
  45666. ApplicationCommandTarget::InvocationInfo info (commandID);
  45667. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  45668. info.isKeyDown = isKeyDown;
  45669. info.keyPress = key;
  45670. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  45671. info.originatingComponent = originatingComponent;
  45672. commandManager->invoke (info, false);
  45673. }
  45674. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  45675. {
  45676. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  45677. {
  45678. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  45679. {
  45680. // if the XML was created as a set of differences from the default mappings,
  45681. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  45682. resetToDefaultMappings();
  45683. }
  45684. else
  45685. {
  45686. // if the XML was created calling createXml (false), then we need to clear all
  45687. // the keys and treat the xml as describing the entire set of mappings.
  45688. clearAllKeyPresses();
  45689. }
  45690. forEachXmlChildElement (xmlVersion, map)
  45691. {
  45692. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  45693. if (commandId != 0)
  45694. {
  45695. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  45696. if (map->hasTagName (T("MAPPING")))
  45697. {
  45698. addKeyPress (commandId, key);
  45699. }
  45700. else if (map->hasTagName (T("UNMAPPING")))
  45701. {
  45702. if (containsMapping (commandId, key))
  45703. removeKeyPress (key);
  45704. }
  45705. }
  45706. }
  45707. return true;
  45708. }
  45709. return false;
  45710. }
  45711. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  45712. {
  45713. KeyPressMappingSet* defaultSet = 0;
  45714. if (saveDifferencesFromDefaultSet)
  45715. {
  45716. defaultSet = new KeyPressMappingSet (commandManager);
  45717. defaultSet->resetToDefaultMappings();
  45718. }
  45719. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  45720. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  45721. int i;
  45722. for (i = 0; i < mappings.size(); ++i)
  45723. {
  45724. const CommandMapping* const cm = mappings.getUnchecked(i);
  45725. for (int j = 0; j < cm->keypresses.size(); ++j)
  45726. {
  45727. if (defaultSet == 0
  45728. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45729. {
  45730. XmlElement* const map = new XmlElement (T("MAPPING"));
  45731. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45732. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45733. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45734. doc->addChildElement (map);
  45735. }
  45736. }
  45737. }
  45738. if (defaultSet != 0)
  45739. {
  45740. for (i = 0; i < defaultSet->mappings.size(); ++i)
  45741. {
  45742. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  45743. for (int j = 0; j < cm->keypresses.size(); ++j)
  45744. {
  45745. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45746. {
  45747. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  45748. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45749. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45750. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45751. doc->addChildElement (map);
  45752. }
  45753. }
  45754. }
  45755. delete defaultSet;
  45756. }
  45757. return doc;
  45758. }
  45759. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  45760. Component* originatingComponent)
  45761. {
  45762. bool used = false;
  45763. const CommandID commandID = findCommandForKeyPress (key);
  45764. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45765. if (ci != 0
  45766. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  45767. {
  45768. ApplicationCommandInfo info (0);
  45769. if (commandManager->getTargetForCommand (commandID, info) != 0
  45770. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  45771. {
  45772. invokeCommand (commandID, key, true, 0, originatingComponent);
  45773. used = true;
  45774. }
  45775. else
  45776. {
  45777. if (originatingComponent != 0)
  45778. originatingComponent->getLookAndFeel().playAlertSound();
  45779. }
  45780. }
  45781. return used;
  45782. }
  45783. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  45784. {
  45785. bool used = false;
  45786. const uint32 now = Time::getMillisecondCounter();
  45787. for (int i = mappings.size(); --i >= 0;)
  45788. {
  45789. CommandMapping* const cm = mappings.getUnchecked(i);
  45790. if (cm->wantsKeyUpDownCallbacks)
  45791. {
  45792. for (int j = cm->keypresses.size(); --j >= 0;)
  45793. {
  45794. const KeyPress key (cm->keypresses.getReference (j));
  45795. const bool isDown = key.isCurrentlyDown();
  45796. int keyPressEntryIndex = 0;
  45797. bool wasDown = false;
  45798. for (int k = keysDown.size(); --k >= 0;)
  45799. {
  45800. if (key == keysDown.getUnchecked(k)->key)
  45801. {
  45802. keyPressEntryIndex = k;
  45803. wasDown = true;
  45804. used = true;
  45805. break;
  45806. }
  45807. }
  45808. if (isDown != wasDown)
  45809. {
  45810. int millisecs = 0;
  45811. if (isDown)
  45812. {
  45813. KeyPressTime* const k = new KeyPressTime();
  45814. k->key = key;
  45815. k->timeWhenPressed = now;
  45816. keysDown.add (k);
  45817. }
  45818. else
  45819. {
  45820. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  45821. if (now > pressTime)
  45822. millisecs = now - pressTime;
  45823. keysDown.remove (keyPressEntryIndex);
  45824. }
  45825. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  45826. used = true;
  45827. }
  45828. }
  45829. }
  45830. }
  45831. return used;
  45832. }
  45833. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  45834. {
  45835. if (focusedComponent != 0)
  45836. focusedComponent->keyStateChanged (false);
  45837. }
  45838. END_JUCE_NAMESPACE
  45839. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  45840. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  45841. BEGIN_JUCE_NAMESPACE
  45842. ModifierKeys::ModifierKeys (const int flags_) throw()
  45843. : flags (flags_)
  45844. {
  45845. }
  45846. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  45847. : flags (other.flags)
  45848. {
  45849. }
  45850. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  45851. {
  45852. flags = other.flags;
  45853. return *this;
  45854. }
  45855. int ModifierKeys::currentModifierFlags = 0;
  45856. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  45857. {
  45858. return ModifierKeys (currentModifierFlags);
  45859. }
  45860. END_JUCE_NAMESPACE
  45861. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  45862. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  45863. BEGIN_JUCE_NAMESPACE
  45864. struct AnimationTask
  45865. {
  45866. AnimationTask (Component* const comp)
  45867. : component (comp),
  45868. watcher (comp)
  45869. {
  45870. }
  45871. Component* component;
  45872. ComponentDeletionWatcher watcher;
  45873. Rectangle destination;
  45874. int msElapsed, msTotal;
  45875. double startSpeed, midSpeed, endSpeed, lastProgress;
  45876. double left, top, right, bottom;
  45877. bool useTimeslice (const int elapsed)
  45878. {
  45879. if (watcher.hasBeenDeleted())
  45880. return false;
  45881. msElapsed += elapsed;
  45882. double newProgress = msElapsed / (double) msTotal;
  45883. if (newProgress >= 0 && newProgress < 1.0)
  45884. {
  45885. newProgress = timeToDistance (newProgress);
  45886. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  45887. jassert (newProgress >= lastProgress);
  45888. lastProgress = newProgress;
  45889. left += (destination.getX() - left) * delta;
  45890. top += (destination.getY() - top) * delta;
  45891. right += (destination.getRight() - right) * delta;
  45892. bottom += (destination.getBottom() - bottom) * delta;
  45893. if (delta < 1.0)
  45894. {
  45895. const Rectangle newBounds (roundDoubleToInt (left),
  45896. roundDoubleToInt (top),
  45897. roundDoubleToInt (right - left),
  45898. roundDoubleToInt (bottom - top));
  45899. if (newBounds != destination)
  45900. {
  45901. component->setBounds (newBounds);
  45902. return true;
  45903. }
  45904. }
  45905. }
  45906. component->setBounds (destination);
  45907. return false;
  45908. }
  45909. void moveToFinalDestination()
  45910. {
  45911. if (! watcher.hasBeenDeleted())
  45912. component->setBounds (destination);
  45913. }
  45914. private:
  45915. inline double timeToDistance (const double time) const
  45916. {
  45917. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  45918. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  45919. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  45920. }
  45921. };
  45922. ComponentAnimator::ComponentAnimator()
  45923. : lastTime (0)
  45924. {
  45925. }
  45926. ComponentAnimator::~ComponentAnimator()
  45927. {
  45928. cancelAllAnimations (false);
  45929. jassert (tasks.size() == 0);
  45930. }
  45931. void* ComponentAnimator::findTaskFor (Component* const component) const
  45932. {
  45933. for (int i = tasks.size(); --i >= 0;)
  45934. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  45935. return tasks.getUnchecked(i);
  45936. return 0;
  45937. }
  45938. void ComponentAnimator::animateComponent (Component* const component,
  45939. const Rectangle& finalPosition,
  45940. const int millisecondsToSpendMoving,
  45941. const double startSpeed,
  45942. const double endSpeed)
  45943. {
  45944. if (component != 0)
  45945. {
  45946. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  45947. if (at == 0)
  45948. {
  45949. at = new AnimationTask (component);
  45950. tasks.add (at);
  45951. sendChangeMessage (this);
  45952. }
  45953. at->msElapsed = 0;
  45954. at->lastProgress = 0;
  45955. at->msTotal = jmax (1, millisecondsToSpendMoving);
  45956. at->destination = finalPosition;
  45957. // the speeds must be 0 or greater!
  45958. jassert (startSpeed >= 0 && endSpeed >= 0)
  45959. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  45960. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  45961. at->midSpeed = invTotalDistance;
  45962. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  45963. at->left = component->getX();
  45964. at->top = component->getY();
  45965. at->right = component->getRight();
  45966. at->bottom = component->getBottom();
  45967. if (! isTimerRunning())
  45968. {
  45969. lastTime = Time::getMillisecondCounter();
  45970. startTimer (1000 / 50);
  45971. }
  45972. }
  45973. }
  45974. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  45975. {
  45976. for (int i = tasks.size(); --i >= 0;)
  45977. {
  45978. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45979. if (moveComponentsToTheirFinalPositions)
  45980. at->moveToFinalDestination();
  45981. delete at;
  45982. tasks.remove (i);
  45983. sendChangeMessage (this);
  45984. }
  45985. }
  45986. void ComponentAnimator::cancelAnimation (Component* const component,
  45987. const bool moveComponentToItsFinalPosition)
  45988. {
  45989. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45990. if (at != 0)
  45991. {
  45992. if (moveComponentToItsFinalPosition)
  45993. at->moveToFinalDestination();
  45994. tasks.removeValue (at);
  45995. delete at;
  45996. sendChangeMessage (this);
  45997. }
  45998. }
  45999. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  46000. {
  46001. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  46002. if (at != 0)
  46003. return at->destination;
  46004. else if (component != 0)
  46005. return component->getBounds();
  46006. return Rectangle();
  46007. }
  46008. bool ComponentAnimator::isAnimating (Component* component) const
  46009. {
  46010. return findTaskFor (component) != 0;
  46011. }
  46012. void ComponentAnimator::timerCallback()
  46013. {
  46014. const uint32 timeNow = Time::getMillisecondCounter();
  46015. if (lastTime == 0 || lastTime == timeNow)
  46016. lastTime = timeNow;
  46017. const int elapsed = timeNow - lastTime;
  46018. for (int i = tasks.size(); --i >= 0;)
  46019. {
  46020. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  46021. if (! at->useTimeslice (elapsed))
  46022. {
  46023. tasks.remove (i);
  46024. delete at;
  46025. sendChangeMessage (this);
  46026. }
  46027. }
  46028. lastTime = timeNow;
  46029. if (tasks.size() == 0)
  46030. stopTimer();
  46031. }
  46032. END_JUCE_NAMESPACE
  46033. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  46034. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  46035. BEGIN_JUCE_NAMESPACE
  46036. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  46037. : minW (0),
  46038. maxW (0x3fffffff),
  46039. minH (0),
  46040. maxH (0x3fffffff),
  46041. minOffTop (0),
  46042. minOffLeft (0),
  46043. minOffBottom (0),
  46044. minOffRight (0),
  46045. aspectRatio (0.0)
  46046. {
  46047. }
  46048. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  46049. {
  46050. }
  46051. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  46052. {
  46053. minW = minimumWidth;
  46054. }
  46055. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  46056. {
  46057. maxW = maximumWidth;
  46058. }
  46059. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  46060. {
  46061. minH = minimumHeight;
  46062. }
  46063. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  46064. {
  46065. maxH = maximumHeight;
  46066. }
  46067. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  46068. {
  46069. jassert (maxW >= minimumWidth);
  46070. jassert (maxH >= minimumHeight);
  46071. jassert (minimumWidth > 0 && minimumHeight > 0);
  46072. minW = minimumWidth;
  46073. minH = minimumHeight;
  46074. if (minW > maxW)
  46075. maxW = minW;
  46076. if (minH > maxH)
  46077. maxH = minH;
  46078. }
  46079. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  46080. {
  46081. jassert (maximumWidth >= minW);
  46082. jassert (maximumHeight >= minH);
  46083. jassert (maximumWidth > 0 && maximumHeight > 0);
  46084. maxW = jmax (minW, maximumWidth);
  46085. maxH = jmax (minH, maximumHeight);
  46086. }
  46087. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  46088. const int minimumHeight,
  46089. const int maximumWidth,
  46090. const int maximumHeight) throw()
  46091. {
  46092. jassert (maximumWidth >= minimumWidth);
  46093. jassert (maximumHeight >= minimumHeight);
  46094. jassert (maximumWidth > 0 && maximumHeight > 0);
  46095. jassert (minimumWidth > 0 && minimumHeight > 0);
  46096. minW = jmax (0, minimumWidth);
  46097. minH = jmax (0, minimumHeight);
  46098. maxW = jmax (minW, maximumWidth);
  46099. maxH = jmax (minH, maximumHeight);
  46100. }
  46101. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  46102. const int minimumWhenOffTheLeft,
  46103. const int minimumWhenOffTheBottom,
  46104. const int minimumWhenOffTheRight) throw()
  46105. {
  46106. minOffTop = minimumWhenOffTheTop;
  46107. minOffLeft = minimumWhenOffTheLeft;
  46108. minOffBottom = minimumWhenOffTheBottom;
  46109. minOffRight = minimumWhenOffTheRight;
  46110. }
  46111. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  46112. {
  46113. aspectRatio = jmax (0.0, widthOverHeight);
  46114. }
  46115. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  46116. {
  46117. return aspectRatio;
  46118. }
  46119. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  46120. int x, int y, int w, int h,
  46121. const bool isStretchingTop,
  46122. const bool isStretchingLeft,
  46123. const bool isStretchingBottom,
  46124. const bool isStretchingRight)
  46125. {
  46126. jassert (component != 0);
  46127. Rectangle limits;
  46128. Component* const p = component->getParentComponent();
  46129. if (p == 0)
  46130. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  46131. else
  46132. limits.setSize (p->getWidth(), p->getHeight());
  46133. if (component->isOnDesktop())
  46134. {
  46135. ComponentPeer* const peer = component->getPeer();
  46136. const BorderSize border (peer->getFrameSize());
  46137. x -= border.getLeft();
  46138. y -= border.getTop();
  46139. w += border.getLeftAndRight();
  46140. h += border.getTopAndBottom();
  46141. checkBounds (x, y, w, h,
  46142. border.addedTo (component->getBounds()), limits,
  46143. isStretchingTop, isStretchingLeft,
  46144. isStretchingBottom, isStretchingRight);
  46145. x += border.getLeft();
  46146. y += border.getTop();
  46147. w -= border.getLeftAndRight();
  46148. h -= border.getTopAndBottom();
  46149. }
  46150. else
  46151. {
  46152. checkBounds (x, y, w, h,
  46153. component->getBounds(), limits,
  46154. isStretchingTop, isStretchingLeft,
  46155. isStretchingBottom, isStretchingRight);
  46156. }
  46157. applyBoundsToComponent (component, x, y, w, h);
  46158. }
  46159. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  46160. {
  46161. setBoundsForComponent (component,
  46162. component->getX(), component->getY(),
  46163. component->getWidth(), component->getHeight(),
  46164. false, false, false, false);
  46165. }
  46166. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  46167. int x, int y, int w, int h)
  46168. {
  46169. component->setBounds (x, y, w, h);
  46170. }
  46171. void ComponentBoundsConstrainer::resizeStart()
  46172. {
  46173. }
  46174. void ComponentBoundsConstrainer::resizeEnd()
  46175. {
  46176. }
  46177. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  46178. const Rectangle& old,
  46179. const Rectangle& limits,
  46180. const bool isStretchingTop,
  46181. const bool isStretchingLeft,
  46182. const bool isStretchingBottom,
  46183. const bool isStretchingRight)
  46184. {
  46185. // constrain the size if it's being stretched..
  46186. if (isStretchingLeft)
  46187. {
  46188. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  46189. w = old.getRight() - x;
  46190. }
  46191. if (isStretchingRight)
  46192. {
  46193. w = jlimit (minW, maxW, w);
  46194. }
  46195. if (isStretchingTop)
  46196. {
  46197. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  46198. h = old.getBottom() - y;
  46199. }
  46200. if (isStretchingBottom)
  46201. {
  46202. h = jlimit (minH, maxH, h);
  46203. }
  46204. // constrain the aspect ratio if one has been specified..
  46205. if (aspectRatio > 0.0 && w > 0 && h > 0)
  46206. {
  46207. bool adjustWidth;
  46208. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46209. {
  46210. adjustWidth = true;
  46211. }
  46212. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46213. {
  46214. adjustWidth = false;
  46215. }
  46216. else
  46217. {
  46218. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  46219. const double newRatio = fabs (w / (double) h);
  46220. adjustWidth = (oldRatio > newRatio);
  46221. }
  46222. if (adjustWidth)
  46223. {
  46224. w = roundDoubleToInt (h * aspectRatio);
  46225. if (w > maxW || w < minW)
  46226. {
  46227. w = jlimit (minW, maxW, w);
  46228. h = roundDoubleToInt (w / aspectRatio);
  46229. }
  46230. }
  46231. else
  46232. {
  46233. h = roundDoubleToInt (w / aspectRatio);
  46234. if (h > maxH || h < minH)
  46235. {
  46236. h = jlimit (minH, maxH, h);
  46237. w = roundDoubleToInt (h * aspectRatio);
  46238. }
  46239. }
  46240. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46241. {
  46242. x = old.getX() + (old.getWidth() - w) / 2;
  46243. }
  46244. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46245. {
  46246. y = old.getY() + (old.getHeight() - h) / 2;
  46247. }
  46248. else
  46249. {
  46250. if (isStretchingLeft)
  46251. x = old.getRight() - w;
  46252. if (isStretchingTop)
  46253. y = old.getBottom() - h;
  46254. }
  46255. }
  46256. // ...and constrain the position if limits have been set for that.
  46257. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  46258. {
  46259. if (minOffTop > 0)
  46260. {
  46261. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  46262. if (y < limit)
  46263. {
  46264. if (isStretchingTop)
  46265. h -= (limit - y);
  46266. y = limit;
  46267. }
  46268. }
  46269. if (minOffLeft > 0)
  46270. {
  46271. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  46272. if (x < limit)
  46273. {
  46274. if (isStretchingLeft)
  46275. w -= (limit - x);
  46276. x = limit;
  46277. }
  46278. }
  46279. if (minOffBottom > 0)
  46280. {
  46281. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  46282. if (y > limit)
  46283. {
  46284. if (isStretchingBottom)
  46285. h += (limit - y);
  46286. else
  46287. y = limit;
  46288. }
  46289. }
  46290. if (minOffRight > 0)
  46291. {
  46292. const int limit = limits.getRight() - jmin (minOffRight, w);
  46293. if (x > limit)
  46294. {
  46295. if (isStretchingRight)
  46296. w += (limit - x);
  46297. else
  46298. x = limit;
  46299. }
  46300. }
  46301. }
  46302. jassert (w >= 0 && h >= 0);
  46303. }
  46304. END_JUCE_NAMESPACE
  46305. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  46306. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46307. BEGIN_JUCE_NAMESPACE
  46308. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  46309. : component (component_),
  46310. lastPeer (0),
  46311. registeredParentComps (4),
  46312. reentrant (false)
  46313. {
  46314. jassert (component != 0); // can't use this with a null pointer..
  46315. #ifdef JUCE_DEBUG
  46316. deletionWatcher = new ComponentDeletionWatcher (component_);
  46317. #endif
  46318. component->addComponentListener (this);
  46319. registerWithParentComps();
  46320. }
  46321. ComponentMovementWatcher::~ComponentMovementWatcher()
  46322. {
  46323. component->removeComponentListener (this);
  46324. unregister();
  46325. #ifdef JUCE_DEBUG
  46326. delete deletionWatcher;
  46327. #endif
  46328. }
  46329. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  46330. {
  46331. #ifdef JUCE_DEBUG
  46332. // agh! don't delete the target component without deleting this object first!
  46333. jassert (! deletionWatcher->hasBeenDeleted());
  46334. #endif
  46335. if (! reentrant)
  46336. {
  46337. reentrant = true;
  46338. ComponentPeer* const peer = component->getPeer();
  46339. if (peer != lastPeer)
  46340. {
  46341. ComponentDeletionWatcher watcher (component);
  46342. componentPeerChanged();
  46343. if (watcher.hasBeenDeleted())
  46344. return;
  46345. lastPeer = peer;
  46346. }
  46347. unregister();
  46348. registerWithParentComps();
  46349. reentrant = false;
  46350. componentMovedOrResized (*component, true, true);
  46351. }
  46352. }
  46353. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  46354. {
  46355. #ifdef JUCE_DEBUG
  46356. // agh! don't delete the target component without deleting this object first!
  46357. jassert (! deletionWatcher->hasBeenDeleted());
  46358. #endif
  46359. if (wasMoved)
  46360. {
  46361. int x = 0, y = 0;
  46362. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  46363. wasMoved = (lastX != x || lastY != y);
  46364. lastX = x;
  46365. lastY = y;
  46366. }
  46367. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  46368. lastWidth = component->getWidth();
  46369. lastHeight = component->getHeight();
  46370. if (wasMoved || wasResized)
  46371. componentMovedOrResized (wasMoved, wasResized);
  46372. }
  46373. void ComponentMovementWatcher::registerWithParentComps() throw()
  46374. {
  46375. Component* p = component->getParentComponent();
  46376. while (p != 0)
  46377. {
  46378. p->addComponentListener (this);
  46379. registeredParentComps.add (p);
  46380. p = p->getParentComponent();
  46381. }
  46382. }
  46383. void ComponentMovementWatcher::unregister() throw()
  46384. {
  46385. for (int i = registeredParentComps.size(); --i >= 0;)
  46386. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  46387. registeredParentComps.clear();
  46388. }
  46389. END_JUCE_NAMESPACE
  46390. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46391. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  46392. BEGIN_JUCE_NAMESPACE
  46393. GroupComponent::GroupComponent (const String& componentName,
  46394. const String& labelText)
  46395. : Component (componentName),
  46396. text (labelText),
  46397. justification (Justification::left)
  46398. {
  46399. setInterceptsMouseClicks (false, true);
  46400. }
  46401. GroupComponent::~GroupComponent()
  46402. {
  46403. }
  46404. void GroupComponent::setText (const String& newText) throw()
  46405. {
  46406. if (text != newText)
  46407. {
  46408. text = newText;
  46409. repaint();
  46410. }
  46411. }
  46412. const String GroupComponent::getText() const throw()
  46413. {
  46414. return text;
  46415. }
  46416. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  46417. {
  46418. if (justification.getFlags() != newJustification.getFlags())
  46419. {
  46420. justification = newJustification;
  46421. repaint();
  46422. }
  46423. }
  46424. void GroupComponent::paint (Graphics& g)
  46425. {
  46426. getLookAndFeel()
  46427. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  46428. text, justification,
  46429. *this);
  46430. }
  46431. void GroupComponent::enablementChanged()
  46432. {
  46433. repaint();
  46434. }
  46435. void GroupComponent::colourChanged()
  46436. {
  46437. repaint();
  46438. }
  46439. END_JUCE_NAMESPACE
  46440. /********* End of inlined file: juce_GroupComponent.cpp *********/
  46441. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  46442. BEGIN_JUCE_NAMESPACE
  46443. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  46444. : DocumentWindow (String::empty, backgroundColour,
  46445. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  46446. {
  46447. }
  46448. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  46449. {
  46450. }
  46451. void MultiDocumentPanelWindow::maximiseButtonPressed()
  46452. {
  46453. MultiDocumentPanel* const owner = getOwner();
  46454. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46455. if (owner != 0)
  46456. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  46457. }
  46458. void MultiDocumentPanelWindow::closeButtonPressed()
  46459. {
  46460. MultiDocumentPanel* const owner = getOwner();
  46461. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46462. if (owner != 0)
  46463. owner->closeDocument (getContentComponent(), true);
  46464. }
  46465. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  46466. {
  46467. DocumentWindow::activeWindowStatusChanged();
  46468. updateOrder();
  46469. }
  46470. void MultiDocumentPanelWindow::broughtToFront()
  46471. {
  46472. DocumentWindow::broughtToFront();
  46473. updateOrder();
  46474. }
  46475. void MultiDocumentPanelWindow::updateOrder()
  46476. {
  46477. MultiDocumentPanel* const owner = getOwner();
  46478. if (owner != 0)
  46479. owner->updateOrder();
  46480. }
  46481. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  46482. {
  46483. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46484. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46485. }
  46486. class MDITabbedComponentInternal : public TabbedComponent
  46487. {
  46488. public:
  46489. MDITabbedComponentInternal()
  46490. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  46491. {
  46492. }
  46493. ~MDITabbedComponentInternal()
  46494. {
  46495. }
  46496. void currentTabChanged (const int, const String&)
  46497. {
  46498. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46499. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46500. if (owner != 0)
  46501. owner->updateOrder();
  46502. }
  46503. };
  46504. MultiDocumentPanel::MultiDocumentPanel()
  46505. : mode (MaximisedWindowsWithTabs),
  46506. tabComponent (0),
  46507. backgroundColour (Colours::lightblue),
  46508. maximumNumDocuments (0),
  46509. numDocsBeforeTabsUsed (0)
  46510. {
  46511. setOpaque (true);
  46512. }
  46513. MultiDocumentPanel::~MultiDocumentPanel()
  46514. {
  46515. closeAllDocuments (false);
  46516. }
  46517. static bool shouldDeleteComp (Component* const c)
  46518. {
  46519. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  46520. }
  46521. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  46522. {
  46523. while (components.size() > 0)
  46524. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  46525. return false;
  46526. return true;
  46527. }
  46528. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  46529. {
  46530. return new MultiDocumentPanelWindow (backgroundColour);
  46531. }
  46532. void MultiDocumentPanel::addWindow (Component* component)
  46533. {
  46534. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  46535. dw->setResizable (true, false);
  46536. dw->setContentComponent (component, false, true);
  46537. dw->setName (component->getName());
  46538. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  46539. int x = 4;
  46540. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  46541. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  46542. x += 16;
  46543. dw->setTopLeftPosition (x, x);
  46544. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  46545. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  46546. addAndMakeVisible (dw);
  46547. dw->toFront (true);
  46548. }
  46549. bool MultiDocumentPanel::addDocument (Component* const component,
  46550. const Colour& docColour,
  46551. const bool deleteWhenRemoved)
  46552. {
  46553. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  46554. // with a frame-within-a-frame! Just pass in the bare content component.
  46555. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  46556. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  46557. return false;
  46558. components.add (component);
  46559. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  46560. component->setComponentProperty (T("mdiDocumentBkg_"), docColour);
  46561. component->addComponentListener (this);
  46562. if (mode == FloatingWindows)
  46563. {
  46564. if (isFullscreenWhenOneDocument())
  46565. {
  46566. if (components.size() == 1)
  46567. {
  46568. addAndMakeVisible (component);
  46569. }
  46570. else
  46571. {
  46572. if (components.size() == 2)
  46573. addWindow (components.getFirst());
  46574. addWindow (component);
  46575. }
  46576. }
  46577. else
  46578. {
  46579. addWindow (component);
  46580. }
  46581. }
  46582. else
  46583. {
  46584. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  46585. {
  46586. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  46587. Array <Component*> temp (components);
  46588. for (int i = 0; i < temp.size(); ++i)
  46589. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  46590. resized();
  46591. }
  46592. else
  46593. {
  46594. if (tabComponent != 0)
  46595. tabComponent->addTab (component->getName(), docColour, component, false);
  46596. else
  46597. addAndMakeVisible (component);
  46598. }
  46599. setActiveDocument (component);
  46600. }
  46601. resized();
  46602. activeDocumentChanged();
  46603. return true;
  46604. }
  46605. bool MultiDocumentPanel::closeDocument (Component* component,
  46606. const bool checkItsOkToCloseFirst)
  46607. {
  46608. if (components.contains (component))
  46609. {
  46610. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  46611. return false;
  46612. component->removeComponentListener (this);
  46613. const bool shouldDelete = shouldDeleteComp (component);
  46614. component->removeComponentProperty (T("mdiDocumentDelete_"));
  46615. component->removeComponentProperty (T("mdiDocumentBkg_"));
  46616. if (mode == FloatingWindows)
  46617. {
  46618. for (int i = getNumChildComponents(); --i >= 0;)
  46619. {
  46620. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46621. if (dw != 0 && dw->getContentComponent() == component)
  46622. {
  46623. dw->setContentComponent (0, false);
  46624. delete dw;
  46625. break;
  46626. }
  46627. }
  46628. if (shouldDelete)
  46629. delete component;
  46630. components.removeValue (component);
  46631. if (isFullscreenWhenOneDocument() && components.size() == 1)
  46632. {
  46633. for (int i = getNumChildComponents(); --i >= 0;)
  46634. {
  46635. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46636. if (dw != 0)
  46637. {
  46638. dw->setContentComponent (0, false);
  46639. delete dw;
  46640. }
  46641. }
  46642. addAndMakeVisible (components.getFirst());
  46643. }
  46644. }
  46645. else
  46646. {
  46647. jassert (components.indexOf (component) >= 0);
  46648. if (tabComponent != 0)
  46649. {
  46650. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46651. if (tabComponent->getTabContentComponent (i) == component)
  46652. tabComponent->removeTab (i);
  46653. }
  46654. else
  46655. {
  46656. removeChildComponent (component);
  46657. }
  46658. if (shouldDelete)
  46659. delete component;
  46660. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  46661. deleteAndZero (tabComponent);
  46662. components.removeValue (component);
  46663. if (components.size() > 0 && tabComponent == 0)
  46664. addAndMakeVisible (components.getFirst());
  46665. }
  46666. resized();
  46667. activeDocumentChanged();
  46668. }
  46669. else
  46670. {
  46671. jassertfalse
  46672. }
  46673. return true;
  46674. }
  46675. int MultiDocumentPanel::getNumDocuments() const throw()
  46676. {
  46677. return components.size();
  46678. }
  46679. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  46680. {
  46681. return components [index];
  46682. }
  46683. Component* MultiDocumentPanel::getActiveDocument() const throw()
  46684. {
  46685. if (mode == FloatingWindows)
  46686. {
  46687. for (int i = getNumChildComponents(); --i >= 0;)
  46688. {
  46689. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46690. if (dw != 0 && dw->isActiveWindow())
  46691. return dw->getContentComponent();
  46692. }
  46693. }
  46694. return components.getLast();
  46695. }
  46696. void MultiDocumentPanel::setActiveDocument (Component* component)
  46697. {
  46698. if (mode == FloatingWindows)
  46699. {
  46700. component = getContainerComp (component);
  46701. if (component != 0)
  46702. component->toFront (true);
  46703. }
  46704. else if (tabComponent != 0)
  46705. {
  46706. jassert (components.indexOf (component) >= 0);
  46707. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46708. {
  46709. if (tabComponent->getTabContentComponent (i) == component)
  46710. {
  46711. tabComponent->setCurrentTabIndex (i);
  46712. break;
  46713. }
  46714. }
  46715. }
  46716. else
  46717. {
  46718. component->grabKeyboardFocus();
  46719. }
  46720. }
  46721. void MultiDocumentPanel::activeDocumentChanged()
  46722. {
  46723. }
  46724. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  46725. {
  46726. maximumNumDocuments = newNumber;
  46727. }
  46728. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  46729. {
  46730. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  46731. }
  46732. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  46733. {
  46734. return numDocsBeforeTabsUsed != 0;
  46735. }
  46736. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  46737. {
  46738. if (mode != newLayoutMode)
  46739. {
  46740. mode = newLayoutMode;
  46741. if (mode == FloatingWindows)
  46742. {
  46743. deleteAndZero (tabComponent);
  46744. }
  46745. else
  46746. {
  46747. for (int i = getNumChildComponents(); --i >= 0;)
  46748. {
  46749. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46750. if (dw != 0)
  46751. {
  46752. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  46753. dw->setContentComponent (0, false);
  46754. delete dw;
  46755. }
  46756. }
  46757. }
  46758. resized();
  46759. const Array <Component*> tempComps (components);
  46760. components.clear();
  46761. for (int i = 0; i < tempComps.size(); ++i)
  46762. {
  46763. Component* const c = tempComps.getUnchecked(i);
  46764. addDocument (c,
  46765. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  46766. shouldDeleteComp (c));
  46767. }
  46768. }
  46769. }
  46770. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  46771. {
  46772. if (backgroundColour != newBackgroundColour)
  46773. {
  46774. backgroundColour = newBackgroundColour;
  46775. setOpaque (newBackgroundColour.isOpaque());
  46776. repaint();
  46777. }
  46778. }
  46779. void MultiDocumentPanel::paint (Graphics& g)
  46780. {
  46781. g.fillAll (backgroundColour);
  46782. }
  46783. void MultiDocumentPanel::resized()
  46784. {
  46785. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  46786. {
  46787. for (int i = getNumChildComponents(); --i >= 0;)
  46788. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  46789. }
  46790. setWantsKeyboardFocus (components.size() == 0);
  46791. }
  46792. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  46793. {
  46794. if (mode == FloatingWindows)
  46795. {
  46796. for (int i = 0; i < getNumChildComponents(); ++i)
  46797. {
  46798. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46799. if (dw != 0 && dw->getContentComponent() == c)
  46800. {
  46801. c = dw;
  46802. break;
  46803. }
  46804. }
  46805. }
  46806. return c;
  46807. }
  46808. void MultiDocumentPanel::componentNameChanged (Component&)
  46809. {
  46810. if (mode == FloatingWindows)
  46811. {
  46812. for (int i = 0; i < getNumChildComponents(); ++i)
  46813. {
  46814. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46815. if (dw != 0)
  46816. dw->setName (dw->getContentComponent()->getName());
  46817. }
  46818. }
  46819. else if (tabComponent != 0)
  46820. {
  46821. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46822. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  46823. }
  46824. }
  46825. void MultiDocumentPanel::updateOrder()
  46826. {
  46827. const Array <Component*> oldList (components);
  46828. if (mode == FloatingWindows)
  46829. {
  46830. components.clear();
  46831. for (int i = 0; i < getNumChildComponents(); ++i)
  46832. {
  46833. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46834. if (dw != 0)
  46835. components.add (dw->getContentComponent());
  46836. }
  46837. }
  46838. else
  46839. {
  46840. if (tabComponent != 0)
  46841. {
  46842. Component* const current = tabComponent->getCurrentContentComponent();
  46843. if (current != 0)
  46844. {
  46845. components.removeValue (current);
  46846. components.add (current);
  46847. }
  46848. }
  46849. }
  46850. if (components != oldList)
  46851. activeDocumentChanged();
  46852. }
  46853. END_JUCE_NAMESPACE
  46854. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  46855. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  46856. BEGIN_JUCE_NAMESPACE
  46857. const int zoneL = 1;
  46858. const int zoneR = 2;
  46859. const int zoneT = 4;
  46860. const int zoneB = 8;
  46861. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  46862. ComponentBoundsConstrainer* const constrainer_)
  46863. : component (componentToResize),
  46864. constrainer (constrainer_),
  46865. borderSize (5),
  46866. mouseZone (0)
  46867. {
  46868. }
  46869. ResizableBorderComponent::~ResizableBorderComponent()
  46870. {
  46871. }
  46872. void ResizableBorderComponent::paint (Graphics& g)
  46873. {
  46874. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  46875. }
  46876. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  46877. {
  46878. updateMouseZone (e);
  46879. }
  46880. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  46881. {
  46882. updateMouseZone (e);
  46883. }
  46884. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  46885. {
  46886. if (component->isValidComponent())
  46887. {
  46888. updateMouseZone (e);
  46889. originalX = component->getX();
  46890. originalY = component->getY();
  46891. originalW = component->getWidth();
  46892. originalH = component->getHeight();
  46893. if (constrainer != 0)
  46894. constrainer->resizeStart();
  46895. }
  46896. else
  46897. {
  46898. jassertfalse
  46899. }
  46900. }
  46901. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  46902. {
  46903. if (! component->isValidComponent())
  46904. {
  46905. jassertfalse
  46906. return;
  46907. }
  46908. int x = originalX;
  46909. int y = originalY;
  46910. int w = originalW;
  46911. int h = originalH;
  46912. const int dx = e.getDistanceFromDragStartX();
  46913. const int dy = e.getDistanceFromDragStartY();
  46914. if ((mouseZone & zoneL) != 0)
  46915. {
  46916. x += dx;
  46917. w -= dx;
  46918. }
  46919. if ((mouseZone & zoneT) != 0)
  46920. {
  46921. y += dy;
  46922. h -= dy;
  46923. }
  46924. if ((mouseZone & zoneR) != 0)
  46925. w += dx;
  46926. if ((mouseZone & zoneB) != 0)
  46927. h += dy;
  46928. if (constrainer != 0)
  46929. constrainer->setBoundsForComponent (component,
  46930. x, y, w, h,
  46931. (mouseZone & zoneT) != 0,
  46932. (mouseZone & zoneL) != 0,
  46933. (mouseZone & zoneB) != 0,
  46934. (mouseZone & zoneR) != 0);
  46935. else
  46936. component->setBounds (x, y, w, h);
  46937. }
  46938. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  46939. {
  46940. if (constrainer != 0)
  46941. constrainer->resizeEnd();
  46942. }
  46943. bool ResizableBorderComponent::hitTest (int x, int y)
  46944. {
  46945. return x < borderSize.getLeft()
  46946. || x >= getWidth() - borderSize.getRight()
  46947. || y < borderSize.getTop()
  46948. || y >= getHeight() - borderSize.getBottom();
  46949. }
  46950. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  46951. {
  46952. if (borderSize != newBorderSize)
  46953. {
  46954. borderSize = newBorderSize;
  46955. repaint();
  46956. }
  46957. }
  46958. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  46959. {
  46960. return borderSize;
  46961. }
  46962. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  46963. {
  46964. int newZone = 0;
  46965. if (ResizableBorderComponent::hitTest (e.x, e.y))
  46966. {
  46967. if (e.x < jmax (borderSize.getLeft(),
  46968. proportionOfWidth (0.1f),
  46969. jmin (10, proportionOfWidth (0.33f))))
  46970. newZone |= zoneL;
  46971. else if (e.x >= jmin (getWidth() - borderSize.getRight(),
  46972. proportionOfWidth (0.9f),
  46973. getWidth() - jmin (10, proportionOfWidth (0.33f))))
  46974. newZone |= zoneR;
  46975. if (e.y < jmax (borderSize.getTop(),
  46976. proportionOfHeight (0.1f),
  46977. jmin (10, proportionOfHeight (0.33f))))
  46978. newZone |= zoneT;
  46979. else if (e.y >= jmin (getHeight() - borderSize.getBottom(),
  46980. proportionOfHeight (0.9f),
  46981. getHeight() - jmin (10, proportionOfHeight (0.33f))))
  46982. newZone |= zoneB;
  46983. }
  46984. if (mouseZone != newZone)
  46985. {
  46986. mouseZone = newZone;
  46987. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  46988. switch (newZone)
  46989. {
  46990. case (zoneL | zoneT):
  46991. mc = MouseCursor::TopLeftCornerResizeCursor;
  46992. break;
  46993. case zoneT:
  46994. mc = MouseCursor::TopEdgeResizeCursor;
  46995. break;
  46996. case (zoneR | zoneT):
  46997. mc = MouseCursor::TopRightCornerResizeCursor;
  46998. break;
  46999. case zoneL:
  47000. mc = MouseCursor::LeftEdgeResizeCursor;
  47001. break;
  47002. case zoneR:
  47003. mc = MouseCursor::RightEdgeResizeCursor;
  47004. break;
  47005. case (zoneL | zoneB):
  47006. mc = MouseCursor::BottomLeftCornerResizeCursor;
  47007. break;
  47008. case zoneB:
  47009. mc = MouseCursor::BottomEdgeResizeCursor;
  47010. break;
  47011. case (zoneR | zoneB):
  47012. mc = MouseCursor::BottomRightCornerResizeCursor;
  47013. break;
  47014. default:
  47015. break;
  47016. }
  47017. setMouseCursor (mc);
  47018. }
  47019. }
  47020. END_JUCE_NAMESPACE
  47021. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  47022. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  47023. BEGIN_JUCE_NAMESPACE
  47024. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  47025. ComponentBoundsConstrainer* const constrainer_)
  47026. : component (componentToResize),
  47027. constrainer (constrainer_)
  47028. {
  47029. setRepaintsOnMouseActivity (true);
  47030. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  47031. }
  47032. ResizableCornerComponent::~ResizableCornerComponent()
  47033. {
  47034. }
  47035. void ResizableCornerComponent::paint (Graphics& g)
  47036. {
  47037. getLookAndFeel()
  47038. .drawCornerResizer (g, getWidth(), getHeight(),
  47039. isMouseOverOrDragging(),
  47040. isMouseButtonDown());
  47041. }
  47042. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  47043. {
  47044. if (component->isValidComponent())
  47045. {
  47046. originalX = component->getX();
  47047. originalY = component->getY();
  47048. originalW = component->getWidth();
  47049. originalH = component->getHeight();
  47050. if (constrainer != 0)
  47051. constrainer->resizeStart();
  47052. }
  47053. else
  47054. {
  47055. jassertfalse
  47056. }
  47057. }
  47058. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  47059. {
  47060. if (! component->isValidComponent())
  47061. {
  47062. jassertfalse
  47063. return;
  47064. }
  47065. int x = originalX;
  47066. int y = originalY;
  47067. int w = originalW + e.getDistanceFromDragStartX();
  47068. int h = originalH + e.getDistanceFromDragStartY();
  47069. if (constrainer != 0)
  47070. constrainer->setBoundsForComponent (component, x, y, w, h,
  47071. false, false, true, true);
  47072. else
  47073. component->setBounds (x, y, w, h);
  47074. }
  47075. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  47076. {
  47077. if (constrainer != 0)
  47078. constrainer->resizeStart();
  47079. }
  47080. bool ResizableCornerComponent::hitTest (int x, int y)
  47081. {
  47082. if (getWidth() <= 0)
  47083. return false;
  47084. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  47085. return y >= yAtX - getHeight() / 4;
  47086. }
  47087. END_JUCE_NAMESPACE
  47088. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  47089. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  47090. BEGIN_JUCE_NAMESPACE
  47091. class ScrollbarButton : public Button
  47092. {
  47093. public:
  47094. int direction;
  47095. ScrollbarButton (const int direction_,
  47096. ScrollBar& owner_) throw()
  47097. : Button (String::empty),
  47098. direction (direction_),
  47099. owner (owner_)
  47100. {
  47101. setWantsKeyboardFocus (false);
  47102. }
  47103. ~ScrollbarButton()
  47104. {
  47105. }
  47106. void paintButton (Graphics& g,
  47107. bool isMouseOver,
  47108. bool isMouseDown)
  47109. {
  47110. getLookAndFeel()
  47111. .drawScrollbarButton (g, owner,
  47112. getWidth(), getHeight(),
  47113. direction,
  47114. owner.isVertical(),
  47115. isMouseOver, isMouseDown);
  47116. }
  47117. void clicked()
  47118. {
  47119. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  47120. }
  47121. juce_UseDebuggingNewOperator
  47122. private:
  47123. ScrollBar& owner;
  47124. ScrollbarButton (const ScrollbarButton&);
  47125. const ScrollbarButton& operator= (const ScrollbarButton&);
  47126. };
  47127. ScrollBar::ScrollBar (const bool vertical_,
  47128. const bool buttonsAreVisible)
  47129. : minimum (0.0),
  47130. maximum (1.0),
  47131. rangeStart (0.0),
  47132. rangeSize (0.1),
  47133. singleStepSize (0.1),
  47134. thumbAreaStart (0),
  47135. thumbAreaSize (0),
  47136. thumbStart (0),
  47137. thumbSize (0),
  47138. initialDelayInMillisecs (100),
  47139. repeatDelayInMillisecs (50),
  47140. minimumDelayInMillisecs (10),
  47141. vertical (vertical_),
  47142. isDraggingThumb (false),
  47143. alwaysVisible (false),
  47144. upButton (0),
  47145. downButton (0),
  47146. listeners (2)
  47147. {
  47148. setButtonVisibility (buttonsAreVisible);
  47149. setRepaintsOnMouseActivity (true);
  47150. setFocusContainer (true);
  47151. }
  47152. ScrollBar::~ScrollBar()
  47153. {
  47154. deleteAllChildren();
  47155. }
  47156. void ScrollBar::setRangeLimits (const double newMinimum,
  47157. const double newMaximum) throw()
  47158. {
  47159. minimum = newMinimum;
  47160. maximum = newMaximum;
  47161. jassert (maximum >= minimum); // these can't be the wrong way round!
  47162. setCurrentRangeStart (rangeStart);
  47163. updateThumbPosition();
  47164. }
  47165. void ScrollBar::setCurrentRange (double newStart,
  47166. double newSize) throw()
  47167. {
  47168. newSize = jlimit (0.0, maximum - minimum, newSize);
  47169. newStart = jlimit (minimum, maximum - newSize, newStart);
  47170. if (rangeStart != newStart
  47171. || rangeSize != newSize)
  47172. {
  47173. rangeStart = newStart;
  47174. rangeSize = newSize;
  47175. updateThumbPosition();
  47176. triggerAsyncUpdate();
  47177. }
  47178. }
  47179. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  47180. {
  47181. setCurrentRange (newStart, rangeSize);
  47182. }
  47183. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  47184. {
  47185. singleStepSize = newSingleStepSize;
  47186. }
  47187. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  47188. {
  47189. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  47190. }
  47191. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  47192. {
  47193. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  47194. }
  47195. void ScrollBar::scrollToTop() throw()
  47196. {
  47197. setCurrentRangeStart (minimum);
  47198. }
  47199. void ScrollBar::scrollToBottom() throw()
  47200. {
  47201. setCurrentRangeStart (maximum - rangeSize);
  47202. }
  47203. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  47204. const int repeatDelayInMillisecs_,
  47205. const int minimumDelayInMillisecs_) throw()
  47206. {
  47207. initialDelayInMillisecs = initialDelayInMillisecs_;
  47208. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  47209. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  47210. if (upButton != 0)
  47211. {
  47212. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47213. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47214. }
  47215. }
  47216. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  47217. {
  47218. jassert (listener != 0);
  47219. if (listener != 0)
  47220. listeners.add (listener);
  47221. }
  47222. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  47223. {
  47224. listeners.removeValue (listener);
  47225. }
  47226. void ScrollBar::handleAsyncUpdate()
  47227. {
  47228. const double value = getCurrentRangeStart();
  47229. for (int i = listeners.size(); --i >= 0;)
  47230. {
  47231. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  47232. i = jmin (i, listeners.size());
  47233. }
  47234. }
  47235. void ScrollBar::updateThumbPosition() throw()
  47236. {
  47237. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  47238. : thumbAreaSize);
  47239. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47240. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  47241. if (newThumbSize > thumbAreaSize)
  47242. newThumbSize = thumbAreaSize;
  47243. int newThumbStart = thumbAreaStart;
  47244. if (maximum - minimum > rangeSize)
  47245. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  47246. / ((maximum - minimum) - rangeSize));
  47247. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  47248. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  47249. {
  47250. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  47251. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  47252. if (vertical)
  47253. repaint (0, repaintStart, getWidth(), repaintSize);
  47254. else
  47255. repaint (repaintStart, 0, repaintSize, getHeight());
  47256. thumbStart = newThumbStart;
  47257. thumbSize = newThumbSize;
  47258. }
  47259. }
  47260. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  47261. {
  47262. if (vertical != shouldBeVertical)
  47263. {
  47264. vertical = shouldBeVertical;
  47265. if (upButton != 0)
  47266. {
  47267. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  47268. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  47269. }
  47270. updateThumbPosition();
  47271. }
  47272. }
  47273. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  47274. {
  47275. deleteAndZero (upButton);
  47276. deleteAndZero (downButton);
  47277. if (buttonsAreVisible)
  47278. {
  47279. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  47280. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  47281. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47282. }
  47283. updateThumbPosition();
  47284. }
  47285. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  47286. {
  47287. alwaysVisible = ! shouldHideWhenFullRange;
  47288. updateThumbPosition();
  47289. }
  47290. void ScrollBar::paint (Graphics& g)
  47291. {
  47292. if (thumbAreaSize > 0)
  47293. {
  47294. LookAndFeel& lf = getLookAndFeel();
  47295. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  47296. ? thumbSize : 0;
  47297. if (vertical)
  47298. {
  47299. lf.drawScrollbar (g, *this,
  47300. 0, thumbAreaStart,
  47301. getWidth(), thumbAreaSize,
  47302. vertical,
  47303. thumbStart, thumb,
  47304. isMouseOver(), isMouseButtonDown());
  47305. }
  47306. else
  47307. {
  47308. lf.drawScrollbar (g, *this,
  47309. thumbAreaStart, 0,
  47310. thumbAreaSize, getHeight(),
  47311. vertical,
  47312. thumbStart, thumb,
  47313. isMouseOver(), isMouseButtonDown());
  47314. }
  47315. }
  47316. }
  47317. void ScrollBar::lookAndFeelChanged()
  47318. {
  47319. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  47320. }
  47321. void ScrollBar::resized()
  47322. {
  47323. const int length = ((vertical) ? getHeight() : getWidth());
  47324. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  47325. : 0;
  47326. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47327. {
  47328. thumbAreaStart = length >> 1;
  47329. thumbAreaSize = 0;
  47330. }
  47331. else
  47332. {
  47333. thumbAreaStart = buttonSize;
  47334. thumbAreaSize = length - (buttonSize << 1);
  47335. }
  47336. if (upButton != 0)
  47337. {
  47338. if (vertical)
  47339. {
  47340. upButton->setBounds (0, 0, getWidth(), buttonSize);
  47341. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  47342. }
  47343. else
  47344. {
  47345. upButton->setBounds (0, 0, buttonSize, getHeight());
  47346. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  47347. }
  47348. }
  47349. updateThumbPosition();
  47350. }
  47351. void ScrollBar::mouseDown (const MouseEvent& e)
  47352. {
  47353. isDraggingThumb = false;
  47354. lastMousePos = vertical ? e.y : e.x;
  47355. dragStartMousePos = lastMousePos;
  47356. dragStartRange = rangeStart;
  47357. if (dragStartMousePos < thumbStart)
  47358. {
  47359. moveScrollbarInPages (-1);
  47360. startTimer (400);
  47361. }
  47362. else if (dragStartMousePos >= thumbStart + thumbSize)
  47363. {
  47364. moveScrollbarInPages (1);
  47365. startTimer (400);
  47366. }
  47367. else
  47368. {
  47369. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47370. && (thumbAreaSize > thumbSize);
  47371. }
  47372. }
  47373. void ScrollBar::mouseDrag (const MouseEvent& e)
  47374. {
  47375. if (isDraggingThumb)
  47376. {
  47377. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  47378. setCurrentRangeStart (dragStartRange
  47379. + deltaPixels * ((maximum - minimum) - rangeSize)
  47380. / (thumbAreaSize - thumbSize));
  47381. }
  47382. else
  47383. {
  47384. lastMousePos = (vertical) ? e.y : e.x;
  47385. }
  47386. }
  47387. void ScrollBar::mouseUp (const MouseEvent&)
  47388. {
  47389. isDraggingThumb = false;
  47390. stopTimer();
  47391. repaint();
  47392. }
  47393. void ScrollBar::mouseWheelMove (const MouseEvent&,
  47394. float wheelIncrementX,
  47395. float wheelIncrementY)
  47396. {
  47397. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  47398. if (increment < 0)
  47399. increment = jmin (increment * 10.0f, -1.0f);
  47400. else if (increment > 0)
  47401. increment = jmax (increment * 10.0f, 1.0f);
  47402. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  47403. }
  47404. void ScrollBar::timerCallback()
  47405. {
  47406. if (isMouseButtonDown())
  47407. {
  47408. startTimer (40);
  47409. if (lastMousePos < thumbStart)
  47410. setCurrentRangeStart (rangeStart - rangeSize);
  47411. else if (lastMousePos > thumbStart + thumbSize)
  47412. setCurrentRangeStart (rangeStart + rangeSize);
  47413. }
  47414. else
  47415. {
  47416. stopTimer();
  47417. }
  47418. }
  47419. bool ScrollBar::keyPressed (const KeyPress& key)
  47420. {
  47421. if (! isVisible())
  47422. return false;
  47423. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  47424. moveScrollbarInSteps (-1);
  47425. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  47426. moveScrollbarInSteps (1);
  47427. else if (key.isKeyCode (KeyPress::pageUpKey))
  47428. moveScrollbarInPages (-1);
  47429. else if (key.isKeyCode (KeyPress::pageDownKey))
  47430. moveScrollbarInPages (1);
  47431. else if (key.isKeyCode (KeyPress::homeKey))
  47432. scrollToTop();
  47433. else if (key.isKeyCode (KeyPress::endKey))
  47434. scrollToBottom();
  47435. else
  47436. return false;
  47437. return true;
  47438. }
  47439. END_JUCE_NAMESPACE
  47440. /********* End of inlined file: juce_ScrollBar.cpp *********/
  47441. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  47442. BEGIN_JUCE_NAMESPACE
  47443. StretchableLayoutManager::StretchableLayoutManager()
  47444. : totalSize (0)
  47445. {
  47446. }
  47447. StretchableLayoutManager::~StretchableLayoutManager()
  47448. {
  47449. }
  47450. void StretchableLayoutManager::clearAllItems()
  47451. {
  47452. items.clear();
  47453. totalSize = 0;
  47454. }
  47455. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  47456. const double minimumSize,
  47457. const double maximumSize,
  47458. const double preferredSize)
  47459. {
  47460. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  47461. if (layout == 0)
  47462. {
  47463. layout = new ItemLayoutProperties();
  47464. layout->itemIndex = itemIndex;
  47465. int i;
  47466. for (i = 0; i < items.size(); ++i)
  47467. if (items.getUnchecked (i)->itemIndex > itemIndex)
  47468. break;
  47469. items.insert (i, layout);
  47470. }
  47471. layout->minSize = minimumSize;
  47472. layout->maxSize = maximumSize;
  47473. layout->preferredSize = preferredSize;
  47474. layout->currentSize = 0;
  47475. }
  47476. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  47477. double& minimumSize,
  47478. double& maximumSize,
  47479. double& preferredSize) const
  47480. {
  47481. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47482. if (layout != 0)
  47483. {
  47484. minimumSize = layout->minSize;
  47485. maximumSize = layout->maxSize;
  47486. preferredSize = layout->preferredSize;
  47487. return true;
  47488. }
  47489. return false;
  47490. }
  47491. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  47492. {
  47493. totalSize = newTotalSize;
  47494. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  47495. }
  47496. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  47497. {
  47498. int pos = 0;
  47499. for (int i = 0; i < itemIndex; ++i)
  47500. {
  47501. const ItemLayoutProperties* const layout = getInfoFor (i);
  47502. if (layout != 0)
  47503. pos += layout->currentSize;
  47504. }
  47505. return pos;
  47506. }
  47507. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  47508. {
  47509. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47510. if (layout != 0)
  47511. return layout->currentSize;
  47512. return 0;
  47513. }
  47514. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  47515. {
  47516. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47517. if (layout != 0)
  47518. return -layout->currentSize / (double) totalSize;
  47519. return 0;
  47520. }
  47521. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  47522. int newPosition)
  47523. {
  47524. for (int i = items.size(); --i >= 0;)
  47525. {
  47526. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  47527. if (layout->itemIndex == itemIndex)
  47528. {
  47529. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  47530. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  47531. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  47532. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  47533. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  47534. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  47535. endPos += layout->currentSize;
  47536. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  47537. updatePrefSizesToMatchCurrentPositions();
  47538. break;
  47539. }
  47540. }
  47541. }
  47542. void StretchableLayoutManager::layOutComponents (Component** const components,
  47543. int numComponents,
  47544. int x, int y, int w, int h,
  47545. const bool vertically,
  47546. const bool resizeOtherDimension)
  47547. {
  47548. setTotalSize (vertically ? h : w);
  47549. int pos = vertically ? y : x;
  47550. for (int i = 0; i < numComponents; ++i)
  47551. {
  47552. const ItemLayoutProperties* const layout = getInfoFor (i);
  47553. if (layout != 0)
  47554. {
  47555. Component* const c = components[i];
  47556. if (c != 0)
  47557. {
  47558. if (i == numComponents - 1)
  47559. {
  47560. // if it's the last item, crop it to exactly fit the available space..
  47561. if (resizeOtherDimension)
  47562. {
  47563. if (vertically)
  47564. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  47565. else
  47566. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  47567. }
  47568. else
  47569. {
  47570. if (vertically)
  47571. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  47572. else
  47573. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  47574. }
  47575. }
  47576. else
  47577. {
  47578. if (resizeOtherDimension)
  47579. {
  47580. if (vertically)
  47581. c->setBounds (x, pos, w, layout->currentSize);
  47582. else
  47583. c->setBounds (pos, y, layout->currentSize, h);
  47584. }
  47585. else
  47586. {
  47587. if (vertically)
  47588. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  47589. else
  47590. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  47591. }
  47592. }
  47593. }
  47594. pos += layout->currentSize;
  47595. }
  47596. }
  47597. }
  47598. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  47599. {
  47600. for (int i = items.size(); --i >= 0;)
  47601. if (items.getUnchecked(i)->itemIndex == itemIndex)
  47602. return items.getUnchecked(i);
  47603. return 0;
  47604. }
  47605. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  47606. const int endIndex,
  47607. const int availableSpace,
  47608. int startPos)
  47609. {
  47610. // calculate the total sizes
  47611. int i;
  47612. double totalIdealSize = 0.0;
  47613. int totalMinimums = 0;
  47614. for (i = startIndex; i < endIndex; ++i)
  47615. {
  47616. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47617. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  47618. totalMinimums += layout->currentSize;
  47619. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  47620. }
  47621. if (totalIdealSize <= 0)
  47622. totalIdealSize = 1.0;
  47623. // now calc the best sizes..
  47624. int extraSpace = availableSpace - totalMinimums;
  47625. while (extraSpace > 0)
  47626. {
  47627. int numWantingMoreSpace = 0;
  47628. int numHavingTakenExtraSpace = 0;
  47629. // first figure out how many comps want a slice of the extra space..
  47630. for (i = startIndex; i < endIndex; ++i)
  47631. {
  47632. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47633. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47634. const int bestSize = jlimit (layout->currentSize,
  47635. jmax (layout->currentSize,
  47636. sizeToRealSize (layout->maxSize, totalSize)),
  47637. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47638. if (bestSize > layout->currentSize)
  47639. ++numWantingMoreSpace;
  47640. }
  47641. // ..share out the extra space..
  47642. for (i = startIndex; i < endIndex; ++i)
  47643. {
  47644. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47645. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47646. int bestSize = jlimit (layout->currentSize,
  47647. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  47648. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47649. const int extraWanted = bestSize - layout->currentSize;
  47650. if (extraWanted > 0)
  47651. {
  47652. const int extraAllowed = jmin (extraWanted,
  47653. extraSpace / jmax (1, numWantingMoreSpace));
  47654. if (extraAllowed > 0)
  47655. {
  47656. ++numHavingTakenExtraSpace;
  47657. --numWantingMoreSpace;
  47658. layout->currentSize += extraAllowed;
  47659. extraSpace -= extraAllowed;
  47660. }
  47661. }
  47662. }
  47663. if (numHavingTakenExtraSpace <= 0)
  47664. break;
  47665. }
  47666. // ..and calculate the end position
  47667. for (i = startIndex; i < endIndex; ++i)
  47668. {
  47669. ItemLayoutProperties* const layout = items.getUnchecked(i);
  47670. startPos += layout->currentSize;
  47671. }
  47672. return startPos;
  47673. }
  47674. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  47675. const int endIndex) const
  47676. {
  47677. int totalMinimums = 0;
  47678. for (int i = startIndex; i < endIndex; ++i)
  47679. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  47680. return totalMinimums;
  47681. }
  47682. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  47683. {
  47684. int totalMaximums = 0;
  47685. for (int i = startIndex; i < endIndex; ++i)
  47686. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  47687. return totalMaximums;
  47688. }
  47689. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  47690. {
  47691. for (int i = 0; i < items.size(); ++i)
  47692. {
  47693. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47694. layout->preferredSize
  47695. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  47696. : getItemCurrentAbsoluteSize (i);
  47697. }
  47698. }
  47699. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  47700. {
  47701. if (size < 0)
  47702. size *= -totalSpace;
  47703. return roundDoubleToInt (size);
  47704. }
  47705. END_JUCE_NAMESPACE
  47706. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  47707. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47708. BEGIN_JUCE_NAMESPACE
  47709. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  47710. const int itemIndex_,
  47711. const bool isVertical_)
  47712. : layout (layout_),
  47713. itemIndex (itemIndex_),
  47714. isVertical (isVertical_)
  47715. {
  47716. setRepaintsOnMouseActivity (true);
  47717. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  47718. : MouseCursor::UpDownResizeCursor));
  47719. }
  47720. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  47721. {
  47722. }
  47723. void StretchableLayoutResizerBar::paint (Graphics& g)
  47724. {
  47725. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  47726. getWidth(), getHeight(),
  47727. isVertical,
  47728. isMouseOver(),
  47729. isMouseButtonDown());
  47730. }
  47731. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  47732. {
  47733. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  47734. }
  47735. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  47736. {
  47737. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  47738. : e.getDistanceFromDragStartY());
  47739. layout->setItemPosition (itemIndex, desiredPos);
  47740. hasBeenMoved();
  47741. }
  47742. void StretchableLayoutResizerBar::hasBeenMoved()
  47743. {
  47744. if (getParentComponent() != 0)
  47745. getParentComponent()->resized();
  47746. }
  47747. END_JUCE_NAMESPACE
  47748. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47749. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  47750. BEGIN_JUCE_NAMESPACE
  47751. StretchableObjectResizer::StretchableObjectResizer()
  47752. {
  47753. }
  47754. StretchableObjectResizer::~StretchableObjectResizer()
  47755. {
  47756. }
  47757. void StretchableObjectResizer::addItem (const double size,
  47758. const double minSize, const double maxSize,
  47759. const int order)
  47760. {
  47761. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  47762. Item* const item = new Item();
  47763. item->size = size;
  47764. item->minSize = minSize;
  47765. item->maxSize = maxSize;
  47766. item->order = order;
  47767. items.add (item);
  47768. }
  47769. double StretchableObjectResizer::getItemSize (const int index) const throw()
  47770. {
  47771. const Item* const it = items [index];
  47772. return it != 0 ? it->size : 0;
  47773. }
  47774. void StretchableObjectResizer::resizeToFit (const double targetSize)
  47775. {
  47776. int order = 0;
  47777. for (;;)
  47778. {
  47779. double currentSize = 0;
  47780. double minSize = 0;
  47781. double maxSize = 0;
  47782. int nextHighestOrder = INT_MAX;
  47783. for (int i = 0; i < items.size(); ++i)
  47784. {
  47785. const Item* const it = items.getUnchecked(i);
  47786. currentSize += it->size;
  47787. if (it->order <= order)
  47788. {
  47789. minSize += it->minSize;
  47790. maxSize += it->maxSize;
  47791. }
  47792. else
  47793. {
  47794. minSize += it->size;
  47795. maxSize += it->size;
  47796. nextHighestOrder = jmin (nextHighestOrder, it->order);
  47797. }
  47798. }
  47799. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  47800. if (thisIterationTarget >= currentSize)
  47801. {
  47802. const double availableExtraSpace = maxSize - currentSize;
  47803. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  47804. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  47805. for (int i = 0; i < items.size(); ++i)
  47806. {
  47807. Item* const it = items.getUnchecked(i);
  47808. if (it->order <= order)
  47809. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  47810. }
  47811. }
  47812. else
  47813. {
  47814. const double amountOfSlack = currentSize - minSize;
  47815. const double targetAmountOfSlack = thisIterationTarget - minSize;
  47816. const double scale = targetAmountOfSlack / amountOfSlack;
  47817. for (int i = 0; i < items.size(); ++i)
  47818. {
  47819. Item* const it = items.getUnchecked(i);
  47820. if (it->order <= order)
  47821. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  47822. }
  47823. }
  47824. if (nextHighestOrder < INT_MAX)
  47825. order = nextHighestOrder;
  47826. else
  47827. break;
  47828. }
  47829. }
  47830. END_JUCE_NAMESPACE
  47831. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  47832. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  47833. BEGIN_JUCE_NAMESPACE
  47834. TabBarButton::TabBarButton (const String& name,
  47835. TabbedButtonBar* const owner_,
  47836. const int index)
  47837. : Button (name),
  47838. owner (owner_),
  47839. tabIndex (index),
  47840. overlapPixels (0)
  47841. {
  47842. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  47843. setComponentEffect (&shadow);
  47844. setWantsKeyboardFocus (false);
  47845. }
  47846. TabBarButton::~TabBarButton()
  47847. {
  47848. }
  47849. void TabBarButton::paintButton (Graphics& g,
  47850. bool isMouseOverButton,
  47851. bool isButtonDown)
  47852. {
  47853. int x, y, w, h;
  47854. getActiveArea (x, y, w, h);
  47855. g.setOrigin (x, y);
  47856. getLookAndFeel()
  47857. .drawTabButton (g, w, h,
  47858. owner->getTabBackgroundColour (tabIndex),
  47859. tabIndex, getButtonText(), *this,
  47860. owner->getOrientation(),
  47861. isMouseOverButton, isButtonDown,
  47862. getToggleState());
  47863. }
  47864. void TabBarButton::clicked (const ModifierKeys& mods)
  47865. {
  47866. if (mods.isPopupMenu())
  47867. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  47868. else
  47869. owner->setCurrentTabIndex (tabIndex);
  47870. }
  47871. bool TabBarButton::hitTest (int mx, int my)
  47872. {
  47873. int x, y, w, h;
  47874. getActiveArea (x, y, w, h);
  47875. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  47876. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  47877. {
  47878. if (((unsigned int) mx) < (unsigned int) getWidth()
  47879. && my >= y + overlapPixels
  47880. && my < y + h - overlapPixels)
  47881. return true;
  47882. }
  47883. else
  47884. {
  47885. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  47886. && ((unsigned int) my) < (unsigned int) getHeight())
  47887. return true;
  47888. }
  47889. Path p;
  47890. getLookAndFeel()
  47891. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  47892. owner->getOrientation(),
  47893. false, false, getToggleState());
  47894. return p.contains ((float) (mx - x),
  47895. (float) (my - y));
  47896. }
  47897. int TabBarButton::getBestTabLength (const int depth)
  47898. {
  47899. return jlimit (depth * 2,
  47900. depth * 7,
  47901. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  47902. }
  47903. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  47904. {
  47905. x = 0;
  47906. y = 0;
  47907. int r = getWidth();
  47908. int b = getHeight();
  47909. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  47910. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  47911. r -= spaceAroundImage;
  47912. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  47913. x += spaceAroundImage;
  47914. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  47915. y += spaceAroundImage;
  47916. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  47917. b -= spaceAroundImage;
  47918. w = r - x;
  47919. h = b - y;
  47920. }
  47921. class TabAreaBehindFrontButtonComponent : public Component
  47922. {
  47923. public:
  47924. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  47925. : owner (owner_)
  47926. {
  47927. setInterceptsMouseClicks (false, false);
  47928. }
  47929. ~TabAreaBehindFrontButtonComponent()
  47930. {
  47931. }
  47932. void paint (Graphics& g)
  47933. {
  47934. getLookAndFeel()
  47935. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  47936. *owner, owner->getOrientation());
  47937. }
  47938. void enablementChanged()
  47939. {
  47940. repaint();
  47941. }
  47942. private:
  47943. TabbedButtonBar* const owner;
  47944. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  47945. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  47946. };
  47947. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  47948. : orientation (orientation_),
  47949. currentTabIndex (-1),
  47950. extraTabsButton (0)
  47951. {
  47952. setInterceptsMouseClicks (false, true);
  47953. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  47954. setFocusContainer (true);
  47955. }
  47956. TabbedButtonBar::~TabbedButtonBar()
  47957. {
  47958. deleteAllChildren();
  47959. }
  47960. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  47961. {
  47962. orientation = newOrientation;
  47963. for (int i = getNumChildComponents(); --i >= 0;)
  47964. getChildComponent (i)->resized();
  47965. resized();
  47966. }
  47967. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  47968. {
  47969. return new TabBarButton (name, this, index);
  47970. }
  47971. void TabbedButtonBar::clearTabs()
  47972. {
  47973. tabs.clear();
  47974. tabColours.clear();
  47975. currentTabIndex = -1;
  47976. deleteAndZero (extraTabsButton);
  47977. removeChildComponent (behindFrontTab);
  47978. deleteAllChildren();
  47979. addChildComponent (behindFrontTab);
  47980. setCurrentTabIndex (-1);
  47981. }
  47982. void TabbedButtonBar::addTab (const String& tabName,
  47983. const Colour& tabBackgroundColour,
  47984. int insertIndex)
  47985. {
  47986. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  47987. if (tabName.isNotEmpty())
  47988. {
  47989. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  47990. insertIndex = tabs.size();
  47991. for (int i = tabs.size(); --i >= insertIndex;)
  47992. {
  47993. TabBarButton* const tb = getTabButton (i);
  47994. if (tb != 0)
  47995. tb->tabIndex++;
  47996. }
  47997. tabs.insert (insertIndex, tabName);
  47998. tabColours.insert (insertIndex, tabBackgroundColour);
  47999. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  48000. jassert (tb != 0); // your createTabButton() mustn't return zero!
  48001. addAndMakeVisible (tb, insertIndex);
  48002. resized();
  48003. if (currentTabIndex < 0)
  48004. setCurrentTabIndex (0);
  48005. }
  48006. }
  48007. void TabbedButtonBar::setTabName (const int tabIndex,
  48008. const String& newName)
  48009. {
  48010. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  48011. && tabs[tabIndex] != newName)
  48012. {
  48013. tabs.set (tabIndex, newName);
  48014. TabBarButton* const tb = getTabButton (tabIndex);
  48015. if (tb != 0)
  48016. tb->setButtonText (newName);
  48017. resized();
  48018. }
  48019. }
  48020. void TabbedButtonBar::removeTab (const int tabIndex)
  48021. {
  48022. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  48023. {
  48024. const int oldTabIndex = currentTabIndex;
  48025. if (currentTabIndex == tabIndex)
  48026. currentTabIndex = -1;
  48027. tabs.remove (tabIndex);
  48028. tabColours.remove (tabIndex);
  48029. TabBarButton* const tb = getTabButton (tabIndex);
  48030. if (tb != 0)
  48031. delete tb;
  48032. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  48033. {
  48034. TabBarButton* const tb = getTabButton (i);
  48035. if (tb != 0)
  48036. tb->tabIndex--;
  48037. }
  48038. resized();
  48039. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  48040. }
  48041. }
  48042. void TabbedButtonBar::moveTab (const int currentIndex,
  48043. const int newIndex)
  48044. {
  48045. tabs.move (currentIndex, newIndex);
  48046. tabColours.move (currentIndex, newIndex);
  48047. resized();
  48048. }
  48049. int TabbedButtonBar::getNumTabs() const
  48050. {
  48051. return tabs.size();
  48052. }
  48053. const StringArray TabbedButtonBar::getTabNames() const
  48054. {
  48055. return tabs;
  48056. }
  48057. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  48058. {
  48059. if (currentTabIndex != newIndex)
  48060. {
  48061. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  48062. newIndex = -1;
  48063. currentTabIndex = newIndex;
  48064. for (int i = 0; i < getNumChildComponents(); ++i)
  48065. {
  48066. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  48067. if (tb != 0)
  48068. tb->setToggleState (tb->tabIndex == newIndex, false);
  48069. }
  48070. resized();
  48071. if (sendChangeMessage_)
  48072. sendChangeMessage (this);
  48073. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  48074. }
  48075. }
  48076. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  48077. {
  48078. for (int i = getNumChildComponents(); --i >= 0;)
  48079. {
  48080. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  48081. if (tb != 0 && tb->tabIndex == index)
  48082. return tb;
  48083. }
  48084. return 0;
  48085. }
  48086. void TabbedButtonBar::lookAndFeelChanged()
  48087. {
  48088. deleteAndZero (extraTabsButton);
  48089. resized();
  48090. }
  48091. void TabbedButtonBar::resized()
  48092. {
  48093. const double minimumScale = 0.7;
  48094. int depth = getWidth();
  48095. int length = getHeight();
  48096. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  48097. swapVariables (depth, length);
  48098. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  48099. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  48100. int i, totalLength = overlap;
  48101. int numVisibleButtons = tabs.size();
  48102. for (i = 0; i < getNumChildComponents(); ++i)
  48103. {
  48104. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  48105. if (tb != 0)
  48106. {
  48107. totalLength += tb->getBestTabLength (depth) - overlap;
  48108. tb->overlapPixels = overlap / 2;
  48109. }
  48110. }
  48111. double scale = 1.0;
  48112. if (totalLength > length)
  48113. scale = jmax (minimumScale, length / (double) totalLength);
  48114. const bool isTooBig = totalLength * scale > length;
  48115. int tabsButtonPos = 0;
  48116. if (isTooBig)
  48117. {
  48118. if (extraTabsButton == 0)
  48119. {
  48120. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  48121. extraTabsButton->addButtonListener (this);
  48122. extraTabsButton->setAlwaysOnTop (true);
  48123. extraTabsButton->setTriggeredOnMouseDown (true);
  48124. }
  48125. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  48126. extraTabsButton->setSize (buttonSize, buttonSize);
  48127. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  48128. {
  48129. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  48130. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  48131. }
  48132. else
  48133. {
  48134. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  48135. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  48136. }
  48137. totalLength = 0;
  48138. for (i = 0; i < tabs.size(); ++i)
  48139. {
  48140. TabBarButton* const tb = getTabButton (i);
  48141. if (tb != 0)
  48142. {
  48143. const int newLength = totalLength + tb->getBestTabLength (depth);
  48144. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  48145. {
  48146. totalLength += overlap;
  48147. break;
  48148. }
  48149. numVisibleButtons = i + 1;
  48150. totalLength = newLength - overlap;
  48151. }
  48152. }
  48153. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  48154. }
  48155. else
  48156. {
  48157. deleteAndZero (extraTabsButton);
  48158. }
  48159. int pos = 0;
  48160. TabBarButton* frontTab = 0;
  48161. for (i = 0; i < tabs.size(); ++i)
  48162. {
  48163. TabBarButton* const tb = getTabButton (i);
  48164. if (tb != 0)
  48165. {
  48166. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  48167. if (i < numVisibleButtons)
  48168. {
  48169. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  48170. tb->setBounds (pos, 0, bestLength, getHeight());
  48171. else
  48172. tb->setBounds (0, pos, getWidth(), bestLength);
  48173. tb->toBack();
  48174. if (tb->tabIndex == currentTabIndex)
  48175. frontTab = tb;
  48176. tb->setVisible (true);
  48177. }
  48178. else
  48179. {
  48180. tb->setVisible (false);
  48181. }
  48182. pos += bestLength - overlap;
  48183. }
  48184. }
  48185. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  48186. if (frontTab != 0)
  48187. {
  48188. frontTab->toFront (false);
  48189. behindFrontTab->toBehind (frontTab);
  48190. }
  48191. }
  48192. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  48193. {
  48194. return tabColours [tabIndex];
  48195. }
  48196. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48197. {
  48198. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  48199. && tabColours [tabIndex] != newColour)
  48200. {
  48201. tabColours.set (tabIndex, newColour);
  48202. repaint();
  48203. }
  48204. }
  48205. void TabbedButtonBar::buttonClicked (Button* button)
  48206. {
  48207. if (extraTabsButton == button)
  48208. {
  48209. PopupMenu m;
  48210. for (int i = 0; i < tabs.size(); ++i)
  48211. {
  48212. TabBarButton* const tb = getTabButton (i);
  48213. if (tb != 0 && ! tb->isVisible())
  48214. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  48215. }
  48216. const int res = m.showAt (extraTabsButton);
  48217. if (res != 0)
  48218. setCurrentTabIndex (res - 1);
  48219. }
  48220. }
  48221. void TabbedButtonBar::currentTabChanged (const int, const String&)
  48222. {
  48223. }
  48224. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  48225. {
  48226. }
  48227. END_JUCE_NAMESPACE
  48228. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  48229. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  48230. BEGIN_JUCE_NAMESPACE
  48231. class TabCompButtonBar : public TabbedButtonBar
  48232. {
  48233. public:
  48234. TabCompButtonBar (TabbedComponent* const owner_,
  48235. const TabbedButtonBar::Orientation orientation)
  48236. : TabbedButtonBar (orientation),
  48237. owner (owner_)
  48238. {
  48239. }
  48240. ~TabCompButtonBar()
  48241. {
  48242. }
  48243. void currentTabChanged (const int newCurrentTabIndex,
  48244. const String& newTabName)
  48245. {
  48246. owner->changeCallback (newCurrentTabIndex, newTabName);
  48247. }
  48248. void popupMenuClickOnTab (const int tabIndex,
  48249. const String& tabName)
  48250. {
  48251. owner->popupMenuClickOnTab (tabIndex, tabName);
  48252. }
  48253. const Colour getTabBackgroundColour (const int tabIndex)
  48254. {
  48255. return owner->tabs->getTabBackgroundColour (tabIndex);
  48256. }
  48257. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  48258. {
  48259. return owner->createTabButton (tabName, tabIndex);
  48260. }
  48261. juce_UseDebuggingNewOperator
  48262. private:
  48263. TabbedComponent* const owner;
  48264. TabCompButtonBar (const TabCompButtonBar&);
  48265. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  48266. };
  48267. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  48268. : panelComponent (0),
  48269. tabDepth (30),
  48270. outlineThickness (1),
  48271. edgeIndent (0)
  48272. {
  48273. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  48274. }
  48275. TabbedComponent::~TabbedComponent()
  48276. {
  48277. clearTabs();
  48278. delete tabs;
  48279. }
  48280. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  48281. {
  48282. tabs->setOrientation (orientation);
  48283. resized();
  48284. }
  48285. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  48286. {
  48287. return tabs->getOrientation();
  48288. }
  48289. void TabbedComponent::setTabBarDepth (const int newDepth)
  48290. {
  48291. if (tabDepth != newDepth)
  48292. {
  48293. tabDepth = newDepth;
  48294. resized();
  48295. }
  48296. }
  48297. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  48298. {
  48299. return new TabBarButton (tabName, tabs, tabIndex);
  48300. }
  48301. void TabbedComponent::clearTabs()
  48302. {
  48303. if (panelComponent != 0)
  48304. {
  48305. panelComponent->setVisible (false);
  48306. removeChildComponent (panelComponent);
  48307. panelComponent = 0;
  48308. }
  48309. tabs->clearTabs();
  48310. for (int i = contentComponents.size(); --i >= 0;)
  48311. {
  48312. Component* const c = contentComponents.getUnchecked(i);
  48313. // be careful not to delete these components until they've been removed from the tab component
  48314. jassert (c == 0 || c->isValidComponent());
  48315. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48316. delete c;
  48317. }
  48318. contentComponents.clear();
  48319. }
  48320. void TabbedComponent::addTab (const String& tabName,
  48321. const Colour& tabBackgroundColour,
  48322. Component* const contentComponent,
  48323. const bool deleteComponentWhenNotNeeded,
  48324. const int insertIndex)
  48325. {
  48326. contentComponents.insert (insertIndex, contentComponent);
  48327. if (contentComponent != 0)
  48328. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  48329. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  48330. }
  48331. void TabbedComponent::setTabName (const int tabIndex,
  48332. const String& newName)
  48333. {
  48334. tabs->setTabName (tabIndex, newName);
  48335. }
  48336. void TabbedComponent::removeTab (const int tabIndex)
  48337. {
  48338. Component* const c = contentComponents [tabIndex];
  48339. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48340. {
  48341. if (c == panelComponent)
  48342. panelComponent = 0;
  48343. delete c;
  48344. }
  48345. contentComponents.remove (tabIndex);
  48346. tabs->removeTab (tabIndex);
  48347. }
  48348. int TabbedComponent::getNumTabs() const
  48349. {
  48350. return tabs->getNumTabs();
  48351. }
  48352. const StringArray TabbedComponent::getTabNames() const
  48353. {
  48354. return tabs->getTabNames();
  48355. }
  48356. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  48357. {
  48358. return contentComponents [tabIndex];
  48359. }
  48360. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  48361. {
  48362. return tabs->getTabBackgroundColour (tabIndex);
  48363. }
  48364. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48365. {
  48366. tabs->setTabBackgroundColour (tabIndex, newColour);
  48367. if (getCurrentTabIndex() == tabIndex)
  48368. repaint();
  48369. }
  48370. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  48371. {
  48372. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  48373. }
  48374. int TabbedComponent::getCurrentTabIndex() const
  48375. {
  48376. return tabs->getCurrentTabIndex();
  48377. }
  48378. const String& TabbedComponent::getCurrentTabName() const
  48379. {
  48380. return tabs->getCurrentTabName();
  48381. }
  48382. void TabbedComponent::setOutline (int thickness)
  48383. {
  48384. outlineThickness = thickness;
  48385. repaint();
  48386. }
  48387. void TabbedComponent::setIndent (const int indentThickness)
  48388. {
  48389. edgeIndent = indentThickness;
  48390. }
  48391. void TabbedComponent::paint (Graphics& g)
  48392. {
  48393. g.fillAll (findColour (backgroundColourId));
  48394. const TabbedButtonBar::Orientation o = getOrientation();
  48395. int x = 0;
  48396. int y = 0;
  48397. int r = getWidth();
  48398. int b = getHeight();
  48399. if (o == TabbedButtonBar::TabsAtTop)
  48400. y += tabDepth;
  48401. else if (o == TabbedButtonBar::TabsAtBottom)
  48402. b -= tabDepth;
  48403. else if (o == TabbedButtonBar::TabsAtLeft)
  48404. x += tabDepth;
  48405. else if (o == TabbedButtonBar::TabsAtRight)
  48406. r -= tabDepth;
  48407. g.reduceClipRegion (x, y, r - x, b - y);
  48408. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  48409. if (outlineThickness > 0)
  48410. {
  48411. if (o == TabbedButtonBar::TabsAtTop)
  48412. --y;
  48413. else if (o == TabbedButtonBar::TabsAtBottom)
  48414. ++b;
  48415. else if (o == TabbedButtonBar::TabsAtLeft)
  48416. --x;
  48417. else if (o == TabbedButtonBar::TabsAtRight)
  48418. ++r;
  48419. g.setColour (findColour (outlineColourId));
  48420. g.drawRect (x, y, r - x, b - y, outlineThickness);
  48421. }
  48422. }
  48423. void TabbedComponent::resized()
  48424. {
  48425. const TabbedButtonBar::Orientation o = getOrientation();
  48426. const int indent = edgeIndent + outlineThickness;
  48427. BorderSize indents (indent);
  48428. if (o == TabbedButtonBar::TabsAtTop)
  48429. {
  48430. tabs->setBounds (0, 0, getWidth(), tabDepth);
  48431. indents.setTop (tabDepth + edgeIndent);
  48432. }
  48433. else if (o == TabbedButtonBar::TabsAtBottom)
  48434. {
  48435. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  48436. indents.setBottom (tabDepth + edgeIndent);
  48437. }
  48438. else if (o == TabbedButtonBar::TabsAtLeft)
  48439. {
  48440. tabs->setBounds (0, 0, tabDepth, getHeight());
  48441. indents.setLeft (tabDepth + edgeIndent);
  48442. }
  48443. else if (o == TabbedButtonBar::TabsAtRight)
  48444. {
  48445. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  48446. indents.setRight (tabDepth + edgeIndent);
  48447. }
  48448. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  48449. for (int i = contentComponents.size(); --i >= 0;)
  48450. if (contentComponents.getUnchecked (i) != 0)
  48451. contentComponents.getUnchecked (i)->setBounds (bounds);
  48452. }
  48453. void TabbedComponent::lookAndFeelChanged()
  48454. {
  48455. for (int i = contentComponents.size(); --i >= 0;)
  48456. if (contentComponents.getUnchecked (i) != 0)
  48457. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  48458. }
  48459. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  48460. const String& newTabName)
  48461. {
  48462. if (panelComponent != 0)
  48463. {
  48464. panelComponent->setVisible (false);
  48465. removeChildComponent (panelComponent);
  48466. panelComponent = 0;
  48467. }
  48468. if (getCurrentTabIndex() >= 0)
  48469. {
  48470. panelComponent = contentComponents [getCurrentTabIndex()];
  48471. if (panelComponent != 0)
  48472. {
  48473. // do these ops as two stages instead of addAndMakeVisible() so that the
  48474. // component has always got a parent when it gets the visibilityChanged() callback
  48475. addChildComponent (panelComponent);
  48476. panelComponent->setVisible (true);
  48477. panelComponent->toFront (true);
  48478. }
  48479. repaint();
  48480. }
  48481. resized();
  48482. currentTabChanged (newCurrentTabIndex, newTabName);
  48483. }
  48484. void TabbedComponent::currentTabChanged (const int, const String&)
  48485. {
  48486. }
  48487. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  48488. {
  48489. }
  48490. END_JUCE_NAMESPACE
  48491. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  48492. /********* Start of inlined file: juce_Viewport.cpp *********/
  48493. BEGIN_JUCE_NAMESPACE
  48494. Viewport::Viewport (const String& componentName)
  48495. : Component (componentName),
  48496. contentComp (0),
  48497. lastVX (0),
  48498. lastVY (0),
  48499. lastVW (0),
  48500. lastVH (0),
  48501. scrollBarThickness (0),
  48502. singleStepX (16),
  48503. singleStepY (16),
  48504. showHScrollbar (true),
  48505. showVScrollbar (true)
  48506. {
  48507. // content holder is used to clip the contents so they don't overlap the scrollbars
  48508. addAndMakeVisible (contentHolder = new Component());
  48509. contentHolder->setInterceptsMouseClicks (false, true);
  48510. verticalScrollBar = new ScrollBar (true);
  48511. horizontalScrollBar = new ScrollBar (false);
  48512. addChildComponent (verticalScrollBar);
  48513. addChildComponent (horizontalScrollBar);
  48514. verticalScrollBar->addListener (this);
  48515. horizontalScrollBar->addListener (this);
  48516. setInterceptsMouseClicks (false, true);
  48517. setWantsKeyboardFocus (true);
  48518. }
  48519. Viewport::~Viewport()
  48520. {
  48521. contentHolder->deleteAllChildren();
  48522. deleteAllChildren();
  48523. }
  48524. void Viewport::visibleAreaChanged (int, int, int, int)
  48525. {
  48526. }
  48527. void Viewport::setViewedComponent (Component* const newViewedComponent)
  48528. {
  48529. if (contentComp != newViewedComponent)
  48530. {
  48531. if (contentComp->isValidComponent())
  48532. {
  48533. Component* const oldComp = contentComp;
  48534. contentComp = 0;
  48535. delete oldComp;
  48536. }
  48537. contentComp = newViewedComponent;
  48538. if (contentComp != 0)
  48539. {
  48540. contentComp->setTopLeftPosition (0, 0);
  48541. contentHolder->addAndMakeVisible (contentComp);
  48542. contentComp->addComponentListener (this);
  48543. }
  48544. updateVisibleRegion();
  48545. }
  48546. }
  48547. int Viewport::getMaximumVisibleWidth() const throw()
  48548. {
  48549. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48550. }
  48551. int Viewport::getMaximumVisibleHeight() const throw()
  48552. {
  48553. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48554. }
  48555. void Viewport::setViewPosition (const int xPixelsOffset,
  48556. const int yPixelsOffset)
  48557. {
  48558. if (contentComp != 0)
  48559. contentComp->setTopLeftPosition (-xPixelsOffset,
  48560. -yPixelsOffset);
  48561. }
  48562. void Viewport::setViewPositionProportionately (const double x,
  48563. const double y)
  48564. {
  48565. if (contentComp != 0)
  48566. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  48567. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  48568. }
  48569. void Viewport::componentMovedOrResized (Component&, bool, bool)
  48570. {
  48571. updateVisibleRegion();
  48572. }
  48573. void Viewport::resized()
  48574. {
  48575. updateVisibleRegion();
  48576. }
  48577. void Viewport::updateVisibleRegion()
  48578. {
  48579. if (contentComp != 0)
  48580. {
  48581. const int newVX = -contentComp->getX();
  48582. const int newVY = -contentComp->getY();
  48583. if (newVX == 0 && newVY == 0
  48584. && contentComp->getWidth() <= getWidth()
  48585. && contentComp->getHeight() <= getHeight())
  48586. {
  48587. horizontalScrollBar->setVisible (false);
  48588. verticalScrollBar->setVisible (false);
  48589. }
  48590. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  48591. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48592. horizontalScrollBar->setSingleStepSize (singleStepX);
  48593. if (! (contentComp->getWidth() > 0 && showHScrollbar && getHeight() > getScrollBarThickness()))
  48594. horizontalScrollBar->setVisible (false);
  48595. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  48596. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48597. verticalScrollBar->setSingleStepSize (singleStepY);
  48598. if (! (contentComp->getHeight() > 0 && showVScrollbar && getWidth() > getScrollBarThickness()))
  48599. verticalScrollBar->setVisible (false);
  48600. if (verticalScrollBar->isVisible())
  48601. {
  48602. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48603. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48604. verticalScrollBar
  48605. ->setBounds (getMaximumVisibleWidth(), 0,
  48606. getScrollBarThickness(), getMaximumVisibleHeight());
  48607. }
  48608. if (horizontalScrollBar->isVisible())
  48609. {
  48610. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48611. horizontalScrollBar
  48612. ->setBounds (0, getMaximumVisibleHeight(),
  48613. getMaximumVisibleWidth(), getScrollBarThickness());
  48614. }
  48615. contentHolder->setSize (getMaximumVisibleWidth(),
  48616. getMaximumVisibleHeight());
  48617. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  48618. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  48619. if (newVX != lastVX
  48620. || newVY != lastVY
  48621. || newVW != lastVW
  48622. || newVH != lastVH)
  48623. {
  48624. lastVX = newVX;
  48625. lastVY = newVY;
  48626. lastVW = newVW;
  48627. lastVH = newVH;
  48628. visibleAreaChanged (newVX, newVY, newVW, newVH);
  48629. }
  48630. horizontalScrollBar->handleUpdateNowIfNeeded();
  48631. verticalScrollBar->handleUpdateNowIfNeeded();
  48632. }
  48633. else
  48634. {
  48635. horizontalScrollBar->setVisible (false);
  48636. verticalScrollBar->setVisible (false);
  48637. }
  48638. }
  48639. void Viewport::setSingleStepSizes (const int stepX,
  48640. const int stepY)
  48641. {
  48642. singleStepX = stepX;
  48643. singleStepY = stepY;
  48644. updateVisibleRegion();
  48645. }
  48646. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  48647. const bool showHorizontalScrollbarIfNeeded)
  48648. {
  48649. showVScrollbar = showVerticalScrollbarIfNeeded;
  48650. showHScrollbar = showHorizontalScrollbarIfNeeded;
  48651. updateVisibleRegion();
  48652. }
  48653. void Viewport::setScrollBarThickness (const int thickness)
  48654. {
  48655. scrollBarThickness = thickness;
  48656. updateVisibleRegion();
  48657. }
  48658. int Viewport::getScrollBarThickness() const throw()
  48659. {
  48660. return (scrollBarThickness > 0) ? scrollBarThickness
  48661. : getLookAndFeel().getDefaultScrollbarWidth();
  48662. }
  48663. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  48664. {
  48665. verticalScrollBar->setButtonVisibility (buttonsVisible);
  48666. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  48667. }
  48668. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  48669. {
  48670. if (scrollBarThatHasMoved == horizontalScrollBar)
  48671. {
  48672. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  48673. }
  48674. else if (scrollBarThatHasMoved == verticalScrollBar)
  48675. {
  48676. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  48677. }
  48678. }
  48679. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48680. {
  48681. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  48682. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  48683. }
  48684. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48685. {
  48686. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  48687. {
  48688. const bool hasVertBar = verticalScrollBar->isVisible();
  48689. const bool hasHorzBar = horizontalScrollBar->isVisible();
  48690. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  48691. {
  48692. if (wheelIncrementX == 0 && ! hasVertBar)
  48693. wheelIncrementX = wheelIncrementY;
  48694. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  48695. wheelIncrementX, wheelIncrementY);
  48696. return true;
  48697. }
  48698. else if (hasVertBar && wheelIncrementY != 0)
  48699. {
  48700. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  48701. wheelIncrementX, wheelIncrementY);
  48702. return true;
  48703. }
  48704. }
  48705. return false;
  48706. }
  48707. bool Viewport::keyPressed (const KeyPress& key)
  48708. {
  48709. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  48710. || key.isKeyCode (KeyPress::downKey)
  48711. || key.isKeyCode (KeyPress::pageUpKey)
  48712. || key.isKeyCode (KeyPress::pageDownKey)
  48713. || key.isKeyCode (KeyPress::homeKey)
  48714. || key.isKeyCode (KeyPress::endKey);
  48715. if (verticalScrollBar->isVisible() && isUpDownKey)
  48716. return verticalScrollBar->keyPressed (key);
  48717. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  48718. || key.isKeyCode (KeyPress::rightKey);
  48719. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  48720. return horizontalScrollBar->keyPressed (key);
  48721. return false;
  48722. }
  48723. END_JUCE_NAMESPACE
  48724. /********* End of inlined file: juce_Viewport.cpp *********/
  48725. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  48726. BEGIN_JUCE_NAMESPACE
  48727. static const Colour createBaseColour (const Colour& buttonColour,
  48728. const bool hasKeyboardFocus,
  48729. const bool isMouseOverButton,
  48730. const bool isButtonDown) throw()
  48731. {
  48732. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  48733. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  48734. if (isButtonDown)
  48735. return baseColour.contrasting (0.2f);
  48736. else if (isMouseOverButton)
  48737. return baseColour.contrasting (0.1f);
  48738. return baseColour;
  48739. }
  48740. static String defaultSansName, defaultSerifName, defaultFixedName;
  48741. void clearUpDefaultFontNames() throw()
  48742. {
  48743. defaultSansName = String::empty;
  48744. defaultSerifName = String::empty;
  48745. defaultFixedName = String::empty;
  48746. }
  48747. LookAndFeel::LookAndFeel()
  48748. {
  48749. /* if this fails it means you're trying to create a LookAndFeel object before
  48750. the static Colours have been initialised. That ain't gonna work. It probably
  48751. means that you're using a static LookAndFeel object and that your compiler has
  48752. decided to intialise it before the Colours class.
  48753. */
  48754. jassert (Colours::white == Colour (0xffffffff));
  48755. // set up the standard set of colours..
  48756. #define textButtonColour 0xffbbbbff
  48757. #define textHighlightColour 0x401111ee
  48758. #define standardOutlineColour 0xb2808080
  48759. static const int standardColours[] =
  48760. {
  48761. TextButton::buttonColourId, textButtonColour,
  48762. TextButton::buttonOnColourId, 0xff4444ff,
  48763. TextButton::textColourId, 0xff000000,
  48764. ComboBox::buttonColourId, 0xffbbbbff,
  48765. ComboBox::outlineColourId, standardOutlineColour,
  48766. ToggleButton::textColourId, 0xff000000,
  48767. TextEditor::backgroundColourId, 0xffffffff,
  48768. TextEditor::textColourId, 0xff000000,
  48769. TextEditor::highlightColourId, textHighlightColour,
  48770. TextEditor::highlightedTextColourId, 0xff000000,
  48771. TextEditor::caretColourId, 0xff000000,
  48772. TextEditor::outlineColourId, 0x00000000,
  48773. TextEditor::focusedOutlineColourId, textButtonColour,
  48774. TextEditor::shadowColourId, 0x38000000,
  48775. Label::backgroundColourId, 0x00000000,
  48776. Label::textColourId, 0xff000000,
  48777. Label::outlineColourId, 0x00000000,
  48778. ScrollBar::backgroundColourId, 0x00000000,
  48779. ScrollBar::thumbColourId, 0xffffffff,
  48780. ScrollBar::trackColourId, 0xffffffff,
  48781. TreeView::linesColourId, 0x4c000000,
  48782. TreeView::backgroundColourId, 0x00000000,
  48783. PopupMenu::backgroundColourId, 0xffffffff,
  48784. PopupMenu::textColourId, 0xff000000,
  48785. PopupMenu::headerTextColourId, 0xff000000,
  48786. PopupMenu::highlightedTextColourId, 0xffffffff,
  48787. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  48788. ComboBox::textColourId, 0xff000000,
  48789. ComboBox::backgroundColourId, 0xffffffff,
  48790. ComboBox::arrowColourId, 0x99000000,
  48791. ListBox::backgroundColourId, 0xffffffff,
  48792. ListBox::outlineColourId, standardOutlineColour,
  48793. ListBox::textColourId, 0xff000000,
  48794. Slider::backgroundColourId, 0x00000000,
  48795. Slider::thumbColourId, textButtonColour,
  48796. Slider::trackColourId, 0x7fffffff,
  48797. Slider::rotarySliderFillColourId, 0x7f0000ff,
  48798. Slider::rotarySliderOutlineColourId, 0x66000000,
  48799. Slider::textBoxTextColourId, 0xff000000,
  48800. Slider::textBoxBackgroundColourId, 0xffffffff,
  48801. Slider::textBoxHighlightColourId, textHighlightColour,
  48802. Slider::textBoxOutlineColourId, standardOutlineColour,
  48803. ResizableWindow::backgroundColourId, 0xff777777,
  48804. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  48805. AlertWindow::backgroundColourId, 0xffededed,
  48806. AlertWindow::textColourId, 0xff000000,
  48807. AlertWindow::outlineColourId, 0xff666666,
  48808. ProgressBar::backgroundColourId, 0xffeeeeee,
  48809. ProgressBar::foregroundColourId, 0xffaaaaee,
  48810. TooltipWindow::backgroundColourId, 0xffeeeebb,
  48811. TooltipWindow::textColourId, 0xff000000,
  48812. TooltipWindow::outlineColourId, 0x4c000000,
  48813. TabbedComponent::backgroundColourId, 0x00000000,
  48814. TabbedComponent::outlineColourId, 0xff777777,
  48815. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  48816. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  48817. Toolbar::backgroundColourId, 0xfff6f8f9,
  48818. Toolbar::separatorColourId, 0x4c000000,
  48819. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  48820. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  48821. Toolbar::labelTextColourId, 0xff000000,
  48822. Toolbar::editingModeOutlineColourId, 0xffff0000,
  48823. HyperlinkButton::textColourId, 0xcc1111ee,
  48824. GroupComponent::outlineColourId, 0x66000000,
  48825. GroupComponent::textColourId, 0xff000000,
  48826. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  48827. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  48828. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  48829. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  48830. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  48831. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  48832. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  48833. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  48834. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  48835. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  48836. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  48837. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  48838. ColourSelector::backgroundColourId, 0xffe5e5e5,
  48839. ColourSelector::labelTextColourId, 0xff000000,
  48840. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  48841. };
  48842. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  48843. setColour (standardColours [i], Colour (standardColours [i + 1]));
  48844. if (defaultSansName.isEmpty())
  48845. Typeface::getDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  48846. defaultSans = defaultSansName;
  48847. defaultSerif = defaultSerifName;
  48848. defaultFixed = defaultFixedName;
  48849. }
  48850. LookAndFeel::~LookAndFeel()
  48851. {
  48852. }
  48853. const Colour LookAndFeel::findColour (const int colourId) const throw()
  48854. {
  48855. const int index = colourIds.indexOf (colourId);
  48856. if (index >= 0)
  48857. return colours [index];
  48858. jassertfalse
  48859. return Colours::black;
  48860. }
  48861. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  48862. {
  48863. const int index = colourIds.indexOf (colourId);
  48864. if (index >= 0)
  48865. colours.set (index, colour);
  48866. colourIds.add (colourId);
  48867. colours.add (colour);
  48868. }
  48869. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  48870. {
  48871. return colourIds.contains (colourId);
  48872. }
  48873. static LookAndFeel* defaultLF = 0;
  48874. static LookAndFeel* currentDefaultLF = 0;
  48875. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  48876. {
  48877. // if this happens, your app hasn't initialised itself properly.. if you're
  48878. // trying to hack your own main() function, have a look at
  48879. // JUCEApplication::initialiseForGUI()
  48880. jassert (currentDefaultLF != 0);
  48881. return *currentDefaultLF;
  48882. }
  48883. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  48884. {
  48885. if (newDefaultLookAndFeel == 0)
  48886. {
  48887. if (defaultLF == 0)
  48888. defaultLF = new LookAndFeel();
  48889. newDefaultLookAndFeel = defaultLF;
  48890. }
  48891. currentDefaultLF = newDefaultLookAndFeel;
  48892. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  48893. {
  48894. Component* const c = Desktop::getInstance().getComponent (i);
  48895. if (c != 0)
  48896. c->sendLookAndFeelChange();
  48897. }
  48898. }
  48899. void LookAndFeel::clearDefaultLookAndFeel() throw()
  48900. {
  48901. if (currentDefaultLF == defaultLF)
  48902. currentDefaultLF = 0;
  48903. deleteAndZero (defaultLF);
  48904. }
  48905. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  48906. {
  48907. String faceName (font.getTypefaceName());
  48908. if (faceName == Typeface::defaultTypefaceNameSans)
  48909. faceName = defaultSans;
  48910. else if (faceName == Typeface::defaultTypefaceNameSerif)
  48911. faceName = defaultSerif;
  48912. else if (faceName == Typeface::defaultTypefaceNameMono)
  48913. faceName = defaultFixed;
  48914. return new Typeface (faceName, font.isBold(), font.isItalic());
  48915. }
  48916. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  48917. {
  48918. defaultSans = newName;
  48919. }
  48920. void LookAndFeel::drawButtonBackground (Graphics& g,
  48921. Button& button,
  48922. const Colour& backgroundColour,
  48923. bool isMouseOverButton,
  48924. bool isButtonDown)
  48925. {
  48926. const int width = button.getWidth();
  48927. const int height = button.getHeight();
  48928. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  48929. const float halfThickness = outlineThickness * 0.5f;
  48930. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  48931. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  48932. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  48933. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  48934. const Colour baseColour (createBaseColour (backgroundColour,
  48935. button.hasKeyboardFocus (true),
  48936. isMouseOverButton, isButtonDown)
  48937. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48938. drawGlassLozenge (g,
  48939. indentL,
  48940. indentT,
  48941. width - indentL - indentR,
  48942. height - indentT - indentB,
  48943. baseColour, outlineThickness, -1.0f,
  48944. button.isConnectedOnLeft(),
  48945. button.isConnectedOnRight(),
  48946. button.isConnectedOnTop(),
  48947. button.isConnectedOnBottom());
  48948. }
  48949. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  48950. {
  48951. return button.getFont();
  48952. }
  48953. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  48954. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  48955. {
  48956. g.setFont (getFontForTextButton (button));
  48957. g.setColour (button.findColour (TextButton::textColourId)
  48958. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48959. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  48960. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  48961. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  48962. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  48963. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  48964. g.drawFittedText (button.getButtonText(),
  48965. leftIndent,
  48966. yIndent,
  48967. button.getWidth() - leftIndent - rightIndent,
  48968. button.getHeight() - yIndent * 2,
  48969. Justification::centred, 2);
  48970. }
  48971. void LookAndFeel::drawTickBox (Graphics& g,
  48972. Component& component,
  48973. int x, int y, int w, int h,
  48974. const bool ticked,
  48975. const bool isEnabled,
  48976. const bool isMouseOverButton,
  48977. const bool isButtonDown)
  48978. {
  48979. const float boxSize = w * 0.7f;
  48980. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  48981. createBaseColour (component.findColour (TextButton::buttonColourId)
  48982. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  48983. true,
  48984. isMouseOverButton,
  48985. isButtonDown),
  48986. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  48987. if (ticked)
  48988. {
  48989. Path tick;
  48990. tick.startNewSubPath (1.5f, 3.0f);
  48991. tick.lineTo (3.0f, 6.0f);
  48992. tick.lineTo (6.0f, 0.0f);
  48993. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48994. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48995. .translated ((float) x, (float) y));
  48996. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48997. }
  48998. }
  48999. void LookAndFeel::drawToggleButton (Graphics& g,
  49000. ToggleButton& button,
  49001. bool isMouseOverButton,
  49002. bool isButtonDown)
  49003. {
  49004. if (button.hasKeyboardFocus (true))
  49005. {
  49006. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  49007. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  49008. }
  49009. const int tickWidth = jmin (20, button.getHeight() - 4);
  49010. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  49011. tickWidth, tickWidth,
  49012. button.getToggleState(),
  49013. button.isEnabled(),
  49014. isMouseOverButton,
  49015. isButtonDown);
  49016. g.setColour (button.findColour (ToggleButton::textColourId));
  49017. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  49018. if (! button.isEnabled())
  49019. g.setOpacity (0.5f);
  49020. const int textX = tickWidth + 5;
  49021. g.drawFittedText (button.getButtonText(),
  49022. textX, 4,
  49023. button.getWidth() - textX - 2, button.getHeight() - 8,
  49024. Justification::centredLeft, 10);
  49025. }
  49026. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  49027. {
  49028. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  49029. const int tickWidth = jmin (24, button.getHeight());
  49030. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  49031. button.getHeight());
  49032. }
  49033. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  49034. const String& message,
  49035. const String& button1,
  49036. const String& button2,
  49037. const String& button3,
  49038. AlertWindow::AlertIconType iconType,
  49039. int numButtons,
  49040. Component* associatedComponent)
  49041. {
  49042. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  49043. if (numButtons == 1)
  49044. {
  49045. aw->addButton (button1, 0,
  49046. KeyPress (KeyPress::escapeKey, 0, 0),
  49047. KeyPress (KeyPress::returnKey, 0, 0));
  49048. }
  49049. else
  49050. {
  49051. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  49052. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  49053. if (button1ShortCut == button2ShortCut)
  49054. button2ShortCut = KeyPress();
  49055. if (numButtons == 2)
  49056. {
  49057. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  49058. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  49059. }
  49060. else if (numButtons == 3)
  49061. {
  49062. aw->addButton (button1, 1, button1ShortCut);
  49063. aw->addButton (button2, 2, button2ShortCut);
  49064. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  49065. }
  49066. }
  49067. return aw;
  49068. }
  49069. void LookAndFeel::drawAlertBox (Graphics& g,
  49070. AlertWindow& alert,
  49071. const Rectangle& textArea,
  49072. TextLayout& textLayout)
  49073. {
  49074. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  49075. int iconSpaceUsed = 0;
  49076. Justification alignment (Justification::horizontallyCentred);
  49077. const int iconWidth = 80;
  49078. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  49079. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  49080. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  49081. const Rectangle iconRect (iconSize / -10, iconSize / -10,
  49082. iconSize, iconSize);
  49083. if (alert.getAlertType() != AlertWindow::NoIcon)
  49084. {
  49085. Path icon;
  49086. uint32 colour;
  49087. char character;
  49088. if (alert.getAlertType() == AlertWindow::WarningIcon)
  49089. {
  49090. colour = 0x55ff5555;
  49091. character = '!';
  49092. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  49093. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  49094. (float) iconRect.getX(), (float) iconRect.getBottom());
  49095. icon = icon.createPathWithRoundedCorners (5.0f);
  49096. }
  49097. else
  49098. {
  49099. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  49100. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  49101. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  49102. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  49103. }
  49104. GlyphArrangement ga;
  49105. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  49106. String::charToString (character),
  49107. (float) iconRect.getX(), (float) iconRect.getY(),
  49108. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  49109. Justification::centred, false);
  49110. ga.createPath (icon);
  49111. icon.setUsingNonZeroWinding (false);
  49112. g.setColour (Colour (colour));
  49113. g.fillPath (icon);
  49114. iconSpaceUsed = iconWidth;
  49115. alignment = Justification::left;
  49116. }
  49117. g.setColour (alert.findColour (AlertWindow::textColourId));
  49118. textLayout.drawWithin (g,
  49119. textArea.getX() + iconSpaceUsed, textArea.getY(),
  49120. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  49121. alignment.getFlags() | Justification::top);
  49122. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  49123. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  49124. }
  49125. int LookAndFeel::getAlertBoxWindowFlags()
  49126. {
  49127. return ComponentPeer::windowAppearsOnTaskbar
  49128. | ComponentPeer::windowHasDropShadow;
  49129. }
  49130. int LookAndFeel::getAlertWindowButtonHeight()
  49131. {
  49132. return 28;
  49133. }
  49134. const Font LookAndFeel::getAlertWindowFont()
  49135. {
  49136. return Font (12.0f);
  49137. }
  49138. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  49139. int width, int height,
  49140. double progress, const String& textToShow)
  49141. {
  49142. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  49143. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  49144. g.fillAll (background);
  49145. if (progress >= 0.0f && progress < 1.0f)
  49146. {
  49147. drawGlassLozenge (g, 1.0f, 1.0f,
  49148. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  49149. (float) (height - 2),
  49150. foreground,
  49151. 0.5f, 0.0f,
  49152. true, true, true, true);
  49153. }
  49154. else
  49155. {
  49156. // spinning bar..
  49157. g.setColour (foreground);
  49158. const int stripeWidth = height * 2;
  49159. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  49160. Path p;
  49161. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  49162. p.addQuadrilateral (x, 0.0f,
  49163. x + stripeWidth * 0.5f, 0.0f,
  49164. x, (float) height,
  49165. x - stripeWidth * 0.5f, (float) height);
  49166. Image im (Image::ARGB, width, height, true);
  49167. {
  49168. Graphics g (im);
  49169. drawGlassLozenge (g, 1.0f, 1.0f,
  49170. (float) (width - 2),
  49171. (float) (height - 2),
  49172. foreground,
  49173. 0.5f, 0.0f,
  49174. true, true, true, true);
  49175. }
  49176. ImageBrush ib (&im, 0, 0, 0.85f);
  49177. g.setBrush (&ib);
  49178. g.fillPath (p);
  49179. }
  49180. if (textToShow.isNotEmpty())
  49181. {
  49182. g.setColour (Colour::contrasting (background, foreground));
  49183. g.setFont (height * 0.6f);
  49184. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  49185. }
  49186. }
  49187. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h)
  49188. {
  49189. const float radius = jmin (w, h) * 0.4f;
  49190. const float thickness = radius * 0.15f;
  49191. Path p;
  49192. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  49193. radius * 0.6f, thickness,
  49194. thickness * 0.5f);
  49195. const float cx = x + w * 0.5f;
  49196. const float cy = y + h * 0.5f;
  49197. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  49198. const Colour col (g.getCurrentColour());
  49199. for (int i = 0; i < 12; ++i)
  49200. {
  49201. const int n = (i + 12 - animationIndex) % 12;
  49202. g.setColour (col.withMultipliedAlpha ((n + 1) / 12.0f));
  49203. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  49204. .translated (cx, cy));
  49205. }
  49206. }
  49207. void LookAndFeel::drawScrollbarButton (Graphics& g,
  49208. ScrollBar& scrollbar,
  49209. int width, int height,
  49210. int buttonDirection,
  49211. bool /*isScrollbarVertical*/,
  49212. bool /*isMouseOverButton*/,
  49213. bool isButtonDown)
  49214. {
  49215. Path p;
  49216. if (buttonDirection == 0)
  49217. p.addTriangle (width * 0.5f, height * 0.2f,
  49218. width * 0.1f, height * 0.7f,
  49219. width * 0.9f, height * 0.7f);
  49220. else if (buttonDirection == 1)
  49221. p.addTriangle (width * 0.8f, height * 0.5f,
  49222. width * 0.3f, height * 0.1f,
  49223. width * 0.3f, height * 0.9f);
  49224. else if (buttonDirection == 2)
  49225. p.addTriangle (width * 0.5f, height * 0.8f,
  49226. width * 0.1f, height * 0.3f,
  49227. width * 0.9f, height * 0.3f);
  49228. else if (buttonDirection == 3)
  49229. p.addTriangle (width * 0.2f, height * 0.5f,
  49230. width * 0.7f, height * 0.1f,
  49231. width * 0.7f, height * 0.9f);
  49232. if (isButtonDown)
  49233. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  49234. else
  49235. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  49236. g.fillPath (p);
  49237. g.setColour (Colour (0x80000000));
  49238. g.strokePath (p, PathStrokeType (0.5f));
  49239. }
  49240. void LookAndFeel::drawScrollbar (Graphics& g,
  49241. ScrollBar& scrollbar,
  49242. int x, int y,
  49243. int width, int height,
  49244. bool isScrollbarVertical,
  49245. int thumbStartPosition,
  49246. int thumbSize,
  49247. bool /*isMouseOver*/,
  49248. bool /*isMouseDown*/)
  49249. {
  49250. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  49251. Path slotPath, thumbPath;
  49252. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  49253. const float slotIndentx2 = slotIndent * 2.0f;
  49254. const float thumbIndent = slotIndent + 1.0f;
  49255. const float thumbIndentx2 = thumbIndent * 2.0f;
  49256. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  49257. if (isScrollbarVertical)
  49258. {
  49259. slotPath.addRoundedRectangle (x + slotIndent,
  49260. y + slotIndent,
  49261. width - slotIndentx2,
  49262. height - slotIndentx2,
  49263. (width - slotIndentx2) * 0.5f);
  49264. if (thumbSize > 0)
  49265. thumbPath.addRoundedRectangle (x + thumbIndent,
  49266. thumbStartPosition + thumbIndent,
  49267. width - thumbIndentx2,
  49268. thumbSize - thumbIndentx2,
  49269. (width - thumbIndentx2) * 0.5f);
  49270. gx1 = (float) x;
  49271. gx2 = x + width * 0.7f;
  49272. }
  49273. else
  49274. {
  49275. slotPath.addRoundedRectangle (x + slotIndent,
  49276. y + slotIndent,
  49277. width - slotIndentx2,
  49278. height - slotIndentx2,
  49279. (height - slotIndentx2) * 0.5f);
  49280. if (thumbSize > 0)
  49281. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  49282. y + thumbIndent,
  49283. thumbSize - thumbIndentx2,
  49284. height - thumbIndentx2,
  49285. (height - thumbIndentx2) * 0.5f);
  49286. gy1 = (float) y;
  49287. gy2 = y + height * 0.7f;
  49288. }
  49289. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  49290. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  49291. gx1, gy1,
  49292. thumbColour.overlaidWith (Colour (0x19000000)),
  49293. gx2, gy2, false);
  49294. g.setBrush (&gb);
  49295. g.fillPath (slotPath);
  49296. if (isScrollbarVertical)
  49297. {
  49298. gx1 = x + width * 0.6f;
  49299. gx2 = (float) x + width;
  49300. }
  49301. else
  49302. {
  49303. gy1 = y + height * 0.6f;
  49304. gy2 = (float) y + height;
  49305. }
  49306. GradientBrush gb2 (Colours::transparentBlack,
  49307. gx1, gy1,
  49308. Colour (0x19000000),
  49309. gx2, gy2, false);
  49310. g.setBrush (&gb2);
  49311. g.fillPath (slotPath);
  49312. g.setColour (thumbColour);
  49313. g.fillPath (thumbPath);
  49314. GradientBrush gb3 (Colour (0x10000000),
  49315. gx1, gy1,
  49316. Colours::transparentBlack,
  49317. gx2, gy2, false);
  49318. g.saveState();
  49319. g.setBrush (&gb3);
  49320. if (isScrollbarVertical)
  49321. g.reduceClipRegion (x + width / 2, y, width, height);
  49322. else
  49323. g.reduceClipRegion (x, y + height / 2, width, height);
  49324. g.fillPath (thumbPath);
  49325. g.restoreState();
  49326. g.setColour (Colour (0x4c000000));
  49327. g.strokePath (thumbPath, PathStrokeType (0.4f));
  49328. }
  49329. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  49330. {
  49331. return 0;
  49332. }
  49333. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  49334. {
  49335. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  49336. }
  49337. int LookAndFeel::getDefaultScrollbarWidth()
  49338. {
  49339. return 18;
  49340. }
  49341. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  49342. {
  49343. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  49344. : scrollbar.getHeight());
  49345. }
  49346. const Path LookAndFeel::getTickShape (const float height)
  49347. {
  49348. static const unsigned char tickShapeData[] =
  49349. {
  49350. 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,
  49351. 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,
  49352. 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,
  49353. 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,
  49354. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  49355. };
  49356. Path p;
  49357. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  49358. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49359. return p;
  49360. }
  49361. const Path LookAndFeel::getCrossShape (const float height)
  49362. {
  49363. static const unsigned char crossShapeData[] =
  49364. {
  49365. 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,
  49366. 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,
  49367. 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,
  49368. 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,
  49369. 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,
  49370. 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,
  49371. 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
  49372. };
  49373. Path p;
  49374. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  49375. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49376. return p;
  49377. }
  49378. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  49379. {
  49380. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  49381. x += (w - boxSize) >> 1;
  49382. y += (h - boxSize) >> 1;
  49383. w = boxSize;
  49384. h = boxSize;
  49385. g.setColour (Colour (0xe5ffffff));
  49386. g.fillRect (x, y, w, h);
  49387. g.setColour (Colour (0x80000000));
  49388. g.drawRect (x, y, w, h);
  49389. const float size = boxSize / 2 + 1.0f;
  49390. const float centre = (float) (boxSize / 2);
  49391. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  49392. if (isPlus)
  49393. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  49394. }
  49395. void LookAndFeel::drawBubble (Graphics& g,
  49396. float tipX, float tipY,
  49397. float boxX, float boxY,
  49398. float boxW, float boxH)
  49399. {
  49400. int side = 0;
  49401. if (tipX < boxX)
  49402. side = 1;
  49403. else if (tipX > boxX + boxW)
  49404. side = 3;
  49405. else if (tipY > boxY + boxH)
  49406. side = 2;
  49407. const float indent = 2.0f;
  49408. Path p;
  49409. p.addBubble (boxX + indent,
  49410. boxY + indent,
  49411. boxW - indent * 2.0f,
  49412. boxH - indent * 2.0f,
  49413. 5.0f,
  49414. tipX, tipY,
  49415. side,
  49416. 0.5f,
  49417. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  49418. //xxx need to take comp as param for colour
  49419. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  49420. g.fillPath (p);
  49421. //xxx as above
  49422. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  49423. g.strokePath (p, PathStrokeType (1.33f));
  49424. }
  49425. const Font LookAndFeel::getPopupMenuFont()
  49426. {
  49427. return Font (17.0f);
  49428. }
  49429. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  49430. const bool isSeparator,
  49431. int standardMenuItemHeight,
  49432. int& idealWidth,
  49433. int& idealHeight)
  49434. {
  49435. if (isSeparator)
  49436. {
  49437. idealWidth = 50;
  49438. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  49439. }
  49440. else
  49441. {
  49442. Font font (getPopupMenuFont());
  49443. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  49444. font.setHeight (standardMenuItemHeight / 1.3f);
  49445. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  49446. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  49447. }
  49448. }
  49449. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  49450. {
  49451. const Colour background (findColour (PopupMenu::backgroundColourId));
  49452. g.fillAll (background);
  49453. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  49454. for (int i = 0; i < height; i += 3)
  49455. g.fillRect (0, i, width, 1);
  49456. #if ! JUCE_MAC
  49457. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  49458. g.drawRect (0, 0, width, height);
  49459. #endif
  49460. }
  49461. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  49462. int width, int height,
  49463. bool isScrollUpArrow)
  49464. {
  49465. const Colour background (findColour (PopupMenu::backgroundColourId));
  49466. GradientBrush gb (background,
  49467. 0.0f, height * 0.5f,
  49468. background.withAlpha (0.0f),
  49469. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  49470. false);
  49471. g.setBrush (&gb);
  49472. g.fillRect (1, 1, width - 2, height - 2);
  49473. const float hw = width * 0.5f;
  49474. const float arrowW = height * 0.3f;
  49475. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  49476. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  49477. Path p;
  49478. p.addTriangle (hw - arrowW, y1,
  49479. hw + arrowW, y1,
  49480. hw, y2);
  49481. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  49482. g.fillPath (p);
  49483. }
  49484. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  49485. int width, int height,
  49486. const bool isSeparator,
  49487. const bool isActive,
  49488. const bool isHighlighted,
  49489. const bool isTicked,
  49490. const bool hasSubMenu,
  49491. const String& text,
  49492. const String& shortcutKeyText,
  49493. Image* image,
  49494. const Colour* const textColourToUse)
  49495. {
  49496. const float halfH = height * 0.5f;
  49497. if (isSeparator)
  49498. {
  49499. const float separatorIndent = 5.5f;
  49500. g.setColour (Colour (0x33000000));
  49501. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  49502. g.setColour (Colour (0x66ffffff));
  49503. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  49504. }
  49505. else
  49506. {
  49507. Colour textColour (findColour (PopupMenu::textColourId));
  49508. if (textColourToUse != 0)
  49509. textColour = *textColourToUse;
  49510. if (isHighlighted)
  49511. {
  49512. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  49513. g.fillRect (1, 1, width - 2, height - 2);
  49514. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  49515. }
  49516. else
  49517. {
  49518. g.setColour (textColour);
  49519. }
  49520. if (! isActive)
  49521. g.setOpacity (0.3f);
  49522. Font font (getPopupMenuFont());
  49523. if (font.getHeight() > height / 1.3f)
  49524. font.setHeight (height / 1.3f);
  49525. g.setFont (font);
  49526. const int leftBorder = (height * 5) / 4;
  49527. const int rightBorder = 4;
  49528. if (image != 0)
  49529. {
  49530. g.drawImageWithin (image,
  49531. 2, 1, leftBorder - 4, height - 2,
  49532. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  49533. }
  49534. else if (isTicked)
  49535. {
  49536. const Path tick (getTickShape (1.0f));
  49537. const float th = font.getAscent();
  49538. const float ty = halfH - th * 0.5f;
  49539. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  49540. th, true));
  49541. }
  49542. g.drawFittedText (text,
  49543. leftBorder, 0,
  49544. width - (leftBorder + rightBorder), height,
  49545. Justification::centredLeft, 1);
  49546. if (shortcutKeyText.isNotEmpty())
  49547. {
  49548. Font f2 (g.getCurrentFont());
  49549. f2.setHeight (f2.getHeight() * 0.75f);
  49550. f2.setHorizontalScale (0.95f);
  49551. g.setFont (f2);
  49552. g.drawText (shortcutKeyText,
  49553. leftBorder,
  49554. 0,
  49555. width - (leftBorder + rightBorder + 4),
  49556. height,
  49557. Justification::centredRight,
  49558. true);
  49559. }
  49560. if (hasSubMenu)
  49561. {
  49562. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  49563. const float x = width - height * 0.6f;
  49564. Path p;
  49565. p.addTriangle (x, halfH - arrowH * 0.5f,
  49566. x, halfH + arrowH * 0.5f,
  49567. x + arrowH * 0.6f, halfH);
  49568. g.fillPath (p);
  49569. }
  49570. }
  49571. }
  49572. int LookAndFeel::getMenuWindowFlags()
  49573. {
  49574. return ComponentPeer::windowHasDropShadow;
  49575. }
  49576. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  49577. bool, MenuBarComponent& menuBar)
  49578. {
  49579. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  49580. if (menuBar.isEnabled())
  49581. {
  49582. drawShinyButtonShape (g,
  49583. -4.0f, 0.0f,
  49584. width + 8.0f, (float) height,
  49585. 0.0f,
  49586. baseColour,
  49587. 0.4f,
  49588. true, true, true, true);
  49589. }
  49590. else
  49591. {
  49592. g.fillAll (baseColour);
  49593. }
  49594. }
  49595. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  49596. {
  49597. return Font (menuBar.getHeight() * 0.7f);
  49598. }
  49599. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  49600. {
  49601. return getMenuBarFont (menuBar, itemIndex, itemText)
  49602. .getStringWidth (itemText) + menuBar.getHeight();
  49603. }
  49604. void LookAndFeel::drawMenuBarItem (Graphics& g,
  49605. int width, int height,
  49606. int itemIndex,
  49607. const String& itemText,
  49608. bool isMouseOverItem,
  49609. bool isMenuOpen,
  49610. bool /*isMouseOverBar*/,
  49611. MenuBarComponent& menuBar)
  49612. {
  49613. if (! menuBar.isEnabled())
  49614. {
  49615. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  49616. .withMultipliedAlpha (0.5f));
  49617. }
  49618. else if (isMenuOpen || isMouseOverItem)
  49619. {
  49620. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  49621. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  49622. }
  49623. else
  49624. {
  49625. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  49626. }
  49627. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  49628. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  49629. }
  49630. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  49631. TextEditor& textEditor)
  49632. {
  49633. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  49634. }
  49635. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  49636. {
  49637. if (textEditor.isEnabled())
  49638. {
  49639. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  49640. {
  49641. const int border = 2;
  49642. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  49643. g.drawRect (0, 0, width, height, border);
  49644. g.setOpacity (1.0f);
  49645. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  49646. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  49647. }
  49648. else
  49649. {
  49650. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  49651. g.drawRect (0, 0, width, height);
  49652. g.setOpacity (1.0f);
  49653. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  49654. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  49655. }
  49656. }
  49657. }
  49658. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  49659. const bool isButtonDown,
  49660. int buttonX, int buttonY,
  49661. int buttonW, int buttonH,
  49662. ComboBox& box)
  49663. {
  49664. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  49665. if (box.isEnabled() && box.hasKeyboardFocus (false))
  49666. {
  49667. g.setColour (box.findColour (TextButton::buttonColourId));
  49668. g.drawRect (0, 0, width, height, 2);
  49669. }
  49670. else
  49671. {
  49672. g.setColour (box.findColour (ComboBox::outlineColourId));
  49673. g.drawRect (0, 0, width, height);
  49674. }
  49675. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  49676. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  49677. box.hasKeyboardFocus (true),
  49678. false, isButtonDown)
  49679. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  49680. drawGlassLozenge (g,
  49681. buttonX + outlineThickness, buttonY + outlineThickness,
  49682. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  49683. baseColour, outlineThickness, -1.0f,
  49684. true, true, true, true);
  49685. if (box.isEnabled())
  49686. {
  49687. const float arrowX = 0.3f;
  49688. const float arrowH = 0.2f;
  49689. Path p;
  49690. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  49691. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  49692. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  49693. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  49694. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  49695. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  49696. g.setColour (box.findColour (ComboBox::arrowColourId));
  49697. g.fillPath (p);
  49698. }
  49699. }
  49700. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  49701. {
  49702. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  49703. }
  49704. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  49705. {
  49706. return new Label (String::empty, String::empty);
  49707. }
  49708. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  49709. {
  49710. label.setBounds (1, 1,
  49711. box.getWidth() + 3 - box.getHeight(),
  49712. box.getHeight() - 2);
  49713. label.setFont (getComboBoxFont (box));
  49714. }
  49715. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  49716. {
  49717. g.fillAll (label.findColour (Label::backgroundColourId));
  49718. if (! label.isBeingEdited())
  49719. {
  49720. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  49721. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  49722. g.setFont (label.getFont());
  49723. g.drawFittedText (label.getText(),
  49724. label.getHorizontalBorderSize(),
  49725. label.getVerticalBorderSize(),
  49726. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  49727. label.getHeight() - 2 * label.getVerticalBorderSize(),
  49728. label.getJustificationType(),
  49729. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  49730. label.getMinimumHorizontalScale());
  49731. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  49732. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49733. }
  49734. else if (label.isEnabled())
  49735. {
  49736. g.setColour (label.findColour (Label::outlineColourId));
  49737. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49738. }
  49739. }
  49740. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  49741. int x, int y,
  49742. int width, int height,
  49743. float /*sliderPos*/,
  49744. float /*minSliderPos*/,
  49745. float /*maxSliderPos*/,
  49746. const Slider::SliderStyle /*style*/,
  49747. Slider& slider)
  49748. {
  49749. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49750. const Colour trackColour (slider.findColour (Slider::trackColourId));
  49751. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  49752. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  49753. Path indent;
  49754. if (slider.isHorizontal())
  49755. {
  49756. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  49757. const float ih = sliderRadius;
  49758. GradientBrush gb (gradCol1, 0.0f, iy,
  49759. gradCol2, 0.0f, iy + ih, false);
  49760. g.setBrush (&gb);
  49761. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  49762. width + sliderRadius, ih,
  49763. 5.0f);
  49764. g.fillPath (indent);
  49765. }
  49766. else
  49767. {
  49768. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  49769. const float iw = sliderRadius;
  49770. GradientBrush gb (gradCol1, ix, 0.0f,
  49771. gradCol2, ix + iw, 0.0f, false);
  49772. g.setBrush (&gb);
  49773. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  49774. iw, height + sliderRadius,
  49775. 5.0f);
  49776. g.fillPath (indent);
  49777. }
  49778. g.setColour (Colour (0x4c000000));
  49779. g.strokePath (indent, PathStrokeType (0.5f));
  49780. }
  49781. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  49782. int x, int y,
  49783. int width, int height,
  49784. float sliderPos,
  49785. float minSliderPos,
  49786. float maxSliderPos,
  49787. const Slider::SliderStyle style,
  49788. Slider& slider)
  49789. {
  49790. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49791. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  49792. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  49793. slider.isMouseOverOrDragging() && slider.isEnabled(),
  49794. slider.isMouseButtonDown() && slider.isEnabled()));
  49795. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  49796. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  49797. {
  49798. float kx, ky;
  49799. if (style == Slider::LinearVertical)
  49800. {
  49801. kx = x + width * 0.5f;
  49802. ky = sliderPos;
  49803. }
  49804. else
  49805. {
  49806. kx = sliderPos;
  49807. ky = y + height * 0.5f;
  49808. }
  49809. drawGlassSphere (g,
  49810. kx - sliderRadius,
  49811. ky - sliderRadius,
  49812. sliderRadius * 2.0f,
  49813. knobColour, outlineThickness);
  49814. }
  49815. else
  49816. {
  49817. if (style == Slider::ThreeValueVertical)
  49818. {
  49819. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  49820. sliderPos - sliderRadius,
  49821. sliderRadius * 2.0f,
  49822. knobColour, outlineThickness);
  49823. }
  49824. else if (style == Slider::ThreeValueHorizontal)
  49825. {
  49826. drawGlassSphere (g,sliderPos - sliderRadius,
  49827. y + height * 0.5f - sliderRadius,
  49828. sliderRadius * 2.0f,
  49829. knobColour, outlineThickness);
  49830. }
  49831. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  49832. {
  49833. const float sr = jmin (sliderRadius, width * 0.4f);
  49834. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  49835. minSliderPos - sliderRadius,
  49836. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  49837. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  49838. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  49839. }
  49840. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  49841. {
  49842. const float sr = jmin (sliderRadius, height * 0.4f);
  49843. drawGlassPointer (g, minSliderPos - sr,
  49844. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  49845. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  49846. drawGlassPointer (g, maxSliderPos - sliderRadius,
  49847. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  49848. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  49849. }
  49850. }
  49851. }
  49852. void LookAndFeel::drawLinearSlider (Graphics& g,
  49853. int x, int y,
  49854. int width, int height,
  49855. float sliderPos,
  49856. float minSliderPos,
  49857. float maxSliderPos,
  49858. const Slider::SliderStyle style,
  49859. Slider& slider)
  49860. {
  49861. g.fillAll (slider.findColour (Slider::backgroundColourId));
  49862. if (style == Slider::LinearBar)
  49863. {
  49864. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49865. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  49866. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  49867. false,
  49868. isMouseOver,
  49869. isMouseOver || slider.isMouseButtonDown()));
  49870. drawShinyButtonShape (g,
  49871. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  49872. baseColour,
  49873. slider.isEnabled() ? 0.9f : 0.3f,
  49874. true, true, true, true);
  49875. }
  49876. else
  49877. {
  49878. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49879. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49880. }
  49881. }
  49882. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  49883. {
  49884. return jmin (7,
  49885. slider.getHeight() / 2,
  49886. slider.getWidth() / 2) + 2;
  49887. }
  49888. void LookAndFeel::drawRotarySlider (Graphics& g,
  49889. int x, int y,
  49890. int width, int height,
  49891. float sliderPos,
  49892. const float rotaryStartAngle,
  49893. const float rotaryEndAngle,
  49894. Slider& slider)
  49895. {
  49896. const float radius = jmin (width / 2, height / 2) - 2.0f;
  49897. const float centreX = x + width * 0.5f;
  49898. const float centreY = y + height * 0.5f;
  49899. const float rx = centreX - radius;
  49900. const float ry = centreY - radius;
  49901. const float rw = radius * 2.0f;
  49902. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  49903. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49904. if (radius > 12.0f)
  49905. {
  49906. if (slider.isEnabled())
  49907. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49908. else
  49909. g.setColour (Colour (0x80808080));
  49910. const float thickness = 0.7f;
  49911. {
  49912. Path filledArc;
  49913. filledArc.addPieSegment (rx, ry, rw, rw,
  49914. rotaryStartAngle,
  49915. angle,
  49916. thickness);
  49917. g.fillPath (filledArc);
  49918. }
  49919. if (thickness > 0)
  49920. {
  49921. const float innerRadius = radius * 0.2f;
  49922. Path p;
  49923. p.addTriangle (-innerRadius, 0.0f,
  49924. 0.0f, -radius * thickness * 1.1f,
  49925. innerRadius, 0.0f);
  49926. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  49927. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49928. }
  49929. if (slider.isEnabled())
  49930. {
  49931. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  49932. Path outlineArc;
  49933. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  49934. outlineArc.closeSubPath();
  49935. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  49936. }
  49937. }
  49938. else
  49939. {
  49940. if (slider.isEnabled())
  49941. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49942. else
  49943. g.setColour (Colour (0x80808080));
  49944. Path p;
  49945. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  49946. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  49947. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  49948. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49949. }
  49950. }
  49951. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  49952. {
  49953. return new TextButton (isIncrement ? "+" : "-", String::empty);
  49954. }
  49955. class SliderLabelComp : public Label
  49956. {
  49957. public:
  49958. SliderLabelComp() : Label (String::empty, String::empty) {}
  49959. ~SliderLabelComp() {}
  49960. void mouseWheelMove (const MouseEvent&, float, float) {}
  49961. };
  49962. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  49963. {
  49964. Label* const l = new SliderLabelComp();
  49965. l->setJustificationType (Justification::centred);
  49966. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49967. l->setColour (Label::backgroundColourId,
  49968. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  49969. : slider.findColour (Slider::textBoxBackgroundColourId));
  49970. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49971. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49972. l->setColour (TextEditor::backgroundColourId,
  49973. slider.findColour (Slider::textBoxBackgroundColourId)
  49974. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  49975. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49976. return l;
  49977. }
  49978. ImageEffectFilter* LookAndFeel::getSliderEffect()
  49979. {
  49980. return 0;
  49981. }
  49982. static const TextLayout layoutTooltipText (const String& text) throw()
  49983. {
  49984. const float tooltipFontSize = 12.0f;
  49985. const int maxToolTipWidth = 400;
  49986. const Font f (tooltipFontSize, Font::bold);
  49987. TextLayout tl (text, f);
  49988. tl.layout (maxToolTipWidth, Justification::left, true);
  49989. return tl;
  49990. }
  49991. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  49992. {
  49993. const TextLayout tl (layoutTooltipText (tipText));
  49994. width = tl.getWidth() + 14;
  49995. height = tl.getHeight() + 6;
  49996. }
  49997. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  49998. {
  49999. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  50000. const Colour textCol (findColour (TooltipWindow::textColourId));
  50001. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  50002. g.setColour (findColour (TooltipWindow::outlineColourId));
  50003. g.drawRect (0, 0, width, height, 1);
  50004. #endif
  50005. const TextLayout tl (layoutTooltipText (text));
  50006. g.setColour (findColour (TooltipWindow::textColourId));
  50007. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  50008. }
  50009. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  50010. {
  50011. return new TextButton (text, TRANS("click to browse for a different file"));
  50012. }
  50013. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  50014. ComboBox* filenameBox,
  50015. Button* browseButton)
  50016. {
  50017. browseButton->setSize (80, filenameComp.getHeight());
  50018. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  50019. if (tb != 0)
  50020. tb->changeWidthToFitText();
  50021. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  50022. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  50023. }
  50024. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  50025. int imageX, int imageY, int imageW, int imageH,
  50026. const Colour& overlayColour,
  50027. float imageOpacity,
  50028. ImageButton& button)
  50029. {
  50030. if (! button.isEnabled())
  50031. imageOpacity *= 0.3f;
  50032. if (! overlayColour.isOpaque())
  50033. {
  50034. g.setOpacity (imageOpacity);
  50035. g.drawImage (image, imageX, imageY, imageW, imageH,
  50036. 0, 0, image->getWidth(), image->getHeight(), false);
  50037. }
  50038. if (! overlayColour.isTransparent())
  50039. {
  50040. g.setColour (overlayColour);
  50041. g.drawImage (image, imageX, imageY, imageW, imageH,
  50042. 0, 0, image->getWidth(), image->getHeight(), true);
  50043. }
  50044. }
  50045. void LookAndFeel::drawCornerResizer (Graphics& g,
  50046. int w, int h,
  50047. bool /*isMouseOver*/,
  50048. bool /*isMouseDragging*/)
  50049. {
  50050. const float lineThickness = jmin (w, h) * 0.075f;
  50051. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  50052. {
  50053. g.setColour (Colours::lightgrey);
  50054. g.drawLine (w * i,
  50055. h + 1.0f,
  50056. w + 1.0f,
  50057. h * i,
  50058. lineThickness);
  50059. g.setColour (Colours::darkgrey);
  50060. g.drawLine (w * i + lineThickness,
  50061. h + 1.0f,
  50062. w + 1.0f,
  50063. h * i + lineThickness,
  50064. lineThickness);
  50065. }
  50066. }
  50067. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  50068. const BorderSize& /*borders*/)
  50069. {
  50070. }
  50071. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  50072. const BorderSize& /*border*/, ResizableWindow& window)
  50073. {
  50074. g.fillAll (window.getBackgroundColour());
  50075. }
  50076. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  50077. const BorderSize& border, ResizableWindow&)
  50078. {
  50079. g.setColour (Colour (0x80000000));
  50080. g.drawRect (0, 0, w, h);
  50081. g.setColour (Colour (0x19000000));
  50082. g.drawRect (border.getLeft() - 1,
  50083. border.getTop() - 1,
  50084. w + 2 - border.getLeftAndRight(),
  50085. h + 2 - border.getTopAndBottom());
  50086. }
  50087. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  50088. Graphics& g, int w, int h,
  50089. int titleSpaceX, int titleSpaceW,
  50090. const Image* icon,
  50091. bool drawTitleTextOnLeft)
  50092. {
  50093. const bool isActive = window.isActiveWindow();
  50094. GradientBrush gb (window.getBackgroundColour(),
  50095. 0.0f, 0.0f,
  50096. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  50097. 0.0f, (float) h, false);
  50098. g.setBrush (&gb);
  50099. g.fillAll();
  50100. g.setFont (h * 0.65f, Font::bold);
  50101. int textW = g.getCurrentFont().getStringWidth (window.getName());
  50102. int iconW = 0;
  50103. int iconH = 0;
  50104. if (icon != 0)
  50105. {
  50106. iconH = (int) g.getCurrentFont().getHeight();
  50107. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  50108. }
  50109. textW = jmin (titleSpaceW, textW + iconW);
  50110. int textX = drawTitleTextOnLeft ? titleSpaceX
  50111. : jmax (titleSpaceX, (w - textW) / 2);
  50112. if (textX + textW > titleSpaceX + titleSpaceW)
  50113. textX = titleSpaceX + titleSpaceW - textW;
  50114. if (icon != 0)
  50115. {
  50116. g.setOpacity (isActive ? 1.0f : 0.6f);
  50117. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  50118. RectanglePlacement::centred, false);
  50119. textX += iconW;
  50120. textW -= iconW;
  50121. }
  50122. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  50123. g.setColour (findColour (DocumentWindow::textColourId));
  50124. else
  50125. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  50126. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  50127. }
  50128. class GlassWindowButton : public Button
  50129. {
  50130. public:
  50131. GlassWindowButton (const String& name, const Colour& col,
  50132. const Path& normalShape_,
  50133. const Path& toggledShape_) throw()
  50134. : Button (name),
  50135. colour (col),
  50136. normalShape (normalShape_),
  50137. toggledShape (toggledShape_)
  50138. {
  50139. }
  50140. ~GlassWindowButton()
  50141. {
  50142. }
  50143. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  50144. {
  50145. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  50146. if (! isEnabled())
  50147. alpha *= 0.5f;
  50148. float x = 0, y = 0, diam;
  50149. if (getWidth() < getHeight())
  50150. {
  50151. diam = (float) getWidth();
  50152. y = (getHeight() - getWidth()) * 0.5f;
  50153. }
  50154. else
  50155. {
  50156. diam = (float) getHeight();
  50157. y = (getWidth() - getHeight()) * 0.5f;
  50158. }
  50159. x += diam * 0.05f;
  50160. y += diam * 0.05f;
  50161. diam *= 0.9f;
  50162. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  50163. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  50164. g.setBrush (&gb1);
  50165. g.fillEllipse (x, y, diam, diam);
  50166. x += 2.0f;
  50167. y += 2.0f;
  50168. diam -= 4.0f;
  50169. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  50170. Path& p = getToggleState() ? toggledShape : normalShape;
  50171. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  50172. diam * 0.4f, diam * 0.4f, true));
  50173. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  50174. g.fillPath (p, t);
  50175. }
  50176. juce_UseDebuggingNewOperator
  50177. private:
  50178. Colour colour;
  50179. Path normalShape, toggledShape;
  50180. GlassWindowButton (const GlassWindowButton&);
  50181. const GlassWindowButton& operator= (const GlassWindowButton&);
  50182. };
  50183. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  50184. {
  50185. Path shape;
  50186. const float crossThickness = 0.25f;
  50187. if (buttonType == DocumentWindow::closeButton)
  50188. {
  50189. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  50190. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  50191. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  50192. }
  50193. else if (buttonType == DocumentWindow::minimiseButton)
  50194. {
  50195. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50196. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  50197. }
  50198. else if (buttonType == DocumentWindow::maximiseButton)
  50199. {
  50200. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  50201. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50202. Path fullscreenShape;
  50203. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  50204. fullscreenShape.lineTo (0.0f, 100.0f);
  50205. fullscreenShape.lineTo (0.0f, 0.0f);
  50206. fullscreenShape.lineTo (100.0f, 0.0f);
  50207. fullscreenShape.lineTo (100.0f, 45.0f);
  50208. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  50209. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  50210. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  50211. }
  50212. jassertfalse
  50213. return 0;
  50214. }
  50215. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  50216. int titleBarX,
  50217. int titleBarY,
  50218. int titleBarW,
  50219. int titleBarH,
  50220. Button* minimiseButton,
  50221. Button* maximiseButton,
  50222. Button* closeButton,
  50223. bool positionTitleBarButtonsOnLeft)
  50224. {
  50225. const int buttonW = titleBarH - titleBarH / 8;
  50226. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  50227. : titleBarX + titleBarW - buttonW - buttonW / 4;
  50228. if (closeButton != 0)
  50229. {
  50230. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50231. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  50232. }
  50233. if (positionTitleBarButtonsOnLeft)
  50234. swapVariables (minimiseButton, maximiseButton);
  50235. if (maximiseButton != 0)
  50236. {
  50237. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50238. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  50239. }
  50240. if (minimiseButton != 0)
  50241. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50242. }
  50243. int LookAndFeel::getDefaultMenuBarHeight()
  50244. {
  50245. return 24;
  50246. }
  50247. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  50248. {
  50249. return new DropShadower (0.4f, 1, 5, 10);
  50250. }
  50251. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  50252. int w, int h,
  50253. bool /*isVerticalBar*/,
  50254. bool isMouseOver,
  50255. bool isMouseDragging)
  50256. {
  50257. float alpha = 0.5f;
  50258. if (isMouseOver || isMouseDragging)
  50259. {
  50260. g.fillAll (Colour (0x190000ff));
  50261. alpha = 1.0f;
  50262. }
  50263. const float cx = w * 0.5f;
  50264. const float cy = h * 0.5f;
  50265. const float cr = jmin (w, h) * 0.4f;
  50266. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  50267. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  50268. true);
  50269. g.setBrush (&gb);
  50270. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  50271. }
  50272. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  50273. const String& text,
  50274. const Justification& position,
  50275. GroupComponent& group)
  50276. {
  50277. const float textH = 15.0f;
  50278. const float indent = 3.0f;
  50279. const float textEdgeGap = 4.0f;
  50280. float cs = 5.0f;
  50281. Font f (textH);
  50282. Path p;
  50283. float x = indent;
  50284. float y = f.getAscent() - 3.0f;
  50285. float w = jmax (0.0f, width - x * 2.0f);
  50286. float h = jmax (0.0f, height - y - indent);
  50287. cs = jmin (cs, w * 0.5f, h * 0.5f);
  50288. const float cs2 = 2.0f * cs;
  50289. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  50290. float textX = cs + textEdgeGap;
  50291. if (position.testFlags (Justification::horizontallyCentred))
  50292. textX = cs + (w - cs2 - textW) * 0.5f;
  50293. else if (position.testFlags (Justification::right))
  50294. textX = w - cs - textW - textEdgeGap;
  50295. p.startNewSubPath (x + textX + textW, y);
  50296. p.lineTo (x + w - cs, y);
  50297. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  50298. p.lineTo (x + w, y + h - cs);
  50299. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50300. p.lineTo (x + cs, y + h);
  50301. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50302. p.lineTo (x, y + cs);
  50303. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50304. p.lineTo (x + textX, y);
  50305. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  50306. g.setColour (group.findColour (GroupComponent::outlineColourId)
  50307. .withMultipliedAlpha (alpha));
  50308. g.strokePath (p, PathStrokeType (2.0f));
  50309. g.setColour (group.findColour (GroupComponent::textColourId)
  50310. .withMultipliedAlpha (alpha));
  50311. g.setFont (f);
  50312. g.drawText (text,
  50313. roundFloatToInt (x + textX), 0,
  50314. roundFloatToInt (textW),
  50315. roundFloatToInt (textH),
  50316. Justification::centred, true);
  50317. }
  50318. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  50319. {
  50320. return 1 + tabDepth / 3;
  50321. }
  50322. int LookAndFeel::getTabButtonSpaceAroundImage()
  50323. {
  50324. return 4;
  50325. }
  50326. void LookAndFeel::createTabButtonShape (Path& p,
  50327. int width, int height,
  50328. int /*tabIndex*/,
  50329. const String& /*text*/,
  50330. Button& /*button*/,
  50331. TabbedButtonBar::Orientation orientation,
  50332. const bool /*isMouseOver*/,
  50333. const bool /*isMouseDown*/,
  50334. const bool /*isFrontTab*/)
  50335. {
  50336. const float w = (float) width;
  50337. const float h = (float) height;
  50338. float length = w;
  50339. float depth = h;
  50340. if (orientation == TabbedButtonBar::TabsAtLeft
  50341. || orientation == TabbedButtonBar::TabsAtRight)
  50342. {
  50343. swapVariables (length, depth);
  50344. }
  50345. const float indent = (float) getTabButtonOverlap ((int) depth);
  50346. const float overhang = 4.0f;
  50347. if (orientation == TabbedButtonBar::TabsAtLeft)
  50348. {
  50349. p.startNewSubPath (w, 0.0f);
  50350. p.lineTo (0.0f, indent);
  50351. p.lineTo (0.0f, h - indent);
  50352. p.lineTo (w, h);
  50353. p.lineTo (w + overhang, h + overhang);
  50354. p.lineTo (w + overhang, -overhang);
  50355. }
  50356. else if (orientation == TabbedButtonBar::TabsAtRight)
  50357. {
  50358. p.startNewSubPath (0.0f, 0.0f);
  50359. p.lineTo (w, indent);
  50360. p.lineTo (w, h - indent);
  50361. p.lineTo (0.0f, h);
  50362. p.lineTo (-overhang, h + overhang);
  50363. p.lineTo (-overhang, -overhang);
  50364. }
  50365. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50366. {
  50367. p.startNewSubPath (0.0f, 0.0f);
  50368. p.lineTo (indent, h);
  50369. p.lineTo (w - indent, h);
  50370. p.lineTo (w, 0.0f);
  50371. p.lineTo (w + overhang, -overhang);
  50372. p.lineTo (-overhang, -overhang);
  50373. }
  50374. else
  50375. {
  50376. p.startNewSubPath (0.0f, h);
  50377. p.lineTo (indent, 0.0f);
  50378. p.lineTo (w - indent, 0.0f);
  50379. p.lineTo (w, h);
  50380. p.lineTo (w + overhang, h + overhang);
  50381. p.lineTo (-overhang, h + overhang);
  50382. }
  50383. p.closeSubPath();
  50384. p = p.createPathWithRoundedCorners (3.0f);
  50385. }
  50386. void LookAndFeel::fillTabButtonShape (Graphics& g,
  50387. const Path& path,
  50388. const Colour& preferredColour,
  50389. int /*tabIndex*/,
  50390. const String& /*text*/,
  50391. Button& button,
  50392. TabbedButtonBar::Orientation /*orientation*/,
  50393. const bool /*isMouseOver*/,
  50394. const bool /*isMouseDown*/,
  50395. const bool isFrontTab)
  50396. {
  50397. g.setColour (isFrontTab ? preferredColour
  50398. : preferredColour.withMultipliedAlpha (0.9f));
  50399. g.fillPath (path);
  50400. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  50401. : TabbedButtonBar::tabOutlineColourId, false)
  50402. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  50403. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  50404. }
  50405. void LookAndFeel::drawTabButtonText (Graphics& g,
  50406. int x, int y, int w, int h,
  50407. const Colour& preferredBackgroundColour,
  50408. int /*tabIndex*/,
  50409. const String& text,
  50410. Button& button,
  50411. TabbedButtonBar::Orientation orientation,
  50412. const bool isMouseOver,
  50413. const bool isMouseDown,
  50414. const bool isFrontTab)
  50415. {
  50416. int length = w;
  50417. int depth = h;
  50418. if (orientation == TabbedButtonBar::TabsAtLeft
  50419. || orientation == TabbedButtonBar::TabsAtRight)
  50420. {
  50421. swapVariables (length, depth);
  50422. }
  50423. Font font (depth * 0.6f);
  50424. font.setUnderline (button.hasKeyboardFocus (false));
  50425. GlyphArrangement textLayout;
  50426. textLayout.addFittedText (font, text.trim(),
  50427. 0.0f, 0.0f, (float) length, (float) depth,
  50428. Justification::centred,
  50429. jmax (1, depth / 12));
  50430. AffineTransform transform;
  50431. if (orientation == TabbedButtonBar::TabsAtLeft)
  50432. {
  50433. transform = transform.rotated (float_Pi * -0.5f)
  50434. .translated ((float) x, (float) (y + h));
  50435. }
  50436. else if (orientation == TabbedButtonBar::TabsAtRight)
  50437. {
  50438. transform = transform.rotated (float_Pi * 0.5f)
  50439. .translated ((float) (x + w), (float) y);
  50440. }
  50441. else
  50442. {
  50443. transform = transform.translated ((float) x, (float) y);
  50444. }
  50445. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  50446. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  50447. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  50448. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  50449. else
  50450. g.setColour (preferredBackgroundColour.contrasting());
  50451. if (! (isMouseOver || isMouseDown))
  50452. g.setOpacity (0.8f);
  50453. if (! button.isEnabled())
  50454. g.setOpacity (0.3f);
  50455. textLayout.draw (g, transform);
  50456. }
  50457. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  50458. const String& text,
  50459. int tabDepth,
  50460. Button&)
  50461. {
  50462. Font f (tabDepth * 0.6f);
  50463. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  50464. }
  50465. void LookAndFeel::drawTabButton (Graphics& g,
  50466. int w, int h,
  50467. const Colour& preferredColour,
  50468. int tabIndex,
  50469. const String& text,
  50470. Button& button,
  50471. TabbedButtonBar::Orientation orientation,
  50472. const bool isMouseOver,
  50473. const bool isMouseDown,
  50474. const bool isFrontTab)
  50475. {
  50476. int length = w;
  50477. int depth = h;
  50478. if (orientation == TabbedButtonBar::TabsAtLeft
  50479. || orientation == TabbedButtonBar::TabsAtRight)
  50480. {
  50481. swapVariables (length, depth);
  50482. }
  50483. Path tabShape;
  50484. createTabButtonShape (tabShape, w, h,
  50485. tabIndex, text, button, orientation,
  50486. isMouseOver, isMouseDown, isFrontTab);
  50487. fillTabButtonShape (g, tabShape, preferredColour,
  50488. tabIndex, text, button, orientation,
  50489. isMouseOver, isMouseDown, isFrontTab);
  50490. const int indent = getTabButtonOverlap (depth);
  50491. int x = 0, y = 0;
  50492. if (orientation == TabbedButtonBar::TabsAtLeft
  50493. || orientation == TabbedButtonBar::TabsAtRight)
  50494. {
  50495. y += indent;
  50496. h -= indent * 2;
  50497. }
  50498. else
  50499. {
  50500. x += indent;
  50501. w -= indent * 2;
  50502. }
  50503. drawTabButtonText (g, x, y, w, h, preferredColour,
  50504. tabIndex, text, button, orientation,
  50505. isMouseOver, isMouseDown, isFrontTab);
  50506. }
  50507. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  50508. int w, int h,
  50509. TabbedButtonBar& tabBar,
  50510. TabbedButtonBar::Orientation orientation)
  50511. {
  50512. const float shadowSize = 0.2f;
  50513. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  50514. Rectangle shadowRect;
  50515. if (orientation == TabbedButtonBar::TabsAtLeft)
  50516. {
  50517. x1 = (float) w;
  50518. x2 = w * (1.0f - shadowSize);
  50519. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  50520. }
  50521. else if (orientation == TabbedButtonBar::TabsAtRight)
  50522. {
  50523. x2 = w * shadowSize;
  50524. shadowRect.setBounds (0, 0, (int) x2, h);
  50525. }
  50526. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50527. {
  50528. y2 = h * shadowSize;
  50529. shadowRect.setBounds (0, 0, w, (int) y2);
  50530. }
  50531. else
  50532. {
  50533. y1 = (float) h;
  50534. y2 = h * (1.0f - shadowSize);
  50535. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  50536. }
  50537. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  50538. Colours::transparentBlack, x2, y2,
  50539. false);
  50540. g.setBrush (&gb);
  50541. shadowRect.expand (2, 2);
  50542. g.fillRect (shadowRect);
  50543. g.setColour (Colour (0x80000000));
  50544. if (orientation == TabbedButtonBar::TabsAtLeft)
  50545. {
  50546. g.fillRect (w - 1, 0, 1, h);
  50547. }
  50548. else if (orientation == TabbedButtonBar::TabsAtRight)
  50549. {
  50550. g.fillRect (0, 0, 1, h);
  50551. }
  50552. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50553. {
  50554. g.fillRect (0, 0, w, 1);
  50555. }
  50556. else
  50557. {
  50558. g.fillRect (0, h - 1, w, 1);
  50559. }
  50560. }
  50561. Button* LookAndFeel::createTabBarExtrasButton()
  50562. {
  50563. const float thickness = 7.0f;
  50564. const float indent = 22.0f;
  50565. Path p;
  50566. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  50567. DrawablePath ellipse;
  50568. ellipse.setPath (p);
  50569. ellipse.setSolidFill (Colour (0x99ffffff));
  50570. p.clear();
  50571. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  50572. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  50573. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  50574. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  50575. p.setUsingNonZeroWinding (false);
  50576. DrawablePath dp;
  50577. dp.setPath (p);
  50578. dp.setSolidFill (Colour (0x59000000));
  50579. DrawableComposite normalImage;
  50580. normalImage.insertDrawable (ellipse);
  50581. normalImage.insertDrawable (dp);
  50582. dp.setSolidFill (Colour (0xcc000000));
  50583. DrawableComposite overImage;
  50584. overImage.insertDrawable (ellipse);
  50585. overImage.insertDrawable (dp);
  50586. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  50587. db->setImages (&normalImage, &overImage, 0);
  50588. return db;
  50589. }
  50590. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  50591. {
  50592. g.fillAll (Colours::white);
  50593. const int w = header.getWidth();
  50594. const int h = header.getHeight();
  50595. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  50596. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  50597. false);
  50598. g.setBrush (&gb);
  50599. g.fillRect (0, h / 2, w, h);
  50600. g.setColour (Colour (0x33000000));
  50601. g.fillRect (0, h - 1, w, 1);
  50602. for (int i = header.getNumColumns (true); --i >= 0;)
  50603. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  50604. }
  50605. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  50606. int width, int height,
  50607. bool isMouseOver, bool isMouseDown,
  50608. int columnFlags)
  50609. {
  50610. if (isMouseDown)
  50611. g.fillAll (Colour (0x8899aadd));
  50612. else if (isMouseOver)
  50613. g.fillAll (Colour (0x5599aadd));
  50614. int rightOfText = width - 4;
  50615. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  50616. {
  50617. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  50618. const float bottom = height - top;
  50619. const float w = height * 0.5f;
  50620. const float x = rightOfText - (w * 1.25f);
  50621. rightOfText = (int) x;
  50622. Path sortArrow;
  50623. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  50624. g.setColour (Colour (0x99000000));
  50625. g.fillPath (sortArrow);
  50626. }
  50627. g.setColour (Colours::black);
  50628. g.setFont (height * 0.5f, Font::bold);
  50629. const int textX = 4;
  50630. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  50631. }
  50632. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  50633. {
  50634. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  50635. GradientBrush gb (background, 0.0f, 0.0f,
  50636. background.darker (0.1f),
  50637. toolbar.isVertical() ? w - 1.0f : 0.0f,
  50638. toolbar.isVertical() ? 0.0f : h - 1.0f,
  50639. false);
  50640. g.setBrush (&gb);
  50641. g.fillAll();
  50642. }
  50643. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  50644. {
  50645. return createTabBarExtrasButton();
  50646. }
  50647. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  50648. bool isMouseOver, bool isMouseDown,
  50649. ToolbarItemComponent& component)
  50650. {
  50651. if (isMouseDown)
  50652. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  50653. else if (isMouseOver)
  50654. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  50655. }
  50656. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  50657. const String& text, ToolbarItemComponent& component)
  50658. {
  50659. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  50660. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  50661. const float fontHeight = jmin (14.0f, height * 0.85f);
  50662. g.setFont (fontHeight);
  50663. g.drawFittedText (text,
  50664. x, y, width, height,
  50665. Justification::centred,
  50666. jmax (1, height / (int) fontHeight));
  50667. }
  50668. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  50669. bool isOpen, int width, int height)
  50670. {
  50671. const int buttonSize = (height * 3) / 4;
  50672. const int buttonIndent = (height - buttonSize) / 2;
  50673. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  50674. const int textX = buttonIndent * 2 + buttonSize + 2;
  50675. g.setColour (Colours::black);
  50676. g.setFont (height * 0.7f, Font::bold);
  50677. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  50678. }
  50679. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  50680. PropertyComponent&)
  50681. {
  50682. g.setColour (Colour (0x66ffffff));
  50683. g.fillRect (0, 0, width, height - 1);
  50684. }
  50685. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  50686. PropertyComponent& component)
  50687. {
  50688. g.setColour (Colours::black);
  50689. if (! component.isEnabled())
  50690. g.setOpacity (g.getCurrentColour().getFloatAlpha() * 0.6f);
  50691. g.setFont (jmin (height, 24) * 0.65f);
  50692. const Rectangle r (getPropertyComponentContentPosition (component));
  50693. g.drawFittedText (component.getName(),
  50694. 3, r.getY(), r.getX() - 5, r.getHeight(),
  50695. Justification::centredLeft, 2);
  50696. }
  50697. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  50698. {
  50699. return Rectangle (component.getWidth() / 3, 1,
  50700. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  50701. }
  50702. void LookAndFeel::createFileChooserHeaderText (const String& title,
  50703. const String& instructions,
  50704. GlyphArrangement& text,
  50705. int width)
  50706. {
  50707. text.clear();
  50708. text.addJustifiedText (Font (17.0f, Font::bold), title,
  50709. 8.0f, 22.0f, width - 16.0f,
  50710. Justification::centred);
  50711. text.addJustifiedText (Font (14.0f), instructions,
  50712. 8.0f, 24.0f + 16.0f, width - 16.0f,
  50713. Justification::centred);
  50714. }
  50715. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  50716. const String& filename, Image* icon,
  50717. const String& fileSizeDescription,
  50718. const String& fileTimeDescription,
  50719. const bool isDirectory,
  50720. const bool isItemSelected,
  50721. const int /*itemIndex*/)
  50722. {
  50723. if (isItemSelected)
  50724. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  50725. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  50726. g.setFont (height * 0.7f);
  50727. Image* im = icon;
  50728. Image* toRelease = 0;
  50729. if (im == 0)
  50730. {
  50731. toRelease = im = (isDirectory ? getDefaultFolderImage()
  50732. : getDefaultDocumentFileImage());
  50733. }
  50734. const int x = 32;
  50735. if (im != 0)
  50736. {
  50737. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  50738. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  50739. false);
  50740. ImageCache::release (toRelease);
  50741. }
  50742. if (width > 450 && ! isDirectory)
  50743. {
  50744. const int sizeX = roundFloatToInt (width * 0.7f);
  50745. const int dateX = roundFloatToInt (width * 0.8f);
  50746. g.drawFittedText (filename,
  50747. x, 0, sizeX - x, height,
  50748. Justification::centredLeft, 1);
  50749. g.setFont (height * 0.5f);
  50750. g.setColour (Colours::darkgrey);
  50751. if (! isDirectory)
  50752. {
  50753. g.drawFittedText (fileSizeDescription,
  50754. sizeX, 0, dateX - sizeX - 8, height,
  50755. Justification::centredRight, 1);
  50756. g.drawFittedText (fileTimeDescription,
  50757. dateX, 0, width - 8 - dateX, height,
  50758. Justification::centredRight, 1);
  50759. }
  50760. }
  50761. else
  50762. {
  50763. g.drawFittedText (filename,
  50764. x, 0, width - x, height,
  50765. Justification::centredLeft, 1);
  50766. }
  50767. }
  50768. Button* LookAndFeel::createFileBrowserGoUpButton()
  50769. {
  50770. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  50771. Path arrowPath;
  50772. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  50773. DrawablePath arrowImage;
  50774. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  50775. arrowImage.setPath (arrowPath);
  50776. goUpButton->setImages (&arrowImage);
  50777. return goUpButton;
  50778. }
  50779. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  50780. DirectoryContentsDisplayComponent* fileListComponent,
  50781. FilePreviewComponent* previewComp,
  50782. ComboBox* currentPathBox,
  50783. TextEditor* filenameBox,
  50784. Button* goUpButton)
  50785. {
  50786. const int x = 8;
  50787. int w = browserComp.getWidth() - x - x;
  50788. if (previewComp != 0)
  50789. {
  50790. const int previewWidth = w / 3;
  50791. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  50792. w -= previewWidth + 4;
  50793. }
  50794. int y = 4;
  50795. const int controlsHeight = 22;
  50796. const int bottomSectionHeight = controlsHeight + 8;
  50797. const int upButtonWidth = 50;
  50798. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  50799. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  50800. y += controlsHeight + 4;
  50801. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  50802. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  50803. y = listAsComp->getBottom() + 4;
  50804. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  50805. }
  50806. Image* LookAndFeel::getDefaultFolderImage()
  50807. {
  50808. 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,
  50809. 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,
  50810. 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,
  50811. 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,
  50812. 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,
  50813. 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,
  50814. 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,
  50815. 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,
  50816. 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,
  50817. 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,
  50818. 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,
  50819. 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,
  50820. 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,
  50821. 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,
  50822. 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,
  50823. 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,
  50824. 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,
  50825. 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,
  50826. 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,
  50827. 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,
  50828. 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,
  50829. 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,
  50830. 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,
  50831. 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,
  50832. 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,
  50833. 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,
  50834. 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,
  50835. 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,
  50836. 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,
  50837. 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,
  50838. 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,
  50839. 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,
  50840. 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,
  50841. 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,
  50842. 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,
  50843. 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,
  50844. 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,
  50845. 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,
  50846. 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,
  50847. 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,
  50848. 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,
  50849. 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,
  50850. 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,
  50851. 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};
  50852. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  50853. }
  50854. Image* LookAndFeel::getDefaultDocumentFileImage()
  50855. {
  50856. 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,
  50857. 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,
  50858. 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,
  50859. 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,
  50860. 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,
  50861. 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,
  50862. 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,
  50863. 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,
  50864. 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,
  50865. 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,
  50866. 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,
  50867. 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,
  50868. 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,
  50869. 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,
  50870. 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,
  50871. 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,
  50872. 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,
  50873. 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,
  50874. 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,
  50875. 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,
  50876. 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,
  50877. 174,66,96,130,0,0};
  50878. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  50879. }
  50880. void LookAndFeel::playAlertSound()
  50881. {
  50882. PlatformUtilities::beep();
  50883. }
  50884. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  50885. {
  50886. g.setColour (Colours::white.withAlpha (0.7f));
  50887. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  50888. g.setColour (Colours::black.withAlpha (0.2f));
  50889. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  50890. const int totalBlocks = 7;
  50891. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  50892. const float w = (width - 6.0f) / (float) totalBlocks;
  50893. for (int i = 0; i < totalBlocks; ++i)
  50894. {
  50895. if (i >= numBlocks)
  50896. g.setColour (Colours::lightblue.withAlpha (0.6f));
  50897. else
  50898. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  50899. : Colours::red);
  50900. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  50901. }
  50902. }
  50903. static void createRoundedPath (Path& p,
  50904. const float x, const float y,
  50905. const float w, const float h,
  50906. const float cs,
  50907. const bool curveTopLeft, const bool curveTopRight,
  50908. const bool curveBottomLeft, const bool curveBottomRight) throw()
  50909. {
  50910. const float cs2 = 2.0f * cs;
  50911. if (curveTopLeft)
  50912. {
  50913. p.startNewSubPath (x, y + cs);
  50914. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50915. }
  50916. else
  50917. {
  50918. p.startNewSubPath (x, y);
  50919. }
  50920. if (curveTopRight)
  50921. {
  50922. p.lineTo (x + w - cs, y);
  50923. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  50924. }
  50925. else
  50926. {
  50927. p.lineTo (x + w, y);
  50928. }
  50929. if (curveBottomRight)
  50930. {
  50931. p.lineTo (x + w, y + h - cs);
  50932. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50933. }
  50934. else
  50935. {
  50936. p.lineTo (x + w, y + h);
  50937. }
  50938. if (curveBottomLeft)
  50939. {
  50940. p.lineTo (x + cs, y + h);
  50941. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50942. }
  50943. else
  50944. {
  50945. p.lineTo (x, y + h);
  50946. }
  50947. p.closeSubPath();
  50948. }
  50949. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  50950. float x, float y, float w, float h,
  50951. float maxCornerSize,
  50952. const Colour& baseColour,
  50953. const float strokeWidth,
  50954. const bool flatOnLeft,
  50955. const bool flatOnRight,
  50956. const bool flatOnTop,
  50957. const bool flatOnBottom) throw()
  50958. {
  50959. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  50960. return;
  50961. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  50962. Path outline;
  50963. createRoundedPath (outline, x, y, w, h, cs,
  50964. ! (flatOnLeft || flatOnTop),
  50965. ! (flatOnRight || flatOnTop),
  50966. ! (flatOnLeft || flatOnBottom),
  50967. ! (flatOnRight || flatOnBottom));
  50968. ColourGradient cg (baseColour, 0.0f, y,
  50969. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  50970. false);
  50971. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  50972. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  50973. GradientBrush gb (cg);
  50974. g.setBrush (&gb);
  50975. g.fillPath (outline);
  50976. g.setColour (Colour (0x80000000));
  50977. g.strokePath (outline, PathStrokeType (strokeWidth));
  50978. }
  50979. void LookAndFeel::drawGlassSphere (Graphics& g,
  50980. const float x, const float y,
  50981. const float diameter,
  50982. const Colour& colour,
  50983. const float outlineThickness) throw()
  50984. {
  50985. if (diameter <= outlineThickness)
  50986. return;
  50987. Path p;
  50988. p.addEllipse (x, y, diameter, diameter);
  50989. {
  50990. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50991. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50992. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50993. GradientBrush gb (cg);
  50994. g.setBrush (&gb);
  50995. g.fillPath (p);
  50996. }
  50997. {
  50998. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  50999. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  51000. g.setBrush (&gb);
  51001. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  51002. }
  51003. {
  51004. ColourGradient cg (Colours::transparentBlack,
  51005. x + diameter * 0.5f, y + diameter * 0.5f,
  51006. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  51007. x, y + diameter * 0.5f, true);
  51008. cg.addColour (0.7, Colours::transparentBlack);
  51009. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  51010. GradientBrush gb (cg);
  51011. g.setBrush (&gb);
  51012. g.fillPath (p);
  51013. }
  51014. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  51015. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  51016. }
  51017. void LookAndFeel::drawGlassPointer (Graphics& g,
  51018. const float x, const float y,
  51019. const float diameter,
  51020. const Colour& colour, const float outlineThickness,
  51021. const int direction) throw()
  51022. {
  51023. if (diameter <= outlineThickness)
  51024. return;
  51025. Path p;
  51026. p.startNewSubPath (x + diameter * 0.5f, y);
  51027. p.lineTo (x + diameter, y + diameter * 0.6f);
  51028. p.lineTo (x + diameter, y + diameter);
  51029. p.lineTo (x, y + diameter);
  51030. p.lineTo (x, y + diameter * 0.6f);
  51031. p.closeSubPath();
  51032. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  51033. {
  51034. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  51035. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  51036. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  51037. GradientBrush gb (cg);
  51038. g.setBrush (&gb);
  51039. g.fillPath (p);
  51040. }
  51041. {
  51042. ColourGradient cg (Colours::transparentBlack,
  51043. x + diameter * 0.5f, y + diameter * 0.5f,
  51044. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  51045. x - diameter * 0.2f, y + diameter * 0.5f, true);
  51046. cg.addColour (0.5, Colours::transparentBlack);
  51047. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  51048. GradientBrush gb (cg);
  51049. g.setBrush (&gb);
  51050. g.fillPath (p);
  51051. }
  51052. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  51053. g.strokePath (p, PathStrokeType (outlineThickness));
  51054. }
  51055. void LookAndFeel::drawGlassLozenge (Graphics& g,
  51056. const float x, const float y,
  51057. const float width, const float height,
  51058. const Colour& colour,
  51059. const float outlineThickness,
  51060. const float cornerSize,
  51061. const bool flatOnLeft,
  51062. const bool flatOnRight,
  51063. const bool flatOnTop,
  51064. const bool flatOnBottom) throw()
  51065. {
  51066. if (width <= outlineThickness || height <= outlineThickness)
  51067. return;
  51068. const int intX = (int) x;
  51069. const int intY = (int) y;
  51070. const int intW = (int) width;
  51071. const int intH = (int) height;
  51072. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  51073. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  51074. const int intEdge = (int) edgeBlurRadius;
  51075. Path outline;
  51076. createRoundedPath (outline, x, y, width, height, cs,
  51077. ! (flatOnLeft || flatOnTop),
  51078. ! (flatOnRight || flatOnTop),
  51079. ! (flatOnLeft || flatOnBottom),
  51080. ! (flatOnRight || flatOnBottom));
  51081. {
  51082. ColourGradient cg (colour.darker (0.2f), 0, y,
  51083. colour.darker (0.2f), 0, y + height, false);
  51084. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  51085. cg.addColour (0.4, colour);
  51086. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  51087. GradientBrush gb (cg);
  51088. g.setBrush (&gb);
  51089. g.fillPath (outline);
  51090. }
  51091. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  51092. colour.darker (0.2f), x, y + height * 0.5f, true);
  51093. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  51094. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  51095. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  51096. {
  51097. GradientBrush gb (cg);
  51098. g.saveState();
  51099. g.setBrush (&gb);
  51100. g.reduceClipRegion (intX, intY, intEdge, intH);
  51101. g.fillPath (outline);
  51102. g.restoreState();
  51103. }
  51104. if (! (flatOnRight || flatOnTop || flatOnBottom))
  51105. {
  51106. cg.x1 = x + width - edgeBlurRadius;
  51107. cg.x2 = x + width;
  51108. GradientBrush gb (cg);
  51109. g.saveState();
  51110. g.setBrush (&gb);
  51111. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  51112. g.fillPath (outline);
  51113. g.restoreState();
  51114. }
  51115. {
  51116. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  51117. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  51118. Path highlight;
  51119. createRoundedPath (highlight,
  51120. x + leftIndent,
  51121. y + cs * 0.1f,
  51122. width - (leftIndent + rightIndent),
  51123. height * 0.4f, cs * 0.4f,
  51124. ! (flatOnLeft || flatOnTop),
  51125. ! (flatOnRight || flatOnTop),
  51126. ! (flatOnLeft || flatOnBottom),
  51127. ! (flatOnRight || flatOnBottom));
  51128. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  51129. Colours::transparentWhite, 0, y + height * 0.4f, false);
  51130. g.setBrush (&gb);
  51131. g.fillPath (highlight);
  51132. }
  51133. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  51134. g.strokePath (outline, PathStrokeType (outlineThickness));
  51135. }
  51136. END_JUCE_NAMESPACE
  51137. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  51138. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51139. BEGIN_JUCE_NAMESPACE
  51140. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  51141. {
  51142. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  51143. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  51144. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  51145. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  51146. setColour (Slider::thumbColourId, Colours::white);
  51147. setColour (Slider::trackColourId, Colour (0x7f000000));
  51148. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  51149. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  51150. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  51151. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  51152. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  51153. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  51154. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  51155. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  51156. }
  51157. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  51158. {
  51159. }
  51160. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  51161. Button& button,
  51162. const Colour& backgroundColour,
  51163. bool isMouseOverButton,
  51164. bool isButtonDown)
  51165. {
  51166. const int width = button.getWidth();
  51167. const int height = button.getHeight();
  51168. const float indent = 2.0f;
  51169. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  51170. roundFloatToInt (height * 0.4f));
  51171. Path p;
  51172. p.addRoundedRectangle (indent, indent,
  51173. width - indent * 2.0f,
  51174. height - indent * 2.0f,
  51175. (float) cornerSize);
  51176. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  51177. if (isMouseOverButton)
  51178. {
  51179. if (isButtonDown)
  51180. bc = bc.brighter();
  51181. else if (bc.getBrightness() > 0.5f)
  51182. bc = bc.darker (0.1f);
  51183. else
  51184. bc = bc.brighter (0.1f);
  51185. }
  51186. g.setColour (bc);
  51187. g.fillPath (p);
  51188. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  51189. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  51190. }
  51191. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  51192. Component& /*component*/,
  51193. int x, int y, int w, int h,
  51194. const bool ticked,
  51195. const bool isEnabled,
  51196. const bool /*isMouseOverButton*/,
  51197. const bool isButtonDown)
  51198. {
  51199. Path box;
  51200. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  51201. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  51202. : Colours::lightgrey.withAlpha (0.1f));
  51203. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51204. .translated ((float) x, (float) y));
  51205. g.fillPath (box, trans);
  51206. g.setColour (Colours::black.withAlpha (0.6f));
  51207. g.strokePath (box, PathStrokeType (0.9f), trans);
  51208. if (ticked)
  51209. {
  51210. Path tick;
  51211. tick.startNewSubPath (1.5f, 3.0f);
  51212. tick.lineTo (3.0f, 6.0f);
  51213. tick.lineTo (6.0f, 0.0f);
  51214. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51215. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51216. }
  51217. }
  51218. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  51219. ToggleButton& button,
  51220. bool isMouseOverButton,
  51221. bool isButtonDown)
  51222. {
  51223. if (button.hasKeyboardFocus (true))
  51224. {
  51225. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51226. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51227. }
  51228. const int tickWidth = jmin (20, button.getHeight() - 4);
  51229. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  51230. tickWidth, tickWidth,
  51231. button.getToggleState(),
  51232. button.isEnabled(),
  51233. isMouseOverButton,
  51234. isButtonDown);
  51235. g.setColour (button.findColour (ToggleButton::textColourId));
  51236. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  51237. if (! button.isEnabled())
  51238. g.setOpacity (0.5f);
  51239. const int textX = tickWidth + 5;
  51240. g.drawFittedText (button.getButtonText(),
  51241. textX, 4,
  51242. button.getWidth() - textX - 2, button.getHeight() - 8,
  51243. Justification::centredLeft, 10);
  51244. }
  51245. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51246. int width, int height,
  51247. double progress, const String& textToShow)
  51248. {
  51249. if (progress < 0 || progress >= 1.0)
  51250. {
  51251. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  51252. }
  51253. else
  51254. {
  51255. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51256. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51257. g.fillAll (background);
  51258. g.setColour (foreground);
  51259. g.fillRect (1, 1,
  51260. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  51261. height - 2);
  51262. if (textToShow.isNotEmpty())
  51263. {
  51264. g.setColour (Colour::contrasting (background, foreground));
  51265. g.setFont (height * 0.6f);
  51266. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51267. }
  51268. }
  51269. }
  51270. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  51271. ScrollBar& bar,
  51272. int width, int height,
  51273. int buttonDirection,
  51274. bool isScrollbarVertical,
  51275. bool isMouseOverButton,
  51276. bool isButtonDown)
  51277. {
  51278. if (isScrollbarVertical)
  51279. width -= 2;
  51280. else
  51281. height -= 2;
  51282. Path p;
  51283. if (buttonDirection == 0)
  51284. p.addTriangle (width * 0.5f, height * 0.2f,
  51285. width * 0.1f, height * 0.7f,
  51286. width * 0.9f, height * 0.7f);
  51287. else if (buttonDirection == 1)
  51288. p.addTriangle (width * 0.8f, height * 0.5f,
  51289. width * 0.3f, height * 0.1f,
  51290. width * 0.3f, height * 0.9f);
  51291. else if (buttonDirection == 2)
  51292. p.addTriangle (width * 0.5f, height * 0.8f,
  51293. width * 0.1f, height * 0.3f,
  51294. width * 0.9f, height * 0.3f);
  51295. else if (buttonDirection == 3)
  51296. p.addTriangle (width * 0.2f, height * 0.5f,
  51297. width * 0.7f, height * 0.1f,
  51298. width * 0.7f, height * 0.9f);
  51299. if (isButtonDown)
  51300. g.setColour (Colours::white);
  51301. else if (isMouseOverButton)
  51302. g.setColour (Colours::white.withAlpha (0.7f));
  51303. else
  51304. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  51305. g.fillPath (p);
  51306. g.setColour (Colours::black.withAlpha (0.5f));
  51307. g.strokePath (p, PathStrokeType (0.5f));
  51308. }
  51309. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  51310. ScrollBar& bar,
  51311. int x, int y,
  51312. int width, int height,
  51313. bool isScrollbarVertical,
  51314. int thumbStartPosition,
  51315. int thumbSize,
  51316. bool isMouseOver,
  51317. bool isMouseDown)
  51318. {
  51319. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  51320. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51321. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  51322. if (thumbSize > 0.0f)
  51323. {
  51324. Rectangle thumb;
  51325. if (isScrollbarVertical)
  51326. {
  51327. width -= 2;
  51328. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  51329. roundFloatToInt (width * 0.3f), height);
  51330. thumb.setBounds (x + 1, thumbStartPosition,
  51331. width - 2, thumbSize);
  51332. }
  51333. else
  51334. {
  51335. height -= 2;
  51336. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  51337. width, roundFloatToInt (height * 0.3f));
  51338. thumb.setBounds (thumbStartPosition, y + 1,
  51339. thumbSize, height - 2);
  51340. }
  51341. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51342. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  51343. g.fillRect (thumb);
  51344. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  51345. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  51346. if (thumbSize > 16)
  51347. {
  51348. for (int i = 3; --i >= 0;)
  51349. {
  51350. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  51351. g.setColour (Colours::black.withAlpha (0.15f));
  51352. if (isScrollbarVertical)
  51353. {
  51354. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  51355. g.setColour (Colours::white.withAlpha (0.15f));
  51356. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  51357. }
  51358. else
  51359. {
  51360. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  51361. g.setColour (Colours::white.withAlpha (0.15f));
  51362. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  51363. }
  51364. }
  51365. }
  51366. }
  51367. }
  51368. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  51369. {
  51370. return &scrollbarShadow;
  51371. }
  51372. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51373. {
  51374. g.fillAll (findColour (PopupMenu::backgroundColourId));
  51375. g.setColour (Colours::black.withAlpha (0.6f));
  51376. g.drawRect (0, 0, width, height);
  51377. }
  51378. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  51379. bool, MenuBarComponent& menuBar)
  51380. {
  51381. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  51382. }
  51383. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  51384. {
  51385. if (textEditor.isEnabled())
  51386. {
  51387. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  51388. g.drawRect (0, 0, width, height);
  51389. }
  51390. }
  51391. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  51392. const bool isButtonDown,
  51393. int buttonX, int buttonY,
  51394. int buttonW, int buttonH,
  51395. ComboBox& box)
  51396. {
  51397. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  51398. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  51399. : ComboBox::backgroundColourId));
  51400. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  51401. g.setColour (box.findColour (ComboBox::outlineColourId));
  51402. g.drawRect (0, 0, width, height);
  51403. const float arrowX = 0.2f;
  51404. const float arrowH = 0.3f;
  51405. if (box.isEnabled())
  51406. {
  51407. Path p;
  51408. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  51409. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  51410. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  51411. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  51412. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  51413. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  51414. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  51415. : ComboBox::buttonColourId));
  51416. g.fillPath (p);
  51417. }
  51418. }
  51419. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  51420. {
  51421. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  51422. f.setHorizontalScale (0.9f);
  51423. return f;
  51424. }
  51425. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  51426. {
  51427. Path p;
  51428. p.addTriangle (x1, y1, x2, y2, x3, y3);
  51429. g.setColour (fill);
  51430. g.fillPath (p);
  51431. g.setColour (outline);
  51432. g.strokePath (p, PathStrokeType (0.3f));
  51433. }
  51434. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  51435. int x, int y,
  51436. int w, int h,
  51437. float sliderPos,
  51438. float minSliderPos,
  51439. float maxSliderPos,
  51440. const Slider::SliderStyle style,
  51441. Slider& slider)
  51442. {
  51443. g.fillAll (slider.findColour (Slider::backgroundColourId));
  51444. if (style == Slider::LinearBar)
  51445. {
  51446. g.setColour (slider.findColour (Slider::thumbColourId));
  51447. g.fillRect (x, y, (int) sliderPos - x, h);
  51448. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  51449. g.drawRect (x, y, (int) sliderPos - x, h);
  51450. }
  51451. else
  51452. {
  51453. g.setColour (slider.findColour (Slider::trackColourId)
  51454. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  51455. if (slider.isHorizontal())
  51456. {
  51457. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  51458. w, roundFloatToInt (h * 0.2f));
  51459. }
  51460. else
  51461. {
  51462. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  51463. jmin (4, roundFloatToInt (w * 0.2f)), h);
  51464. }
  51465. float alpha = 0.35f;
  51466. if (slider.isEnabled())
  51467. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  51468. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  51469. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  51470. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  51471. {
  51472. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  51473. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  51474. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  51475. fill, outline);
  51476. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  51477. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  51478. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  51479. fill, outline);
  51480. }
  51481. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  51482. {
  51483. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51484. minSliderPos - 7.0f, y + h * 0.9f ,
  51485. minSliderPos, y + h * 0.9f,
  51486. fill, outline);
  51487. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51488. maxSliderPos, y + h * 0.9f,
  51489. maxSliderPos + 7.0f, y + h * 0.9f,
  51490. fill, outline);
  51491. }
  51492. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  51493. {
  51494. drawTriangle (g, sliderPos, y + h * 0.9f,
  51495. sliderPos - 7.0f, y + h * 0.2f,
  51496. sliderPos + 7.0f, y + h * 0.2f,
  51497. fill, outline);
  51498. }
  51499. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  51500. {
  51501. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  51502. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  51503. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  51504. fill, outline);
  51505. }
  51506. }
  51507. }
  51508. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  51509. {
  51510. if (isIncrement)
  51511. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  51512. else
  51513. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  51514. }
  51515. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  51516. {
  51517. return &scrollbarShadow;
  51518. }
  51519. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  51520. {
  51521. return 8;
  51522. }
  51523. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  51524. int w, int h,
  51525. bool isMouseOver,
  51526. bool isMouseDragging)
  51527. {
  51528. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  51529. : Colours::darkgrey);
  51530. const float lineThickness = jmin (w, h) * 0.1f;
  51531. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  51532. {
  51533. g.drawLine (w * i,
  51534. h + 1.0f,
  51535. w + 1.0f,
  51536. h * i,
  51537. lineThickness);
  51538. }
  51539. }
  51540. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  51541. {
  51542. Path shape;
  51543. if (buttonType == DocumentWindow::closeButton)
  51544. {
  51545. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  51546. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  51547. ShapeButton* const b = new ShapeButton ("close",
  51548. Colour (0x7fff3333),
  51549. Colour (0xd7ff3333),
  51550. Colour (0xf7ff3333));
  51551. b->setShape (shape, true, true, true);
  51552. return b;
  51553. }
  51554. else if (buttonType == DocumentWindow::minimiseButton)
  51555. {
  51556. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51557. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  51558. DrawablePath dp;
  51559. dp.setPath (shape);
  51560. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51561. b->setImages (&dp);
  51562. return b;
  51563. }
  51564. else if (buttonType == DocumentWindow::maximiseButton)
  51565. {
  51566. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  51567. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51568. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  51569. DrawablePath dp;
  51570. dp.setPath (shape);
  51571. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51572. b->setImages (&dp);
  51573. return b;
  51574. }
  51575. jassertfalse
  51576. return 0;
  51577. }
  51578. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  51579. int titleBarX,
  51580. int titleBarY,
  51581. int titleBarW,
  51582. int titleBarH,
  51583. Button* minimiseButton,
  51584. Button* maximiseButton,
  51585. Button* closeButton,
  51586. bool positionTitleBarButtonsOnLeft)
  51587. {
  51588. titleBarY += titleBarH / 8;
  51589. titleBarH -= titleBarH / 4;
  51590. const int buttonW = titleBarH;
  51591. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  51592. : titleBarX + titleBarW - buttonW - 4;
  51593. if (closeButton != 0)
  51594. {
  51595. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  51596. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  51597. : -(buttonW + buttonW / 5);
  51598. }
  51599. if (positionTitleBarButtonsOnLeft)
  51600. swapVariables (minimiseButton, maximiseButton);
  51601. if (maximiseButton != 0)
  51602. {
  51603. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51604. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  51605. }
  51606. if (minimiseButton != 0)
  51607. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51608. }
  51609. END_JUCE_NAMESPACE
  51610. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51611. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  51612. BEGIN_JUCE_NAMESPACE
  51613. class DummyMenuComponent : public Component
  51614. {
  51615. DummyMenuComponent (const DummyMenuComponent&);
  51616. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  51617. public:
  51618. DummyMenuComponent() {}
  51619. ~DummyMenuComponent() {}
  51620. void inputAttemptWhenModal()
  51621. {
  51622. exitModalState (0);
  51623. }
  51624. };
  51625. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  51626. : model (0),
  51627. itemUnderMouse (-1),
  51628. currentPopupIndex (-1),
  51629. indexToShowAgain (-1),
  51630. lastMouseX (0),
  51631. lastMouseY (0),
  51632. inModalState (false),
  51633. currentPopup (0)
  51634. {
  51635. setRepaintsOnMouseActivity (true);
  51636. setWantsKeyboardFocus (false);
  51637. setMouseClickGrabsKeyboardFocus (false);
  51638. setModel (model_);
  51639. }
  51640. MenuBarComponent::~MenuBarComponent()
  51641. {
  51642. setModel (0);
  51643. Desktop::getInstance().removeGlobalMouseListener (this);
  51644. deleteAndZero (currentPopup);
  51645. }
  51646. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  51647. {
  51648. if (model != newModel)
  51649. {
  51650. if (model != 0)
  51651. model->removeListener (this);
  51652. model = newModel;
  51653. if (model != 0)
  51654. model->addListener (this);
  51655. repaint();
  51656. menuBarItemsChanged (0);
  51657. }
  51658. }
  51659. void MenuBarComponent::paint (Graphics& g)
  51660. {
  51661. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  51662. getLookAndFeel().drawMenuBarBackground (g,
  51663. getWidth(),
  51664. getHeight(),
  51665. isMouseOverBar,
  51666. *this);
  51667. if (model != 0)
  51668. {
  51669. for (int i = 0; i < menuNames.size(); ++i)
  51670. {
  51671. g.saveState();
  51672. g.setOrigin (xPositions [i], 0);
  51673. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  51674. getLookAndFeel().drawMenuBarItem (g,
  51675. xPositions[i + 1] - xPositions[i],
  51676. getHeight(),
  51677. i,
  51678. menuNames[i],
  51679. i == itemUnderMouse,
  51680. i == currentPopupIndex,
  51681. isMouseOverBar,
  51682. *this);
  51683. g.restoreState();
  51684. }
  51685. }
  51686. }
  51687. void MenuBarComponent::resized()
  51688. {
  51689. xPositions.clear();
  51690. int x = 2;
  51691. xPositions.add (x);
  51692. for (int i = 0; i < menuNames.size(); ++i)
  51693. {
  51694. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  51695. xPositions.add (x);
  51696. }
  51697. }
  51698. int MenuBarComponent::getItemAt (const int x, const int y)
  51699. {
  51700. for (int i = 0; i < xPositions.size(); ++i)
  51701. if (x >= xPositions[i] && x < xPositions[i + 1])
  51702. return reallyContains (x, y, true) ? i : -1;
  51703. return -1;
  51704. }
  51705. void MenuBarComponent::repaintMenuItem (int index)
  51706. {
  51707. if (((unsigned int) index) < (unsigned int) xPositions.size())
  51708. {
  51709. const int x1 = xPositions [index];
  51710. const int x2 = xPositions [index + 1];
  51711. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  51712. }
  51713. }
  51714. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  51715. {
  51716. const int newItem = getItemAt (x, y);
  51717. if (itemUnderMouse != newItem)
  51718. {
  51719. repaintMenuItem (itemUnderMouse);
  51720. itemUnderMouse = newItem;
  51721. repaintMenuItem (itemUnderMouse);
  51722. }
  51723. }
  51724. void MenuBarComponent::hideCurrentMenu()
  51725. {
  51726. deleteAndZero (currentPopup);
  51727. repaint();
  51728. }
  51729. void MenuBarComponent::showMenu (int index)
  51730. {
  51731. if (index != currentPopupIndex)
  51732. {
  51733. if (inModalState)
  51734. {
  51735. hideCurrentMenu();
  51736. indexToShowAgain = index;
  51737. return;
  51738. }
  51739. indexToShowAgain = -1;
  51740. currentPopupIndex = -1;
  51741. itemUnderMouse = index;
  51742. deleteAndZero (currentPopup);
  51743. menuBarItemsChanged (0);
  51744. Component* const prevFocused = getCurrentlyFocusedComponent();
  51745. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  51746. if (prevFocused != 0)
  51747. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  51748. ComponentDeletionWatcher deletionChecker (this);
  51749. enterModalState (false);
  51750. inModalState = true;
  51751. int result = 0;
  51752. ApplicationCommandManager* managerOfChosenCommand = 0;
  51753. Desktop::getInstance().addGlobalMouseListener (this);
  51754. for (;;)
  51755. {
  51756. const int x = getScreenX() + xPositions [itemUnderMouse];
  51757. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  51758. currentPopupIndex = itemUnderMouse;
  51759. indexToShowAgain = -1;
  51760. repaint();
  51761. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  51762. {
  51763. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  51764. menuNames [itemUnderMouse]));
  51765. if (m.lookAndFeel == 0)
  51766. m.setLookAndFeel (&getLookAndFeel());
  51767. currentPopup = m.createMenuComponent (x, getScreenY(),
  51768. w, getHeight(),
  51769. 0, w, 0, 0,
  51770. true, this,
  51771. &managerOfChosenCommand,
  51772. this);
  51773. }
  51774. if (currentPopup == 0)
  51775. {
  51776. currentPopup = new DummyMenuComponent();
  51777. addAndMakeVisible (currentPopup);
  51778. }
  51779. currentPopup->enterModalState (false);
  51780. currentPopup->toFront (false); // need to do this after making it modal, or it could
  51781. // be stuck behind other comps that are already modal..
  51782. result = currentPopup->runModalLoop();
  51783. if (deletionChecker.hasBeenDeleted())
  51784. {
  51785. delete prevCompDeletionChecker;
  51786. return;
  51787. }
  51788. const int lastPopupIndex = currentPopupIndex;
  51789. deleteAndZero (currentPopup);
  51790. currentPopupIndex = -1;
  51791. if (result != 0)
  51792. {
  51793. topLevelIndexClicked = lastPopupIndex;
  51794. break;
  51795. }
  51796. else if (indexToShowAgain >= 0)
  51797. {
  51798. menuBarItemsChanged (0);
  51799. repaint();
  51800. itemUnderMouse = indexToShowAgain;
  51801. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  51802. break;
  51803. }
  51804. else
  51805. {
  51806. break;
  51807. }
  51808. }
  51809. Desktop::getInstance().removeGlobalMouseListener (this);
  51810. inModalState = false;
  51811. exitModalState (0);
  51812. if (prevCompDeletionChecker != 0)
  51813. {
  51814. if (! prevCompDeletionChecker->hasBeenDeleted())
  51815. prevFocused->grabKeyboardFocus();
  51816. delete prevCompDeletionChecker;
  51817. }
  51818. int mx, my;
  51819. getMouseXYRelative (mx, my);
  51820. updateItemUnderMouse (mx, my);
  51821. repaint();
  51822. if (result != 0)
  51823. {
  51824. if (managerOfChosenCommand != 0)
  51825. {
  51826. ApplicationCommandTarget::InvocationInfo info (result);
  51827. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  51828. managerOfChosenCommand->invoke (info, true);
  51829. }
  51830. postCommandMessage (result);
  51831. }
  51832. }
  51833. }
  51834. void MenuBarComponent::handleCommandMessage (int commandId)
  51835. {
  51836. if (model != 0)
  51837. model->menuItemSelected (commandId, topLevelIndexClicked);
  51838. }
  51839. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  51840. {
  51841. if (e.eventComponent == this)
  51842. updateItemUnderMouse (e.x, e.y);
  51843. }
  51844. void MenuBarComponent::mouseExit (const MouseEvent& e)
  51845. {
  51846. if (e.eventComponent == this)
  51847. updateItemUnderMouse (e.x, e.y);
  51848. }
  51849. void MenuBarComponent::mouseDown (const MouseEvent& e)
  51850. {
  51851. const MouseEvent e2 (e.getEventRelativeTo (this));
  51852. if (currentPopupIndex < 0)
  51853. {
  51854. updateItemUnderMouse (e2.x, e2.y);
  51855. currentPopupIndex = -2;
  51856. showMenu (itemUnderMouse);
  51857. }
  51858. }
  51859. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  51860. {
  51861. const MouseEvent e2 (e.getEventRelativeTo (this));
  51862. const int item = getItemAt (e2.x, e2.y);
  51863. if (item >= 0)
  51864. showMenu (item);
  51865. }
  51866. void MenuBarComponent::mouseUp (const MouseEvent& e)
  51867. {
  51868. const MouseEvent e2 (e.getEventRelativeTo (this));
  51869. updateItemUnderMouse (e2.x, e2.y);
  51870. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  51871. hideCurrentMenu();
  51872. }
  51873. void MenuBarComponent::mouseMove (const MouseEvent& e)
  51874. {
  51875. const MouseEvent e2 (e.getEventRelativeTo (this));
  51876. if (lastMouseX != e2.x || lastMouseY != e2.y)
  51877. {
  51878. if (currentPopupIndex >= 0)
  51879. {
  51880. const int item = getItemAt (e2.x, e2.y);
  51881. if (item >= 0)
  51882. showMenu (item);
  51883. }
  51884. else
  51885. {
  51886. updateItemUnderMouse (e2.x, e2.y);
  51887. }
  51888. lastMouseX = e2.x;
  51889. lastMouseY = e2.y;
  51890. }
  51891. }
  51892. bool MenuBarComponent::keyPressed (const KeyPress& key)
  51893. {
  51894. bool used = false;
  51895. const int numMenus = menuNames.size();
  51896. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  51897. if (key.isKeyCode (KeyPress::leftKey))
  51898. {
  51899. showMenu ((currentIndex + numMenus - 1) % numMenus);
  51900. used = true;
  51901. }
  51902. else if (key.isKeyCode (KeyPress::rightKey))
  51903. {
  51904. showMenu ((currentIndex + 1) % numMenus);
  51905. used = true;
  51906. }
  51907. return used;
  51908. }
  51909. void MenuBarComponent::inputAttemptWhenModal()
  51910. {
  51911. hideCurrentMenu();
  51912. }
  51913. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  51914. {
  51915. StringArray newNames;
  51916. if (model != 0)
  51917. newNames = model->getMenuBarNames();
  51918. if (newNames != menuNames)
  51919. {
  51920. menuNames = newNames;
  51921. repaint();
  51922. resized();
  51923. }
  51924. }
  51925. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  51926. const ApplicationCommandTarget::InvocationInfo& info)
  51927. {
  51928. if (model == 0
  51929. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  51930. return;
  51931. for (int i = 0; i < menuNames.size(); ++i)
  51932. {
  51933. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  51934. if (menu.containsCommandItem (info.commandID))
  51935. {
  51936. itemUnderMouse = i;
  51937. repaintMenuItem (i);
  51938. startTimer (200);
  51939. break;
  51940. }
  51941. }
  51942. }
  51943. void MenuBarComponent::timerCallback()
  51944. {
  51945. stopTimer();
  51946. int mx, my;
  51947. getMouseXYRelative (mx, my);
  51948. updateItemUnderMouse (mx, my);
  51949. }
  51950. END_JUCE_NAMESPACE
  51951. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  51952. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  51953. BEGIN_JUCE_NAMESPACE
  51954. MenuBarModel::MenuBarModel() throw()
  51955. : manager (0)
  51956. {
  51957. }
  51958. MenuBarModel::~MenuBarModel()
  51959. {
  51960. setApplicationCommandManagerToWatch (0);
  51961. }
  51962. void MenuBarModel::menuItemsChanged()
  51963. {
  51964. triggerAsyncUpdate();
  51965. }
  51966. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  51967. {
  51968. if (manager != newManager)
  51969. {
  51970. if (manager != 0)
  51971. manager->removeListener (this);
  51972. manager = newManager;
  51973. if (manager != 0)
  51974. manager->addListener (this);
  51975. }
  51976. }
  51977. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  51978. {
  51979. jassert (newListener != 0);
  51980. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  51981. if (newListener != 0)
  51982. listeners.add (newListener);
  51983. }
  51984. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  51985. {
  51986. // Trying to remove a listener that isn't on the list!
  51987. // If this assertion happens because this object is a dangling pointer, make sure you've not
  51988. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  51989. jassert (listeners.contains (listenerToRemove));
  51990. listeners.removeValue (listenerToRemove);
  51991. }
  51992. void MenuBarModel::handleAsyncUpdate()
  51993. {
  51994. for (int i = listeners.size(); --i >= 0;)
  51995. {
  51996. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  51997. i = jmin (i, listeners.size());
  51998. }
  51999. }
  52000. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  52001. {
  52002. for (int i = listeners.size(); --i >= 0;)
  52003. {
  52004. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  52005. i = jmin (i, listeners.size());
  52006. }
  52007. }
  52008. void MenuBarModel::applicationCommandListChanged()
  52009. {
  52010. menuItemsChanged();
  52011. }
  52012. END_JUCE_NAMESPACE
  52013. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  52014. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  52015. BEGIN_JUCE_NAMESPACE
  52016. static VoidArray activeMenuWindows;
  52017. class MenuItemInfo
  52018. {
  52019. public:
  52020. const int itemId;
  52021. String text;
  52022. const Colour textColour;
  52023. const bool active, isSeparator, isTicked, usesColour;
  52024. Image* image;
  52025. PopupMenuCustomComponent* const customComp;
  52026. PopupMenu* subMenu;
  52027. ApplicationCommandManager* const commandManager;
  52028. MenuItemInfo() throw()
  52029. : itemId (0),
  52030. active (true),
  52031. isSeparator (true),
  52032. isTicked (false),
  52033. usesColour (false),
  52034. image (0),
  52035. customComp (0),
  52036. subMenu (0),
  52037. commandManager (0)
  52038. {
  52039. }
  52040. MenuItemInfo (const int itemId_,
  52041. const String& text_,
  52042. const bool active_,
  52043. const bool isTicked_,
  52044. const Image* im,
  52045. const Colour& textColour_,
  52046. const bool usesColour_,
  52047. PopupMenuCustomComponent* const customComp_,
  52048. const PopupMenu* const subMenu_,
  52049. ApplicationCommandManager* const commandManager_) throw()
  52050. : itemId (itemId_),
  52051. text (text_),
  52052. textColour (textColour_),
  52053. active (active_),
  52054. isSeparator (false),
  52055. isTicked (isTicked_),
  52056. usesColour (usesColour_),
  52057. image (0),
  52058. customComp (customComp_),
  52059. commandManager (commandManager_)
  52060. {
  52061. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  52062. if (customComp != 0)
  52063. customComp->refCount_++;
  52064. if (im != 0)
  52065. image = im->createCopy();
  52066. if (commandManager_ != 0 && itemId_ != 0)
  52067. {
  52068. String shortcutKey;
  52069. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  52070. ->getKeyPressesAssignedToCommand (itemId_));
  52071. for (int i = 0; i < keyPresses.size(); ++i)
  52072. {
  52073. const String key (keyPresses.getReference(i).getTextDescription());
  52074. if (shortcutKey.isNotEmpty())
  52075. shortcutKey << ", ";
  52076. if (key.length() == 1)
  52077. shortcutKey << "shortcut: '" << key << '\'';
  52078. else
  52079. shortcutKey << key;
  52080. }
  52081. shortcutKey = shortcutKey.trim();
  52082. if (shortcutKey.isNotEmpty())
  52083. text << "<end>" << shortcutKey;
  52084. }
  52085. }
  52086. MenuItemInfo (const MenuItemInfo& other) throw()
  52087. : itemId (other.itemId),
  52088. text (other.text),
  52089. textColour (other.textColour),
  52090. active (other.active),
  52091. isSeparator (other.isSeparator),
  52092. isTicked (other.isTicked),
  52093. usesColour (other.usesColour),
  52094. customComp (other.customComp),
  52095. commandManager (other.commandManager)
  52096. {
  52097. if (other.subMenu != 0)
  52098. subMenu = new PopupMenu (*(other.subMenu));
  52099. else
  52100. subMenu = 0;
  52101. if (other.image != 0)
  52102. image = other.image->createCopy();
  52103. else
  52104. image = 0;
  52105. if (customComp != 0)
  52106. customComp->refCount_++;
  52107. }
  52108. ~MenuItemInfo() throw()
  52109. {
  52110. delete subMenu;
  52111. delete image;
  52112. if (customComp != 0 && --(customComp->refCount_) == 0)
  52113. delete customComp;
  52114. }
  52115. bool canBeTriggered() const throw()
  52116. {
  52117. return active && ! (isSeparator || (subMenu != 0));
  52118. }
  52119. bool hasActiveSubMenu() const throw()
  52120. {
  52121. return active && (subMenu != 0);
  52122. }
  52123. juce_UseDebuggingNewOperator
  52124. private:
  52125. const MenuItemInfo& operator= (const MenuItemInfo&);
  52126. };
  52127. class MenuItemComponent : public Component
  52128. {
  52129. bool isHighlighted;
  52130. public:
  52131. MenuItemInfo itemInfo;
  52132. MenuItemComponent (const MenuItemInfo& itemInfo_)
  52133. : isHighlighted (false),
  52134. itemInfo (itemInfo_)
  52135. {
  52136. if (itemInfo.customComp != 0)
  52137. addAndMakeVisible (itemInfo.customComp);
  52138. }
  52139. ~MenuItemComponent()
  52140. {
  52141. if (itemInfo.customComp != 0)
  52142. removeChildComponent (itemInfo.customComp);
  52143. }
  52144. void getIdealSize (int& idealWidth,
  52145. int& idealHeight,
  52146. const int standardItemHeight)
  52147. {
  52148. if (itemInfo.customComp != 0)
  52149. {
  52150. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  52151. }
  52152. else
  52153. {
  52154. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  52155. itemInfo.isSeparator,
  52156. standardItemHeight,
  52157. idealWidth,
  52158. idealHeight);
  52159. }
  52160. }
  52161. void paint (Graphics& g)
  52162. {
  52163. if (itemInfo.customComp == 0)
  52164. {
  52165. String mainText (itemInfo.text);
  52166. String endText;
  52167. const int endIndex = mainText.indexOf (T("<end>"));
  52168. if (endIndex >= 0)
  52169. {
  52170. endText = mainText.substring (endIndex + 5).trim();
  52171. mainText = mainText.substring (0, endIndex);
  52172. }
  52173. getLookAndFeel()
  52174. .drawPopupMenuItem (g, getWidth(), getHeight(),
  52175. itemInfo.isSeparator,
  52176. itemInfo.active,
  52177. isHighlighted,
  52178. itemInfo.isTicked,
  52179. itemInfo.subMenu != 0,
  52180. mainText, endText,
  52181. itemInfo.image,
  52182. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  52183. }
  52184. }
  52185. void resized()
  52186. {
  52187. if (getNumChildComponents() > 0)
  52188. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  52189. }
  52190. void setHighlighted (bool shouldBeHighlighted)
  52191. {
  52192. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  52193. if (isHighlighted != shouldBeHighlighted)
  52194. {
  52195. isHighlighted = shouldBeHighlighted;
  52196. if (itemInfo.customComp != 0)
  52197. {
  52198. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  52199. itemInfo.customComp->repaint();
  52200. }
  52201. repaint();
  52202. }
  52203. }
  52204. private:
  52205. MenuItemComponent (const MenuItemComponent&);
  52206. const MenuItemComponent& operator= (const MenuItemComponent&);
  52207. };
  52208. static const int scrollZone = 24;
  52209. static const int borderSize = 2;
  52210. static const int timerInterval = 50;
  52211. static const int dismissCommandId = 0x6287345f;
  52212. static bool wasHiddenBecauseOfAppChange = false;
  52213. class PopupMenuWindow : public Component,
  52214. private Timer
  52215. {
  52216. public:
  52217. PopupMenuWindow() throw()
  52218. : Component (T("menu")),
  52219. owner (0),
  52220. currentChild (0),
  52221. activeSubMenu (0),
  52222. menuBarComponent (0),
  52223. managerOfChosenCommand (0),
  52224. componentAttachedTo (0),
  52225. attachedCompWatcher (0),
  52226. lastMouseX (0),
  52227. lastMouseY (0),
  52228. minimumWidth (0),
  52229. maximumNumColumns (7),
  52230. standardItemHeight (0),
  52231. isOver (false),
  52232. hasBeenOver (false),
  52233. isDown (false),
  52234. needsToScroll (false),
  52235. hideOnExit (false),
  52236. disableMouseMoves (false),
  52237. hasAnyJuceCompHadFocus (false),
  52238. numColumns (0),
  52239. contentHeight (0),
  52240. childYOffset (0),
  52241. timeEnteredCurrentChildComp (0),
  52242. scrollAcceleration (1.0)
  52243. {
  52244. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  52245. setWantsKeyboardFocus (true);
  52246. setMouseClickGrabsKeyboardFocus (false);
  52247. setOpaque (true);
  52248. setAlwaysOnTop (true);
  52249. Desktop::getInstance().addGlobalMouseListener (this);
  52250. activeMenuWindows.add (this);
  52251. }
  52252. ~PopupMenuWindow()
  52253. {
  52254. activeMenuWindows.removeValue (this);
  52255. Desktop::getInstance().removeGlobalMouseListener (this);
  52256. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52257. delete activeSubMenu;
  52258. deleteAllChildren();
  52259. delete attachedCompWatcher;
  52260. }
  52261. static PopupMenuWindow* create (const PopupMenu& menu,
  52262. const bool dismissOnMouseUp,
  52263. PopupMenuWindow* const owner_,
  52264. const int minX, const int maxX,
  52265. const int minY, const int maxY,
  52266. const int minimumWidth,
  52267. const int maximumNumColumns,
  52268. const int standardItemHeight,
  52269. const bool alignToRectangle,
  52270. const int itemIdThatMustBeVisible,
  52271. Component* const menuBarComponent,
  52272. ApplicationCommandManager** managerOfChosenCommand,
  52273. Component* const componentAttachedTo) throw()
  52274. {
  52275. if (menu.items.size() > 0)
  52276. {
  52277. int totalItems = 0;
  52278. PopupMenuWindow* const mw = new PopupMenuWindow();
  52279. mw->setLookAndFeel (menu.lookAndFeel);
  52280. mw->setWantsKeyboardFocus (false);
  52281. mw->minimumWidth = minimumWidth;
  52282. mw->maximumNumColumns = maximumNumColumns;
  52283. mw->standardItemHeight = standardItemHeight;
  52284. mw->dismissOnMouseUp = dismissOnMouseUp;
  52285. for (int i = 0; i < menu.items.size(); ++i)
  52286. {
  52287. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  52288. mw->addItem (*item);
  52289. ++totalItems;
  52290. }
  52291. if (totalItems == 0)
  52292. {
  52293. delete mw;
  52294. }
  52295. else
  52296. {
  52297. mw->owner = owner_;
  52298. mw->menuBarComponent = menuBarComponent;
  52299. mw->managerOfChosenCommand = managerOfChosenCommand;
  52300. mw->componentAttachedTo = componentAttachedTo;
  52301. delete mw->attachedCompWatcher;
  52302. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  52303. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  52304. mw->setTopLeftPosition (mw->windowPos.getX(),
  52305. mw->windowPos.getY());
  52306. mw->updateYPositions();
  52307. if (itemIdThatMustBeVisible != 0)
  52308. {
  52309. const int y = minY - mw->windowPos.getY();
  52310. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  52311. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  52312. }
  52313. mw->resizeToBestWindowPos();
  52314. mw->addToDesktop (ComponentPeer::windowIsTemporary
  52315. | mw->getLookAndFeel().getMenuWindowFlags());
  52316. return mw;
  52317. }
  52318. }
  52319. return 0;
  52320. }
  52321. void paint (Graphics& g)
  52322. {
  52323. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  52324. }
  52325. void paintOverChildren (Graphics& g)
  52326. {
  52327. if (isScrolling())
  52328. {
  52329. LookAndFeel& lf = getLookAndFeel();
  52330. if (isScrollZoneActive (false))
  52331. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  52332. if (isScrollZoneActive (true))
  52333. {
  52334. g.setOrigin (0, getHeight() - scrollZone);
  52335. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  52336. }
  52337. }
  52338. }
  52339. bool isScrollZoneActive (bool bottomOne) const
  52340. {
  52341. return isScrolling()
  52342. && (bottomOne
  52343. ? childYOffset < contentHeight - windowPos.getHeight()
  52344. : childYOffset > 0);
  52345. }
  52346. void addItem (const MenuItemInfo& item) throw()
  52347. {
  52348. MenuItemComponent* const mic = new MenuItemComponent (item);
  52349. addAndMakeVisible (mic);
  52350. int itemW = 80;
  52351. int itemH = 16;
  52352. mic->getIdealSize (itemW, itemH, standardItemHeight);
  52353. mic->setSize (itemW, jlimit (2, 600, itemH));
  52354. mic->addMouseListener (this, false);
  52355. }
  52356. // hide this and all sub-comps
  52357. void hide (const MenuItemInfo* const item) throw()
  52358. {
  52359. if (isVisible())
  52360. {
  52361. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52362. deleteAndZero (activeSubMenu);
  52363. currentChild = 0;
  52364. exitModalState (item != 0 ? item->itemId : 0);
  52365. setVisible (false);
  52366. if (item != 0
  52367. && item->commandManager != 0
  52368. && item->itemId != 0)
  52369. {
  52370. *managerOfChosenCommand = item->commandManager;
  52371. }
  52372. }
  52373. }
  52374. void dismissMenu (const MenuItemInfo* const item) throw()
  52375. {
  52376. if (owner != 0)
  52377. {
  52378. owner->dismissMenu (item);
  52379. }
  52380. else
  52381. {
  52382. if (item != 0)
  52383. {
  52384. // need a copy of this on the stack as the one passed in will get deleted during this call
  52385. const MenuItemInfo mi (*item);
  52386. hide (&mi);
  52387. }
  52388. else
  52389. {
  52390. hide (0);
  52391. }
  52392. }
  52393. }
  52394. void mouseMove (const MouseEvent&)
  52395. {
  52396. timerCallback();
  52397. }
  52398. void mouseDown (const MouseEvent&)
  52399. {
  52400. timerCallback();
  52401. }
  52402. void mouseDrag (const MouseEvent&)
  52403. {
  52404. timerCallback();
  52405. }
  52406. void mouseUp (const MouseEvent&)
  52407. {
  52408. timerCallback();
  52409. }
  52410. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  52411. {
  52412. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  52413. lastMouseX = -1;
  52414. }
  52415. bool keyPressed (const KeyPress& key)
  52416. {
  52417. if (key.isKeyCode (KeyPress::downKey))
  52418. {
  52419. selectNextItem (1);
  52420. }
  52421. else if (key.isKeyCode (KeyPress::upKey))
  52422. {
  52423. selectNextItem (-1);
  52424. }
  52425. else if (key.isKeyCode (KeyPress::leftKey))
  52426. {
  52427. PopupMenuWindow* parentWindow = owner;
  52428. if (parentWindow != 0)
  52429. {
  52430. MenuItemComponent* currentChildOfParent
  52431. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  52432. hide (0);
  52433. if (parentWindow->isValidComponent())
  52434. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  52435. disableTimerUntilMouseMoves();
  52436. }
  52437. else if (menuBarComponent != 0)
  52438. {
  52439. menuBarComponent->keyPressed (key);
  52440. }
  52441. }
  52442. else if (key.isKeyCode (KeyPress::rightKey))
  52443. {
  52444. disableTimerUntilMouseMoves();
  52445. if (showSubMenuFor (currentChild))
  52446. {
  52447. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52448. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  52449. activeSubMenu->selectNextItem (1);
  52450. }
  52451. else if (menuBarComponent != 0)
  52452. {
  52453. menuBarComponent->keyPressed (key);
  52454. }
  52455. }
  52456. else if (key.isKeyCode (KeyPress::returnKey))
  52457. {
  52458. triggerCurrentlyHighlightedItem();
  52459. }
  52460. else if (key.isKeyCode (KeyPress::escapeKey))
  52461. {
  52462. dismissMenu (0);
  52463. }
  52464. else
  52465. {
  52466. return false;
  52467. }
  52468. return true;
  52469. }
  52470. void inputAttemptWhenModal()
  52471. {
  52472. timerCallback();
  52473. if (! isOverAnyMenu())
  52474. {
  52475. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  52476. {
  52477. // we want to dismiss the menu, but if we do it synchronously, then
  52478. // the mouse-click will be allowed to pass through. That's good, except
  52479. // when the user clicks on the button that orginally popped the menu up,
  52480. // as they'll expect the menu to go away, and in fact it'll just
  52481. // come back. So only dismiss synchronously if they're not on the original
  52482. // comp that we're attached to.
  52483. int mx, my;
  52484. componentAttachedTo->getMouseXYRelative (mx, my);
  52485. if (componentAttachedTo->reallyContains (mx, my, true))
  52486. {
  52487. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  52488. return;
  52489. }
  52490. }
  52491. dismissMenu (0);
  52492. }
  52493. }
  52494. void handleCommandMessage (int commandId)
  52495. {
  52496. Component::handleCommandMessage (commandId);
  52497. if (commandId == dismissCommandId)
  52498. dismissMenu (0);
  52499. }
  52500. void timerCallback()
  52501. {
  52502. if (! isVisible())
  52503. return;
  52504. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  52505. {
  52506. dismissMenu (0);
  52507. return;
  52508. }
  52509. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  52510. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  52511. return;
  52512. startTimer (timerInterval); // do this in case it was called from a mouse
  52513. // move rather than a real timer callback
  52514. int mx, my;
  52515. Desktop::getMousePosition (mx, my);
  52516. int x = mx, y = my;
  52517. globalPositionToRelative (x, y);
  52518. const uint32 now = Time::getMillisecondCounter();
  52519. if (now > timeEnteredCurrentChildComp + 100
  52520. && reallyContains (x, y, true)
  52521. && currentChild->isValidComponent()
  52522. && (! disableMouseMoves)
  52523. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  52524. {
  52525. showSubMenuFor (currentChild);
  52526. }
  52527. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  52528. {
  52529. highlightItemUnderMouse (mx, my, x, y);
  52530. }
  52531. bool overScrollArea = false;
  52532. if (isScrolling()
  52533. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  52534. && ((isScrollZoneActive (false) && y < scrollZone)
  52535. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  52536. {
  52537. if (now > lastScroll + 20)
  52538. {
  52539. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  52540. int amount = 0;
  52541. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  52542. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  52543. alterChildYPos (y < scrollZone ? -amount : amount);
  52544. lastScroll = now;
  52545. }
  52546. overScrollArea = true;
  52547. lastMouseX = -1; // trigger a mouse-move
  52548. }
  52549. else
  52550. {
  52551. scrollAcceleration = 1.0;
  52552. }
  52553. const bool wasDown = isDown;
  52554. bool isOverAny = isOverAnyMenu();
  52555. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  52556. {
  52557. activeSubMenu->updateMouseOverStatus (mx, my);
  52558. isOverAny = isOverAnyMenu();
  52559. }
  52560. if (hideOnExit && hasBeenOver && ! isOverAny)
  52561. {
  52562. hide (0);
  52563. }
  52564. else
  52565. {
  52566. isDown = hasBeenOver
  52567. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  52568. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  52569. bool anyFocused = Process::isForegroundProcess();
  52570. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  52571. {
  52572. // because no component at all may have focus, our test here will
  52573. // only be triggered when something has focus and then loses it.
  52574. anyFocused = ! hasAnyJuceCompHadFocus;
  52575. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  52576. {
  52577. if (ComponentPeer::getPeer (i)->isFocused())
  52578. {
  52579. anyFocused = true;
  52580. hasAnyJuceCompHadFocus = true;
  52581. break;
  52582. }
  52583. }
  52584. }
  52585. if (! anyFocused)
  52586. {
  52587. if (now > lastFocused + 10)
  52588. {
  52589. wasHiddenBecauseOfAppChange = true;
  52590. dismissMenu (0);
  52591. return; // may have been deleted by the previous call..
  52592. }
  52593. }
  52594. else if (wasDown && now > menuCreationTime + 250
  52595. && ! (isDown || overScrollArea))
  52596. {
  52597. isOver = reallyContains (x, y, true);
  52598. if (isOver)
  52599. {
  52600. triggerCurrentlyHighlightedItem();
  52601. }
  52602. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  52603. {
  52604. dismissMenu (0);
  52605. }
  52606. return; // may have been deleted by the previous calls..
  52607. }
  52608. else
  52609. {
  52610. lastFocused = now;
  52611. }
  52612. }
  52613. }
  52614. juce_UseDebuggingNewOperator
  52615. private:
  52616. PopupMenuWindow* owner;
  52617. MenuItemComponent* currentChild;
  52618. PopupMenuWindow* activeSubMenu;
  52619. Component* menuBarComponent;
  52620. ApplicationCommandManager** managerOfChosenCommand;
  52621. Component* componentAttachedTo;
  52622. ComponentDeletionWatcher* attachedCompWatcher;
  52623. Rectangle windowPos;
  52624. int lastMouseX, lastMouseY;
  52625. int minimumWidth, maximumNumColumns, standardItemHeight;
  52626. bool isOver, hasBeenOver, isDown, needsToScroll;
  52627. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  52628. int numColumns, contentHeight, childYOffset;
  52629. Array <int> columnWidths;
  52630. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  52631. double scrollAcceleration;
  52632. bool overlaps (const Rectangle& r) const throw()
  52633. {
  52634. return r.intersects (getBounds())
  52635. || (owner != 0 && owner->overlaps (r));
  52636. }
  52637. bool isOverAnyMenu() const throw()
  52638. {
  52639. return (owner != 0) ? owner->isOverAnyMenu()
  52640. : isOverChildren();
  52641. }
  52642. bool isOverChildren() const throw()
  52643. {
  52644. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52645. return isVisible()
  52646. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  52647. }
  52648. void updateMouseOverStatus (const int mx, const int my) throw()
  52649. {
  52650. int rx = mx, ry = my;
  52651. globalPositionToRelative (rx, ry);
  52652. isOver = reallyContains (rx, ry, true);
  52653. if (activeSubMenu != 0)
  52654. activeSubMenu->updateMouseOverStatus (mx, my);
  52655. }
  52656. bool treeContains (const PopupMenuWindow* const window) const throw()
  52657. {
  52658. const PopupMenuWindow* mw = this;
  52659. while (mw->owner != 0)
  52660. mw = mw->owner;
  52661. while (mw != 0)
  52662. {
  52663. if (mw == window)
  52664. return true;
  52665. mw = mw->activeSubMenu;
  52666. }
  52667. return false;
  52668. }
  52669. void calculateWindowPos (const int minX, const int maxX,
  52670. const int minY, const int maxY,
  52671. const bool alignToRectangle)
  52672. {
  52673. const Rectangle mon (Desktop::getInstance()
  52674. .getMonitorAreaContaining ((minX + maxX) / 2,
  52675. (minY + maxY) / 2,
  52676. #if JUCE_MAC
  52677. true));
  52678. #else
  52679. false)); // on windows, don't stop the menu overlapping the taskbar
  52680. #endif
  52681. int x, y, widthToUse, heightToUse;
  52682. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  52683. if (alignToRectangle)
  52684. {
  52685. x = minX;
  52686. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  52687. const int spaceOver = minY - mon.getY();
  52688. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  52689. y = maxY;
  52690. else
  52691. y = minY - heightToUse;
  52692. }
  52693. else
  52694. {
  52695. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  52696. if (owner != 0)
  52697. {
  52698. if (owner->owner != 0)
  52699. {
  52700. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  52701. > owner->owner->getX() + owner->owner->getWidth() / 2);
  52702. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  52703. tendTowardsRight = true;
  52704. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  52705. tendTowardsRight = false;
  52706. }
  52707. else if (maxX + widthToUse < mon.getRight() - 32)
  52708. {
  52709. tendTowardsRight = true;
  52710. }
  52711. }
  52712. const int biggestSpace = jmax (mon.getRight() - maxX,
  52713. minX - mon.getX()) - 32;
  52714. if (biggestSpace < widthToUse)
  52715. {
  52716. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  52717. if (numColumns > 1)
  52718. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  52719. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  52720. }
  52721. if (tendTowardsRight)
  52722. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  52723. else
  52724. x = jmax (mon.getX() + 4, minX - widthToUse);
  52725. y = minY;
  52726. if ((minY + maxY) / 2 > mon.getCentreY())
  52727. y = jmax (mon.getY(), maxY - heightToUse);
  52728. }
  52729. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  52730. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  52731. windowPos.setBounds (x, y, widthToUse, heightToUse);
  52732. // sets this flag if it's big enough to obscure any of its parent menus
  52733. hideOnExit = (owner != 0)
  52734. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  52735. }
  52736. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  52737. {
  52738. numColumns = 0;
  52739. contentHeight = 0;
  52740. const int maxMenuH = getParentHeight() - 24;
  52741. int totalW;
  52742. do
  52743. {
  52744. ++numColumns;
  52745. totalW = workOutBestSize (numColumns, maxMenuW);
  52746. if (totalW > maxMenuW)
  52747. {
  52748. numColumns = jmax (1, numColumns - 1);
  52749. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  52750. break;
  52751. }
  52752. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  52753. {
  52754. break;
  52755. }
  52756. } while (numColumns < maximumNumColumns);
  52757. const int actualH = jmin (contentHeight, maxMenuH);
  52758. needsToScroll = contentHeight > actualH;
  52759. width = updateYPositions();
  52760. height = actualH + borderSize * 2;
  52761. }
  52762. int workOutBestSize (const int numColumns, const int maxMenuW)
  52763. {
  52764. int totalW = 0;
  52765. contentHeight = 0;
  52766. int childNum = 0;
  52767. for (int col = 0; col < numColumns; ++col)
  52768. {
  52769. int i, colW = 50, colH = 0;
  52770. const int numChildren = jmin (getNumChildComponents() - childNum,
  52771. (getNumChildComponents() + numColumns - 1) / numColumns);
  52772. for (i = numChildren; --i >= 0;)
  52773. {
  52774. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  52775. colH += getChildComponent (childNum + i)->getHeight();
  52776. }
  52777. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  52778. columnWidths.set (col, colW);
  52779. totalW += colW;
  52780. contentHeight = jmax (contentHeight, colH);
  52781. childNum += numChildren;
  52782. }
  52783. if (totalW < minimumWidth)
  52784. {
  52785. totalW = minimumWidth;
  52786. for (int col = 0; col < numColumns; ++col)
  52787. columnWidths.set (0, totalW / numColumns);
  52788. }
  52789. return totalW;
  52790. }
  52791. void ensureItemIsVisible (const int itemId, int wantedY)
  52792. {
  52793. jassert (itemId != 0)
  52794. for (int i = getNumChildComponents(); --i >= 0;)
  52795. {
  52796. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  52797. if (m != 0
  52798. && m->itemInfo.itemId == itemId
  52799. && windowPos.getHeight() > scrollZone * 4)
  52800. {
  52801. const int currentY = m->getY();
  52802. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  52803. {
  52804. if (wantedY < 0)
  52805. wantedY = jlimit (scrollZone,
  52806. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  52807. currentY);
  52808. const Rectangle mon (Desktop::getInstance()
  52809. .getMonitorAreaContaining (windowPos.getX(),
  52810. windowPos.getY(),
  52811. true));
  52812. int deltaY = wantedY - currentY;
  52813. const int newY = jlimit (mon.getY(),
  52814. mon.getBottom() - windowPos.getHeight(),
  52815. windowPos.getY() + deltaY);
  52816. deltaY -= newY - windowPos.getY();
  52817. childYOffset -= deltaY;
  52818. windowPos.setPosition (windowPos.getX(), newY);
  52819. updateYPositions();
  52820. }
  52821. break;
  52822. }
  52823. }
  52824. }
  52825. void resizeToBestWindowPos()
  52826. {
  52827. Rectangle r (windowPos);
  52828. if (childYOffset < 0)
  52829. {
  52830. r.setBounds (r.getX(), r.getY() - childYOffset,
  52831. r.getWidth(), r.getHeight() + childYOffset);
  52832. }
  52833. else if (childYOffset > 0)
  52834. {
  52835. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  52836. if (spaceAtBottom > 0)
  52837. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  52838. }
  52839. setBounds (r);
  52840. updateYPositions();
  52841. }
  52842. void alterChildYPos (const int delta)
  52843. {
  52844. if (isScrolling())
  52845. {
  52846. childYOffset += delta;
  52847. if (delta < 0)
  52848. {
  52849. childYOffset = jmax (childYOffset, 0);
  52850. }
  52851. else if (delta > 0)
  52852. {
  52853. childYOffset = jmin (childYOffset,
  52854. contentHeight - windowPos.getHeight() + borderSize);
  52855. }
  52856. updateYPositions();
  52857. }
  52858. else
  52859. {
  52860. childYOffset = 0;
  52861. }
  52862. resizeToBestWindowPos();
  52863. repaint();
  52864. }
  52865. int updateYPositions()
  52866. {
  52867. int x = 0;
  52868. int childNum = 0;
  52869. for (int col = 0; col < numColumns; ++col)
  52870. {
  52871. const int numChildren = jmin (getNumChildComponents() - childNum,
  52872. (getNumChildComponents() + numColumns - 1) / numColumns);
  52873. const int colW = columnWidths [col];
  52874. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  52875. for (int i = 0; i < numChildren; ++i)
  52876. {
  52877. Component* const c = getChildComponent (childNum + i);
  52878. c->setBounds (x, y, colW, c->getHeight());
  52879. y += c->getHeight();
  52880. }
  52881. x += colW;
  52882. childNum += numChildren;
  52883. }
  52884. return x;
  52885. }
  52886. bool isScrolling() const throw()
  52887. {
  52888. return childYOffset != 0 || needsToScroll;
  52889. }
  52890. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  52891. {
  52892. if (currentChild->isValidComponent())
  52893. currentChild->setHighlighted (false);
  52894. currentChild = child;
  52895. if (currentChild != 0)
  52896. {
  52897. currentChild->setHighlighted (true);
  52898. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  52899. }
  52900. }
  52901. bool showSubMenuFor (MenuItemComponent* const childComp)
  52902. {
  52903. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52904. deleteAndZero (activeSubMenu);
  52905. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  52906. {
  52907. int left = 0, top = 0;
  52908. childComp->relativePositionToGlobal (left, top);
  52909. int right = childComp->getWidth(), bottom = childComp->getHeight();
  52910. childComp->relativePositionToGlobal (right, bottom);
  52911. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  52912. dismissOnMouseUp,
  52913. this,
  52914. left, right, top, bottom,
  52915. 0, maximumNumColumns,
  52916. standardItemHeight,
  52917. false, 0, menuBarComponent,
  52918. managerOfChosenCommand,
  52919. componentAttachedTo);
  52920. if (activeSubMenu != 0)
  52921. {
  52922. activeSubMenu->setVisible (true);
  52923. activeSubMenu->enterModalState (false);
  52924. activeSubMenu->toFront (false);
  52925. return true;
  52926. }
  52927. }
  52928. return false;
  52929. }
  52930. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  52931. {
  52932. isOver = reallyContains (x, y, true);
  52933. if (isOver)
  52934. hasBeenOver = true;
  52935. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  52936. {
  52937. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  52938. if (disableMouseMoves && isOver)
  52939. disableMouseMoves = false;
  52940. }
  52941. if (disableMouseMoves)
  52942. return;
  52943. bool isMovingTowardsMenu = false;
  52944. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  52945. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  52946. {
  52947. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  52948. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  52949. // extends from the last mouse pos to the submenu's rectangle..
  52950. float subX = (float) activeSubMenu->getScreenX();
  52951. if (activeSubMenu->getX() > getX())
  52952. {
  52953. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  52954. }
  52955. else
  52956. {
  52957. lastMouseX += 2;
  52958. subX += activeSubMenu->getWidth();
  52959. }
  52960. Path areaTowardsSubMenu;
  52961. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  52962. (float) lastMouseY,
  52963. subX,
  52964. (float) activeSubMenu->getScreenY(),
  52965. subX,
  52966. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  52967. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  52968. }
  52969. lastMouseX = mx;
  52970. lastMouseY = my;
  52971. if (! isMovingTowardsMenu)
  52972. {
  52973. Component* c = getComponentAt (x, y);
  52974. if (c == this)
  52975. c = 0;
  52976. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  52977. if (mic == 0 && c != 0)
  52978. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  52979. if (mic != currentChild
  52980. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  52981. {
  52982. if (isOver && (c != 0) && (activeSubMenu != 0))
  52983. {
  52984. activeSubMenu->hide (0);
  52985. }
  52986. if (! isOver)
  52987. mic = 0;
  52988. setCurrentlyHighlightedChild (mic);
  52989. }
  52990. }
  52991. }
  52992. void triggerCurrentlyHighlightedItem()
  52993. {
  52994. if (currentChild->isValidComponent()
  52995. && currentChild->itemInfo.canBeTriggered()
  52996. && (currentChild->itemInfo.customComp == 0
  52997. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  52998. {
  52999. dismissMenu (&currentChild->itemInfo);
  53000. }
  53001. }
  53002. void selectNextItem (const int delta)
  53003. {
  53004. disableTimerUntilMouseMoves();
  53005. MenuItemComponent* mic = 0;
  53006. bool wasLastOne = (currentChild == 0);
  53007. const int numItems = getNumChildComponents();
  53008. for (int i = 0; i < numItems + 1; ++i)
  53009. {
  53010. int index = (delta > 0) ? i : (numItems - 1 - i);
  53011. index = (index + numItems) % numItems;
  53012. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  53013. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  53014. && wasLastOne)
  53015. break;
  53016. if (mic == currentChild)
  53017. wasLastOne = true;
  53018. }
  53019. setCurrentlyHighlightedChild (mic);
  53020. }
  53021. void disableTimerUntilMouseMoves() throw()
  53022. {
  53023. disableMouseMoves = true;
  53024. if (owner != 0)
  53025. owner->disableTimerUntilMouseMoves();
  53026. }
  53027. PopupMenuWindow (const PopupMenuWindow&);
  53028. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  53029. };
  53030. PopupMenu::PopupMenu() throw()
  53031. : items (8),
  53032. lookAndFeel (0),
  53033. separatorPending (false)
  53034. {
  53035. }
  53036. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  53037. : items (8),
  53038. lookAndFeel (other.lookAndFeel),
  53039. separatorPending (false)
  53040. {
  53041. items.ensureStorageAllocated (other.items.size());
  53042. for (int i = 0; i < other.items.size(); ++i)
  53043. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  53044. }
  53045. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  53046. {
  53047. if (this != &other)
  53048. {
  53049. lookAndFeel = other.lookAndFeel;
  53050. clear();
  53051. items.ensureStorageAllocated (other.items.size());
  53052. for (int i = 0; i < other.items.size(); ++i)
  53053. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  53054. }
  53055. return *this;
  53056. }
  53057. PopupMenu::~PopupMenu() throw()
  53058. {
  53059. clear();
  53060. }
  53061. void PopupMenu::clear() throw()
  53062. {
  53063. for (int i = items.size(); --i >= 0;)
  53064. {
  53065. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  53066. delete mi;
  53067. }
  53068. items.clear();
  53069. separatorPending = false;
  53070. }
  53071. void PopupMenu::addSeparatorIfPending()
  53072. {
  53073. if (separatorPending)
  53074. {
  53075. separatorPending = false;
  53076. if (items.size() > 0)
  53077. items.add (new MenuItemInfo());
  53078. }
  53079. }
  53080. void PopupMenu::addItem (const int itemResultId,
  53081. const String& itemText,
  53082. const bool isActive,
  53083. const bool isTicked,
  53084. const Image* const iconToUse) throw()
  53085. {
  53086. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  53087. // didn't pick anything, so you shouldn't use it as the id
  53088. // for an item..
  53089. addSeparatorIfPending();
  53090. items.add (new MenuItemInfo (itemResultId,
  53091. itemText,
  53092. isActive,
  53093. isTicked,
  53094. iconToUse,
  53095. Colours::black,
  53096. false,
  53097. 0, 0, 0));
  53098. }
  53099. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  53100. const int commandID,
  53101. const String& displayName) throw()
  53102. {
  53103. jassert (commandManager != 0 && commandID != 0);
  53104. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  53105. if (registeredInfo != 0)
  53106. {
  53107. ApplicationCommandInfo info (*registeredInfo);
  53108. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  53109. addSeparatorIfPending();
  53110. items.add (new MenuItemInfo (commandID,
  53111. displayName.isNotEmpty() ? displayName
  53112. : info.shortName,
  53113. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  53114. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  53115. 0,
  53116. Colours::black,
  53117. false,
  53118. 0, 0,
  53119. commandManager));
  53120. }
  53121. }
  53122. void PopupMenu::addColouredItem (const int itemResultId,
  53123. const String& itemText,
  53124. const Colour& itemTextColour,
  53125. const bool isActive,
  53126. const bool isTicked,
  53127. const Image* const iconToUse) throw()
  53128. {
  53129. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  53130. // didn't pick anything, so you shouldn't use it as the id
  53131. // for an item..
  53132. addSeparatorIfPending();
  53133. items.add (new MenuItemInfo (itemResultId,
  53134. itemText,
  53135. isActive,
  53136. isTicked,
  53137. iconToUse,
  53138. itemTextColour,
  53139. true,
  53140. 0, 0, 0));
  53141. }
  53142. void PopupMenu::addCustomItem (const int itemResultId,
  53143. PopupMenuCustomComponent* const customComponent) throw()
  53144. {
  53145. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  53146. // didn't pick anything, so you shouldn't use it as the id
  53147. // for an item..
  53148. addSeparatorIfPending();
  53149. items.add (new MenuItemInfo (itemResultId,
  53150. String::empty,
  53151. true,
  53152. false,
  53153. 0,
  53154. Colours::black,
  53155. false,
  53156. customComponent,
  53157. 0, 0));
  53158. }
  53159. class NormalComponentWrapper : public PopupMenuCustomComponent
  53160. {
  53161. public:
  53162. NormalComponentWrapper (Component* const comp,
  53163. const int w, const int h,
  53164. const bool triggerMenuItemAutomaticallyWhenClicked)
  53165. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  53166. width (w),
  53167. height (h)
  53168. {
  53169. addAndMakeVisible (comp);
  53170. }
  53171. ~NormalComponentWrapper() {}
  53172. void getIdealSize (int& idealWidth, int& idealHeight)
  53173. {
  53174. idealWidth = width;
  53175. idealHeight = height;
  53176. }
  53177. void resized()
  53178. {
  53179. if (getChildComponent(0) != 0)
  53180. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  53181. }
  53182. juce_UseDebuggingNewOperator
  53183. private:
  53184. const int width, height;
  53185. NormalComponentWrapper (const NormalComponentWrapper&);
  53186. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  53187. };
  53188. void PopupMenu::addCustomItem (const int itemResultId,
  53189. Component* customComponent,
  53190. int idealWidth, int idealHeight,
  53191. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  53192. {
  53193. addCustomItem (itemResultId,
  53194. new NormalComponentWrapper (customComponent,
  53195. idealWidth, idealHeight,
  53196. triggerMenuItemAutomaticallyWhenClicked));
  53197. }
  53198. void PopupMenu::addSubMenu (const String& subMenuName,
  53199. const PopupMenu& subMenu,
  53200. const bool isActive,
  53201. Image* const iconToUse,
  53202. const bool isTicked) throw()
  53203. {
  53204. addSeparatorIfPending();
  53205. items.add (new MenuItemInfo (0,
  53206. subMenuName,
  53207. isActive && (subMenu.getNumItems() > 0),
  53208. isTicked,
  53209. iconToUse,
  53210. Colours::black,
  53211. false,
  53212. 0,
  53213. &subMenu,
  53214. 0));
  53215. }
  53216. void PopupMenu::addSeparator() throw()
  53217. {
  53218. separatorPending = true;
  53219. }
  53220. class HeaderItemComponent : public PopupMenuCustomComponent
  53221. {
  53222. public:
  53223. HeaderItemComponent (const String& name)
  53224. : PopupMenuCustomComponent (false)
  53225. {
  53226. setName (name);
  53227. }
  53228. ~HeaderItemComponent()
  53229. {
  53230. }
  53231. void paint (Graphics& g)
  53232. {
  53233. Font f (getLookAndFeel().getPopupMenuFont());
  53234. f.setBold (true);
  53235. g.setFont (f);
  53236. g.setColour (findColour (PopupMenu::headerTextColourId));
  53237. g.drawFittedText (getName(),
  53238. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  53239. Justification::bottomLeft, 1);
  53240. }
  53241. void getIdealSize (int& idealWidth,
  53242. int& idealHeight)
  53243. {
  53244. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  53245. idealHeight += idealHeight / 2;
  53246. idealWidth += idealWidth / 4;
  53247. }
  53248. juce_UseDebuggingNewOperator
  53249. };
  53250. void PopupMenu::addSectionHeader (const String& title) throw()
  53251. {
  53252. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  53253. }
  53254. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  53255. const int itemIdThatMustBeVisible,
  53256. const int minimumWidth,
  53257. const int maximumNumColumns,
  53258. const int standardItemHeight,
  53259. const bool alignToRectangle,
  53260. Component* menuBarComponent,
  53261. ApplicationCommandManager** managerOfChosenCommand,
  53262. Component* const componentAttachedTo) throw()
  53263. {
  53264. PopupMenuWindow* const pw
  53265. = PopupMenuWindow::create (*this,
  53266. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  53267. 0,
  53268. x, x + w,
  53269. y, y + h,
  53270. minimumWidth,
  53271. maximumNumColumns,
  53272. standardItemHeight,
  53273. alignToRectangle,
  53274. itemIdThatMustBeVisible,
  53275. menuBarComponent,
  53276. managerOfChosenCommand,
  53277. componentAttachedTo);
  53278. if (pw != 0)
  53279. pw->setVisible (true);
  53280. return pw;
  53281. }
  53282. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  53283. const int itemIdThatMustBeVisible,
  53284. const int minimumWidth,
  53285. const int maximumNumColumns,
  53286. const int standardItemHeight,
  53287. const bool alignToRectangle,
  53288. Component* const componentAttachedTo) throw()
  53289. {
  53290. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  53291. ComponentDeletionWatcher* deletionChecker1 = 0;
  53292. if (prevFocused != 0)
  53293. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  53294. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  53295. ComponentDeletionWatcher* deletionChecker2 = 0;
  53296. if (prevTopLevel != 0)
  53297. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  53298. wasHiddenBecauseOfAppChange = false;
  53299. int result = 0;
  53300. ApplicationCommandManager* managerOfChosenCommand = 0;
  53301. Component* const popupComp = createMenuComponent (x, y, w, h,
  53302. itemIdThatMustBeVisible,
  53303. minimumWidth,
  53304. maximumNumColumns > 0 ? maximumNumColumns : 7,
  53305. standardItemHeight,
  53306. alignToRectangle, 0,
  53307. &managerOfChosenCommand,
  53308. componentAttachedTo);
  53309. if (popupComp != 0)
  53310. {
  53311. popupComp->enterModalState (false);
  53312. popupComp->toFront (false); // need to do this after making it modal, or it could
  53313. // be stuck behind other comps that are already modal..
  53314. result = popupComp->runModalLoop();
  53315. delete popupComp;
  53316. if (! wasHiddenBecauseOfAppChange)
  53317. {
  53318. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  53319. prevTopLevel->toFront (true);
  53320. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  53321. prevFocused->grabKeyboardFocus();
  53322. }
  53323. }
  53324. delete deletionChecker1;
  53325. delete deletionChecker2;
  53326. if (managerOfChosenCommand != 0 && result != 0)
  53327. {
  53328. ApplicationCommandTarget::InvocationInfo info (result);
  53329. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  53330. managerOfChosenCommand->invoke (info, true);
  53331. }
  53332. return result;
  53333. }
  53334. int PopupMenu::show (const int itemIdThatMustBeVisible,
  53335. const int minimumWidth,
  53336. const int maximumNumColumns,
  53337. const int standardItemHeight)
  53338. {
  53339. int x, y;
  53340. Desktop::getMousePosition (x, y);
  53341. return showAt (x, y,
  53342. itemIdThatMustBeVisible,
  53343. minimumWidth,
  53344. maximumNumColumns,
  53345. standardItemHeight);
  53346. }
  53347. int PopupMenu::showAt (const int screenX,
  53348. const int screenY,
  53349. const int itemIdThatMustBeVisible,
  53350. const int minimumWidth,
  53351. const int maximumNumColumns,
  53352. const int standardItemHeight)
  53353. {
  53354. return showMenu (screenX, screenY, 1, 1,
  53355. itemIdThatMustBeVisible,
  53356. minimumWidth, maximumNumColumns,
  53357. standardItemHeight,
  53358. false, 0);
  53359. }
  53360. int PopupMenu::showAt (Component* componentToAttachTo,
  53361. const int itemIdThatMustBeVisible,
  53362. const int minimumWidth,
  53363. const int maximumNumColumns,
  53364. const int standardItemHeight)
  53365. {
  53366. if (componentToAttachTo != 0)
  53367. {
  53368. return showMenu (componentToAttachTo->getScreenX(),
  53369. componentToAttachTo->getScreenY(),
  53370. componentToAttachTo->getWidth(),
  53371. componentToAttachTo->getHeight(),
  53372. itemIdThatMustBeVisible,
  53373. minimumWidth,
  53374. maximumNumColumns,
  53375. standardItemHeight,
  53376. true, componentToAttachTo);
  53377. }
  53378. else
  53379. {
  53380. return show (itemIdThatMustBeVisible,
  53381. minimumWidth,
  53382. maximumNumColumns,
  53383. standardItemHeight);
  53384. }
  53385. }
  53386. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  53387. {
  53388. for (int i = activeMenuWindows.size(); --i >= 0;)
  53389. {
  53390. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  53391. if (pmw != 0)
  53392. pmw->dismissMenu (0);
  53393. }
  53394. }
  53395. int PopupMenu::getNumItems() const throw()
  53396. {
  53397. int num = 0;
  53398. for (int i = items.size(); --i >= 0;)
  53399. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  53400. ++num;
  53401. return num;
  53402. }
  53403. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  53404. {
  53405. for (int i = items.size(); --i >= 0;)
  53406. {
  53407. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  53408. if ((mi->itemId == commandID && mi->commandManager != 0)
  53409. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  53410. {
  53411. return true;
  53412. }
  53413. }
  53414. return false;
  53415. }
  53416. bool PopupMenu::containsAnyActiveItems() const throw()
  53417. {
  53418. for (int i = items.size(); --i >= 0;)
  53419. {
  53420. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  53421. if (mi->subMenu != 0)
  53422. {
  53423. if (mi->subMenu->containsAnyActiveItems())
  53424. return true;
  53425. }
  53426. else if (mi->active)
  53427. {
  53428. return true;
  53429. }
  53430. }
  53431. return false;
  53432. }
  53433. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  53434. {
  53435. lookAndFeel = newLookAndFeel;
  53436. }
  53437. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  53438. : refCount_ (0),
  53439. isHighlighted (false),
  53440. isTriggeredAutomatically (isTriggeredAutomatically_)
  53441. {
  53442. }
  53443. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  53444. {
  53445. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  53446. }
  53447. void PopupMenuCustomComponent::triggerMenuItem()
  53448. {
  53449. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  53450. if (mic != 0)
  53451. {
  53452. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  53453. if (pmw != 0)
  53454. {
  53455. pmw->dismissMenu (&mic->itemInfo);
  53456. }
  53457. else
  53458. {
  53459. // something must have gone wrong with the component hierarchy if this happens..
  53460. jassertfalse
  53461. }
  53462. }
  53463. else
  53464. {
  53465. // why isn't this component inside a menu? Not much point triggering the item if
  53466. // there's no menu.
  53467. jassertfalse
  53468. }
  53469. }
  53470. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  53471. : subMenu (0),
  53472. itemId (0),
  53473. isSeparator (false),
  53474. isTicked (false),
  53475. isEnabled (false),
  53476. isCustomComponent (false),
  53477. isSectionHeader (false),
  53478. customColour (0),
  53479. customImage (0),
  53480. menu (menu_),
  53481. index (0)
  53482. {
  53483. }
  53484. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  53485. {
  53486. }
  53487. bool PopupMenu::MenuItemIterator::next() throw()
  53488. {
  53489. if (index >= menu.items.size())
  53490. return false;
  53491. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  53492. ++index;
  53493. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  53494. subMenu = item->subMenu;
  53495. itemId = item->itemId;
  53496. isSeparator = item->isSeparator;
  53497. isTicked = item->isTicked;
  53498. isEnabled = item->active;
  53499. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  53500. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  53501. customColour = item->usesColour ? &(item->textColour) : 0;
  53502. customImage = item->image;
  53503. commandManager = item->commandManager;
  53504. return true;
  53505. }
  53506. END_JUCE_NAMESPACE
  53507. /********* End of inlined file: juce_PopupMenu.cpp *********/
  53508. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  53509. BEGIN_JUCE_NAMESPACE
  53510. ComponentDragger::ComponentDragger()
  53511. : constrainer (0),
  53512. originalX (0),
  53513. originalY (0)
  53514. {
  53515. }
  53516. ComponentDragger::~ComponentDragger()
  53517. {
  53518. }
  53519. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  53520. ComponentBoundsConstrainer* const constrainer_)
  53521. {
  53522. jassert (componentToDrag->isValidComponent());
  53523. if (componentToDrag->isValidComponent())
  53524. {
  53525. constrainer = constrainer_;
  53526. originalX = 0;
  53527. originalY = 0;
  53528. componentToDrag->relativePositionToGlobal (originalX, originalY);
  53529. }
  53530. }
  53531. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  53532. {
  53533. jassert (componentToDrag->isValidComponent());
  53534. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  53535. if (componentToDrag->isValidComponent())
  53536. {
  53537. int x = originalX;
  53538. int y = originalY;
  53539. int w = componentToDrag->getWidth();
  53540. int h = componentToDrag->getHeight();
  53541. const Component* const parentComp = componentToDrag->getParentComponent();
  53542. if (parentComp != 0)
  53543. parentComp->globalPositionToRelative (x, y);
  53544. x += e.getDistanceFromDragStartX();
  53545. y += e.getDistanceFromDragStartY();
  53546. if (constrainer != 0)
  53547. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  53548. false, false, false, false);
  53549. else
  53550. componentToDrag->setBounds (x, y, w, h);
  53551. }
  53552. }
  53553. END_JUCE_NAMESPACE
  53554. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  53555. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  53556. BEGIN_JUCE_NAMESPACE
  53557. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  53558. bool juce_performDragDropText (const String& text, bool& shouldStop);
  53559. class DragImageComponent : public Component,
  53560. public Timer
  53561. {
  53562. private:
  53563. Image* image;
  53564. Component* const source;
  53565. DragAndDropContainer* const owner;
  53566. ComponentDeletionWatcher* sourceWatcher;
  53567. Component* mouseDragSource;
  53568. ComponentDeletionWatcher* mouseDragSourceWatcher;
  53569. DragAndDropTarget* currentlyOver;
  53570. ComponentDeletionWatcher* currentlyOverWatcher;
  53571. String dragDesc;
  53572. int xOff, yOff;
  53573. bool hasCheckedForExternalDrag, drawImage;
  53574. DragImageComponent (const DragImageComponent&);
  53575. const DragImageComponent& operator= (const DragImageComponent&);
  53576. public:
  53577. DragImageComponent (Image* const im,
  53578. const String& desc,
  53579. Component* const s,
  53580. DragAndDropContainer* const o)
  53581. : image (im),
  53582. source (s),
  53583. owner (o),
  53584. currentlyOver (0),
  53585. currentlyOverWatcher (0),
  53586. dragDesc (desc),
  53587. hasCheckedForExternalDrag (false),
  53588. drawImage (true)
  53589. {
  53590. setSize (im->getWidth(), im->getHeight());
  53591. sourceWatcher = new ComponentDeletionWatcher (source);
  53592. mouseDragSource = Component::getComponentUnderMouse();
  53593. if (mouseDragSource == 0)
  53594. mouseDragSource = source;
  53595. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  53596. mouseDragSource->addMouseListener (this, false);
  53597. int mx, my;
  53598. Desktop::getLastMouseDownPosition (mx, my);
  53599. source->globalPositionToRelative (mx, my);
  53600. xOff = jlimit (0, im->getWidth(), mx);
  53601. yOff = jlimit (0, im->getHeight(), my);
  53602. startTimer (200);
  53603. setInterceptsMouseClicks (false, false);
  53604. setAlwaysOnTop (true);
  53605. }
  53606. ~DragImageComponent()
  53607. {
  53608. if (owner->dragImageComponent == this)
  53609. owner->dragImageComponent = 0;
  53610. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53611. {
  53612. mouseDragSource->removeMouseListener (this);
  53613. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53614. if (currentlyOver->isInterestedInDragSource (dragDesc, source))
  53615. currentlyOver->itemDragExit (dragDesc, source);
  53616. }
  53617. delete mouseDragSourceWatcher;
  53618. delete sourceWatcher;
  53619. delete image;
  53620. delete currentlyOverWatcher;
  53621. }
  53622. void paint (Graphics& g)
  53623. {
  53624. if (isOpaque())
  53625. g.fillAll (Colours::white);
  53626. if (drawImage)
  53627. {
  53628. g.setOpacity (1.0f);
  53629. g.drawImageAt (image, 0, 0);
  53630. }
  53631. }
  53632. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  53633. int& relX, int& relY) const throw()
  53634. {
  53635. Component* hit = getParentComponent();
  53636. if (hit == 0)
  53637. {
  53638. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  53639. }
  53640. else
  53641. {
  53642. int rx = screenX, ry = screenY;
  53643. hit->globalPositionToRelative (rx, ry);
  53644. hit = hit->getComponentAt (rx, ry);
  53645. }
  53646. // (note: use a local copy of the dragDesc member in case the callback runs
  53647. // a modal loop and deletes this object before the method completes)
  53648. const String dragDescLocal (dragDesc);
  53649. while (hit != 0)
  53650. {
  53651. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  53652. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  53653. {
  53654. relX = screenX;
  53655. relY = screenY;
  53656. hit->globalPositionToRelative (relX, relY);
  53657. return ddt;
  53658. }
  53659. hit = hit->getParentComponent();
  53660. }
  53661. return 0;
  53662. }
  53663. void mouseUp (const MouseEvent& e)
  53664. {
  53665. if (e.originalComponent != this)
  53666. {
  53667. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53668. mouseDragSource->removeMouseListener (this);
  53669. bool dropAccepted = false;
  53670. DragAndDropTarget* ddt = 0;
  53671. int relX = 0, relY = 0;
  53672. if (isVisible())
  53673. {
  53674. setVisible (false);
  53675. ddt = findTarget (e.getScreenX(),
  53676. e.getScreenY(),
  53677. relX, relY);
  53678. // fade this component and remove it - it'll be deleted later by the timer callback
  53679. dropAccepted = ddt != 0;
  53680. setVisible (true);
  53681. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  53682. {
  53683. fadeOutComponent (120);
  53684. }
  53685. else
  53686. {
  53687. int targetX = source->getWidth() / 2;
  53688. int targetY = source->getHeight() / 2;
  53689. source->relativePositionToGlobal (targetX, targetY);
  53690. int ourCentreX = getWidth() / 2;
  53691. int ourCentreY = getHeight() / 2;
  53692. relativePositionToGlobal (ourCentreX, ourCentreY);
  53693. fadeOutComponent (120,
  53694. targetX - ourCentreX,
  53695. targetY - ourCentreY);
  53696. }
  53697. }
  53698. if (getParentComponent() != 0)
  53699. getParentComponent()->removeChildComponent (this);
  53700. if (dropAccepted && ddt != 0)
  53701. {
  53702. // (note: use a local copy of the dragDesc member in case the callback runs
  53703. // a modal loop and deletes this object before the method completes)
  53704. const String dragDescLocal (dragDesc);
  53705. currentlyOver = 0;
  53706. deleteAndZero (currentlyOverWatcher);
  53707. ddt->itemDropped (dragDescLocal, source, relX, relY);
  53708. }
  53709. // careful - this object could now be deleted..
  53710. }
  53711. }
  53712. void updateLocation (const bool canDoExternalDrag, int x, int y)
  53713. {
  53714. // (note: use a local copy of the dragDesc member in case the callback runs
  53715. // a modal loop and deletes this object before it returns)
  53716. const String dragDescLocal (dragDesc);
  53717. int newX = x - xOff;
  53718. int newY = y - yOff;
  53719. if (getParentComponent() != 0)
  53720. getParentComponent()->globalPositionToRelative (newX, newY);
  53721. if (newX != getX() || newY != getY())
  53722. {
  53723. setTopLeftPosition (newX, newY);
  53724. int relX = 0, relY = 0;
  53725. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  53726. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  53727. if (ddt != currentlyOver)
  53728. {
  53729. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53730. {
  53731. Component* const over = dynamic_cast <Component*> (currentlyOver);
  53732. if (over != 0
  53733. && over->isValidComponent()
  53734. && ! (sourceWatcher->hasBeenDeleted())
  53735. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53736. {
  53737. currentlyOver->itemDragExit (dragDescLocal, source);
  53738. }
  53739. }
  53740. currentlyOver = ddt;
  53741. deleteAndZero (currentlyOverWatcher);
  53742. if (ddt != 0)
  53743. {
  53744. currentlyOverWatcher = new ComponentDeletionWatcher (dynamic_cast <Component*> (ddt));
  53745. if (currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53746. currentlyOver->itemDragEnter (dragDescLocal, source, relX, relY);
  53747. }
  53748. }
  53749. else if (currentlyOverWatcher != 0 && currentlyOverWatcher->hasBeenDeleted())
  53750. {
  53751. currentlyOver = 0;
  53752. deleteAndZero (currentlyOverWatcher);
  53753. }
  53754. if (currentlyOver != 0
  53755. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53756. currentlyOver->itemDragMove (dragDescLocal, source, relX, relY);
  53757. if (currentlyOver == 0
  53758. && canDoExternalDrag
  53759. && ! hasCheckedForExternalDrag)
  53760. {
  53761. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  53762. {
  53763. hasCheckedForExternalDrag = true;
  53764. StringArray files;
  53765. bool canMoveFiles = false;
  53766. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  53767. && files.size() > 0)
  53768. {
  53769. ComponentDeletionWatcher cdw (this);
  53770. setVisible (false);
  53771. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  53772. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  53773. if (! cdw.hasBeenDeleted())
  53774. delete this;
  53775. return;
  53776. }
  53777. }
  53778. }
  53779. }
  53780. }
  53781. void mouseDrag (const MouseEvent& e)
  53782. {
  53783. if (e.originalComponent != this)
  53784. updateLocation (true, e.getScreenX(), e.getScreenY());
  53785. }
  53786. void timerCallback()
  53787. {
  53788. if (sourceWatcher->hasBeenDeleted())
  53789. {
  53790. delete this;
  53791. }
  53792. else if (! isMouseButtonDownAnywhere())
  53793. {
  53794. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53795. mouseDragSource->removeMouseListener (this);
  53796. delete this;
  53797. }
  53798. }
  53799. };
  53800. DragAndDropContainer::DragAndDropContainer()
  53801. : dragImageComponent (0)
  53802. {
  53803. }
  53804. DragAndDropContainer::~DragAndDropContainer()
  53805. {
  53806. if (dragImageComponent != 0)
  53807. delete dragImageComponent;
  53808. }
  53809. void DragAndDropContainer::startDragging (const String& sourceDescription,
  53810. Component* sourceComponent,
  53811. Image* im,
  53812. const bool allowDraggingToExternalWindows)
  53813. {
  53814. if (dragImageComponent != 0)
  53815. {
  53816. if (im != 0)
  53817. delete im;
  53818. }
  53819. else
  53820. {
  53821. Component* const thisComp = dynamic_cast <Component*> (this);
  53822. if (thisComp != 0)
  53823. {
  53824. int mx, my;
  53825. Desktop::getLastMouseDownPosition (mx, my);
  53826. if (im == 0)
  53827. {
  53828. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  53829. if (im->getFormat() != Image::ARGB)
  53830. {
  53831. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  53832. Graphics g2 (*newIm);
  53833. g2.drawImageAt (im, 0, 0);
  53834. delete im;
  53835. im = newIm;
  53836. }
  53837. im->multiplyAllAlphas (0.6f);
  53838. const int lo = 150;
  53839. const int hi = 400;
  53840. int rx = mx, ry = my;
  53841. sourceComponent->globalPositionToRelative (rx, ry);
  53842. const int cx = jlimit (0, im->getWidth(), rx);
  53843. const int cy = jlimit (0, im->getHeight(), ry);
  53844. for (int y = im->getHeight(); --y >= 0;)
  53845. {
  53846. const double dy = (y - cy) * (y - cy);
  53847. for (int x = im->getWidth(); --x >= 0;)
  53848. {
  53849. const int dx = x - cx;
  53850. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  53851. if (distance > lo)
  53852. {
  53853. const float alpha = (distance > hi) ? 0
  53854. : (hi - distance) / (float) (hi - lo)
  53855. + Random::getSystemRandom().nextFloat() * 0.008f;
  53856. im->multiplyAlphaAt (x, y, alpha);
  53857. }
  53858. }
  53859. }
  53860. }
  53861. DragImageComponent* const dic
  53862. = new DragImageComponent (im,
  53863. sourceDescription,
  53864. sourceComponent,
  53865. this);
  53866. dragImageComponent = dic;
  53867. currentDragDesc = sourceDescription;
  53868. if (allowDraggingToExternalWindows)
  53869. {
  53870. if (! Desktop::canUseSemiTransparentWindows())
  53871. dic->setOpaque (true);
  53872. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53873. | ComponentPeer::windowIsTemporary
  53874. | ComponentPeer::windowIgnoresKeyPresses);
  53875. }
  53876. else
  53877. thisComp->addChildComponent (dic);
  53878. dic->updateLocation (false, mx, my);
  53879. dic->setVisible (true);
  53880. }
  53881. else
  53882. {
  53883. // this class must only be implemented by an object that
  53884. // is also a Component.
  53885. jassertfalse
  53886. if (im != 0)
  53887. delete im;
  53888. }
  53889. }
  53890. }
  53891. bool DragAndDropContainer::isDragAndDropActive() const
  53892. {
  53893. return dragImageComponent != 0;
  53894. }
  53895. const String DragAndDropContainer::getCurrentDragDescription() const
  53896. {
  53897. return (dragImageComponent != 0) ? currentDragDesc
  53898. : String::empty;
  53899. }
  53900. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  53901. {
  53902. if (c == 0)
  53903. return 0;
  53904. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  53905. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  53906. }
  53907. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  53908. {
  53909. return false;
  53910. }
  53911. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  53912. {
  53913. }
  53914. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  53915. {
  53916. }
  53917. void DragAndDropTarget::itemDragExit (const String&, Component*)
  53918. {
  53919. }
  53920. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  53921. {
  53922. return true;
  53923. }
  53924. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  53925. {
  53926. }
  53927. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  53928. {
  53929. }
  53930. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  53931. {
  53932. }
  53933. END_JUCE_NAMESPACE
  53934. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  53935. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  53936. BEGIN_JUCE_NAMESPACE
  53937. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  53938. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  53939. // isStandard set depending on which interface was used to create the cursor
  53940. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  53941. static CriticalSection mouseCursorLock;
  53942. static VoidArray standardCursors (2);
  53943. class RefCountedMouseCursor
  53944. {
  53945. public:
  53946. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  53947. : refCount (1),
  53948. standardType (t),
  53949. isStandard (true)
  53950. {
  53951. handle = juce_createStandardMouseCursor (standardType);
  53952. standardCursors.add (this);
  53953. }
  53954. RefCountedMouseCursor (Image& image,
  53955. const int hotSpotX,
  53956. const int hotSpotY) throw()
  53957. : refCount (1),
  53958. standardType (MouseCursor::NormalCursor),
  53959. isStandard (false)
  53960. {
  53961. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  53962. }
  53963. ~RefCountedMouseCursor() throw()
  53964. {
  53965. juce_deleteMouseCursor (handle, isStandard);
  53966. standardCursors.removeValue (this);
  53967. }
  53968. void decRef() throw()
  53969. {
  53970. if (--refCount == 0)
  53971. delete this;
  53972. }
  53973. void incRef() throw()
  53974. {
  53975. ++refCount;
  53976. }
  53977. void* getHandle() const throw()
  53978. {
  53979. return handle;
  53980. }
  53981. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  53982. {
  53983. const ScopedLock sl (mouseCursorLock);
  53984. for (int i = 0; i < standardCursors.size(); i++)
  53985. {
  53986. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  53987. if (r->standardType == type)
  53988. {
  53989. r->incRef();
  53990. return r;
  53991. }
  53992. }
  53993. return new RefCountedMouseCursor (type);
  53994. }
  53995. juce_UseDebuggingNewOperator
  53996. private:
  53997. void* handle;
  53998. int refCount;
  53999. const MouseCursor::StandardCursorType standardType;
  54000. const bool isStandard;
  54001. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  54002. };
  54003. MouseCursor::MouseCursor() throw()
  54004. {
  54005. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  54006. }
  54007. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  54008. {
  54009. cursorHandle = RefCountedMouseCursor::findInstance (type);
  54010. }
  54011. MouseCursor::MouseCursor (Image& image,
  54012. const int hotSpotX,
  54013. const int hotSpotY) throw()
  54014. {
  54015. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  54016. }
  54017. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  54018. : cursorHandle (other.cursorHandle)
  54019. {
  54020. const ScopedLock sl (mouseCursorLock);
  54021. cursorHandle->incRef();
  54022. }
  54023. MouseCursor::~MouseCursor() throw()
  54024. {
  54025. const ScopedLock sl (mouseCursorLock);
  54026. cursorHandle->decRef();
  54027. }
  54028. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  54029. {
  54030. if (this != &other)
  54031. {
  54032. const ScopedLock sl (mouseCursorLock);
  54033. cursorHandle->decRef();
  54034. cursorHandle = other.cursorHandle;
  54035. cursorHandle->incRef();
  54036. }
  54037. return *this;
  54038. }
  54039. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  54040. {
  54041. return cursorHandle == other.cursorHandle;
  54042. }
  54043. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  54044. {
  54045. return cursorHandle != other.cursorHandle;
  54046. }
  54047. void* MouseCursor::getHandle() const throw()
  54048. {
  54049. return cursorHandle->getHandle();
  54050. }
  54051. void MouseCursor::showWaitCursor() throw()
  54052. {
  54053. const MouseCursor mc (MouseCursor::WaitCursor);
  54054. mc.showInAllWindows();
  54055. }
  54056. void MouseCursor::hideWaitCursor() throw()
  54057. {
  54058. if (Component::getComponentUnderMouse()->isValidComponent())
  54059. {
  54060. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  54061. }
  54062. else
  54063. {
  54064. const MouseCursor mc (MouseCursor::NormalCursor);
  54065. mc.showInAllWindows();
  54066. }
  54067. }
  54068. END_JUCE_NAMESPACE
  54069. /********* End of inlined file: juce_MouseCursor.cpp *********/
  54070. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  54071. BEGIN_JUCE_NAMESPACE
  54072. MouseEvent::MouseEvent (const int x_,
  54073. const int y_,
  54074. const ModifierKeys& mods_,
  54075. Component* const originator,
  54076. const Time& eventTime_,
  54077. const int mouseDownX_,
  54078. const int mouseDownY_,
  54079. const Time& mouseDownTime_,
  54080. const int numberOfClicks_,
  54081. const bool mouseWasDragged) throw()
  54082. : x (x_),
  54083. y (y_),
  54084. mods (mods_),
  54085. eventComponent (originator),
  54086. originalComponent (originator),
  54087. eventTime (eventTime_),
  54088. mouseDownX (mouseDownX_),
  54089. mouseDownY (mouseDownY_),
  54090. mouseDownTime (mouseDownTime_),
  54091. numberOfClicks (numberOfClicks_),
  54092. wasMovedSinceMouseDown (mouseWasDragged)
  54093. {
  54094. }
  54095. MouseEvent::~MouseEvent() throw()
  54096. {
  54097. }
  54098. bool MouseEvent::mouseWasClicked() const throw()
  54099. {
  54100. return ! wasMovedSinceMouseDown;
  54101. }
  54102. int MouseEvent::getMouseDownX() const throw()
  54103. {
  54104. return mouseDownX;
  54105. }
  54106. int MouseEvent::getMouseDownY() const throw()
  54107. {
  54108. return mouseDownY;
  54109. }
  54110. int MouseEvent::getDistanceFromDragStartX() const throw()
  54111. {
  54112. return x - mouseDownX;
  54113. }
  54114. int MouseEvent::getDistanceFromDragStartY() const throw()
  54115. {
  54116. return y - mouseDownY;
  54117. }
  54118. int MouseEvent::getDistanceFromDragStart() const throw()
  54119. {
  54120. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  54121. getDistanceFromDragStartY()));
  54122. }
  54123. int MouseEvent::getLengthOfMousePress() const throw()
  54124. {
  54125. if (mouseDownTime.toMilliseconds() > 0)
  54126. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  54127. return 0;
  54128. }
  54129. int MouseEvent::getScreenX() const throw()
  54130. {
  54131. int sx = x, sy = y;
  54132. eventComponent->relativePositionToGlobal (sx, sy);
  54133. return sx;
  54134. }
  54135. int MouseEvent::getScreenY() const throw()
  54136. {
  54137. int sx = x, sy = y;
  54138. eventComponent->relativePositionToGlobal (sx, sy);
  54139. return sy;
  54140. }
  54141. int MouseEvent::getMouseDownScreenX() const throw()
  54142. {
  54143. int sx = mouseDownX, sy = mouseDownY;
  54144. eventComponent->relativePositionToGlobal (sx, sy);
  54145. return sx;
  54146. }
  54147. int MouseEvent::getMouseDownScreenY() const throw()
  54148. {
  54149. int sx = mouseDownX, sy = mouseDownY;
  54150. eventComponent->relativePositionToGlobal (sx, sy);
  54151. return sy;
  54152. }
  54153. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  54154. {
  54155. if (otherComponent == 0)
  54156. {
  54157. jassertfalse
  54158. return *this;
  54159. }
  54160. MouseEvent me (*this);
  54161. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  54162. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  54163. me.eventComponent = otherComponent;
  54164. return me;
  54165. }
  54166. static int doubleClickTimeOutMs = 400;
  54167. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  54168. {
  54169. doubleClickTimeOutMs = newTime;
  54170. }
  54171. int MouseEvent::getDoubleClickTimeout() throw()
  54172. {
  54173. return doubleClickTimeOutMs;
  54174. }
  54175. END_JUCE_NAMESPACE
  54176. /********* End of inlined file: juce_MouseEvent.cpp *********/
  54177. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  54178. BEGIN_JUCE_NAMESPACE
  54179. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  54180. : source (0),
  54181. hoverTimeMillisecs (hoverTimeMillisecs_),
  54182. hasJustHovered (false)
  54183. {
  54184. internalTimer.owner = this;
  54185. }
  54186. MouseHoverDetector::~MouseHoverDetector()
  54187. {
  54188. setHoverComponent (0);
  54189. }
  54190. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  54191. {
  54192. hoverTimeMillisecs = newTimeInMillisecs;
  54193. }
  54194. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  54195. {
  54196. if (source != newSourceComponent)
  54197. {
  54198. internalTimer.stopTimer();
  54199. hasJustHovered = false;
  54200. if (source != 0)
  54201. {
  54202. // ! you need to delete the hover detector before deleting its component
  54203. jassert (source->isValidComponent());
  54204. source->removeMouseListener (&internalTimer);
  54205. }
  54206. source = newSourceComponent;
  54207. if (newSourceComponent != 0)
  54208. newSourceComponent->addMouseListener (&internalTimer, false);
  54209. }
  54210. }
  54211. void MouseHoverDetector::hoverTimerCallback()
  54212. {
  54213. internalTimer.stopTimer();
  54214. if (source != 0)
  54215. {
  54216. int mx, my;
  54217. source->getMouseXYRelative (mx, my);
  54218. if (source->reallyContains (mx, my, false))
  54219. {
  54220. hasJustHovered = true;
  54221. mouseHovered (mx, my);
  54222. }
  54223. }
  54224. }
  54225. void MouseHoverDetector::checkJustHoveredCallback()
  54226. {
  54227. if (hasJustHovered)
  54228. {
  54229. hasJustHovered = false;
  54230. mouseMovedAfterHover();
  54231. }
  54232. }
  54233. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  54234. {
  54235. owner->hoverTimerCallback();
  54236. }
  54237. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  54238. {
  54239. stopTimer();
  54240. owner->checkJustHoveredCallback();
  54241. }
  54242. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  54243. {
  54244. stopTimer();
  54245. owner->checkJustHoveredCallback();
  54246. }
  54247. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  54248. {
  54249. stopTimer();
  54250. owner->checkJustHoveredCallback();
  54251. }
  54252. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  54253. {
  54254. stopTimer();
  54255. owner->checkJustHoveredCallback();
  54256. }
  54257. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  54258. {
  54259. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  54260. {
  54261. lastX = e.x;
  54262. lastY = e.y;
  54263. if (owner->source != 0)
  54264. startTimer (owner->hoverTimeMillisecs);
  54265. owner->checkJustHoveredCallback();
  54266. }
  54267. }
  54268. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  54269. {
  54270. stopTimer();
  54271. owner->checkJustHoveredCallback();
  54272. }
  54273. END_JUCE_NAMESPACE
  54274. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  54275. /********* Start of inlined file: juce_MouseListener.cpp *********/
  54276. BEGIN_JUCE_NAMESPACE
  54277. void MouseListener::mouseEnter (const MouseEvent&)
  54278. {
  54279. }
  54280. void MouseListener::mouseExit (const MouseEvent&)
  54281. {
  54282. }
  54283. void MouseListener::mouseDown (const MouseEvent&)
  54284. {
  54285. }
  54286. void MouseListener::mouseUp (const MouseEvent&)
  54287. {
  54288. }
  54289. void MouseListener::mouseDrag (const MouseEvent&)
  54290. {
  54291. }
  54292. void MouseListener::mouseMove (const MouseEvent&)
  54293. {
  54294. }
  54295. void MouseListener::mouseDoubleClick (const MouseEvent&)
  54296. {
  54297. }
  54298. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  54299. {
  54300. }
  54301. END_JUCE_NAMESPACE
  54302. /********* End of inlined file: juce_MouseListener.cpp *********/
  54303. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54304. BEGIN_JUCE_NAMESPACE
  54305. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  54306. const String& buttonTextWhenTrue,
  54307. const String& buttonTextWhenFalse)
  54308. : PropertyComponent (name),
  54309. onText (buttonTextWhenTrue),
  54310. offText (buttonTextWhenFalse)
  54311. {
  54312. addAndMakeVisible (button = new ToggleButton (String::empty));
  54313. button->setClickingTogglesState (false);
  54314. button->addButtonListener (this);
  54315. }
  54316. BooleanPropertyComponent::~BooleanPropertyComponent()
  54317. {
  54318. deleteAllChildren();
  54319. }
  54320. void BooleanPropertyComponent::paint (Graphics& g)
  54321. {
  54322. PropertyComponent::paint (g);
  54323. const Rectangle r (button->getBounds());
  54324. g.setColour (Colours::white);
  54325. g.fillRect (r);
  54326. g.setColour (findColour (ComboBox::outlineColourId));
  54327. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  54328. }
  54329. void BooleanPropertyComponent::refresh()
  54330. {
  54331. button->setToggleState (getState(), false);
  54332. button->setButtonText (button->getToggleState() ? onText : offText);
  54333. }
  54334. void BooleanPropertyComponent::buttonClicked (Button*)
  54335. {
  54336. setState (! getState());
  54337. }
  54338. END_JUCE_NAMESPACE
  54339. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54340. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54341. BEGIN_JUCE_NAMESPACE
  54342. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  54343. const bool triggerOnMouseDown)
  54344. : PropertyComponent (name)
  54345. {
  54346. addAndMakeVisible (button = new TextButton (String::empty));
  54347. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  54348. button->addButtonListener (this);
  54349. }
  54350. ButtonPropertyComponent::~ButtonPropertyComponent()
  54351. {
  54352. deleteAllChildren();
  54353. }
  54354. void ButtonPropertyComponent::refresh()
  54355. {
  54356. button->setButtonText (getButtonText());
  54357. }
  54358. void ButtonPropertyComponent::buttonClicked (Button*)
  54359. {
  54360. buttonClicked();
  54361. }
  54362. END_JUCE_NAMESPACE
  54363. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54364. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54365. BEGIN_JUCE_NAMESPACE
  54366. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  54367. : PropertyComponent (name),
  54368. comboBox (0)
  54369. {
  54370. }
  54371. ChoicePropertyComponent::~ChoicePropertyComponent()
  54372. {
  54373. deleteAllChildren();
  54374. }
  54375. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  54376. {
  54377. return choices;
  54378. }
  54379. void ChoicePropertyComponent::refresh()
  54380. {
  54381. if (comboBox == 0)
  54382. {
  54383. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  54384. for (int i = 0; i < choices.size(); ++i)
  54385. {
  54386. if (choices[i].isNotEmpty())
  54387. comboBox->addItem (choices[i], i + 1);
  54388. else
  54389. comboBox->addSeparator();
  54390. }
  54391. comboBox->setEditableText (false);
  54392. comboBox->addListener (this);
  54393. }
  54394. comboBox->setSelectedId (getIndex() + 1, true);
  54395. }
  54396. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  54397. {
  54398. const int newIndex = comboBox->getSelectedId() - 1;
  54399. if (newIndex != getIndex())
  54400. setIndex (newIndex);
  54401. }
  54402. END_JUCE_NAMESPACE
  54403. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54404. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  54405. BEGIN_JUCE_NAMESPACE
  54406. PropertyComponent::PropertyComponent (const String& name,
  54407. const int preferredHeight_)
  54408. : Component (name),
  54409. preferredHeight (preferredHeight_)
  54410. {
  54411. jassert (name.isNotEmpty());
  54412. }
  54413. PropertyComponent::~PropertyComponent()
  54414. {
  54415. }
  54416. void PropertyComponent::paint (Graphics& g)
  54417. {
  54418. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  54419. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  54420. }
  54421. void PropertyComponent::resized()
  54422. {
  54423. if (getNumChildComponents() > 0)
  54424. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  54425. }
  54426. void PropertyComponent::enablementChanged()
  54427. {
  54428. repaint();
  54429. }
  54430. END_JUCE_NAMESPACE
  54431. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  54432. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  54433. BEGIN_JUCE_NAMESPACE
  54434. class PropertyHolderComponent : public Component
  54435. {
  54436. public:
  54437. PropertyHolderComponent()
  54438. {
  54439. }
  54440. ~PropertyHolderComponent()
  54441. {
  54442. deleteAllChildren();
  54443. }
  54444. void paint (Graphics&)
  54445. {
  54446. }
  54447. void updateLayout (const int width);
  54448. void refreshAll() const;
  54449. };
  54450. class PropertySectionComponent : public Component
  54451. {
  54452. public:
  54453. PropertySectionComponent (const String& sectionTitle,
  54454. const Array <PropertyComponent*>& newProperties,
  54455. const bool open)
  54456. : Component (sectionTitle),
  54457. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  54458. isOpen_ (open)
  54459. {
  54460. for (int i = newProperties.size(); --i >= 0;)
  54461. {
  54462. addAndMakeVisible (newProperties.getUnchecked(i));
  54463. newProperties.getUnchecked(i)->refresh();
  54464. }
  54465. }
  54466. ~PropertySectionComponent()
  54467. {
  54468. deleteAllChildren();
  54469. }
  54470. void paint (Graphics& g)
  54471. {
  54472. if (titleHeight > 0)
  54473. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  54474. }
  54475. void resized()
  54476. {
  54477. int y = titleHeight;
  54478. for (int i = getNumChildComponents(); --i >= 0;)
  54479. {
  54480. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54481. if (pec != 0)
  54482. {
  54483. const int prefH = pec->getPreferredHeight();
  54484. pec->setBounds (1, y, getWidth() - 2, prefH);
  54485. y += prefH;
  54486. }
  54487. }
  54488. }
  54489. int getPreferredHeight() const
  54490. {
  54491. int y = titleHeight;
  54492. if (isOpen())
  54493. {
  54494. for (int i = 0; i < getNumChildComponents(); ++i)
  54495. {
  54496. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54497. if (pec != 0)
  54498. y += pec->getPreferredHeight();
  54499. }
  54500. }
  54501. return y;
  54502. }
  54503. void setOpen (const bool open)
  54504. {
  54505. if (isOpen_ != open)
  54506. {
  54507. isOpen_ = open;
  54508. for (int i = 0; i < getNumChildComponents(); ++i)
  54509. {
  54510. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54511. if (pec != 0)
  54512. pec->setVisible (open);
  54513. }
  54514. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  54515. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  54516. if (pp != 0)
  54517. pp->resized();
  54518. }
  54519. }
  54520. bool isOpen() const throw()
  54521. {
  54522. return isOpen_;
  54523. }
  54524. void refreshAll() const
  54525. {
  54526. for (int i = 0; i < getNumChildComponents(); ++i)
  54527. {
  54528. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54529. if (pec != 0)
  54530. pec->refresh();
  54531. }
  54532. }
  54533. void mouseDown (const MouseEvent&)
  54534. {
  54535. }
  54536. void mouseUp (const MouseEvent& e)
  54537. {
  54538. if (e.getMouseDownX() < titleHeight
  54539. && e.x < titleHeight
  54540. && e.y < titleHeight
  54541. && e.getNumberOfClicks() != 2)
  54542. {
  54543. setOpen (! isOpen());
  54544. }
  54545. }
  54546. void mouseDoubleClick (const MouseEvent& e)
  54547. {
  54548. if (e.y < titleHeight)
  54549. setOpen (! isOpen());
  54550. }
  54551. private:
  54552. int titleHeight;
  54553. bool isOpen_;
  54554. };
  54555. void PropertyHolderComponent::updateLayout (const int width)
  54556. {
  54557. int y = 0;
  54558. for (int i = getNumChildComponents(); --i >= 0;)
  54559. {
  54560. PropertySectionComponent* const section
  54561. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54562. if (section != 0)
  54563. {
  54564. const int prefH = section->getPreferredHeight();
  54565. section->setBounds (0, y, width, prefH);
  54566. y += prefH;
  54567. }
  54568. }
  54569. setSize (width, y);
  54570. repaint();
  54571. }
  54572. void PropertyHolderComponent::refreshAll() const
  54573. {
  54574. for (int i = getNumChildComponents(); --i >= 0;)
  54575. {
  54576. PropertySectionComponent* const section
  54577. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54578. if (section != 0)
  54579. section->refreshAll();
  54580. }
  54581. }
  54582. PropertyPanel::PropertyPanel()
  54583. {
  54584. messageWhenEmpty = TRANS("(nothing selected)");
  54585. addAndMakeVisible (viewport = new Viewport());
  54586. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  54587. viewport->setFocusContainer (true);
  54588. }
  54589. PropertyPanel::~PropertyPanel()
  54590. {
  54591. clear();
  54592. deleteAllChildren();
  54593. }
  54594. void PropertyPanel::paint (Graphics& g)
  54595. {
  54596. if (propertyHolderComponent->getNumChildComponents() == 0)
  54597. {
  54598. g.setColour (Colours::black.withAlpha (0.5f));
  54599. g.setFont (14.0f);
  54600. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  54601. Justification::centred, true);
  54602. }
  54603. }
  54604. void PropertyPanel::resized()
  54605. {
  54606. viewport->setBounds (0, 0, getWidth(), getHeight());
  54607. updatePropHolderLayout();
  54608. }
  54609. void PropertyPanel::clear()
  54610. {
  54611. if (propertyHolderComponent->getNumChildComponents() > 0)
  54612. {
  54613. propertyHolderComponent->deleteAllChildren();
  54614. repaint();
  54615. }
  54616. }
  54617. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  54618. {
  54619. if (propertyHolderComponent->getNumChildComponents() == 0)
  54620. repaint();
  54621. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  54622. newProperties,
  54623. true), 0);
  54624. updatePropHolderLayout();
  54625. }
  54626. void PropertyPanel::addSection (const String& sectionTitle,
  54627. const Array <PropertyComponent*>& newProperties,
  54628. const bool shouldBeOpen)
  54629. {
  54630. jassert (sectionTitle.isNotEmpty());
  54631. if (propertyHolderComponent->getNumChildComponents() == 0)
  54632. repaint();
  54633. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  54634. newProperties,
  54635. shouldBeOpen), 0);
  54636. updatePropHolderLayout();
  54637. }
  54638. void PropertyPanel::updatePropHolderLayout() const
  54639. {
  54640. const int maxWidth = viewport->getMaximumVisibleWidth();
  54641. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  54642. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  54643. if (maxWidth != newMaxWidth)
  54644. {
  54645. // need to do this twice because of scrollbars changing the size, etc.
  54646. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  54647. }
  54648. }
  54649. void PropertyPanel::refreshAll() const
  54650. {
  54651. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  54652. }
  54653. const StringArray PropertyPanel::getSectionNames() const
  54654. {
  54655. StringArray s;
  54656. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54657. {
  54658. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54659. if (section != 0 && section->getName().isNotEmpty())
  54660. s.add (section->getName());
  54661. }
  54662. return s;
  54663. }
  54664. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  54665. {
  54666. int index = 0;
  54667. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54668. {
  54669. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54670. if (section != 0 && section->getName().isNotEmpty())
  54671. {
  54672. if (index == sectionIndex)
  54673. return section->isOpen();
  54674. ++index;
  54675. }
  54676. }
  54677. return false;
  54678. }
  54679. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  54680. {
  54681. int index = 0;
  54682. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54683. {
  54684. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54685. if (section != 0 && section->getName().isNotEmpty())
  54686. {
  54687. if (index == sectionIndex)
  54688. {
  54689. section->setOpen (shouldBeOpen);
  54690. break;
  54691. }
  54692. ++index;
  54693. }
  54694. }
  54695. }
  54696. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  54697. {
  54698. int index = 0;
  54699. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54700. {
  54701. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54702. if (section != 0 && section->getName().isNotEmpty())
  54703. {
  54704. if (index == sectionIndex)
  54705. {
  54706. section->setEnabled (shouldBeEnabled);
  54707. break;
  54708. }
  54709. ++index;
  54710. }
  54711. }
  54712. }
  54713. XmlElement* PropertyPanel::getOpennessState() const
  54714. {
  54715. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  54716. const StringArray sections (getSectionNames());
  54717. for (int i = 0; i < sections.size(); ++i)
  54718. {
  54719. if (sections[i].isNotEmpty())
  54720. {
  54721. XmlElement* const e = new XmlElement (T("SECTION"));
  54722. e->setAttribute (T("name"), sections[i]);
  54723. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  54724. xml->addChildElement (e);
  54725. }
  54726. }
  54727. return xml;
  54728. }
  54729. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  54730. {
  54731. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  54732. {
  54733. const StringArray sections (getSectionNames());
  54734. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  54735. {
  54736. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  54737. e->getBoolAttribute (T("open")));
  54738. }
  54739. }
  54740. }
  54741. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  54742. {
  54743. if (messageWhenEmpty != newMessage)
  54744. {
  54745. messageWhenEmpty = newMessage;
  54746. repaint();
  54747. }
  54748. }
  54749. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  54750. {
  54751. return messageWhenEmpty;
  54752. }
  54753. END_JUCE_NAMESPACE
  54754. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  54755. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  54756. BEGIN_JUCE_NAMESPACE
  54757. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  54758. const double rangeMin,
  54759. const double rangeMax,
  54760. const double interval,
  54761. const double skewFactor)
  54762. : PropertyComponent (name)
  54763. {
  54764. addAndMakeVisible (slider = new Slider (name));
  54765. slider->setRange (rangeMin, rangeMax, interval);
  54766. slider->setSkewFactor (skewFactor);
  54767. slider->setSliderStyle (Slider::LinearBar);
  54768. slider->addListener (this);
  54769. }
  54770. SliderPropertyComponent::~SliderPropertyComponent()
  54771. {
  54772. deleteAllChildren();
  54773. }
  54774. void SliderPropertyComponent::refresh()
  54775. {
  54776. slider->setValue (getValue(), false);
  54777. }
  54778. void SliderPropertyComponent::sliderValueChanged (Slider*)
  54779. {
  54780. if (getValue() != slider->getValue())
  54781. setValue (slider->getValue());
  54782. }
  54783. END_JUCE_NAMESPACE
  54784. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  54785. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  54786. BEGIN_JUCE_NAMESPACE
  54787. class TextPropLabel : public Label
  54788. {
  54789. TextPropertyComponent& owner;
  54790. int maxChars;
  54791. bool isMultiline;
  54792. public:
  54793. TextPropLabel (TextPropertyComponent& owner_,
  54794. const int maxChars_, const bool isMultiline_)
  54795. : Label (String::empty, String::empty),
  54796. owner (owner_),
  54797. maxChars (maxChars_),
  54798. isMultiline (isMultiline_)
  54799. {
  54800. setEditable (true, true, false);
  54801. setColour (backgroundColourId, Colours::white);
  54802. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  54803. }
  54804. ~TextPropLabel()
  54805. {
  54806. }
  54807. TextEditor* createEditorComponent()
  54808. {
  54809. TextEditor* const textEditor = Label::createEditorComponent();
  54810. textEditor->setInputRestrictions (maxChars);
  54811. if (isMultiline)
  54812. {
  54813. textEditor->setMultiLine (true, true);
  54814. textEditor->setReturnKeyStartsNewLine (true);
  54815. }
  54816. return textEditor;
  54817. }
  54818. void textWasEdited()
  54819. {
  54820. owner.textWasEdited();
  54821. }
  54822. };
  54823. TextPropertyComponent::TextPropertyComponent (const String& name,
  54824. const int maxNumChars,
  54825. const bool isMultiLine)
  54826. : PropertyComponent (name)
  54827. {
  54828. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  54829. if (isMultiLine)
  54830. {
  54831. textEditor->setJustificationType (Justification::topLeft);
  54832. preferredHeight = 120;
  54833. }
  54834. }
  54835. TextPropertyComponent::~TextPropertyComponent()
  54836. {
  54837. deleteAllChildren();
  54838. }
  54839. void TextPropertyComponent::refresh()
  54840. {
  54841. textEditor->setText (getText(), false);
  54842. }
  54843. void TextPropertyComponent::textWasEdited()
  54844. {
  54845. const String newText (textEditor->getText());
  54846. if (getText() != newText)
  54847. setText (newText);
  54848. }
  54849. END_JUCE_NAMESPACE
  54850. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  54851. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  54852. BEGIN_JUCE_NAMESPACE
  54853. class SimpleDeviceManagerInputLevelMeter : public Component,
  54854. public Timer
  54855. {
  54856. public:
  54857. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  54858. : manager (manager_),
  54859. level (0)
  54860. {
  54861. startTimer (50);
  54862. manager->enableInputLevelMeasurement (true);
  54863. }
  54864. ~SimpleDeviceManagerInputLevelMeter()
  54865. {
  54866. manager->enableInputLevelMeasurement (false);
  54867. }
  54868. void timerCallback()
  54869. {
  54870. const float newLevel = (float) manager->getCurrentInputLevel();
  54871. if (fabsf (level - newLevel) > 0.005f)
  54872. {
  54873. level = newLevel;
  54874. repaint();
  54875. }
  54876. }
  54877. void paint (Graphics& g)
  54878. {
  54879. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  54880. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  54881. }
  54882. private:
  54883. AudioDeviceManager* const manager;
  54884. float level;
  54885. };
  54886. class MidiInputSelectorComponentListBox : public ListBox,
  54887. public ListBoxModel
  54888. {
  54889. public:
  54890. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  54891. const String& noItemsMessage_,
  54892. const int minNumber_,
  54893. const int maxNumber_)
  54894. : ListBox (String::empty, 0),
  54895. deviceManager (deviceManager_),
  54896. noItemsMessage (noItemsMessage_),
  54897. minNumber (minNumber_),
  54898. maxNumber (maxNumber_)
  54899. {
  54900. items = MidiInput::getDevices();
  54901. setModel (this);
  54902. setOutlineThickness (1);
  54903. }
  54904. ~MidiInputSelectorComponentListBox()
  54905. {
  54906. }
  54907. int getNumRows()
  54908. {
  54909. return items.size();
  54910. }
  54911. void paintListBoxItem (int row,
  54912. Graphics& g,
  54913. int width, int height,
  54914. bool rowIsSelected)
  54915. {
  54916. if (((unsigned int) row) < (unsigned int) items.size())
  54917. {
  54918. if (rowIsSelected)
  54919. g.fillAll (findColour (TextEditor::highlightColourId)
  54920. .withMultipliedAlpha (0.3f));
  54921. const String item (items [row]);
  54922. bool enabled = deviceManager.isMidiInputEnabled (item);
  54923. const int x = getTickX();
  54924. const int tickW = height - height / 4;
  54925. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  54926. enabled, true, true, false);
  54927. g.setFont (height * 0.6f);
  54928. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  54929. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  54930. }
  54931. }
  54932. void listBoxItemClicked (int row, const MouseEvent& e)
  54933. {
  54934. selectRow (row);
  54935. if (e.x < getTickX())
  54936. flipEnablement (row);
  54937. }
  54938. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  54939. {
  54940. flipEnablement (row);
  54941. }
  54942. void returnKeyPressed (int row)
  54943. {
  54944. flipEnablement (row);
  54945. }
  54946. void paint (Graphics& g)
  54947. {
  54948. ListBox::paint (g);
  54949. if (items.size() == 0)
  54950. {
  54951. g.setColour (Colours::grey);
  54952. g.setFont (13.0f);
  54953. g.drawText (noItemsMessage,
  54954. 0, 0, getWidth(), getHeight() / 2,
  54955. Justification::centred, true);
  54956. }
  54957. }
  54958. int getBestHeight (const int preferredHeight)
  54959. {
  54960. const int extra = getOutlineThickness() * 2;
  54961. return jmax (getRowHeight() * 2 + extra,
  54962. jmin (getRowHeight() * getNumRows() + extra,
  54963. preferredHeight));
  54964. }
  54965. juce_UseDebuggingNewOperator
  54966. private:
  54967. AudioDeviceManager& deviceManager;
  54968. const String noItemsMessage;
  54969. StringArray items;
  54970. int minNumber, maxNumber;
  54971. void flipEnablement (const int row)
  54972. {
  54973. if (((unsigned int) row) < (unsigned int) items.size())
  54974. {
  54975. const String item (items [row]);
  54976. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  54977. }
  54978. }
  54979. int getTickX() const throw()
  54980. {
  54981. return getRowHeight() + 5;
  54982. }
  54983. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  54984. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  54985. };
  54986. class AudioDeviceSettingsPanel : public Component,
  54987. public ComboBoxListener,
  54988. public ChangeListener,
  54989. public ButtonListener
  54990. {
  54991. public:
  54992. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  54993. AudioIODeviceType::DeviceSetupDetails& setup_,
  54994. const bool hideAdvancedOptionsWithButton)
  54995. : type (type_),
  54996. setup (setup_)
  54997. {
  54998. sampleRateDropDown = 0;
  54999. sampleRateLabel = 0;
  55000. bufferSizeDropDown = 0;
  55001. bufferSizeLabel = 0;
  55002. outputDeviceDropDown = 0;
  55003. outputDeviceLabel = 0;
  55004. inputDeviceDropDown = 0;
  55005. inputDeviceLabel = 0;
  55006. testButton = 0;
  55007. inputLevelMeter = 0;
  55008. showUIButton = 0;
  55009. inputChanList = 0;
  55010. outputChanList = 0;
  55011. inputChanLabel = 0;
  55012. outputChanLabel = 0;
  55013. showAdvancedSettingsButton = 0;
  55014. if (hideAdvancedOptionsWithButton)
  55015. {
  55016. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  55017. showAdvancedSettingsButton->addButtonListener (this);
  55018. }
  55019. type->scanForDevices();
  55020. setup.manager->addChangeListener (this);
  55021. changeListenerCallback (0);
  55022. }
  55023. ~AudioDeviceSettingsPanel()
  55024. {
  55025. setup.manager->removeChangeListener (this);
  55026. deleteAndZero (outputDeviceLabel);
  55027. deleteAndZero (inputDeviceLabel);
  55028. deleteAndZero (sampleRateLabel);
  55029. deleteAndZero (bufferSizeLabel);
  55030. deleteAndZero (showUIButton);
  55031. deleteAndZero (inputChanLabel);
  55032. deleteAndZero (outputChanLabel);
  55033. deleteAndZero (showAdvancedSettingsButton);
  55034. deleteAllChildren();
  55035. }
  55036. void resized()
  55037. {
  55038. const int lx = proportionOfWidth (0.35f);
  55039. const int w = proportionOfWidth (0.4f);
  55040. const int h = 24;
  55041. const int space = 6;
  55042. const int dh = h + space;
  55043. int y = 0;
  55044. if (outputDeviceDropDown != 0)
  55045. {
  55046. outputDeviceDropDown->setBounds (lx, y, w, h);
  55047. if (testButton != 0)
  55048. testButton->setBounds (proportionOfWidth (0.77f),
  55049. outputDeviceDropDown->getY(),
  55050. proportionOfWidth (0.18f),
  55051. h);
  55052. y += dh;
  55053. }
  55054. if (inputDeviceDropDown != 0)
  55055. {
  55056. inputDeviceDropDown->setBounds (lx, y, w, h);
  55057. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  55058. inputDeviceDropDown->getY(),
  55059. proportionOfWidth (0.18f),
  55060. h);
  55061. y += dh;
  55062. }
  55063. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  55064. if (outputChanList != 0)
  55065. {
  55066. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  55067. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  55068. y += bh + space;
  55069. }
  55070. if (inputChanList != 0)
  55071. {
  55072. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  55073. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  55074. y += bh + space;
  55075. }
  55076. y += space * 2;
  55077. if (showAdvancedSettingsButton != 0)
  55078. {
  55079. showAdvancedSettingsButton->changeWidthToFitText (h);
  55080. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  55081. }
  55082. if (sampleRateDropDown != 0)
  55083. {
  55084. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  55085. || ! showAdvancedSettingsButton->isVisible());
  55086. sampleRateDropDown->setBounds (lx, y, w, h);
  55087. y += dh;
  55088. }
  55089. if (bufferSizeDropDown != 0)
  55090. {
  55091. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  55092. || ! showAdvancedSettingsButton->isVisible());
  55093. bufferSizeDropDown->setBounds (lx, y, w, h);
  55094. y += dh;
  55095. }
  55096. if (showUIButton != 0)
  55097. {
  55098. showUIButton->setVisible (showAdvancedSettingsButton == 0
  55099. || ! showAdvancedSettingsButton->isVisible());
  55100. showUIButton->changeWidthToFitText (h);
  55101. showUIButton->setTopLeftPosition (lx, y);
  55102. }
  55103. }
  55104. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55105. {
  55106. if (comboBoxThatHasChanged == 0)
  55107. return;
  55108. AudioDeviceManager::AudioDeviceSetup config;
  55109. setup.manager->getAudioDeviceSetup (config);
  55110. String error;
  55111. if (comboBoxThatHasChanged == outputDeviceDropDown
  55112. || comboBoxThatHasChanged == inputDeviceDropDown)
  55113. {
  55114. if (outputDeviceDropDown != 0)
  55115. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  55116. : outputDeviceDropDown->getText();
  55117. if (inputDeviceDropDown != 0)
  55118. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  55119. : inputDeviceDropDown->getText();
  55120. if (! type->hasSeparateInputsAndOutputs())
  55121. config.inputDeviceName = config.outputDeviceName;
  55122. if (comboBoxThatHasChanged == inputDeviceDropDown)
  55123. config.useDefaultInputChannels = true;
  55124. else
  55125. config.useDefaultOutputChannels = true;
  55126. error = setup.manager->setAudioDeviceSetup (config, true);
  55127. showCorrectDeviceName (inputDeviceDropDown, true);
  55128. showCorrectDeviceName (outputDeviceDropDown, false);
  55129. updateControlPanelButton();
  55130. resized();
  55131. }
  55132. else if (comboBoxThatHasChanged == sampleRateDropDown)
  55133. {
  55134. if (sampleRateDropDown->getSelectedId() > 0)
  55135. {
  55136. config.sampleRate = sampleRateDropDown->getSelectedId();
  55137. error = setup.manager->setAudioDeviceSetup (config, true);
  55138. }
  55139. }
  55140. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  55141. {
  55142. if (bufferSizeDropDown->getSelectedId() > 0)
  55143. {
  55144. config.bufferSize = bufferSizeDropDown->getSelectedId();
  55145. error = setup.manager->setAudioDeviceSetup (config, true);
  55146. }
  55147. }
  55148. if (error.isNotEmpty())
  55149. {
  55150. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  55151. T("Error when trying to open audio device!"),
  55152. error);
  55153. }
  55154. }
  55155. void buttonClicked (Button* button)
  55156. {
  55157. if (button == showAdvancedSettingsButton)
  55158. {
  55159. showAdvancedSettingsButton->setVisible (false);
  55160. resized();
  55161. }
  55162. else if (button == showUIButton)
  55163. {
  55164. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  55165. if (device != 0 && device->showControlPanel())
  55166. {
  55167. setup.manager->closeAudioDevice();
  55168. setup.manager->restartLastAudioDevice();
  55169. getTopLevelComponent()->toFront (true);
  55170. }
  55171. }
  55172. else if (button == testButton && testButton != 0)
  55173. {
  55174. setup.manager->playTestSound();
  55175. }
  55176. }
  55177. void updateControlPanelButton()
  55178. {
  55179. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55180. deleteAndZero (showUIButton);
  55181. if (currentDevice != 0 && currentDevice->hasControlPanel())
  55182. {
  55183. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  55184. TRANS ("opens the device's own control panel")));
  55185. showUIButton->addButtonListener (this);
  55186. }
  55187. resized();
  55188. }
  55189. void changeListenerCallback (void*)
  55190. {
  55191. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55192. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  55193. {
  55194. if (outputDeviceDropDown == 0)
  55195. {
  55196. outputDeviceDropDown = new ComboBox (String::empty);
  55197. outputDeviceDropDown->addListener (this);
  55198. addAndMakeVisible (outputDeviceDropDown);
  55199. outputDeviceLabel = new Label (String::empty,
  55200. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  55201. : TRANS ("device:"));
  55202. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  55203. if (setup.maxNumOutputChannels > 0)
  55204. {
  55205. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  55206. testButton->addButtonListener (this);
  55207. }
  55208. }
  55209. addNamesToDeviceBox (*outputDeviceDropDown, false);
  55210. }
  55211. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  55212. {
  55213. if (inputDeviceDropDown == 0)
  55214. {
  55215. inputDeviceDropDown = new ComboBox (String::empty);
  55216. inputDeviceDropDown->addListener (this);
  55217. addAndMakeVisible (inputDeviceDropDown);
  55218. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  55219. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  55220. addAndMakeVisible (inputLevelMeter
  55221. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  55222. }
  55223. addNamesToDeviceBox (*inputDeviceDropDown, true);
  55224. }
  55225. updateControlPanelButton();
  55226. showCorrectDeviceName (inputDeviceDropDown, true);
  55227. showCorrectDeviceName (outputDeviceDropDown, false);
  55228. if (currentDevice != 0)
  55229. {
  55230. if (setup.maxNumOutputChannels > 0
  55231. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  55232. {
  55233. if (outputChanList == 0)
  55234. {
  55235. addAndMakeVisible (outputChanList
  55236. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  55237. TRANS ("(no audio output channels found)")));
  55238. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  55239. outputChanLabel->attachToComponent (outputChanList, true);
  55240. }
  55241. outputChanList->refresh();
  55242. }
  55243. else
  55244. {
  55245. deleteAndZero (outputChanLabel);
  55246. deleteAndZero (outputChanList);
  55247. }
  55248. if (setup.maxNumInputChannels > 0
  55249. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  55250. {
  55251. if (inputChanList == 0)
  55252. {
  55253. addAndMakeVisible (inputChanList
  55254. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  55255. TRANS ("(no audio input channels found)")));
  55256. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  55257. inputChanLabel->attachToComponent (inputChanList, true);
  55258. }
  55259. inputChanList->refresh();
  55260. }
  55261. else
  55262. {
  55263. deleteAndZero (inputChanLabel);
  55264. deleteAndZero (inputChanList);
  55265. }
  55266. // sample rate..
  55267. {
  55268. if (sampleRateDropDown == 0)
  55269. {
  55270. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  55271. sampleRateDropDown->addListener (this);
  55272. delete sampleRateLabel;
  55273. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  55274. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  55275. }
  55276. else
  55277. {
  55278. sampleRateDropDown->clear();
  55279. sampleRateDropDown->removeListener (this);
  55280. }
  55281. const int numRates = currentDevice->getNumSampleRates();
  55282. for (int i = 0; i < numRates; ++i)
  55283. {
  55284. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  55285. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  55286. }
  55287. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  55288. sampleRateDropDown->addListener (this);
  55289. }
  55290. // buffer size
  55291. {
  55292. if (bufferSizeDropDown == 0)
  55293. {
  55294. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  55295. bufferSizeDropDown->addListener (this);
  55296. delete bufferSizeLabel;
  55297. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  55298. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  55299. }
  55300. else
  55301. {
  55302. bufferSizeDropDown->clear();
  55303. }
  55304. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  55305. double currentRate = currentDevice->getCurrentSampleRate();
  55306. if (currentRate == 0)
  55307. currentRate = 48000.0;
  55308. for (int i = 0; i < numBufferSizes; ++i)
  55309. {
  55310. const int bs = currentDevice->getBufferSizeSamples (i);
  55311. bufferSizeDropDown->addItem (String (bs)
  55312. + T(" samples (")
  55313. + String (bs * 1000.0 / currentRate, 1)
  55314. + T(" ms)"),
  55315. bs);
  55316. }
  55317. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  55318. }
  55319. }
  55320. else
  55321. {
  55322. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  55323. deleteAndZero (sampleRateLabel);
  55324. deleteAndZero (bufferSizeLabel);
  55325. deleteAndZero (sampleRateDropDown);
  55326. deleteAndZero (bufferSizeDropDown);
  55327. if (outputDeviceDropDown != 0)
  55328. outputDeviceDropDown->setSelectedId (-1, true);
  55329. if (inputDeviceDropDown != 0)
  55330. inputDeviceDropDown->setSelectedId (-1, true);
  55331. }
  55332. resized();
  55333. setSize (getWidth(), getLowestY() + 4);
  55334. }
  55335. private:
  55336. AudioIODeviceType* const type;
  55337. const AudioIODeviceType::DeviceSetupDetails setup;
  55338. ComboBox* outputDeviceDropDown;
  55339. ComboBox* inputDeviceDropDown;
  55340. ComboBox* sampleRateDropDown;
  55341. ComboBox* bufferSizeDropDown;
  55342. Label* outputDeviceLabel;
  55343. Label* inputDeviceLabel;
  55344. Label* sampleRateLabel;
  55345. Label* bufferSizeLabel;
  55346. Label* inputChanLabel;
  55347. Label* outputChanLabel;
  55348. TextButton* testButton;
  55349. Component* inputLevelMeter;
  55350. TextButton* showUIButton;
  55351. TextButton* showAdvancedSettingsButton;
  55352. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  55353. {
  55354. if (box != 0)
  55355. {
  55356. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  55357. const int index = type->getIndexOfDevice (currentDevice, isInput);
  55358. box->setSelectedId (index + 1, true);
  55359. if (testButton != 0 && ! isInput)
  55360. testButton->setEnabled (index >= 0);
  55361. }
  55362. }
  55363. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  55364. {
  55365. const StringArray devs (type->getDeviceNames (isInputs));
  55366. combo.clear (true);
  55367. for (int i = 0; i < devs.size(); ++i)
  55368. combo.addItem (devs[i], i + 1);
  55369. combo.addItem (TRANS("<< none >>"), -1);
  55370. combo.setSelectedId (-1, true);
  55371. }
  55372. int getLowestY() const
  55373. {
  55374. int y = 0;
  55375. for (int i = getNumChildComponents(); --i >= 0;)
  55376. y = jmax (y, getChildComponent (i)->getBottom());
  55377. return y;
  55378. }
  55379. class ChannelSelectorListBox : public ListBox,
  55380. public ListBoxModel
  55381. {
  55382. public:
  55383. enum BoxType
  55384. {
  55385. audioInputType,
  55386. audioOutputType
  55387. };
  55388. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  55389. const BoxType type_,
  55390. const String& noItemsMessage_)
  55391. : ListBox (String::empty, 0),
  55392. setup (setup_),
  55393. type (type_),
  55394. noItemsMessage (noItemsMessage_)
  55395. {
  55396. refresh();
  55397. setModel (this);
  55398. setOutlineThickness (1);
  55399. }
  55400. ~ChannelSelectorListBox()
  55401. {
  55402. }
  55403. void refresh()
  55404. {
  55405. items.clear();
  55406. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55407. if (currentDevice != 0)
  55408. {
  55409. if (type == audioInputType)
  55410. items = currentDevice->getInputChannelNames();
  55411. else if (type == audioOutputType)
  55412. items = currentDevice->getOutputChannelNames();
  55413. if (setup.useStereoPairs)
  55414. {
  55415. StringArray pairs;
  55416. for (int i = 0; i < items.size(); i += 2)
  55417. {
  55418. String name (items[i]);
  55419. String name2 (items[i + 1]);
  55420. String commonBit;
  55421. for (int j = 0; j < name.length(); ++j)
  55422. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  55423. commonBit = name.substring (0, j);
  55424. pairs.add (name.trim()
  55425. + " + "
  55426. + name2.substring (commonBit.length()).trim());
  55427. }
  55428. items = pairs;
  55429. }
  55430. }
  55431. updateContent();
  55432. repaint();
  55433. }
  55434. int getNumRows()
  55435. {
  55436. return items.size();
  55437. }
  55438. void paintListBoxItem (int row,
  55439. Graphics& g,
  55440. int width, int height,
  55441. bool rowIsSelected)
  55442. {
  55443. if (((unsigned int) row) < (unsigned int) items.size())
  55444. {
  55445. if (rowIsSelected)
  55446. g.fillAll (findColour (TextEditor::highlightColourId)
  55447. .withMultipliedAlpha (0.3f));
  55448. const String item (items [row]);
  55449. bool enabled = false;
  55450. AudioDeviceManager::AudioDeviceSetup config;
  55451. setup.manager->getAudioDeviceSetup (config);
  55452. if (setup.useStereoPairs)
  55453. {
  55454. if (type == audioInputType)
  55455. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  55456. else if (type == audioOutputType)
  55457. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  55458. }
  55459. else
  55460. {
  55461. if (type == audioInputType)
  55462. enabled = config.inputChannels [row];
  55463. else if (type == audioOutputType)
  55464. enabled = config.outputChannels [row];
  55465. }
  55466. const int x = getTickX();
  55467. const int tickW = height - height / 4;
  55468. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  55469. enabled, true, true, false);
  55470. g.setFont (height * 0.6f);
  55471. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  55472. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  55473. }
  55474. }
  55475. void listBoxItemClicked (int row, const MouseEvent& e)
  55476. {
  55477. selectRow (row);
  55478. if (e.x < getTickX())
  55479. flipEnablement (row);
  55480. }
  55481. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  55482. {
  55483. flipEnablement (row);
  55484. }
  55485. void returnKeyPressed (int row)
  55486. {
  55487. flipEnablement (row);
  55488. }
  55489. void paint (Graphics& g)
  55490. {
  55491. ListBox::paint (g);
  55492. if (items.size() == 0)
  55493. {
  55494. g.setColour (Colours::grey);
  55495. g.setFont (13.0f);
  55496. g.drawText (noItemsMessage,
  55497. 0, 0, getWidth(), getHeight() / 2,
  55498. Justification::centred, true);
  55499. }
  55500. }
  55501. int getBestHeight (int maxHeight)
  55502. {
  55503. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  55504. getNumRows())
  55505. + getOutlineThickness() * 2;
  55506. }
  55507. juce_UseDebuggingNewOperator
  55508. private:
  55509. const AudioIODeviceType::DeviceSetupDetails setup;
  55510. const BoxType type;
  55511. const String noItemsMessage;
  55512. StringArray items;
  55513. void flipEnablement (const int row)
  55514. {
  55515. jassert (type == audioInputType || type == audioOutputType);
  55516. if (((unsigned int) row) < (unsigned int) items.size())
  55517. {
  55518. AudioDeviceManager::AudioDeviceSetup config;
  55519. setup.manager->getAudioDeviceSetup (config);
  55520. if (setup.useStereoPairs)
  55521. {
  55522. BitArray bits;
  55523. BitArray& original = (type == audioInputType ? config.inputChannels
  55524. : config.outputChannels);
  55525. int i;
  55526. for (i = 0; i < 256; i += 2)
  55527. bits.setBit (i / 2, original [i] || original [i + 1]);
  55528. if (type == audioInputType)
  55529. {
  55530. config.useDefaultInputChannels = false;
  55531. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  55532. }
  55533. else
  55534. {
  55535. config.useDefaultOutputChannels = false;
  55536. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  55537. }
  55538. for (i = 0; i < 256; ++i)
  55539. original.setBit (i, bits [i / 2]);
  55540. }
  55541. else
  55542. {
  55543. if (type == audioInputType)
  55544. {
  55545. config.useDefaultInputChannels = false;
  55546. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  55547. }
  55548. else
  55549. {
  55550. config.useDefaultOutputChannels = false;
  55551. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  55552. }
  55553. }
  55554. String error (setup.manager->setAudioDeviceSetup (config, true));
  55555. if (! error.isEmpty())
  55556. {
  55557. //xxx
  55558. }
  55559. }
  55560. }
  55561. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  55562. {
  55563. const int numActive = chans.countNumberOfSetBits();
  55564. if (chans [index])
  55565. {
  55566. if (numActive > minNumber)
  55567. chans.setBit (index, false);
  55568. }
  55569. else
  55570. {
  55571. if (numActive >= maxNumber)
  55572. {
  55573. const int firstActiveChan = chans.findNextSetBit();
  55574. chans.setBit (index > firstActiveChan
  55575. ? firstActiveChan : chans.getHighestBit(),
  55576. false);
  55577. }
  55578. chans.setBit (index, true);
  55579. }
  55580. }
  55581. int getTickX() const throw()
  55582. {
  55583. return getRowHeight() + 5;
  55584. }
  55585. ChannelSelectorListBox (const ChannelSelectorListBox&);
  55586. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  55587. };
  55588. ChannelSelectorListBox* inputChanList;
  55589. ChannelSelectorListBox* outputChanList;
  55590. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  55591. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  55592. };
  55593. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  55594. const int minInputChannels_,
  55595. const int maxInputChannels_,
  55596. const int minOutputChannels_,
  55597. const int maxOutputChannels_,
  55598. const bool showMidiInputOptions,
  55599. const bool showMidiOutputSelector,
  55600. const bool showChannelsAsStereoPairs_,
  55601. const bool hideAdvancedOptionsWithButton_)
  55602. : deviceManager (deviceManager_),
  55603. deviceTypeDropDown (0),
  55604. deviceTypeDropDownLabel (0),
  55605. audioDeviceSettingsComp (0),
  55606. minOutputChannels (minOutputChannels_),
  55607. maxOutputChannels (maxOutputChannels_),
  55608. minInputChannels (minInputChannels_),
  55609. maxInputChannels (maxInputChannels_),
  55610. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  55611. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  55612. {
  55613. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  55614. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  55615. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  55616. {
  55617. deviceTypeDropDown = new ComboBox (String::empty);
  55618. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  55619. {
  55620. deviceTypeDropDown
  55621. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  55622. i + 1);
  55623. }
  55624. addAndMakeVisible (deviceTypeDropDown);
  55625. deviceTypeDropDown->addListener (this);
  55626. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  55627. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  55628. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  55629. }
  55630. if (showMidiInputOptions)
  55631. {
  55632. addAndMakeVisible (midiInputsList
  55633. = new MidiInputSelectorComponentListBox (deviceManager,
  55634. TRANS("(no midi inputs available)"),
  55635. 0, 0));
  55636. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  55637. midiInputsLabel->setJustificationType (Justification::topRight);
  55638. midiInputsLabel->attachToComponent (midiInputsList, true);
  55639. }
  55640. else
  55641. {
  55642. midiInputsList = 0;
  55643. midiInputsLabel = 0;
  55644. }
  55645. if (showMidiOutputSelector)
  55646. {
  55647. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  55648. midiOutputSelector->addListener (this);
  55649. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  55650. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  55651. }
  55652. else
  55653. {
  55654. midiOutputSelector = 0;
  55655. midiOutputLabel = 0;
  55656. }
  55657. deviceManager_.addChangeListener (this);
  55658. changeListenerCallback (0);
  55659. }
  55660. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  55661. {
  55662. deviceManager.removeChangeListener (this);
  55663. deleteAllChildren();
  55664. }
  55665. void AudioDeviceSelectorComponent::resized()
  55666. {
  55667. const int lx = proportionOfWidth (0.35f);
  55668. const int w = proportionOfWidth (0.4f);
  55669. const int h = 24;
  55670. const int space = 6;
  55671. const int dh = h + space;
  55672. int y = 15;
  55673. if (deviceTypeDropDown != 0)
  55674. {
  55675. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  55676. y += dh + space * 2;
  55677. }
  55678. if (audioDeviceSettingsComp != 0)
  55679. {
  55680. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  55681. y += audioDeviceSettingsComp->getHeight() + space;
  55682. }
  55683. if (midiInputsList != 0)
  55684. {
  55685. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  55686. midiInputsList->setBounds (lx, y, w, bh);
  55687. y += bh + space;
  55688. }
  55689. if (midiOutputSelector != 0)
  55690. midiOutputSelector->setBounds (lx, y, w, h);
  55691. }
  55692. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  55693. {
  55694. if (child == audioDeviceSettingsComp)
  55695. resized();
  55696. }
  55697. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  55698. {
  55699. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  55700. if (device != 0 && device->hasControlPanel())
  55701. {
  55702. if (device->showControlPanel())
  55703. deviceManager.restartLastAudioDevice();
  55704. getTopLevelComponent()->toFront (true);
  55705. }
  55706. }
  55707. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55708. {
  55709. if (comboBoxThatHasChanged == deviceTypeDropDown)
  55710. {
  55711. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  55712. if (type != 0)
  55713. {
  55714. deleteAndZero (audioDeviceSettingsComp);
  55715. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  55716. changeListenerCallback (0); // needed in case the type hasn't actally changed
  55717. }
  55718. }
  55719. else if (comboBoxThatHasChanged == midiOutputSelector)
  55720. {
  55721. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  55722. }
  55723. }
  55724. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  55725. {
  55726. if (deviceTypeDropDown != 0)
  55727. {
  55728. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  55729. }
  55730. if (audioDeviceSettingsComp == 0
  55731. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  55732. {
  55733. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  55734. deleteAndZero (audioDeviceSettingsComp);
  55735. AudioIODeviceType* const type
  55736. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  55737. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  55738. if (type != 0)
  55739. {
  55740. AudioIODeviceType::DeviceSetupDetails details;
  55741. details.manager = &deviceManager;
  55742. details.minNumInputChannels = minInputChannels;
  55743. details.maxNumInputChannels = maxInputChannels;
  55744. details.minNumOutputChannels = minOutputChannels;
  55745. details.maxNumOutputChannels = maxOutputChannels;
  55746. details.useStereoPairs = showChannelsAsStereoPairs;
  55747. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  55748. if (audioDeviceSettingsComp != 0)
  55749. {
  55750. addAndMakeVisible (audioDeviceSettingsComp);
  55751. audioDeviceSettingsComp->resized();
  55752. }
  55753. }
  55754. }
  55755. if (midiInputsList != 0)
  55756. {
  55757. midiInputsList->updateContent();
  55758. midiInputsList->repaint();
  55759. }
  55760. if (midiOutputSelector != 0)
  55761. {
  55762. midiOutputSelector->clear();
  55763. const StringArray midiOuts (MidiOutput::getDevices());
  55764. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  55765. midiOutputSelector->addSeparator();
  55766. for (int i = 0; i < midiOuts.size(); ++i)
  55767. midiOutputSelector->addItem (midiOuts[i], i + 1);
  55768. int current = -1;
  55769. if (deviceManager.getDefaultMidiOutput() != 0)
  55770. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  55771. midiOutputSelector->setSelectedId (current, true);
  55772. }
  55773. resized();
  55774. }
  55775. END_JUCE_NAMESPACE
  55776. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  55777. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  55778. BEGIN_JUCE_NAMESPACE
  55779. BubbleComponent::BubbleComponent()
  55780. : side (0),
  55781. allowablePlacements (above | below | left | right),
  55782. arrowTipX (0.0f),
  55783. arrowTipY (0.0f)
  55784. {
  55785. setInterceptsMouseClicks (false, false);
  55786. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  55787. setComponentEffect (&shadow);
  55788. }
  55789. BubbleComponent::~BubbleComponent()
  55790. {
  55791. }
  55792. void BubbleComponent::paint (Graphics& g)
  55793. {
  55794. int x = content.getX();
  55795. int y = content.getY();
  55796. int w = content.getWidth();
  55797. int h = content.getHeight();
  55798. int cw, ch;
  55799. getContentSize (cw, ch);
  55800. if (side == 3)
  55801. x += w - cw;
  55802. else if (side != 1)
  55803. x += (w - cw) / 2;
  55804. w = cw;
  55805. if (side == 2)
  55806. y += h - ch;
  55807. else if (side != 0)
  55808. y += (h - ch) / 2;
  55809. h = ch;
  55810. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  55811. (float) x, (float) y,
  55812. (float) w, (float) h);
  55813. const int cx = x + (w - cw) / 2;
  55814. const int cy = y + (h - ch) / 2;
  55815. const int indent = 3;
  55816. g.setOrigin (cx + indent, cy + indent);
  55817. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  55818. paintContent (g, cw - indent * 2, ch - indent * 2);
  55819. }
  55820. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  55821. {
  55822. allowablePlacements = newPlacement;
  55823. }
  55824. void BubbleComponent::setPosition (Component* componentToPointTo)
  55825. {
  55826. jassert (componentToPointTo->isValidComponent());
  55827. int tx = 0;
  55828. int ty = 0;
  55829. if (getParentComponent() != 0)
  55830. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  55831. else
  55832. componentToPointTo->relativePositionToGlobal (tx, ty);
  55833. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  55834. }
  55835. void BubbleComponent::setPosition (const int arrowTipX,
  55836. const int arrowTipY)
  55837. {
  55838. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  55839. }
  55840. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  55841. {
  55842. Rectangle availableSpace;
  55843. if (getParentComponent() != 0)
  55844. {
  55845. availableSpace.setSize (getParentComponent()->getWidth(),
  55846. getParentComponent()->getHeight());
  55847. }
  55848. else
  55849. {
  55850. availableSpace = getParentMonitorArea();
  55851. }
  55852. int x = 0;
  55853. int y = 0;
  55854. int w = 150;
  55855. int h = 30;
  55856. getContentSize (w, h);
  55857. w += 30;
  55858. h += 30;
  55859. const float edgeIndent = 2.0f;
  55860. const int arrowLength = jmin (10, h / 3, w / 3);
  55861. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  55862. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  55863. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  55864. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  55865. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  55866. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  55867. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  55868. {
  55869. spaceLeft = spaceRight = 0;
  55870. }
  55871. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  55872. && (spaceLeft > w + 20 || spaceRight > w + 20))
  55873. {
  55874. spaceAbove = spaceBelow = 0;
  55875. }
  55876. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  55877. {
  55878. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  55879. arrowTipX = w * 0.5f;
  55880. content.setSize (w, h - arrowLength);
  55881. if (spaceAbove >= spaceBelow)
  55882. {
  55883. // above
  55884. y = rectangleToPointTo.getY() - h;
  55885. content.setPosition (0, 0);
  55886. arrowTipY = h - edgeIndent;
  55887. side = 2;
  55888. }
  55889. else
  55890. {
  55891. // below
  55892. y = rectangleToPointTo.getBottom();
  55893. content.setPosition (0, arrowLength);
  55894. arrowTipY = edgeIndent;
  55895. side = 0;
  55896. }
  55897. }
  55898. else
  55899. {
  55900. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  55901. arrowTipY = h * 0.5f;
  55902. content.setSize (w - arrowLength, h);
  55903. if (spaceLeft > spaceRight)
  55904. {
  55905. // on the left
  55906. x = rectangleToPointTo.getX() - w;
  55907. content.setPosition (0, 0);
  55908. arrowTipX = w - edgeIndent;
  55909. side = 3;
  55910. }
  55911. else
  55912. {
  55913. // on the right
  55914. x = rectangleToPointTo.getRight();
  55915. content.setPosition (arrowLength, 0);
  55916. arrowTipX = edgeIndent;
  55917. side = 1;
  55918. }
  55919. }
  55920. setBounds (x, y, w, h);
  55921. }
  55922. END_JUCE_NAMESPACE
  55923. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  55924. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  55925. BEGIN_JUCE_NAMESPACE
  55926. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  55927. : fadeOutLength (fadeOutLengthMs),
  55928. deleteAfterUse (false)
  55929. {
  55930. }
  55931. BubbleMessageComponent::~BubbleMessageComponent()
  55932. {
  55933. fadeOutComponent (fadeOutLength);
  55934. }
  55935. void BubbleMessageComponent::showAt (int x, int y,
  55936. const String& text,
  55937. const int numMillisecondsBeforeRemoving,
  55938. const bool removeWhenMouseClicked,
  55939. const bool deleteSelfAfterUse)
  55940. {
  55941. textLayout.clear();
  55942. textLayout.setText (text, Font (14.0f));
  55943. textLayout.layout (256, Justification::centredLeft, true);
  55944. setPosition (x, y);
  55945. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55946. }
  55947. void BubbleMessageComponent::showAt (Component* const component,
  55948. const String& text,
  55949. const int numMillisecondsBeforeRemoving,
  55950. const bool removeWhenMouseClicked,
  55951. const bool deleteSelfAfterUse)
  55952. {
  55953. textLayout.clear();
  55954. textLayout.setText (text, Font (14.0f));
  55955. textLayout.layout (256, Justification::centredLeft, true);
  55956. setPosition (component);
  55957. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55958. }
  55959. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  55960. const bool removeWhenMouseClicked,
  55961. const bool deleteSelfAfterUse)
  55962. {
  55963. setVisible (true);
  55964. deleteAfterUse = deleteSelfAfterUse;
  55965. if (numMillisecondsBeforeRemoving > 0)
  55966. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  55967. else
  55968. expiryTime = 0;
  55969. startTimer (77);
  55970. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  55971. if (! (removeWhenMouseClicked && isShowing()))
  55972. mouseClickCounter += 0xfffff;
  55973. repaint();
  55974. }
  55975. void BubbleMessageComponent::getContentSize (int& w, int& h)
  55976. {
  55977. w = textLayout.getWidth() + 16;
  55978. h = textLayout.getHeight() + 16;
  55979. }
  55980. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  55981. {
  55982. g.setColour (findColour (TooltipWindow::textColourId));
  55983. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  55984. }
  55985. void BubbleMessageComponent::timerCallback()
  55986. {
  55987. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  55988. {
  55989. stopTimer();
  55990. setVisible (false);
  55991. if (deleteAfterUse)
  55992. delete this;
  55993. }
  55994. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  55995. {
  55996. stopTimer();
  55997. fadeOutComponent (fadeOutLength);
  55998. if (deleteAfterUse)
  55999. delete this;
  56000. }
  56001. }
  56002. END_JUCE_NAMESPACE
  56003. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  56004. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  56005. BEGIN_JUCE_NAMESPACE
  56006. static const int swatchesPerRow = 8;
  56007. static const int swatchHeight = 22;
  56008. class ColourComponentSlider : public Slider
  56009. {
  56010. public:
  56011. ColourComponentSlider (const String& name)
  56012. : Slider (name)
  56013. {
  56014. setRange (0.0, 255.0, 1.0);
  56015. }
  56016. ~ColourComponentSlider()
  56017. {
  56018. }
  56019. const String getTextFromValue (double currentValue)
  56020. {
  56021. return String::formatted (T("%02X"), (int)currentValue);
  56022. }
  56023. double getValueFromText (const String& text)
  56024. {
  56025. return (double) text.getHexValue32();
  56026. }
  56027. private:
  56028. ColourComponentSlider (const ColourComponentSlider&);
  56029. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  56030. };
  56031. class ColourSpaceMarker : public Component
  56032. {
  56033. public:
  56034. ColourSpaceMarker()
  56035. {
  56036. setInterceptsMouseClicks (false, false);
  56037. }
  56038. ~ColourSpaceMarker()
  56039. {
  56040. }
  56041. void paint (Graphics& g)
  56042. {
  56043. g.setColour (Colour::greyLevel (0.1f));
  56044. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  56045. g.setColour (Colour::greyLevel (0.9f));
  56046. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  56047. }
  56048. private:
  56049. ColourSpaceMarker (const ColourSpaceMarker&);
  56050. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  56051. };
  56052. class ColourSpaceView : public Component
  56053. {
  56054. ColourSelector* const owner;
  56055. float& h;
  56056. float& s;
  56057. float& v;
  56058. float lastHue;
  56059. ColourSpaceMarker* marker;
  56060. const int edge;
  56061. public:
  56062. ColourSpaceView (ColourSelector* owner_,
  56063. float& h_, float& s_, float& v_,
  56064. const int edgeSize)
  56065. : owner (owner_),
  56066. h (h_), s (s_), v (v_),
  56067. lastHue (0.0f),
  56068. edge (edgeSize)
  56069. {
  56070. addAndMakeVisible (marker = new ColourSpaceMarker());
  56071. setMouseCursor (MouseCursor::CrosshairCursor);
  56072. }
  56073. ~ColourSpaceView()
  56074. {
  56075. deleteAllChildren();
  56076. }
  56077. void paint (Graphics& g)
  56078. {
  56079. const float hue = h;
  56080. const float xScale = 1.0f / (getWidth() - edge * 2);
  56081. const float yScale = 1.0f / (getHeight() - edge * 2);
  56082. const Rectangle clip (g.getClipBounds());
  56083. const int x1 = jmax (clip.getX(), edge) & ~1;
  56084. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  56085. const int y1 = jmax (clip.getY(), edge) & ~1;
  56086. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  56087. for (int y = y1; y < y2; y += 2)
  56088. {
  56089. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  56090. for (int x = x1; x < x2; x += 2)
  56091. {
  56092. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  56093. g.setColour (Colour (hue, s, v, 1.0f));
  56094. g.fillRect (x, y, 2, 2);
  56095. }
  56096. }
  56097. }
  56098. void mouseDown (const MouseEvent& e)
  56099. {
  56100. mouseDrag (e);
  56101. }
  56102. void mouseDrag (const MouseEvent& e)
  56103. {
  56104. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  56105. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  56106. owner->setSV (s, v);
  56107. }
  56108. void updateIfNeeded()
  56109. {
  56110. if (lastHue != h)
  56111. {
  56112. lastHue = h;
  56113. repaint();
  56114. }
  56115. resized();
  56116. }
  56117. void resized()
  56118. {
  56119. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  56120. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  56121. edge * 2, edge * 2);
  56122. }
  56123. private:
  56124. ColourSpaceView (const ColourSpaceView&);
  56125. const ColourSpaceView& operator= (const ColourSpaceView&);
  56126. };
  56127. class HueSelectorMarker : public Component
  56128. {
  56129. public:
  56130. HueSelectorMarker()
  56131. {
  56132. setInterceptsMouseClicks (false, false);
  56133. }
  56134. ~HueSelectorMarker()
  56135. {
  56136. }
  56137. void paint (Graphics& g)
  56138. {
  56139. Path p;
  56140. p.addTriangle (1.0f, 1.0f,
  56141. getWidth() * 0.3f, getHeight() * 0.5f,
  56142. 1.0f, getHeight() - 1.0f);
  56143. p.addTriangle (getWidth() - 1.0f, 1.0f,
  56144. getWidth() * 0.7f, getHeight() * 0.5f,
  56145. getWidth() - 1.0f, getHeight() - 1.0f);
  56146. g.setColour (Colours::white.withAlpha (0.75f));
  56147. g.fillPath (p);
  56148. g.setColour (Colours::black.withAlpha (0.75f));
  56149. g.strokePath (p, PathStrokeType (1.2f));
  56150. }
  56151. private:
  56152. HueSelectorMarker (const HueSelectorMarker&);
  56153. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  56154. };
  56155. class HueSelectorComp : public Component
  56156. {
  56157. public:
  56158. HueSelectorComp (ColourSelector* owner_,
  56159. float& h_, float& s_, float& v_,
  56160. const int edgeSize)
  56161. : owner (owner_),
  56162. h (h_), s (s_), v (v_),
  56163. lastHue (0.0f),
  56164. edge (edgeSize)
  56165. {
  56166. addAndMakeVisible (marker = new HueSelectorMarker());
  56167. }
  56168. ~HueSelectorComp()
  56169. {
  56170. deleteAllChildren();
  56171. }
  56172. void paint (Graphics& g)
  56173. {
  56174. const float yScale = 1.0f / (getHeight() - edge * 2);
  56175. const Rectangle clip (g.getClipBounds());
  56176. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  56177. {
  56178. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  56179. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  56180. }
  56181. }
  56182. void resized()
  56183. {
  56184. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  56185. getWidth(), edge * 2);
  56186. }
  56187. void mouseDown (const MouseEvent& e)
  56188. {
  56189. mouseDrag (e);
  56190. }
  56191. void mouseDrag (const MouseEvent& e)
  56192. {
  56193. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  56194. owner->setHue (hue);
  56195. }
  56196. void updateIfNeeded()
  56197. {
  56198. resized();
  56199. }
  56200. private:
  56201. ColourSelector* const owner;
  56202. float& h;
  56203. float& s;
  56204. float& v;
  56205. float lastHue;
  56206. HueSelectorMarker* marker;
  56207. const int edge;
  56208. HueSelectorComp (const HueSelectorComp&);
  56209. const HueSelectorComp& operator= (const HueSelectorComp&);
  56210. };
  56211. class SwatchComponent : public Component
  56212. {
  56213. public:
  56214. SwatchComponent (ColourSelector* owner_, int index_)
  56215. : owner (owner_),
  56216. index (index_)
  56217. {
  56218. }
  56219. ~SwatchComponent()
  56220. {
  56221. }
  56222. void paint (Graphics& g)
  56223. {
  56224. const Colour colour (owner->getSwatchColour (index));
  56225. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  56226. 6, 6,
  56227. Colour (0xffdddddd).overlaidWith (colour),
  56228. Colour (0xffffffff).overlaidWith (colour));
  56229. }
  56230. void mouseDown (const MouseEvent&)
  56231. {
  56232. PopupMenu m;
  56233. m.addItem (1, TRANS("Use this swatch as the current colour"));
  56234. m.addSeparator();
  56235. m.addItem (2, TRANS("Set this swatch to the current colour"));
  56236. const int r = m.showAt (this);
  56237. if (r == 1)
  56238. {
  56239. owner->setCurrentColour (owner->getSwatchColour (index));
  56240. }
  56241. else if (r == 2)
  56242. {
  56243. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  56244. {
  56245. owner->setSwatchColour (index, owner->getCurrentColour());
  56246. repaint();
  56247. }
  56248. }
  56249. }
  56250. private:
  56251. ColourSelector* const owner;
  56252. const int index;
  56253. SwatchComponent (const SwatchComponent&);
  56254. const SwatchComponent& operator= (const SwatchComponent&);
  56255. };
  56256. ColourSelector::ColourSelector (const int flags_,
  56257. const int edgeGap_,
  56258. const int gapAroundColourSpaceComponent)
  56259. : colour (Colours::white),
  56260. flags (flags_),
  56261. topSpace (0),
  56262. edgeGap (edgeGap_)
  56263. {
  56264. // not much point having a selector with no components in it!
  56265. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  56266. updateHSV();
  56267. if ((flags & showSliders) != 0)
  56268. {
  56269. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  56270. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  56271. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  56272. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  56273. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  56274. for (int i = 4; --i >= 0;)
  56275. sliders[i]->addListener (this);
  56276. }
  56277. else
  56278. {
  56279. zeromem (sliders, sizeof (sliders));
  56280. }
  56281. if ((flags & showColourspace) != 0)
  56282. {
  56283. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  56284. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  56285. }
  56286. else
  56287. {
  56288. colourSpace = 0;
  56289. hueSelector = 0;
  56290. }
  56291. update();
  56292. }
  56293. ColourSelector::~ColourSelector()
  56294. {
  56295. dispatchPendingMessages();
  56296. deleteAllChildren();
  56297. }
  56298. const Colour ColourSelector::getCurrentColour() const
  56299. {
  56300. return ((flags & showAlphaChannel) != 0) ? colour
  56301. : colour.withAlpha ((uint8) 0xff);
  56302. }
  56303. void ColourSelector::setCurrentColour (const Colour& c)
  56304. {
  56305. if (c != colour)
  56306. {
  56307. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  56308. updateHSV();
  56309. update();
  56310. }
  56311. }
  56312. void ColourSelector::setHue (float newH)
  56313. {
  56314. newH = jlimit (0.0f, 1.0f, newH);
  56315. if (h != newH)
  56316. {
  56317. h = newH;
  56318. colour = Colour (h, s, v, colour.getFloatAlpha());
  56319. update();
  56320. }
  56321. }
  56322. void ColourSelector::setSV (float newS, float newV)
  56323. {
  56324. newS = jlimit (0.0f, 1.0f, newS);
  56325. newV = jlimit (0.0f, 1.0f, newV);
  56326. if (s != newS || v != newV)
  56327. {
  56328. s = newS;
  56329. v = newV;
  56330. colour = Colour (h, s, v, colour.getFloatAlpha());
  56331. update();
  56332. }
  56333. }
  56334. void ColourSelector::updateHSV()
  56335. {
  56336. colour.getHSB (h, s, v);
  56337. }
  56338. void ColourSelector::update()
  56339. {
  56340. if (sliders[0] != 0)
  56341. {
  56342. sliders[0]->setValue ((int) colour.getRed());
  56343. sliders[1]->setValue ((int) colour.getGreen());
  56344. sliders[2]->setValue ((int) colour.getBlue());
  56345. sliders[3]->setValue ((int) colour.getAlpha());
  56346. }
  56347. if (colourSpace != 0)
  56348. {
  56349. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  56350. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  56351. }
  56352. if ((flags & showColourAtTop) != 0)
  56353. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  56354. sendChangeMessage (this);
  56355. }
  56356. void ColourSelector::paint (Graphics& g)
  56357. {
  56358. g.fillAll (findColour (backgroundColourId));
  56359. if ((flags & showColourAtTop) != 0)
  56360. {
  56361. const Colour colour (getCurrentColour());
  56362. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  56363. 10, 10,
  56364. Colour (0xffdddddd).overlaidWith (colour),
  56365. Colour (0xffffffff).overlaidWith (colour));
  56366. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  56367. g.setFont (14.0f, true);
  56368. g.drawText (((flags & showAlphaChannel) != 0)
  56369. ? String::formatted (T("#%02X%02X%02X%02X"),
  56370. (int) colour.getAlpha(),
  56371. (int) colour.getRed(),
  56372. (int) colour.getGreen(),
  56373. (int) colour.getBlue())
  56374. : String::formatted (T("#%02X%02X%02X"),
  56375. (int) colour.getRed(),
  56376. (int) colour.getGreen(),
  56377. (int) colour.getBlue()),
  56378. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  56379. Justification::centred, false);
  56380. }
  56381. if ((flags & showSliders) != 0)
  56382. {
  56383. g.setColour (findColour (labelTextColourId));
  56384. g.setFont (11.0f);
  56385. for (int i = 4; --i >= 0;)
  56386. {
  56387. if (sliders[i]->isVisible())
  56388. g.drawText (sliders[i]->getName() + T(":"),
  56389. 0, sliders[i]->getY(),
  56390. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  56391. Justification::centredRight, false);
  56392. }
  56393. }
  56394. }
  56395. void ColourSelector::resized()
  56396. {
  56397. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  56398. const int numSwatches = getNumSwatches();
  56399. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  56400. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  56401. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  56402. int y = topSpace;
  56403. if ((flags & showColourspace) != 0)
  56404. {
  56405. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  56406. colourSpace->setBounds (edgeGap, y,
  56407. getWidth() - hueWidth - edgeGap - 4,
  56408. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  56409. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  56410. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  56411. colourSpace->getHeight());
  56412. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  56413. }
  56414. if ((flags & showSliders) != 0)
  56415. {
  56416. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  56417. for (int i = 0; i < numSliders; ++i)
  56418. {
  56419. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  56420. proportionOfWidth (0.72f), sliderHeight - 2);
  56421. y += sliderHeight;
  56422. }
  56423. }
  56424. if (numSwatches > 0)
  56425. {
  56426. const int startX = 8;
  56427. const int xGap = 4;
  56428. const int yGap = 4;
  56429. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  56430. y += edgeGap;
  56431. if (swatchComponents.size() != numSwatches)
  56432. {
  56433. int i;
  56434. for (i = swatchComponents.size(); --i >= 0;)
  56435. {
  56436. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56437. delete sc;
  56438. }
  56439. for (i = 0; i < numSwatches; ++i)
  56440. {
  56441. SwatchComponent* const sc = new SwatchComponent (this, i);
  56442. swatchComponents.add (sc);
  56443. addAndMakeVisible (sc);
  56444. }
  56445. }
  56446. int x = startX;
  56447. for (int i = 0; i < swatchComponents.size(); ++i)
  56448. {
  56449. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56450. sc->setBounds (x + xGap / 2,
  56451. y + yGap / 2,
  56452. swatchWidth - xGap,
  56453. swatchHeight - yGap);
  56454. if (((i + 1) % swatchesPerRow) == 0)
  56455. {
  56456. x = startX;
  56457. y += swatchHeight;
  56458. }
  56459. else
  56460. {
  56461. x += swatchWidth;
  56462. }
  56463. }
  56464. }
  56465. }
  56466. void ColourSelector::sliderValueChanged (Slider*)
  56467. {
  56468. if (sliders[0] != 0)
  56469. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  56470. (uint8) sliders[1]->getValue(),
  56471. (uint8) sliders[2]->getValue(),
  56472. (uint8) sliders[3]->getValue()));
  56473. }
  56474. int ColourSelector::getNumSwatches() const
  56475. {
  56476. return 0;
  56477. }
  56478. const Colour ColourSelector::getSwatchColour (const int) const
  56479. {
  56480. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56481. return Colours::black;
  56482. }
  56483. void ColourSelector::setSwatchColour (const int, const Colour&) const
  56484. {
  56485. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56486. }
  56487. END_JUCE_NAMESPACE
  56488. /********* End of inlined file: juce_ColourSelector.cpp *********/
  56489. /********* Start of inlined file: juce_DropShadower.cpp *********/
  56490. BEGIN_JUCE_NAMESPACE
  56491. class ShadowWindow : public Component
  56492. {
  56493. Component* owner;
  56494. Image** shadowImageSections;
  56495. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  56496. public:
  56497. ShadowWindow (Component* const owner_,
  56498. const int type_,
  56499. Image** const shadowImageSections_)
  56500. : owner (owner_),
  56501. shadowImageSections (shadowImageSections_),
  56502. type (type_)
  56503. {
  56504. setInterceptsMouseClicks (false, false);
  56505. if (owner_->isOnDesktop())
  56506. {
  56507. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  56508. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56509. | ComponentPeer::windowIsTemporary
  56510. | ComponentPeer::windowIgnoresKeyPresses);
  56511. }
  56512. else if (owner_->getParentComponent() != 0)
  56513. {
  56514. owner_->getParentComponent()->addChildComponent (this);
  56515. }
  56516. }
  56517. ~ShadowWindow()
  56518. {
  56519. }
  56520. void paint (Graphics& g)
  56521. {
  56522. Image* const topLeft = shadowImageSections [type * 3];
  56523. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  56524. Image* const filler = shadowImageSections [type * 3 + 2];
  56525. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  56526. g.setOpacity (1.0f);
  56527. if (type < 2)
  56528. {
  56529. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  56530. g.drawImage (topLeft,
  56531. 0, 0, topLeft->getWidth(), imH,
  56532. 0, 0, topLeft->getWidth(), imH);
  56533. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  56534. g.drawImage (bottomRight,
  56535. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  56536. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  56537. g.setBrush (&fillBrush);
  56538. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  56539. }
  56540. else
  56541. {
  56542. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  56543. g.drawImage (topLeft,
  56544. 0, 0, imW, topLeft->getHeight(),
  56545. 0, 0, imW, topLeft->getHeight());
  56546. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  56547. g.drawImage (bottomRight,
  56548. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  56549. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  56550. g.setBrush (&fillBrush);
  56551. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  56552. }
  56553. }
  56554. void resized()
  56555. {
  56556. repaint(); // (needed for correct repainting)
  56557. }
  56558. private:
  56559. ShadowWindow (const ShadowWindow&);
  56560. const ShadowWindow& operator= (const ShadowWindow&);
  56561. };
  56562. DropShadower::DropShadower (const float alpha_,
  56563. const int xOffset_,
  56564. const int yOffset_,
  56565. const float blurRadius_)
  56566. : owner (0),
  56567. numShadows (0),
  56568. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  56569. xOffset (xOffset_),
  56570. yOffset (yOffset_),
  56571. alpha (alpha_),
  56572. blurRadius (blurRadius_),
  56573. inDestructor (false),
  56574. reentrant (false)
  56575. {
  56576. }
  56577. DropShadower::~DropShadower()
  56578. {
  56579. if (owner != 0)
  56580. owner->removeComponentListener (this);
  56581. inDestructor = true;
  56582. deleteShadowWindows();
  56583. }
  56584. void DropShadower::deleteShadowWindows()
  56585. {
  56586. if (numShadows > 0)
  56587. {
  56588. int i;
  56589. for (i = numShadows; --i >= 0;)
  56590. delete shadowWindows[i];
  56591. for (i = 12; --i >= 0;)
  56592. delete shadowImageSections[i];
  56593. numShadows = 0;
  56594. }
  56595. }
  56596. void DropShadower::setOwner (Component* componentToFollow)
  56597. {
  56598. if (componentToFollow != owner)
  56599. {
  56600. if (owner != 0)
  56601. owner->removeComponentListener (this);
  56602. // (the component can't be null)
  56603. jassert (componentToFollow != 0);
  56604. owner = componentToFollow;
  56605. jassert (owner != 0);
  56606. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  56607. owner->addComponentListener (this);
  56608. updateShadows();
  56609. }
  56610. }
  56611. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  56612. {
  56613. updateShadows();
  56614. }
  56615. void DropShadower::componentBroughtToFront (Component&)
  56616. {
  56617. bringShadowWindowsToFront();
  56618. }
  56619. void DropShadower::componentChildrenChanged (Component&)
  56620. {
  56621. }
  56622. void DropShadower::componentParentHierarchyChanged (Component&)
  56623. {
  56624. deleteShadowWindows();
  56625. updateShadows();
  56626. }
  56627. void DropShadower::componentVisibilityChanged (Component&)
  56628. {
  56629. updateShadows();
  56630. }
  56631. void DropShadower::updateShadows()
  56632. {
  56633. if (reentrant || inDestructor || (owner == 0))
  56634. return;
  56635. reentrant = true;
  56636. ComponentPeer* const nw = owner->getPeer();
  56637. const bool isOwnerVisible = owner->isVisible()
  56638. && (nw == 0 || ! nw->isMinimised());
  56639. const bool createShadowWindows = numShadows == 0
  56640. && owner->getWidth() > 0
  56641. && owner->getHeight() > 0
  56642. && isOwnerVisible
  56643. && (Desktop::canUseSemiTransparentWindows()
  56644. || owner->getParentComponent() != 0);
  56645. if (createShadowWindows)
  56646. {
  56647. // keep a cached version of the image to save doing the gaussian too often
  56648. String imageId;
  56649. imageId << shadowEdge << T(',')
  56650. << xOffset << T(',')
  56651. << yOffset << T(',')
  56652. << alpha;
  56653. const int hash = imageId.hashCode();
  56654. Image* bigIm = ImageCache::getFromHashCode (hash);
  56655. if (bigIm == 0)
  56656. {
  56657. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  56658. Graphics bigG (*bigIm);
  56659. bigG.setColour (Colours::black.withAlpha (alpha));
  56660. bigG.fillRect (shadowEdge + xOffset,
  56661. shadowEdge + yOffset,
  56662. bigIm->getWidth() - (shadowEdge * 2),
  56663. bigIm->getHeight() - (shadowEdge * 2));
  56664. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  56665. blurKernel.createGaussianBlur (blurRadius);
  56666. blurKernel.applyToImage (*bigIm, 0,
  56667. xOffset,
  56668. yOffset,
  56669. bigIm->getWidth(),
  56670. bigIm->getHeight());
  56671. ImageCache::addImageToCache (bigIm, hash);
  56672. }
  56673. const int iw = bigIm->getWidth();
  56674. const int ih = bigIm->getHeight();
  56675. const int shadowEdge2 = shadowEdge * 2;
  56676. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  56677. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  56678. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  56679. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  56680. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  56681. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  56682. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  56683. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  56684. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  56685. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  56686. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  56687. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  56688. ImageCache::release (bigIm);
  56689. for (int i = 0; i < 4; ++i)
  56690. {
  56691. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  56692. ++numShadows;
  56693. }
  56694. }
  56695. if (numShadows > 0)
  56696. {
  56697. for (int i = numShadows; --i >= 0;)
  56698. {
  56699. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  56700. shadowWindows[i]->setVisible (isOwnerVisible);
  56701. }
  56702. const int x = owner->getX();
  56703. const int y = owner->getY() - shadowEdge;
  56704. const int w = owner->getWidth();
  56705. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  56706. shadowWindows[0]->setBounds (x - shadowEdge,
  56707. y,
  56708. shadowEdge,
  56709. h);
  56710. shadowWindows[1]->setBounds (x + w,
  56711. y,
  56712. shadowEdge,
  56713. h);
  56714. shadowWindows[2]->setBounds (x,
  56715. y,
  56716. w,
  56717. shadowEdge);
  56718. shadowWindows[3]->setBounds (x,
  56719. owner->getBottom(),
  56720. w,
  56721. shadowEdge);
  56722. }
  56723. reentrant = false;
  56724. if (createShadowWindows)
  56725. bringShadowWindowsToFront();
  56726. }
  56727. void DropShadower::setShadowImage (Image* const src,
  56728. const int num,
  56729. const int w,
  56730. const int h,
  56731. const int sx,
  56732. const int sy) throw()
  56733. {
  56734. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  56735. Graphics g (*shadowImageSections[num]);
  56736. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  56737. }
  56738. void DropShadower::bringShadowWindowsToFront()
  56739. {
  56740. if (! (inDestructor || reentrant))
  56741. {
  56742. updateShadows();
  56743. reentrant = true;
  56744. for (int i = numShadows; --i >= 0;)
  56745. shadowWindows[i]->toBehind (owner);
  56746. reentrant = false;
  56747. }
  56748. }
  56749. END_JUCE_NAMESPACE
  56750. /********* End of inlined file: juce_DropShadower.cpp *********/
  56751. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  56752. BEGIN_JUCE_NAMESPACE
  56753. class MagnifyingPeer : public ComponentPeer
  56754. {
  56755. public:
  56756. MagnifyingPeer (Component* const component_,
  56757. MagnifierComponent* const magnifierComp_)
  56758. : ComponentPeer (component_, 0),
  56759. magnifierComp (magnifierComp_)
  56760. {
  56761. }
  56762. ~MagnifyingPeer()
  56763. {
  56764. }
  56765. void* getNativeHandle() const { return 0; }
  56766. void setVisible (bool) {}
  56767. void setTitle (const String&) {}
  56768. void setPosition (int, int) {}
  56769. void setSize (int, int) {}
  56770. void setBounds (int, int, int, int, const bool) {}
  56771. void setMinimised (bool) {}
  56772. bool isMinimised() const { return false; }
  56773. void setFullScreen (bool) {}
  56774. bool isFullScreen() const { return false; }
  56775. const BorderSize getFrameSize() const { return BorderSize (0); }
  56776. bool setAlwaysOnTop (bool) { return true; }
  56777. void toFront (bool) {}
  56778. void toBehind (ComponentPeer*) {}
  56779. void setIcon (const Image&) {}
  56780. bool isFocused() const
  56781. {
  56782. return magnifierComp->hasKeyboardFocus (true);
  56783. }
  56784. void grabFocus()
  56785. {
  56786. ComponentPeer* peer = magnifierComp->getPeer();
  56787. if (peer != 0)
  56788. peer->grabFocus();
  56789. }
  56790. void textInputRequired (int x, int y)
  56791. {
  56792. ComponentPeer* peer = magnifierComp->getPeer();
  56793. if (peer != 0)
  56794. peer->textInputRequired (x, y);
  56795. }
  56796. void getBounds (int& x, int& y, int& w, int& h) const
  56797. {
  56798. x = magnifierComp->getScreenX();
  56799. y = magnifierComp->getScreenY();
  56800. w = component->getWidth();
  56801. h = component->getHeight();
  56802. }
  56803. int getScreenX() const { return magnifierComp->getScreenX(); }
  56804. int getScreenY() const { return magnifierComp->getScreenY(); }
  56805. void relativePositionToGlobal (int& x, int& y)
  56806. {
  56807. const double zoom = magnifierComp->getScaleFactor();
  56808. x = roundDoubleToInt (x * zoom);
  56809. y = roundDoubleToInt (y * zoom);
  56810. magnifierComp->relativePositionToGlobal (x, y);
  56811. }
  56812. void globalPositionToRelative (int& x, int& y)
  56813. {
  56814. magnifierComp->globalPositionToRelative (x, y);
  56815. const double zoom = magnifierComp->getScaleFactor();
  56816. x = roundDoubleToInt (x / zoom);
  56817. y = roundDoubleToInt (y / zoom);
  56818. }
  56819. bool contains (int x, int y, bool) const
  56820. {
  56821. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  56822. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  56823. }
  56824. void repaint (int x, int y, int w, int h)
  56825. {
  56826. const double zoom = magnifierComp->getScaleFactor();
  56827. magnifierComp->repaint ((int) (x * zoom),
  56828. (int) (y * zoom),
  56829. roundDoubleToInt (w * zoom) + 1,
  56830. roundDoubleToInt (h * zoom) + 1);
  56831. }
  56832. void performAnyPendingRepaintsNow()
  56833. {
  56834. }
  56835. juce_UseDebuggingNewOperator
  56836. private:
  56837. MagnifierComponent* const magnifierComp;
  56838. MagnifyingPeer (const MagnifyingPeer&);
  56839. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  56840. };
  56841. class PeerHolderComp : public Component
  56842. {
  56843. public:
  56844. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  56845. : magnifierComp (magnifierComp_)
  56846. {
  56847. setVisible (true);
  56848. }
  56849. ~PeerHolderComp()
  56850. {
  56851. }
  56852. ComponentPeer* createNewPeer (int, void*)
  56853. {
  56854. return new MagnifyingPeer (this, magnifierComp);
  56855. }
  56856. void childBoundsChanged (Component* c)
  56857. {
  56858. if (c != 0)
  56859. {
  56860. setSize (c->getWidth(), c->getHeight());
  56861. magnifierComp->childBoundsChanged (this);
  56862. }
  56863. }
  56864. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56865. {
  56866. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  56867. Component* const p = magnifierComp->getParentComponent();
  56868. if (p != 0)
  56869. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  56870. }
  56871. private:
  56872. MagnifierComponent* const magnifierComp;
  56873. PeerHolderComp (const PeerHolderComp&);
  56874. const PeerHolderComp& operator= (const PeerHolderComp&);
  56875. };
  56876. MagnifierComponent::MagnifierComponent (Component* const content_,
  56877. const bool deleteContentCompWhenNoLongerNeeded)
  56878. : content (content_),
  56879. scaleFactor (0.0),
  56880. peer (0),
  56881. deleteContent (deleteContentCompWhenNoLongerNeeded),
  56882. quality (Graphics::lowResamplingQuality)
  56883. {
  56884. holderComp = new PeerHolderComp (this);
  56885. setScaleFactor (1.0);
  56886. }
  56887. MagnifierComponent::~MagnifierComponent()
  56888. {
  56889. delete holderComp;
  56890. if (deleteContent)
  56891. delete content;
  56892. }
  56893. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  56894. {
  56895. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  56896. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  56897. if (scaleFactor != newScaleFactor)
  56898. {
  56899. scaleFactor = newScaleFactor;
  56900. if (scaleFactor == 1.0)
  56901. {
  56902. holderComp->removeFromDesktop();
  56903. peer = 0;
  56904. addChildComponent (content);
  56905. childBoundsChanged (content);
  56906. }
  56907. else
  56908. {
  56909. holderComp->addAndMakeVisible (content);
  56910. holderComp->childBoundsChanged (content);
  56911. childBoundsChanged (holderComp);
  56912. holderComp->addToDesktop (0);
  56913. peer = holderComp->getPeer();
  56914. }
  56915. repaint();
  56916. }
  56917. }
  56918. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  56919. {
  56920. quality = newQuality;
  56921. }
  56922. void MagnifierComponent::paint (Graphics& g)
  56923. {
  56924. const int w = holderComp->getWidth();
  56925. const int h = holderComp->getHeight();
  56926. if (w == 0 || h == 0)
  56927. return;
  56928. const Rectangle r (g.getClipBounds());
  56929. const int srcX = (int) (r.getX() / scaleFactor);
  56930. const int srcY = (int) (r.getY() / scaleFactor);
  56931. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  56932. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  56933. if (scaleFactor >= 1.0)
  56934. {
  56935. ++srcW;
  56936. ++srcH;
  56937. }
  56938. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  56939. temp.clear (srcX, srcY, srcW, srcH);
  56940. Graphics g2 (temp);
  56941. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  56942. holderComp->paintEntireComponent (g2);
  56943. g.setImageResamplingQuality (quality);
  56944. g.drawImage (&temp,
  56945. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  56946. 0, 0, w, h,
  56947. false);
  56948. }
  56949. void MagnifierComponent::childBoundsChanged (Component* c)
  56950. {
  56951. if (c != 0)
  56952. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  56953. roundDoubleToInt (c->getHeight() * scaleFactor));
  56954. }
  56955. void MagnifierComponent::mouseDown (const MouseEvent& e)
  56956. {
  56957. if (peer != 0)
  56958. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56959. }
  56960. void MagnifierComponent::mouseUp (const MouseEvent& e)
  56961. {
  56962. if (peer != 0)
  56963. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56964. }
  56965. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  56966. {
  56967. if (peer != 0)
  56968. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56969. }
  56970. void MagnifierComponent::mouseMove (const MouseEvent& e)
  56971. {
  56972. if (peer != 0)
  56973. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56974. }
  56975. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  56976. {
  56977. if (peer != 0)
  56978. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56979. }
  56980. void MagnifierComponent::mouseExit (const MouseEvent& e)
  56981. {
  56982. if (peer != 0)
  56983. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56984. }
  56985. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56986. {
  56987. if (peer != 0)
  56988. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  56989. roundFloatToInt (iy * 256.0f),
  56990. e.eventTime.toMilliseconds());
  56991. else
  56992. Component::mouseWheelMove (e, ix, iy);
  56993. }
  56994. int MagnifierComponent::scaleInt (const int n) const throw()
  56995. {
  56996. return roundDoubleToInt (n / scaleFactor);
  56997. }
  56998. END_JUCE_NAMESPACE
  56999. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  57000. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  57001. BEGIN_JUCE_NAMESPACE
  57002. class MidiKeyboardUpDownButton : public Button
  57003. {
  57004. public:
  57005. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  57006. const int delta_)
  57007. : Button (String::empty),
  57008. owner (owner_),
  57009. delta (delta_)
  57010. {
  57011. setOpaque (true);
  57012. }
  57013. ~MidiKeyboardUpDownButton()
  57014. {
  57015. }
  57016. void clicked()
  57017. {
  57018. int note = owner->getLowestVisibleKey();
  57019. if (delta < 0)
  57020. note = (note - 1) / 12;
  57021. else
  57022. note = note / 12 + 1;
  57023. owner->setLowestVisibleKey (note * 12);
  57024. }
  57025. void paintButton (Graphics& g,
  57026. bool isMouseOverButton,
  57027. bool isButtonDown)
  57028. {
  57029. owner->drawUpDownButton (g, getWidth(), getHeight(),
  57030. isMouseOverButton, isButtonDown,
  57031. delta > 0);
  57032. }
  57033. private:
  57034. MidiKeyboardComponent* const owner;
  57035. const int delta;
  57036. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  57037. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  57038. };
  57039. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  57040. const Orientation orientation_)
  57041. : state (state_),
  57042. xOffset (0),
  57043. blackNoteLength (1),
  57044. keyWidth (16.0f),
  57045. orientation (orientation_),
  57046. midiChannel (1),
  57047. midiInChannelMask (0xffff),
  57048. velocity (1.0f),
  57049. noteUnderMouse (-1),
  57050. mouseDownNote (-1),
  57051. rangeStart (0),
  57052. rangeEnd (127),
  57053. firstKey (12 * 4),
  57054. canScroll (true),
  57055. mouseDragging (false),
  57056. keyPresses (4),
  57057. keyPressNotes (16),
  57058. keyMappingOctave (6),
  57059. octaveNumForMiddleC (3)
  57060. {
  57061. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  57062. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  57063. // initialise with a default set of querty key-mappings..
  57064. const char* const keymap = "awsedftgyhujkolp;";
  57065. for (int i = String (keymap).length(); --i >= 0;)
  57066. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  57067. setOpaque (true);
  57068. setWantsKeyboardFocus (true);
  57069. state.addListener (this);
  57070. }
  57071. MidiKeyboardComponent::~MidiKeyboardComponent()
  57072. {
  57073. state.removeListener (this);
  57074. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  57075. deleteAllChildren();
  57076. }
  57077. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  57078. {
  57079. keyWidth = widthInPixels;
  57080. resized();
  57081. }
  57082. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  57083. {
  57084. if (orientation != newOrientation)
  57085. {
  57086. orientation = newOrientation;
  57087. resized();
  57088. }
  57089. }
  57090. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  57091. const int highestNote)
  57092. {
  57093. jassert (lowestNote >= 0 && lowestNote <= 127);
  57094. jassert (highestNote >= 0 && highestNote <= 127);
  57095. jassert (lowestNote <= highestNote);
  57096. if (rangeStart != lowestNote || rangeEnd != highestNote)
  57097. {
  57098. rangeStart = jlimit (0, 127, lowestNote);
  57099. rangeEnd = jlimit (0, 127, highestNote);
  57100. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  57101. resized();
  57102. }
  57103. }
  57104. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  57105. {
  57106. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  57107. if (noteNumber != firstKey)
  57108. {
  57109. firstKey = noteNumber;
  57110. sendChangeMessage (this);
  57111. resized();
  57112. }
  57113. }
  57114. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  57115. {
  57116. if (canScroll != canScroll_)
  57117. {
  57118. canScroll = canScroll_;
  57119. resized();
  57120. }
  57121. }
  57122. void MidiKeyboardComponent::colourChanged()
  57123. {
  57124. repaint();
  57125. }
  57126. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  57127. {
  57128. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  57129. if (midiChannel != midiChannelNumber)
  57130. {
  57131. resetAnyKeysInUse();
  57132. midiChannel = jlimit (1, 16, midiChannelNumber);
  57133. }
  57134. }
  57135. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  57136. {
  57137. midiInChannelMask = midiChannelMask;
  57138. triggerAsyncUpdate();
  57139. }
  57140. void MidiKeyboardComponent::setVelocity (const float velocity_)
  57141. {
  57142. velocity = jlimit (0.0f, 1.0f, velocity_);
  57143. }
  57144. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  57145. {
  57146. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  57147. static const float blackNoteWidth = 0.7f;
  57148. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  57149. 1.0f, 2 - blackNoteWidth * 0.4f,
  57150. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  57151. 4.0f, 5 - blackNoteWidth * 0.5f,
  57152. 5.0f, 6 - blackNoteWidth * 0.3f,
  57153. 6.0f };
  57154. static const float widths[] = { 1.0f, blackNoteWidth,
  57155. 1.0f, blackNoteWidth,
  57156. 1.0f, 1.0f, blackNoteWidth,
  57157. 1.0f, blackNoteWidth,
  57158. 1.0f, blackNoteWidth,
  57159. 1.0f };
  57160. const int octave = midiNoteNumber / 12;
  57161. const int note = midiNoteNumber % 12;
  57162. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  57163. w = roundFloatToInt (widths [note] * keyWidth);
  57164. }
  57165. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  57166. {
  57167. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  57168. int rx, rw;
  57169. getKeyPosition (rangeStart, keyWidth, rx, rw);
  57170. x -= xOffset + rx;
  57171. }
  57172. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  57173. {
  57174. int x, y;
  57175. getKeyPos (midiNoteNumber, x, y);
  57176. return x;
  57177. }
  57178. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  57179. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  57180. int MidiKeyboardComponent::xyToNote (int x, int y)
  57181. {
  57182. if (! reallyContains (x, y, false))
  57183. return -1;
  57184. if (orientation != horizontalKeyboard)
  57185. {
  57186. swapVariables (x, y);
  57187. if (orientation == verticalKeyboardFacingLeft)
  57188. y = getWidth() - y;
  57189. else
  57190. x = getHeight() - x;
  57191. }
  57192. return remappedXYToNote (x + xOffset, y);
  57193. }
  57194. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  57195. {
  57196. if (y < blackNoteLength)
  57197. {
  57198. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57199. {
  57200. for (int i = 0; i < 5; ++i)
  57201. {
  57202. const int note = octaveStart + blackNotes [i];
  57203. if (note >= rangeStart && note <= rangeEnd)
  57204. {
  57205. int kx, kw;
  57206. getKeyPos (note, kx, kw);
  57207. kx += xOffset;
  57208. if (x >= kx && x < kx + kw)
  57209. return note;
  57210. }
  57211. }
  57212. }
  57213. }
  57214. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57215. {
  57216. for (int i = 0; i < 7; ++i)
  57217. {
  57218. const int note = octaveStart + whiteNotes [i];
  57219. if (note >= rangeStart && note <= rangeEnd)
  57220. {
  57221. int kx, kw;
  57222. getKeyPos (note, kx, kw);
  57223. kx += xOffset;
  57224. if (x >= kx && x < kx + kw)
  57225. return note;
  57226. }
  57227. }
  57228. }
  57229. return -1;
  57230. }
  57231. void MidiKeyboardComponent::repaintNote (const int noteNum)
  57232. {
  57233. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57234. {
  57235. int x, w;
  57236. getKeyPos (noteNum, x, w);
  57237. if (orientation == horizontalKeyboard)
  57238. repaint (x, 0, w, getHeight());
  57239. else if (orientation == verticalKeyboardFacingLeft)
  57240. repaint (0, x, getWidth(), w);
  57241. else if (orientation == verticalKeyboardFacingRight)
  57242. repaint (0, getHeight() - x - w, getWidth(), w);
  57243. }
  57244. }
  57245. void MidiKeyboardComponent::paint (Graphics& g)
  57246. {
  57247. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  57248. const Colour lineColour (findColour (keySeparatorLineColourId));
  57249. const Colour textColour (findColour (textLabelColourId));
  57250. int x, w, octave;
  57251. for (octave = 0; octave < 128; octave += 12)
  57252. {
  57253. for (int white = 0; white < 7; ++white)
  57254. {
  57255. const int noteNum = octave + whiteNotes [white];
  57256. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57257. {
  57258. getKeyPos (noteNum, x, w);
  57259. if (orientation == horizontalKeyboard)
  57260. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  57261. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57262. noteUnderMouse == noteNum,
  57263. lineColour, textColour);
  57264. else if (orientation == verticalKeyboardFacingLeft)
  57265. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  57266. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57267. noteUnderMouse == noteNum,
  57268. lineColour, textColour);
  57269. else if (orientation == verticalKeyboardFacingRight)
  57270. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  57271. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57272. noteUnderMouse == noteNum,
  57273. lineColour, textColour);
  57274. }
  57275. }
  57276. }
  57277. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  57278. if (orientation == verticalKeyboardFacingLeft)
  57279. {
  57280. x1 = getWidth() - 1.0f;
  57281. x2 = getWidth() - 5.0f;
  57282. }
  57283. else if (orientation == verticalKeyboardFacingRight)
  57284. x2 = 5.0f;
  57285. else
  57286. y2 = 5.0f;
  57287. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  57288. Colours::transparentBlack, x2, y2, false);
  57289. g.setBrush (&gb);
  57290. getKeyPos (rangeEnd, x, w);
  57291. x += w;
  57292. if (orientation == verticalKeyboardFacingLeft)
  57293. g.fillRect (getWidth() - 5, 0, 5, x);
  57294. else if (orientation == verticalKeyboardFacingRight)
  57295. g.fillRect (0, 0, 5, x);
  57296. else
  57297. g.fillRect (0, 0, x, 5);
  57298. g.setColour (lineColour);
  57299. if (orientation == verticalKeyboardFacingLeft)
  57300. g.fillRect (0, 0, 1, x);
  57301. else if (orientation == verticalKeyboardFacingRight)
  57302. g.fillRect (getWidth() - 1, 0, 1, x);
  57303. else
  57304. g.fillRect (0, getHeight() - 1, x, 1);
  57305. const Colour blackNoteColour (findColour (blackNoteColourId));
  57306. for (octave = 0; octave < 128; octave += 12)
  57307. {
  57308. for (int black = 0; black < 5; ++black)
  57309. {
  57310. const int noteNum = octave + blackNotes [black];
  57311. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57312. {
  57313. getKeyPos (noteNum, x, w);
  57314. if (orientation == horizontalKeyboard)
  57315. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  57316. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57317. noteUnderMouse == noteNum,
  57318. blackNoteColour);
  57319. else if (orientation == verticalKeyboardFacingLeft)
  57320. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  57321. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57322. noteUnderMouse == noteNum,
  57323. blackNoteColour);
  57324. else if (orientation == verticalKeyboardFacingRight)
  57325. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  57326. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57327. noteUnderMouse == noteNum,
  57328. blackNoteColour);
  57329. }
  57330. }
  57331. }
  57332. }
  57333. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  57334. Graphics& g, int x, int y, int w, int h,
  57335. bool isDown, bool isOver,
  57336. const Colour& lineColour,
  57337. const Colour& textColour)
  57338. {
  57339. Colour c (Colours::transparentWhite);
  57340. if (isDown)
  57341. c = findColour (keyDownOverlayColourId);
  57342. if (isOver)
  57343. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57344. g.setColour (c);
  57345. g.fillRect (x, y, w, h);
  57346. const String text (getWhiteNoteText (midiNoteNumber));
  57347. if (! text.isEmpty())
  57348. {
  57349. g.setColour (textColour);
  57350. Font f (jmin (12.0f, keyWidth * 0.9f));
  57351. f.setHorizontalScale (0.8f);
  57352. g.setFont (f);
  57353. Justification justification (Justification::centredBottom);
  57354. if (orientation == verticalKeyboardFacingLeft)
  57355. justification = Justification::centredLeft;
  57356. else if (orientation == verticalKeyboardFacingRight)
  57357. justification = Justification::centredRight;
  57358. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  57359. }
  57360. g.setColour (lineColour);
  57361. if (orientation == horizontalKeyboard)
  57362. g.fillRect (x, y, 1, h);
  57363. else if (orientation == verticalKeyboardFacingLeft)
  57364. g.fillRect (x, y, w, 1);
  57365. else if (orientation == verticalKeyboardFacingRight)
  57366. g.fillRect (x, y + h - 1, w, 1);
  57367. if (midiNoteNumber == rangeEnd)
  57368. {
  57369. if (orientation == horizontalKeyboard)
  57370. g.fillRect (x + w, y, 1, h);
  57371. else if (orientation == verticalKeyboardFacingLeft)
  57372. g.fillRect (x, y + h, w, 1);
  57373. else if (orientation == verticalKeyboardFacingRight)
  57374. g.fillRect (x, y - 1, w, 1);
  57375. }
  57376. }
  57377. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  57378. Graphics& g, int x, int y, int w, int h,
  57379. bool isDown, bool isOver,
  57380. const Colour& noteFillColour)
  57381. {
  57382. Colour c (noteFillColour);
  57383. if (isDown)
  57384. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  57385. if (isOver)
  57386. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57387. g.setColour (c);
  57388. g.fillRect (x, y, w, h);
  57389. if (isDown)
  57390. {
  57391. g.setColour (noteFillColour);
  57392. g.drawRect (x, y, w, h);
  57393. }
  57394. else
  57395. {
  57396. const int xIndent = jmax (1, jmin (w, h) / 8);
  57397. g.setColour (c.brighter());
  57398. if (orientation == horizontalKeyboard)
  57399. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  57400. else if (orientation == verticalKeyboardFacingLeft)
  57401. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  57402. else if (orientation == verticalKeyboardFacingRight)
  57403. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  57404. }
  57405. }
  57406. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  57407. {
  57408. octaveNumForMiddleC = octaveNumForMiddleC_;
  57409. repaint();
  57410. }
  57411. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  57412. {
  57413. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  57414. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  57415. return String::empty;
  57416. }
  57417. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  57418. const bool isMouseOver,
  57419. const bool isButtonDown,
  57420. const bool movesOctavesUp)
  57421. {
  57422. g.fillAll (findColour (upDownButtonBackgroundColourId));
  57423. float angle;
  57424. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  57425. angle = movesOctavesUp ? 0.0f : 0.5f;
  57426. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  57427. angle = movesOctavesUp ? 0.25f : 0.75f;
  57428. else
  57429. angle = movesOctavesUp ? 0.75f : 0.25f;
  57430. Path path;
  57431. path.lineTo (0.0f, 1.0f);
  57432. path.lineTo (1.0f, 0.5f);
  57433. path.closeSubPath();
  57434. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  57435. g.setColour (findColour (upDownButtonArrowColourId)
  57436. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  57437. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  57438. w - 2.0f,
  57439. h - 2.0f,
  57440. true));
  57441. }
  57442. void MidiKeyboardComponent::resized()
  57443. {
  57444. int w = getWidth();
  57445. int h = getHeight();
  57446. if (w > 0 && h > 0)
  57447. {
  57448. if (orientation != horizontalKeyboard)
  57449. swapVariables (w, h);
  57450. blackNoteLength = roundFloatToInt (h * 0.7f);
  57451. int kx2, kw2;
  57452. getKeyPos (rangeEnd, kx2, kw2);
  57453. kx2 += kw2;
  57454. if (firstKey != rangeStart)
  57455. {
  57456. int kx1, kw1;
  57457. getKeyPos (rangeStart, kx1, kw1);
  57458. if (kx2 - kx1 <= w)
  57459. {
  57460. firstKey = rangeStart;
  57461. sendChangeMessage (this);
  57462. repaint();
  57463. }
  57464. }
  57465. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  57466. scrollDown->setVisible (showScrollButtons);
  57467. scrollUp->setVisible (showScrollButtons);
  57468. xOffset = 0;
  57469. if (showScrollButtons)
  57470. {
  57471. const int scrollButtonW = jmin (12, w / 2);
  57472. if (orientation == horizontalKeyboard)
  57473. {
  57474. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  57475. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  57476. }
  57477. else if (orientation == verticalKeyboardFacingLeft)
  57478. {
  57479. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  57480. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57481. }
  57482. else if (orientation == verticalKeyboardFacingRight)
  57483. {
  57484. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57485. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  57486. }
  57487. int endOfLastKey, kw;
  57488. getKeyPos (rangeEnd, endOfLastKey, kw);
  57489. endOfLastKey += kw;
  57490. const int spaceAvailable = w - scrollButtonW * 2;
  57491. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  57492. if (lastStartKey >= 0 && firstKey > lastStartKey)
  57493. {
  57494. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  57495. sendChangeMessage (this);
  57496. }
  57497. int newOffset = 0;
  57498. getKeyPos (firstKey, newOffset, kw);
  57499. xOffset = newOffset - scrollButtonW;
  57500. }
  57501. else
  57502. {
  57503. firstKey = rangeStart;
  57504. }
  57505. timerCallback();
  57506. repaint();
  57507. }
  57508. }
  57509. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  57510. {
  57511. triggerAsyncUpdate();
  57512. }
  57513. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  57514. {
  57515. triggerAsyncUpdate();
  57516. }
  57517. void MidiKeyboardComponent::handleAsyncUpdate()
  57518. {
  57519. for (int i = rangeStart; i <= rangeEnd; ++i)
  57520. {
  57521. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  57522. {
  57523. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  57524. repaintNote (i);
  57525. }
  57526. }
  57527. }
  57528. void MidiKeyboardComponent::resetAnyKeysInUse()
  57529. {
  57530. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  57531. {
  57532. state.allNotesOff (midiChannel);
  57533. keysPressed.clear();
  57534. mouseDownNote = -1;
  57535. }
  57536. }
  57537. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  57538. {
  57539. const int newNote = (mouseDragging || isMouseOver())
  57540. ? xyToNote (x, y) : -1;
  57541. if (noteUnderMouse != newNote)
  57542. {
  57543. if (mouseDownNote >= 0)
  57544. {
  57545. state.noteOff (midiChannel, mouseDownNote);
  57546. mouseDownNote = -1;
  57547. }
  57548. if (mouseDragging && newNote >= 0)
  57549. {
  57550. state.noteOn (midiChannel, newNote, velocity);
  57551. mouseDownNote = newNote;
  57552. }
  57553. repaintNote (noteUnderMouse);
  57554. noteUnderMouse = newNote;
  57555. repaintNote (noteUnderMouse);
  57556. }
  57557. else if (mouseDownNote >= 0 && ! mouseDragging)
  57558. {
  57559. state.noteOff (midiChannel, mouseDownNote);
  57560. mouseDownNote = -1;
  57561. }
  57562. }
  57563. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  57564. {
  57565. updateNoteUnderMouse (e.x, e.y);
  57566. stopTimer();
  57567. }
  57568. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  57569. {
  57570. const int newNote = xyToNote (e.x, e.y);
  57571. if (newNote >= 0)
  57572. mouseDraggedToKey (newNote, e);
  57573. updateNoteUnderMouse (e.x, e.y);
  57574. }
  57575. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  57576. {
  57577. return true;
  57578. }
  57579. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  57580. {
  57581. }
  57582. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  57583. {
  57584. const int newNote = xyToNote (e.x, e.y);
  57585. mouseDragging = false;
  57586. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  57587. {
  57588. repaintNote (noteUnderMouse);
  57589. noteUnderMouse = -1;
  57590. mouseDragging = true;
  57591. updateNoteUnderMouse (e.x, e.y);
  57592. startTimer (500);
  57593. }
  57594. }
  57595. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  57596. {
  57597. mouseDragging = false;
  57598. updateNoteUnderMouse (e.x, e.y);
  57599. stopTimer();
  57600. }
  57601. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  57602. {
  57603. updateNoteUnderMouse (e.x, e.y);
  57604. }
  57605. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  57606. {
  57607. updateNoteUnderMouse (e.x, e.y);
  57608. }
  57609. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  57610. {
  57611. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  57612. }
  57613. void MidiKeyboardComponent::timerCallback()
  57614. {
  57615. int mx, my;
  57616. getMouseXYRelative (mx, my);
  57617. updateNoteUnderMouse (mx, my);
  57618. }
  57619. void MidiKeyboardComponent::clearKeyMappings()
  57620. {
  57621. resetAnyKeysInUse();
  57622. keyPressNotes.clear();
  57623. keyPresses.clear();
  57624. }
  57625. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  57626. const int midiNoteOffsetFromC)
  57627. {
  57628. removeKeyPressForNote (midiNoteOffsetFromC);
  57629. keyPressNotes.add (midiNoteOffsetFromC);
  57630. keyPresses.add (key);
  57631. }
  57632. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  57633. {
  57634. for (int i = keyPressNotes.size(); --i >= 0;)
  57635. {
  57636. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  57637. {
  57638. keyPressNotes.remove (i);
  57639. keyPresses.remove (i);
  57640. }
  57641. }
  57642. }
  57643. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  57644. {
  57645. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  57646. keyMappingOctave = newOctaveNumber;
  57647. }
  57648. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  57649. {
  57650. bool keyPressUsed = false;
  57651. for (int i = keyPresses.size(); --i >= 0;)
  57652. {
  57653. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  57654. if (keyPresses.getReference(i).isCurrentlyDown())
  57655. {
  57656. if (! keysPressed [note])
  57657. {
  57658. keysPressed.setBit (note);
  57659. state.noteOn (midiChannel, note, velocity);
  57660. keyPressUsed = true;
  57661. }
  57662. }
  57663. else
  57664. {
  57665. if (keysPressed [note])
  57666. {
  57667. keysPressed.clearBit (note);
  57668. state.noteOff (midiChannel, note);
  57669. keyPressUsed = true;
  57670. }
  57671. }
  57672. }
  57673. return keyPressUsed;
  57674. }
  57675. void MidiKeyboardComponent::focusLost (FocusChangeType)
  57676. {
  57677. resetAnyKeysInUse();
  57678. }
  57679. END_JUCE_NAMESPACE
  57680. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  57681. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  57682. #if JUCE_OPENGL
  57683. BEGIN_JUCE_NAMESPACE
  57684. extern void juce_glViewport (const int w, const int h);
  57685. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  57686. const int alphaBits_,
  57687. const int depthBufferBits_,
  57688. const int stencilBufferBits_) throw()
  57689. : redBits (bitsPerRGBComponent),
  57690. greenBits (bitsPerRGBComponent),
  57691. blueBits (bitsPerRGBComponent),
  57692. alphaBits (alphaBits_),
  57693. depthBufferBits (depthBufferBits_),
  57694. stencilBufferBits (stencilBufferBits_),
  57695. accumulationBufferRedBits (0),
  57696. accumulationBufferGreenBits (0),
  57697. accumulationBufferBlueBits (0),
  57698. accumulationBufferAlphaBits (0),
  57699. fullSceneAntiAliasingNumSamples (0)
  57700. {
  57701. }
  57702. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  57703. {
  57704. return memcmp (this, &other, sizeof (other)) == 0;
  57705. }
  57706. static VoidArray knownContexts;
  57707. OpenGLContext::OpenGLContext() throw()
  57708. {
  57709. knownContexts.add (this);
  57710. }
  57711. OpenGLContext::~OpenGLContext()
  57712. {
  57713. knownContexts.removeValue (this);
  57714. }
  57715. OpenGLContext* OpenGLContext::getCurrentContext()
  57716. {
  57717. for (int i = knownContexts.size(); --i >= 0;)
  57718. {
  57719. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  57720. if (oglc->isActive())
  57721. return oglc;
  57722. }
  57723. return 0;
  57724. }
  57725. class OpenGLComponentWatcher : public ComponentMovementWatcher
  57726. {
  57727. public:
  57728. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  57729. : ComponentMovementWatcher (owner_),
  57730. owner (owner_),
  57731. wasShowing (false)
  57732. {
  57733. }
  57734. ~OpenGLComponentWatcher() {}
  57735. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  57736. {
  57737. owner->updateContextPosition();
  57738. }
  57739. void componentPeerChanged()
  57740. {
  57741. const ScopedLock sl (owner->getContextLock());
  57742. owner->deleteContext();
  57743. }
  57744. void componentVisibilityChanged (Component&)
  57745. {
  57746. const bool isShowingNow = owner->isShowing();
  57747. if (wasShowing != isShowingNow)
  57748. {
  57749. wasShowing = isShowingNow;
  57750. owner->updateContextPosition();
  57751. }
  57752. }
  57753. juce_UseDebuggingNewOperator
  57754. private:
  57755. OpenGLComponent* const owner;
  57756. bool wasShowing;
  57757. };
  57758. OpenGLComponent::OpenGLComponent()
  57759. : context (0),
  57760. contextToShareListsWith (0),
  57761. needToUpdateViewport (true)
  57762. {
  57763. setOpaque (true);
  57764. componentWatcher = new OpenGLComponentWatcher (this);
  57765. }
  57766. OpenGLComponent::~OpenGLComponent()
  57767. {
  57768. deleteContext();
  57769. delete componentWatcher;
  57770. }
  57771. void OpenGLComponent::deleteContext()
  57772. {
  57773. const ScopedLock sl (contextLock);
  57774. deleteAndZero (context);
  57775. }
  57776. void OpenGLComponent::updateContextPosition()
  57777. {
  57778. needToUpdateViewport = true;
  57779. if (getWidth() > 0 && getHeight() > 0)
  57780. {
  57781. Component* const topComp = getTopLevelComponent();
  57782. if (topComp->getPeer() != 0)
  57783. {
  57784. const ScopedLock sl (contextLock);
  57785. if (context != 0)
  57786. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  57787. getScreenY() - topComp->getScreenY(),
  57788. getWidth(),
  57789. getHeight(),
  57790. topComp->getHeight());
  57791. }
  57792. }
  57793. }
  57794. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  57795. {
  57796. OpenGLPixelFormat pf;
  57797. const ScopedLock sl (contextLock);
  57798. if (context != 0)
  57799. pf = context->getPixelFormat();
  57800. return pf;
  57801. }
  57802. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  57803. {
  57804. if (! (preferredPixelFormat == formatToUse))
  57805. {
  57806. const ScopedLock sl (contextLock);
  57807. deleteContext();
  57808. preferredPixelFormat = formatToUse;
  57809. }
  57810. }
  57811. void OpenGLComponent::shareWith (OpenGLContext* context)
  57812. {
  57813. if (contextToShareListsWith != context)
  57814. {
  57815. const ScopedLock sl (contextLock);
  57816. deleteContext();
  57817. contextToShareListsWith = context;
  57818. }
  57819. }
  57820. bool OpenGLComponent::makeCurrentContextActive()
  57821. {
  57822. if (context == 0)
  57823. {
  57824. const ScopedLock sl (contextLock);
  57825. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  57826. {
  57827. context = OpenGLContext::createContextForWindow (this,
  57828. preferredPixelFormat,
  57829. contextToShareListsWith);
  57830. if (context != 0)
  57831. {
  57832. updateContextPosition();
  57833. if (context->makeActive())
  57834. newOpenGLContextCreated();
  57835. }
  57836. }
  57837. }
  57838. return context != 0 && context->makeActive();
  57839. }
  57840. void OpenGLComponent::makeCurrentContextInactive()
  57841. {
  57842. if (context != 0)
  57843. context->makeInactive();
  57844. }
  57845. bool OpenGLComponent::isActiveContext() const throw()
  57846. {
  57847. return context != 0 && context->isActive();
  57848. }
  57849. void OpenGLComponent::swapBuffers()
  57850. {
  57851. if (context != 0)
  57852. context->swapBuffers();
  57853. }
  57854. void OpenGLComponent::paint (Graphics&)
  57855. {
  57856. if (renderAndSwapBuffers())
  57857. {
  57858. ComponentPeer* const peer = getPeer();
  57859. if (peer != 0)
  57860. {
  57861. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  57862. getScreenY() - peer->getScreenY(),
  57863. getWidth(), getHeight());
  57864. }
  57865. }
  57866. }
  57867. bool OpenGLComponent::renderAndSwapBuffers()
  57868. {
  57869. const ScopedLock sl (contextLock);
  57870. if (! makeCurrentContextActive())
  57871. return false;
  57872. if (needToUpdateViewport)
  57873. {
  57874. needToUpdateViewport = false;
  57875. juce_glViewport (getWidth(), getHeight());
  57876. }
  57877. renderOpenGL();
  57878. swapBuffers();
  57879. return true;
  57880. }
  57881. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  57882. {
  57883. Component::internalRepaint (x, y, w, h);
  57884. if (context != 0)
  57885. context->repaint();
  57886. }
  57887. END_JUCE_NAMESPACE
  57888. #endif
  57889. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  57890. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  57891. BEGIN_JUCE_NAMESPACE
  57892. PreferencesPanel::PreferencesPanel()
  57893. : currentPage (0),
  57894. buttonSize (70)
  57895. {
  57896. }
  57897. PreferencesPanel::~PreferencesPanel()
  57898. {
  57899. deleteAllChildren();
  57900. }
  57901. void PreferencesPanel::addSettingsPage (const String& title,
  57902. const Drawable* icon,
  57903. const Drawable* overIcon,
  57904. const Drawable* downIcon)
  57905. {
  57906. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  57907. button->setImages (icon, overIcon, downIcon);
  57908. button->setRadioGroupId (1);
  57909. button->addButtonListener (this);
  57910. button->setClickingTogglesState (true);
  57911. button->setWantsKeyboardFocus (false);
  57912. addAndMakeVisible (button);
  57913. resized();
  57914. if (currentPage == 0)
  57915. setCurrentPage (title);
  57916. }
  57917. void PreferencesPanel::addSettingsPage (const String& title,
  57918. const char* imageData,
  57919. const int imageDataSize)
  57920. {
  57921. DrawableImage icon, iconOver, iconDown;
  57922. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57923. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57924. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  57925. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57926. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  57927. addSettingsPage (title, &icon, &iconOver, &iconDown);
  57928. }
  57929. class PrefsDialogWindow : public DialogWindow
  57930. {
  57931. public:
  57932. PrefsDialogWindow (const String& dialogtitle,
  57933. const Colour& backgroundColour)
  57934. : DialogWindow (dialogtitle, backgroundColour, true)
  57935. {
  57936. }
  57937. ~PrefsDialogWindow()
  57938. {
  57939. }
  57940. void closeButtonPressed()
  57941. {
  57942. exitModalState (0);
  57943. }
  57944. private:
  57945. PrefsDialogWindow (const PrefsDialogWindow&);
  57946. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  57947. };
  57948. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  57949. int dialogWidth,
  57950. int dialogHeight,
  57951. const Colour& backgroundColour)
  57952. {
  57953. setSize (dialogWidth, dialogHeight);
  57954. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  57955. dw.setContentComponent (this, true, true);
  57956. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  57957. dw.runModalLoop();
  57958. dw.setContentComponent (0, false, false);
  57959. }
  57960. void PreferencesPanel::resized()
  57961. {
  57962. int x = 0;
  57963. for (int i = 0; i < getNumChildComponents(); ++i)
  57964. {
  57965. Component* c = getChildComponent (i);
  57966. if (dynamic_cast <DrawableButton*> (c) == 0)
  57967. {
  57968. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  57969. }
  57970. else
  57971. {
  57972. c->setBounds (x, 0, buttonSize, buttonSize);
  57973. x += buttonSize;
  57974. }
  57975. }
  57976. }
  57977. void PreferencesPanel::paint (Graphics& g)
  57978. {
  57979. g.setColour (Colours::grey);
  57980. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  57981. }
  57982. void PreferencesPanel::setCurrentPage (const String& pageName)
  57983. {
  57984. if (currentPageName != pageName)
  57985. {
  57986. currentPageName = pageName;
  57987. deleteAndZero (currentPage);
  57988. currentPage = createComponentForPage (pageName);
  57989. if (currentPage != 0)
  57990. {
  57991. addAndMakeVisible (currentPage);
  57992. currentPage->toBack();
  57993. resized();
  57994. }
  57995. for (int i = 0; i < getNumChildComponents(); ++i)
  57996. {
  57997. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57998. if (db != 0 && db->getName() == pageName)
  57999. {
  58000. db->setToggleState (true, false);
  58001. break;
  58002. }
  58003. }
  58004. }
  58005. }
  58006. void PreferencesPanel::buttonClicked (Button*)
  58007. {
  58008. for (int i = 0; i < getNumChildComponents(); ++i)
  58009. {
  58010. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  58011. if (db != 0 && db->getToggleState())
  58012. {
  58013. setCurrentPage (db->getName());
  58014. break;
  58015. }
  58016. }
  58017. }
  58018. END_JUCE_NAMESPACE
  58019. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  58020. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  58021. #if JUCE_WINDOWS || JUCE_LINUX
  58022. BEGIN_JUCE_NAMESPACE
  58023. SystemTrayIconComponent::SystemTrayIconComponent()
  58024. {
  58025. addToDesktop (0);
  58026. }
  58027. SystemTrayIconComponent::~SystemTrayIconComponent()
  58028. {
  58029. }
  58030. END_JUCE_NAMESPACE
  58031. #endif
  58032. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  58033. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  58034. BEGIN_JUCE_NAMESPACE
  58035. static const int titleH = 24;
  58036. static const int iconWidth = 80;
  58037. class AlertWindowTextEditor : public TextEditor
  58038. {
  58039. public:
  58040. #if JUCE_LINUX
  58041. #define PASSWORD_CHAR 0x2022
  58042. #else
  58043. #define PASSWORD_CHAR 0x25cf
  58044. #endif
  58045. AlertWindowTextEditor (const String& name,
  58046. const bool isPasswordBox)
  58047. : TextEditor (name,
  58048. isPasswordBox ? (const tchar) PASSWORD_CHAR
  58049. : (const tchar) 0)
  58050. {
  58051. setSelectAllWhenFocused (true);
  58052. }
  58053. ~AlertWindowTextEditor()
  58054. {
  58055. }
  58056. void returnPressed()
  58057. {
  58058. // pass these up the component hierarchy to be trigger the buttons
  58059. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  58060. }
  58061. void escapePressed()
  58062. {
  58063. // pass these up the component hierarchy to be trigger the buttons
  58064. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  58065. }
  58066. private:
  58067. AlertWindowTextEditor (const AlertWindowTextEditor&);
  58068. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  58069. };
  58070. AlertWindow::AlertWindow (const String& title,
  58071. const String& message,
  58072. AlertIconType iconType,
  58073. Component* associatedComponent_)
  58074. : TopLevelWindow (title, true),
  58075. alertIconType (iconType),
  58076. associatedComponent (associatedComponent_)
  58077. {
  58078. if (message.isEmpty())
  58079. text = T(" "); // to force an update if the message is empty
  58080. setMessage (message);
  58081. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  58082. {
  58083. Component* const c = Desktop::getInstance().getComponent (i);
  58084. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  58085. {
  58086. setAlwaysOnTop (true);
  58087. break;
  58088. }
  58089. }
  58090. if (JUCEApplication::getInstance() == 0)
  58091. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  58092. lookAndFeelChanged();
  58093. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  58094. }
  58095. AlertWindow::~AlertWindow()
  58096. {
  58097. for (int i = customComps.size(); --i >= 0;)
  58098. removeChildComponent ((Component*) customComps[i]);
  58099. deleteAllChildren();
  58100. }
  58101. void AlertWindow::userTriedToCloseWindow()
  58102. {
  58103. exitModalState (0);
  58104. }
  58105. void AlertWindow::setMessage (const String& message)
  58106. {
  58107. const String newMessage (message.substring (0, 2048));
  58108. if (text != newMessage)
  58109. {
  58110. text = newMessage;
  58111. font.setHeight (15.0f);
  58112. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  58113. textLayout.setText (getName() + T("\n\n"), titleFont);
  58114. textLayout.appendText (text, font);
  58115. updateLayout (true);
  58116. repaint();
  58117. }
  58118. }
  58119. void AlertWindow::buttonClicked (Button* button)
  58120. {
  58121. for (int i = 0; i < buttons.size(); i++)
  58122. {
  58123. TextButton* const c = (TextButton*) buttons[i];
  58124. if (button->getName() == c->getName())
  58125. {
  58126. if (c->getParentComponent() != 0)
  58127. c->getParentComponent()->exitModalState (c->getCommandID());
  58128. break;
  58129. }
  58130. }
  58131. }
  58132. void AlertWindow::addButton (const String& name,
  58133. const int returnValue,
  58134. const KeyPress& shortcutKey1,
  58135. const KeyPress& shortcutKey2)
  58136. {
  58137. TextButton* const b = new TextButton (name, String::empty);
  58138. b->setWantsKeyboardFocus (true);
  58139. b->setMouseClickGrabsKeyboardFocus (false);
  58140. b->setCommandToTrigger (0, returnValue, false);
  58141. b->addShortcut (shortcutKey1);
  58142. b->addShortcut (shortcutKey2);
  58143. b->addButtonListener (this);
  58144. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  58145. addAndMakeVisible (b, 0);
  58146. buttons.add (b);
  58147. updateLayout (false);
  58148. }
  58149. int AlertWindow::getNumButtons() const
  58150. {
  58151. return buttons.size();
  58152. }
  58153. void AlertWindow::addTextEditor (const String& name,
  58154. const String& initialContents,
  58155. const String& onScreenLabel,
  58156. const bool isPasswordBox)
  58157. {
  58158. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  58159. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  58160. tc->setFont (font);
  58161. tc->setText (initialContents);
  58162. tc->setCaretPosition (initialContents.length());
  58163. addAndMakeVisible (tc);
  58164. textBoxes.add (tc);
  58165. allComps.add (tc);
  58166. textboxNames.add (onScreenLabel);
  58167. updateLayout (false);
  58168. }
  58169. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  58170. {
  58171. for (int i = textBoxes.size(); --i >= 0;)
  58172. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  58173. return ((TextEditor*)textBoxes[i])->getText();
  58174. return String::empty;
  58175. }
  58176. void AlertWindow::addComboBox (const String& name,
  58177. const StringArray& items,
  58178. const String& onScreenLabel)
  58179. {
  58180. ComboBox* const cb = new ComboBox (name);
  58181. for (int i = 0; i < items.size(); ++i)
  58182. cb->addItem (items[i], i + 1);
  58183. addAndMakeVisible (cb);
  58184. cb->setSelectedItemIndex (0);
  58185. comboBoxes.add (cb);
  58186. allComps.add (cb);
  58187. comboBoxNames.add (onScreenLabel);
  58188. updateLayout (false);
  58189. }
  58190. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  58191. {
  58192. for (int i = comboBoxes.size(); --i >= 0;)
  58193. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  58194. return (ComboBox*) comboBoxes[i];
  58195. return 0;
  58196. }
  58197. class AlertTextComp : public TextEditor
  58198. {
  58199. AlertTextComp (const AlertTextComp&);
  58200. const AlertTextComp& operator= (const AlertTextComp&);
  58201. int bestWidth;
  58202. public:
  58203. AlertTextComp (const String& message,
  58204. const Font& font)
  58205. {
  58206. setReadOnly (true);
  58207. setMultiLine (true, true);
  58208. setCaretVisible (false);
  58209. setScrollbarsShown (true);
  58210. lookAndFeelChanged();
  58211. setWantsKeyboardFocus (false);
  58212. setFont (font);
  58213. setText (message, false);
  58214. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  58215. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  58216. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  58217. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  58218. }
  58219. ~AlertTextComp()
  58220. {
  58221. }
  58222. int getPreferredWidth() const throw() { return bestWidth; }
  58223. void updateLayout (const int width)
  58224. {
  58225. TextLayout text;
  58226. text.appendText (getText(), getFont());
  58227. text.layout (width - 8, Justification::topLeft, true);
  58228. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  58229. }
  58230. };
  58231. void AlertWindow::addTextBlock (const String& text)
  58232. {
  58233. AlertTextComp* const c = new AlertTextComp (text, font);
  58234. textBlocks.add (c);
  58235. allComps.add (c);
  58236. addAndMakeVisible (c);
  58237. updateLayout (false);
  58238. }
  58239. void AlertWindow::addProgressBarComponent (double& progressValue)
  58240. {
  58241. ProgressBar* const pb = new ProgressBar (progressValue);
  58242. progressBars.add (pb);
  58243. allComps.add (pb);
  58244. addAndMakeVisible (pb);
  58245. updateLayout (false);
  58246. }
  58247. void AlertWindow::addCustomComponent (Component* const component)
  58248. {
  58249. customComps.add (component);
  58250. allComps.add (component);
  58251. addAndMakeVisible (component);
  58252. updateLayout (false);
  58253. }
  58254. int AlertWindow::getNumCustomComponents() const
  58255. {
  58256. return customComps.size();
  58257. }
  58258. Component* AlertWindow::getCustomComponent (const int index) const
  58259. {
  58260. return (Component*) customComps [index];
  58261. }
  58262. Component* AlertWindow::removeCustomComponent (const int index)
  58263. {
  58264. Component* const c = getCustomComponent (index);
  58265. if (c != 0)
  58266. {
  58267. customComps.removeValue (c);
  58268. allComps.removeValue (c);
  58269. removeChildComponent (c);
  58270. updateLayout (false);
  58271. }
  58272. return c;
  58273. }
  58274. void AlertWindow::paint (Graphics& g)
  58275. {
  58276. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  58277. g.setColour (findColour (textColourId));
  58278. g.setFont (getLookAndFeel().getAlertWindowFont());
  58279. int i;
  58280. for (i = textBoxes.size(); --i >= 0;)
  58281. {
  58282. if (textboxNames[i].isNotEmpty())
  58283. {
  58284. const TextEditor* const te = (TextEditor*) textBoxes[i];
  58285. g.drawFittedText (textboxNames[i],
  58286. te->getX(), te->getY() - 14,
  58287. te->getWidth(), 14,
  58288. Justification::centredLeft, 1);
  58289. }
  58290. }
  58291. for (i = comboBoxNames.size(); --i >= 0;)
  58292. {
  58293. if (comboBoxNames[i].isNotEmpty())
  58294. {
  58295. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  58296. g.drawFittedText (comboBoxNames[i],
  58297. cb->getX(), cb->getY() - 14,
  58298. cb->getWidth(), 14,
  58299. Justification::centredLeft, 1);
  58300. }
  58301. }
  58302. }
  58303. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  58304. {
  58305. const int wid = jmax (font.getStringWidth (text),
  58306. font.getStringWidth (getName()));
  58307. const int sw = (int) sqrt (font.getHeight() * wid);
  58308. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  58309. const int edgeGap = 10;
  58310. int iconSpace;
  58311. if (alertIconType == NoIcon)
  58312. {
  58313. textLayout.layout (w, Justification::horizontallyCentred, true);
  58314. iconSpace = 0;
  58315. }
  58316. else
  58317. {
  58318. textLayout.layout (w, Justification::left, true);
  58319. iconSpace = iconWidth;
  58320. }
  58321. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  58322. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58323. const int textLayoutH = textLayout.getHeight();
  58324. const int textBottom = 16 + titleH + textLayoutH;
  58325. int h = textBottom;
  58326. int buttonW = 40;
  58327. int i;
  58328. for (i = 0; i < buttons.size(); ++i)
  58329. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  58330. w = jmax (buttonW, w);
  58331. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  58332. if (buttons.size() > 0)
  58333. h += 20 + ((TextButton*) buttons[0])->getHeight();
  58334. for (i = customComps.size(); --i >= 0;)
  58335. {
  58336. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  58337. h += 10 + ((Component*) customComps[i])->getHeight();
  58338. }
  58339. for (i = textBlocks.size(); --i >= 0;)
  58340. {
  58341. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58342. w = jmax (w, ac->getPreferredWidth());
  58343. }
  58344. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58345. for (i = textBlocks.size(); --i >= 0;)
  58346. {
  58347. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58348. ac->updateLayout ((int) (w * 0.8f));
  58349. h += ac->getHeight() + 10;
  58350. }
  58351. h = jmin (getParentHeight() - 50, h);
  58352. if (onlyIncreaseSize)
  58353. {
  58354. w = jmax (w, getWidth());
  58355. h = jmax (h, getHeight());
  58356. }
  58357. if (! isVisible())
  58358. {
  58359. centreAroundComponent (associatedComponent, w, h);
  58360. }
  58361. else
  58362. {
  58363. const int cx = getX() + getWidth() / 2;
  58364. const int cy = getY() + getHeight() / 2;
  58365. setBounds (cx - w / 2,
  58366. cy - h / 2,
  58367. w, h);
  58368. }
  58369. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  58370. const int spacer = 16;
  58371. int totalWidth = -spacer;
  58372. for (i = buttons.size(); --i >= 0;)
  58373. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  58374. int x = (w - totalWidth) / 2;
  58375. int y = (int) (getHeight() * 0.95f);
  58376. for (i = 0; i < buttons.size(); ++i)
  58377. {
  58378. TextButton* const c = (TextButton*) buttons[i];
  58379. int ny = proportionOfHeight (0.95f) - c->getHeight();
  58380. c->setTopLeftPosition (x, ny);
  58381. if (ny < y)
  58382. y = ny;
  58383. x += c->getWidth() + spacer;
  58384. c->toFront (false);
  58385. }
  58386. y = textBottom;
  58387. for (i = 0; i < allComps.size(); ++i)
  58388. {
  58389. Component* const c = (Component*) allComps[i];
  58390. const int h = 22;
  58391. const int comboIndex = comboBoxes.indexOf (c);
  58392. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  58393. y += 18;
  58394. const int tbIndex = textBoxes.indexOf (c);
  58395. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  58396. y += 18;
  58397. if (customComps.contains (c) || textBlocks.contains (c))
  58398. {
  58399. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  58400. y += c->getHeight() + 10;
  58401. }
  58402. else
  58403. {
  58404. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  58405. y += h + 10;
  58406. }
  58407. }
  58408. setWantsKeyboardFocus (getNumChildComponents() == 0);
  58409. }
  58410. bool AlertWindow::containsAnyExtraComponents() const
  58411. {
  58412. return textBoxes.size()
  58413. + comboBoxes.size()
  58414. + progressBars.size()
  58415. + customComps.size() > 0;
  58416. }
  58417. void AlertWindow::mouseDown (const MouseEvent&)
  58418. {
  58419. dragger.startDraggingComponent (this, &constrainer);
  58420. }
  58421. void AlertWindow::mouseDrag (const MouseEvent& e)
  58422. {
  58423. dragger.dragComponent (this, e);
  58424. }
  58425. bool AlertWindow::keyPressed (const KeyPress& key)
  58426. {
  58427. for (int i = buttons.size(); --i >= 0;)
  58428. {
  58429. TextButton* const b = (TextButton*) buttons[i];
  58430. if (b->isRegisteredForShortcut (key))
  58431. {
  58432. b->triggerClick();
  58433. return true;
  58434. }
  58435. }
  58436. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  58437. {
  58438. exitModalState (0);
  58439. return true;
  58440. }
  58441. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  58442. {
  58443. ((TextButton*) buttons.getFirst())->triggerClick();
  58444. return true;
  58445. }
  58446. return false;
  58447. }
  58448. void AlertWindow::lookAndFeelChanged()
  58449. {
  58450. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  58451. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  58452. setDropShadowEnabled (isOpaque() && (flags & ComponentPeer::windowHasDropShadow) != 0);
  58453. }
  58454. int AlertWindow::getDesktopWindowStyleFlags() const
  58455. {
  58456. return getLookAndFeel().getAlertBoxWindowFlags();
  58457. }
  58458. struct AlertWindowInfo
  58459. {
  58460. String title, message, button1, button2, button3;
  58461. AlertWindow::AlertIconType iconType;
  58462. int numButtons;
  58463. Component* associatedComponent;
  58464. int run() const
  58465. {
  58466. return (int) (pointer_sized_int)
  58467. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  58468. }
  58469. private:
  58470. int show() const
  58471. {
  58472. jassert (associatedComponent == 0 || associatedComponent->isValidComponent()); // has your comp been deleted?
  58473. LookAndFeel& lf = associatedComponent->isValidComponent() ? associatedComponent->getLookAndFeel()
  58474. : LookAndFeel::getDefaultLookAndFeel();
  58475. Component* const alertBox = lf.createAlertWindow (title, message, button1, button2, button3,
  58476. iconType, numButtons, associatedComponent);
  58477. jassert (alertBox != 0); // you have to return one of these!
  58478. const int result = alertBox->runModalLoop();
  58479. delete alertBox;
  58480. return result;
  58481. }
  58482. static void* showCallback (void* userData)
  58483. {
  58484. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  58485. }
  58486. };
  58487. void AlertWindow::showMessageBox (AlertIconType iconType,
  58488. const String& title,
  58489. const String& message,
  58490. const String& buttonText,
  58491. Component* associatedComponent)
  58492. {
  58493. AlertWindowInfo info;
  58494. info.title = title;
  58495. info.message = message;
  58496. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  58497. info.iconType = iconType;
  58498. info.numButtons = 1;
  58499. info.associatedComponent = associatedComponent;
  58500. info.run();
  58501. }
  58502. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  58503. const String& title,
  58504. const String& message,
  58505. const String& button1Text,
  58506. const String& button2Text,
  58507. Component* associatedComponent)
  58508. {
  58509. AlertWindowInfo info;
  58510. info.title = title;
  58511. info.message = message;
  58512. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  58513. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  58514. info.iconType = iconType;
  58515. info.numButtons = 2;
  58516. info.associatedComponent = associatedComponent;
  58517. return info.run() != 0;
  58518. }
  58519. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  58520. const String& title,
  58521. const String& message,
  58522. const String& button1Text,
  58523. const String& button2Text,
  58524. const String& button3Text,
  58525. Component* associatedComponent)
  58526. {
  58527. AlertWindowInfo info;
  58528. info.title = title;
  58529. info.message = message;
  58530. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  58531. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  58532. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  58533. info.iconType = iconType;
  58534. info.numButtons = 3;
  58535. info.associatedComponent = associatedComponent;
  58536. return info.run();
  58537. }
  58538. END_JUCE_NAMESPACE
  58539. /********* End of inlined file: juce_AlertWindow.cpp *********/
  58540. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  58541. BEGIN_JUCE_NAMESPACE
  58542. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  58543. // these are over in juce_component.cpp
  58544. extern int64 juce_recentMouseDownTimes[4];
  58545. extern int juce_recentMouseDownX [4];
  58546. extern int juce_recentMouseDownY [4];
  58547. extern Component* juce_recentMouseDownComponent [4];
  58548. extern int juce_LastMousePosX;
  58549. extern int juce_LastMousePosY;
  58550. extern int juce_MouseClickCounter;
  58551. extern bool juce_MouseHasMovedSignificantlySincePressed;
  58552. static const int fakeMouseMoveMessage = 0x7fff00ff;
  58553. static VoidArray heavyweightPeers (4);
  58554. ComponentPeer::ComponentPeer (Component* const component_,
  58555. const int styleFlags_) throw()
  58556. : component (component_),
  58557. styleFlags (styleFlags_),
  58558. lastPaintTime (0),
  58559. constrainer (0),
  58560. lastFocusedComponent (0),
  58561. dragAndDropTargetComponent (0),
  58562. lastDragAndDropCompUnderMouse (0),
  58563. fakeMouseMessageSent (false),
  58564. isWindowMinimised (false)
  58565. {
  58566. heavyweightPeers.add (this);
  58567. }
  58568. ComponentPeer::~ComponentPeer()
  58569. {
  58570. heavyweightPeers.removeValue (this);
  58571. delete dragAndDropTargetComponent;
  58572. Desktop::getInstance().triggerFocusCallback();
  58573. }
  58574. int ComponentPeer::getNumPeers() throw()
  58575. {
  58576. return heavyweightPeers.size();
  58577. }
  58578. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  58579. {
  58580. return (ComponentPeer*) heavyweightPeers [index];
  58581. }
  58582. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  58583. {
  58584. for (int i = heavyweightPeers.size(); --i >= 0;)
  58585. {
  58586. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  58587. if (peer->getComponent() == component)
  58588. return peer;
  58589. }
  58590. return 0;
  58591. }
  58592. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  58593. {
  58594. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  58595. }
  58596. void ComponentPeer::updateCurrentModifiers() throw()
  58597. {
  58598. ModifierKeys::updateCurrentModifiers();
  58599. }
  58600. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  58601. {
  58602. jassert (component->isValidComponent());
  58603. updateCurrentModifiers();
  58604. Component* c = component->getComponentAt (x, y);
  58605. const ComponentDeletionWatcher deletionChecker (component);
  58606. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  58607. {
  58608. jassert (Component::componentUnderMouse->isValidComponent());
  58609. const int oldX = x;
  58610. const int oldY = y;
  58611. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58612. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58613. Component::componentUnderMouse = 0;
  58614. if (deletionChecker.hasBeenDeleted())
  58615. return;
  58616. c = component->getComponentAt (oldX, oldY);
  58617. }
  58618. Component::componentUnderMouse = c;
  58619. if (Component::componentUnderMouse != 0)
  58620. {
  58621. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58622. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58623. }
  58624. }
  58625. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  58626. {
  58627. jassert (component->isValidComponent());
  58628. updateCurrentModifiers();
  58629. fakeMouseMessageSent = false;
  58630. const ComponentDeletionWatcher deletionChecker (component);
  58631. Component* c = component->getComponentAt (x, y);
  58632. if (c != Component::componentUnderMouse)
  58633. {
  58634. const int oldX = x;
  58635. const int oldY = y;
  58636. if (Component::componentUnderMouse != 0)
  58637. {
  58638. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58639. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58640. x = oldX;
  58641. y = oldY;
  58642. Component::componentUnderMouse = 0;
  58643. if (deletionChecker.hasBeenDeleted())
  58644. return; // if this window has just been deleted..
  58645. c = component->getComponentAt (x, y);
  58646. }
  58647. Component::componentUnderMouse = c;
  58648. if (c != 0)
  58649. {
  58650. component->relativePositionToOtherComponent (c, x, y);
  58651. c->internalMouseEnter (x, y, time);
  58652. x = oldX;
  58653. y = oldY;
  58654. if (deletionChecker.hasBeenDeleted())
  58655. return; // if this window has just been deleted..
  58656. }
  58657. }
  58658. if (Component::componentUnderMouse != 0)
  58659. {
  58660. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58661. Component::componentUnderMouse->internalMouseMove (x, y, time);
  58662. }
  58663. }
  58664. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  58665. {
  58666. ++juce_MouseClickCounter;
  58667. updateCurrentModifiers();
  58668. int numMouseButtonsDown = 0;
  58669. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  58670. ++numMouseButtonsDown;
  58671. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  58672. ++numMouseButtonsDown;
  58673. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  58674. ++numMouseButtonsDown;
  58675. if (numMouseButtonsDown == 1)
  58676. {
  58677. Component::componentUnderMouse = component->getComponentAt (x, y);
  58678. if (Component::componentUnderMouse != 0)
  58679. {
  58680. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  58681. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  58682. {
  58683. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  58684. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  58685. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  58686. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  58687. }
  58688. juce_recentMouseDownTimes[0] = time;
  58689. juce_recentMouseDownX[0] = x;
  58690. juce_recentMouseDownY[0] = y;
  58691. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  58692. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  58693. juce_MouseHasMovedSignificantlySincePressed = false;
  58694. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58695. Component::componentUnderMouse->internalMouseDown (x, y);
  58696. }
  58697. }
  58698. }
  58699. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  58700. {
  58701. updateCurrentModifiers();
  58702. if (Component::componentUnderMouse != 0)
  58703. {
  58704. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58705. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  58706. }
  58707. }
  58708. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  58709. {
  58710. updateCurrentModifiers();
  58711. int numMouseButtonsDown = 0;
  58712. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  58713. ++numMouseButtonsDown;
  58714. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  58715. ++numMouseButtonsDown;
  58716. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  58717. ++numMouseButtonsDown;
  58718. if (numMouseButtonsDown == 1)
  58719. {
  58720. const ComponentDeletionWatcher deletionChecker (component);
  58721. Component* c = component->getComponentAt (x, y);
  58722. if (c != Component::componentUnderMouse)
  58723. {
  58724. const int oldX = x;
  58725. const int oldY = y;
  58726. if (Component::componentUnderMouse != 0)
  58727. {
  58728. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58729. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58730. x = oldX;
  58731. y = oldY;
  58732. if (Component::componentUnderMouse != 0)
  58733. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58734. if (deletionChecker.hasBeenDeleted())
  58735. return;
  58736. c = component->getComponentAt (oldX, oldY);
  58737. }
  58738. Component::componentUnderMouse = c;
  58739. if (Component::componentUnderMouse != 0)
  58740. {
  58741. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58742. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58743. }
  58744. }
  58745. else
  58746. {
  58747. if (Component::componentUnderMouse != 0)
  58748. {
  58749. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58750. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58751. }
  58752. }
  58753. }
  58754. }
  58755. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  58756. {
  58757. jassert (component->isValidComponent());
  58758. updateCurrentModifiers();
  58759. if (Component::componentUnderMouse != 0)
  58760. {
  58761. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58762. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58763. Component::componentUnderMouse = 0;
  58764. }
  58765. }
  58766. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  58767. {
  58768. updateCurrentModifiers();
  58769. if (Component::componentUnderMouse != 0)
  58770. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  58771. }
  58772. void ComponentPeer::sendFakeMouseMove() throw()
  58773. {
  58774. if ((! fakeMouseMessageSent)
  58775. && component->flags.hasHeavyweightPeerFlag
  58776. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58777. {
  58778. if (! isMinimised())
  58779. {
  58780. int realX, realY, realW, realH;
  58781. getBounds (realX, realY, realW, realH);
  58782. component->bounds_.setBounds (realX, realY, realW, realH);
  58783. }
  58784. int x, y;
  58785. component->getMouseXYRelative (x, y);
  58786. if (((unsigned int) x) < (unsigned int) component->getWidth()
  58787. && ((unsigned int) y) < (unsigned int) component->getHeight()
  58788. && contains (x, y, false))
  58789. {
  58790. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  58791. }
  58792. fakeMouseMessageSent = true;
  58793. }
  58794. }
  58795. void ComponentPeer::handleMessage (const Message& message)
  58796. {
  58797. if (message.intParameter1 == fakeMouseMoveMessage)
  58798. {
  58799. if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58800. handleMouseMove (message.intParameter2,
  58801. message.intParameter3,
  58802. Time::currentTimeMillis());
  58803. }
  58804. }
  58805. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  58806. {
  58807. Graphics g (&contextToPaintTo);
  58808. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58809. g.saveState();
  58810. #endif
  58811. JUCE_TRY
  58812. {
  58813. component->paintEntireComponent (g);
  58814. }
  58815. JUCE_CATCH_EXCEPTION
  58816. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58817. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  58818. // clearly when things are being repainted.
  58819. {
  58820. g.restoreState();
  58821. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  58822. (uint8) Random::getSystemRandom().nextInt (255),
  58823. (uint8) Random::getSystemRandom().nextInt (255),
  58824. (uint8) 0x50));
  58825. }
  58826. #endif
  58827. }
  58828. bool ComponentPeer::handleKeyPress (const int keyCode,
  58829. const juce_wchar textCharacter)
  58830. {
  58831. updateCurrentModifiers();
  58832. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58833. ? Component::currentlyFocusedComponent
  58834. : component;
  58835. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58836. {
  58837. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58838. if (currentModalComp != 0)
  58839. target = currentModalComp;
  58840. }
  58841. const KeyPress keyInfo (keyCode,
  58842. ModifierKeys::getCurrentModifiers().getRawFlags()
  58843. & ModifierKeys::allKeyboardModifiers,
  58844. textCharacter);
  58845. bool keyWasUsed = false;
  58846. while (target != 0)
  58847. {
  58848. const ComponentDeletionWatcher deletionChecker (target);
  58849. if (target->keyListeners_ != 0)
  58850. {
  58851. for (int i = target->keyListeners_->size(); --i >= 0;)
  58852. {
  58853. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  58854. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58855. return keyWasUsed;
  58856. i = jmin (i, target->keyListeners_->size());
  58857. }
  58858. }
  58859. keyWasUsed = target->keyPressed (keyInfo);
  58860. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58861. break;
  58862. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  58863. {
  58864. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  58865. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  58866. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  58867. break;
  58868. }
  58869. target = target->parentComponent_;
  58870. }
  58871. return keyWasUsed;
  58872. }
  58873. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  58874. {
  58875. updateCurrentModifiers();
  58876. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58877. ? Component::currentlyFocusedComponent
  58878. : component;
  58879. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58880. {
  58881. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58882. if (currentModalComp != 0)
  58883. target = currentModalComp;
  58884. }
  58885. bool keyWasUsed = false;
  58886. while (target != 0)
  58887. {
  58888. const ComponentDeletionWatcher deletionChecker (target);
  58889. keyWasUsed = target->keyStateChanged (isKeyDown);
  58890. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58891. break;
  58892. if (target->keyListeners_ != 0)
  58893. {
  58894. for (int i = target->keyListeners_->size(); --i >= 0;)
  58895. {
  58896. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  58897. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58898. return keyWasUsed;
  58899. i = jmin (i, target->keyListeners_->size());
  58900. }
  58901. }
  58902. target = target->parentComponent_;
  58903. }
  58904. return keyWasUsed;
  58905. }
  58906. void ComponentPeer::handleModifierKeysChange()
  58907. {
  58908. updateCurrentModifiers();
  58909. Component* target = Component::getComponentUnderMouse();
  58910. if (target == 0)
  58911. target = Component::getCurrentlyFocusedComponent();
  58912. if (target == 0)
  58913. target = component;
  58914. if (target->isValidComponent())
  58915. target->internalModifierKeysChanged();
  58916. }
  58917. void ComponentPeer::handleBroughtToFront()
  58918. {
  58919. updateCurrentModifiers();
  58920. if (component != 0)
  58921. component->internalBroughtToFront();
  58922. }
  58923. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  58924. {
  58925. constrainer = newConstrainer;
  58926. }
  58927. void ComponentPeer::handleMovedOrResized()
  58928. {
  58929. jassert (component->isValidComponent());
  58930. updateCurrentModifiers();
  58931. const bool nowMinimised = isMinimised();
  58932. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  58933. {
  58934. const ComponentDeletionWatcher deletionChecker (component);
  58935. int realX, realY, realW, realH;
  58936. getBounds (realX, realY, realW, realH);
  58937. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  58938. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  58939. if (wasMoved || wasResized)
  58940. {
  58941. component->bounds_.setBounds (realX, realY, realW, realH);
  58942. if (wasResized)
  58943. component->repaint();
  58944. component->sendMovedResizedMessages (wasMoved, wasResized);
  58945. if (deletionChecker.hasBeenDeleted())
  58946. return;
  58947. }
  58948. }
  58949. if (isWindowMinimised != nowMinimised)
  58950. {
  58951. isWindowMinimised = nowMinimised;
  58952. component->minimisationStateChanged (nowMinimised);
  58953. component->sendVisibilityChangeMessage();
  58954. }
  58955. if (! isFullScreen())
  58956. lastNonFullscreenBounds = component->getBounds();
  58957. }
  58958. void ComponentPeer::handleFocusGain()
  58959. {
  58960. updateCurrentModifiers();
  58961. if (component->isParentOf (lastFocusedComponent))
  58962. {
  58963. Component::currentlyFocusedComponent = lastFocusedComponent;
  58964. Desktop::getInstance().triggerFocusCallback();
  58965. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  58966. }
  58967. else
  58968. {
  58969. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  58970. component->grabKeyboardFocus();
  58971. else
  58972. Component::bringModalComponentToFront();
  58973. }
  58974. }
  58975. void ComponentPeer::handleFocusLoss()
  58976. {
  58977. updateCurrentModifiers();
  58978. if (component->hasKeyboardFocus (true))
  58979. {
  58980. lastFocusedComponent = Component::currentlyFocusedComponent;
  58981. if (lastFocusedComponent != 0)
  58982. {
  58983. Component::currentlyFocusedComponent = 0;
  58984. Desktop::getInstance().triggerFocusCallback();
  58985. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  58986. }
  58987. }
  58988. }
  58989. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  58990. {
  58991. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  58992. ? lastFocusedComponent
  58993. : component;
  58994. }
  58995. void ComponentPeer::handleScreenSizeChange()
  58996. {
  58997. updateCurrentModifiers();
  58998. component->parentSizeChanged();
  58999. handleMovedOrResized();
  59000. }
  59001. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  59002. {
  59003. lastNonFullscreenBounds = newBounds;
  59004. }
  59005. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  59006. {
  59007. return lastNonFullscreenBounds;
  59008. }
  59009. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  59010. const StringArray& files,
  59011. FileDragAndDropTarget* const lastOne)
  59012. {
  59013. while (c != 0)
  59014. {
  59015. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  59016. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  59017. return t;
  59018. c = c->getParentComponent();
  59019. }
  59020. return 0;
  59021. }
  59022. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  59023. {
  59024. updateCurrentModifiers();
  59025. FileDragAndDropTarget* lastTarget = 0;
  59026. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  59027. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  59028. FileDragAndDropTarget* newTarget = 0;
  59029. Component* const compUnderMouse = component->getComponentAt (x, y);
  59030. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  59031. {
  59032. lastDragAndDropCompUnderMouse = compUnderMouse;
  59033. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  59034. if (newTarget != lastTarget)
  59035. {
  59036. if (lastTarget != 0)
  59037. lastTarget->fileDragExit (files);
  59038. deleteAndZero (dragAndDropTargetComponent);
  59039. if (newTarget != 0)
  59040. {
  59041. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  59042. int mx = x, my = y;
  59043. component->relativePositionToOtherComponent (targetComp, mx, my);
  59044. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  59045. newTarget->fileDragEnter (files, mx, my);
  59046. }
  59047. }
  59048. }
  59049. else
  59050. {
  59051. newTarget = lastTarget;
  59052. }
  59053. if (newTarget != 0)
  59054. {
  59055. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  59056. component->relativePositionToOtherComponent (targetComp, x, y);
  59057. newTarget->fileDragMove (files, x, y);
  59058. }
  59059. }
  59060. void ComponentPeer::handleFileDragExit (const StringArray& files)
  59061. {
  59062. handleFileDragMove (files, -1, -1);
  59063. jassert (dragAndDropTargetComponent == 0);
  59064. lastDragAndDropCompUnderMouse = 0;
  59065. }
  59066. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  59067. {
  59068. handleFileDragMove (files, x, y);
  59069. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  59070. {
  59071. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  59072. deleteAndZero (dragAndDropTargetComponent);
  59073. lastDragAndDropCompUnderMouse = 0;
  59074. if (target != 0)
  59075. {
  59076. Component* const targetComp = dynamic_cast <Component*> (target);
  59077. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  59078. {
  59079. targetComp->internalModalInputAttempt();
  59080. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  59081. return;
  59082. }
  59083. component->relativePositionToOtherComponent (targetComp, x, y);
  59084. target->filesDropped (files, x, y);
  59085. }
  59086. }
  59087. }
  59088. void ComponentPeer::handleUserClosingWindow()
  59089. {
  59090. updateCurrentModifiers();
  59091. component->userTriedToCloseWindow();
  59092. }
  59093. void ComponentPeer::bringModalComponentToFront()
  59094. {
  59095. Component::bringModalComponentToFront();
  59096. }
  59097. void ComponentPeer::clearMaskedRegion() throw()
  59098. {
  59099. maskedRegion.clear();
  59100. }
  59101. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  59102. {
  59103. maskedRegion.add (x, y, w, h);
  59104. }
  59105. END_JUCE_NAMESPACE
  59106. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  59107. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  59108. BEGIN_JUCE_NAMESPACE
  59109. DialogWindow::DialogWindow (const String& name,
  59110. const Colour& backgroundColour_,
  59111. const bool escapeKeyTriggersCloseButton_,
  59112. const bool addToDesktop_)
  59113. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  59114. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  59115. {
  59116. }
  59117. DialogWindow::~DialogWindow()
  59118. {
  59119. }
  59120. void DialogWindow::resized()
  59121. {
  59122. DocumentWindow::resized();
  59123. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  59124. if (escapeKeyTriggersCloseButton
  59125. && getCloseButton() != 0
  59126. && ! getCloseButton()->isRegisteredForShortcut (esc))
  59127. {
  59128. getCloseButton()->addShortcut (esc);
  59129. }
  59130. }
  59131. class TempDialogWindow : public DialogWindow
  59132. {
  59133. public:
  59134. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  59135. : DialogWindow (title, colour, escapeCloses, true)
  59136. {
  59137. }
  59138. ~TempDialogWindow()
  59139. {
  59140. }
  59141. void closeButtonPressed()
  59142. {
  59143. setVisible (false);
  59144. }
  59145. private:
  59146. TempDialogWindow (const TempDialogWindow&);
  59147. const TempDialogWindow& operator= (const TempDialogWindow&);
  59148. };
  59149. int DialogWindow::showModalDialog (const String& dialogTitle,
  59150. Component* contentComponent,
  59151. Component* componentToCentreAround,
  59152. const Colour& colour,
  59153. const bool escapeKeyTriggersCloseButton,
  59154. const bool shouldBeResizable,
  59155. const bool useBottomRightCornerResizer)
  59156. {
  59157. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  59158. dw.setContentComponent (contentComponent, true, true);
  59159. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  59160. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59161. const int result = dw.runModalLoop();
  59162. dw.setContentComponent (0, false);
  59163. return result;
  59164. }
  59165. END_JUCE_NAMESPACE
  59166. /********* End of inlined file: juce_DialogWindow.cpp *********/
  59167. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  59168. BEGIN_JUCE_NAMESPACE
  59169. DocumentWindow::DocumentWindow (const String& title,
  59170. const Colour& backgroundColour,
  59171. const int requiredButtons_,
  59172. const bool addToDesktop_)
  59173. : ResizableWindow (title, backgroundColour, addToDesktop_),
  59174. titleBarHeight (26),
  59175. menuBarHeight (24),
  59176. requiredButtons (requiredButtons_),
  59177. #if JUCE_MAC
  59178. positionTitleBarButtonsOnLeft (true),
  59179. #else
  59180. positionTitleBarButtonsOnLeft (false),
  59181. #endif
  59182. drawTitleTextCentred (true),
  59183. titleBarIcon (0),
  59184. menuBar (0),
  59185. menuBarModel (0)
  59186. {
  59187. zeromem (titleBarButtons, sizeof (titleBarButtons));
  59188. setResizeLimits (128, 128, 32768, 32768);
  59189. lookAndFeelChanged();
  59190. }
  59191. DocumentWindow::~DocumentWindow()
  59192. {
  59193. for (int i = 0; i < 3; ++i)
  59194. delete titleBarButtons[i];
  59195. delete titleBarIcon;
  59196. delete menuBar;
  59197. }
  59198. void DocumentWindow::repaintTitleBar()
  59199. {
  59200. const Rectangle titleBarArea (getTitleBarArea());
  59201. repaint (titleBarArea.getX(), titleBarArea.getY(),
  59202. titleBarArea.getWidth(), titleBarArea.getHeight());
  59203. }
  59204. void DocumentWindow::setName (const String& newName)
  59205. {
  59206. if (newName != getName())
  59207. {
  59208. Component::setName (newName);
  59209. repaintTitleBar();
  59210. }
  59211. }
  59212. void DocumentWindow::setIcon (const Image* imageToUse)
  59213. {
  59214. deleteAndZero (titleBarIcon);
  59215. if (imageToUse != 0)
  59216. titleBarIcon = imageToUse->createCopy();
  59217. repaintTitleBar();
  59218. }
  59219. void DocumentWindow::setTitleBarHeight (const int newHeight)
  59220. {
  59221. titleBarHeight = newHeight;
  59222. resized();
  59223. repaintTitleBar();
  59224. }
  59225. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  59226. const bool positionTitleBarButtonsOnLeft_)
  59227. {
  59228. requiredButtons = requiredButtons_;
  59229. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  59230. lookAndFeelChanged();
  59231. }
  59232. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  59233. {
  59234. drawTitleTextCentred = textShouldBeCentred;
  59235. repaintTitleBar();
  59236. }
  59237. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  59238. const int menuBarHeight_)
  59239. {
  59240. if (menuBarModel != menuBarModel_)
  59241. {
  59242. delete menuBar;
  59243. menuBar = 0;
  59244. menuBarModel = menuBarModel_;
  59245. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  59246. : getLookAndFeel().getDefaultMenuBarHeight();
  59247. if (menuBarModel != 0)
  59248. {
  59249. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59250. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  59251. menuBar->setEnabled (isActiveWindow());
  59252. }
  59253. resized();
  59254. }
  59255. }
  59256. void DocumentWindow::closeButtonPressed()
  59257. {
  59258. /* If you've got a close button, you have to override this method to get
  59259. rid of your window!
  59260. If the window is just a pop-up, you should override this method and make
  59261. it delete the window in whatever way is appropriate for your app. E.g. you
  59262. might just want to call "delete this".
  59263. If your app is centred around this window such that the whole app should quit when
  59264. the window is closed, then you will probably want to use this method as an opportunity
  59265. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  59266. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  59267. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  59268. or closing it via the taskbar icon on Windows).
  59269. */
  59270. jassertfalse
  59271. }
  59272. void DocumentWindow::minimiseButtonPressed()
  59273. {
  59274. setMinimised (true);
  59275. }
  59276. void DocumentWindow::maximiseButtonPressed()
  59277. {
  59278. setFullScreen (! isFullScreen());
  59279. }
  59280. void DocumentWindow::paint (Graphics& g)
  59281. {
  59282. ResizableWindow::paint (g);
  59283. if (resizableBorder == 0)
  59284. {
  59285. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  59286. const BorderSize border (getBorderThickness());
  59287. g.fillRect (0, 0, getWidth(), border.getTop());
  59288. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  59289. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  59290. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  59291. }
  59292. const Rectangle titleBarArea (getTitleBarArea());
  59293. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  59294. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  59295. int titleSpaceX1 = 6;
  59296. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  59297. for (int i = 0; i < 3; ++i)
  59298. {
  59299. if (titleBarButtons[i] != 0)
  59300. {
  59301. if (positionTitleBarButtonsOnLeft)
  59302. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  59303. else
  59304. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  59305. }
  59306. }
  59307. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  59308. titleBarArea.getWidth(),
  59309. titleBarArea.getHeight(),
  59310. titleSpaceX1,
  59311. jmax (1, titleSpaceX2 - titleSpaceX1),
  59312. titleBarIcon,
  59313. ! drawTitleTextCentred);
  59314. }
  59315. void DocumentWindow::resized()
  59316. {
  59317. ResizableWindow::resized();
  59318. if (titleBarButtons[1] != 0)
  59319. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  59320. const Rectangle titleBarArea (getTitleBarArea());
  59321. getLookAndFeel()
  59322. .positionDocumentWindowButtons (*this,
  59323. titleBarArea.getX(), titleBarArea.getY(),
  59324. titleBarArea.getWidth(), titleBarArea.getHeight(),
  59325. titleBarButtons[0],
  59326. titleBarButtons[1],
  59327. titleBarButtons[2],
  59328. positionTitleBarButtonsOnLeft);
  59329. if (menuBar != 0)
  59330. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  59331. titleBarArea.getWidth(), menuBarHeight);
  59332. }
  59333. const BorderSize DocumentWindow::getBorderThickness()
  59334. {
  59335. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  59336. ? 0 : (resizableBorder != 0 ? 4 : 1));
  59337. }
  59338. const BorderSize DocumentWindow::getContentComponentBorder()
  59339. {
  59340. BorderSize border (getBorderThickness());
  59341. border.setTop (border.getTop()
  59342. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  59343. + (menuBar != 0 ? menuBarHeight : 0));
  59344. return border;
  59345. }
  59346. int DocumentWindow::getTitleBarHeight() const
  59347. {
  59348. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  59349. }
  59350. const Rectangle DocumentWindow::getTitleBarArea()
  59351. {
  59352. const BorderSize border (getBorderThickness());
  59353. return Rectangle (border.getLeft(), border.getTop(),
  59354. getWidth() - border.getLeftAndRight(),
  59355. getTitleBarHeight());
  59356. }
  59357. Button* DocumentWindow::getCloseButton() const throw()
  59358. {
  59359. return titleBarButtons[2];
  59360. }
  59361. Button* DocumentWindow::getMinimiseButton() const throw()
  59362. {
  59363. return titleBarButtons[0];
  59364. }
  59365. Button* DocumentWindow::getMaximiseButton() const throw()
  59366. {
  59367. return titleBarButtons[1];
  59368. }
  59369. int DocumentWindow::getDesktopWindowStyleFlags() const
  59370. {
  59371. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  59372. if ((requiredButtons & minimiseButton) != 0)
  59373. flags |= ComponentPeer::windowHasMinimiseButton;
  59374. if ((requiredButtons & maximiseButton) != 0)
  59375. flags |= ComponentPeer::windowHasMaximiseButton;
  59376. if ((requiredButtons & closeButton) != 0)
  59377. flags |= ComponentPeer::windowHasCloseButton;
  59378. return flags;
  59379. }
  59380. void DocumentWindow::lookAndFeelChanged()
  59381. {
  59382. int i;
  59383. for (i = 0; i < 3; ++i)
  59384. deleteAndZero (titleBarButtons[i]);
  59385. if (! isUsingNativeTitleBar())
  59386. {
  59387. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  59388. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  59389. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  59390. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  59391. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  59392. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  59393. for (i = 0; i < 3; ++i)
  59394. {
  59395. if (titleBarButtons[i] != 0)
  59396. {
  59397. buttonListener.owner = this;
  59398. titleBarButtons[i]->addButtonListener (&buttonListener);
  59399. titleBarButtons[i]->setWantsKeyboardFocus (false);
  59400. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59401. Component::addAndMakeVisible (titleBarButtons[i]);
  59402. }
  59403. }
  59404. if (getCloseButton() != 0)
  59405. {
  59406. #if JUCE_MAC
  59407. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  59408. #else
  59409. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  59410. #endif
  59411. }
  59412. }
  59413. activeWindowStatusChanged();
  59414. ResizableWindow::lookAndFeelChanged();
  59415. }
  59416. void DocumentWindow::parentHierarchyChanged()
  59417. {
  59418. lookAndFeelChanged();
  59419. }
  59420. void DocumentWindow::activeWindowStatusChanged()
  59421. {
  59422. ResizableWindow::activeWindowStatusChanged();
  59423. for (int i = 0; i < 3; ++i)
  59424. if (titleBarButtons[i] != 0)
  59425. titleBarButtons[i]->setEnabled (isActiveWindow());
  59426. if (menuBar != 0)
  59427. menuBar->setEnabled (isActiveWindow());
  59428. }
  59429. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  59430. {
  59431. if (getTitleBarArea().contains (e.x, e.y)
  59432. && getMaximiseButton() != 0)
  59433. {
  59434. getMaximiseButton()->triggerClick();
  59435. }
  59436. }
  59437. void DocumentWindow::userTriedToCloseWindow()
  59438. {
  59439. closeButtonPressed();
  59440. }
  59441. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  59442. {
  59443. }
  59444. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  59445. {
  59446. if (button == owner->getMinimiseButton())
  59447. {
  59448. owner->minimiseButtonPressed();
  59449. }
  59450. else if (button == owner->getMaximiseButton())
  59451. {
  59452. owner->maximiseButtonPressed();
  59453. }
  59454. else if (button == owner->getCloseButton())
  59455. {
  59456. owner->closeButtonPressed();
  59457. }
  59458. }
  59459. END_JUCE_NAMESPACE
  59460. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  59461. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  59462. BEGIN_JUCE_NAMESPACE
  59463. ResizableWindow::ResizableWindow (const String& name,
  59464. const bool addToDesktop_)
  59465. : TopLevelWindow (name, addToDesktop_),
  59466. resizableCorner (0),
  59467. resizableBorder (0),
  59468. contentComponent (0),
  59469. resizeToFitContent (false),
  59470. fullscreen (false),
  59471. lastNonFullScreenPos (50, 50, 256, 256),
  59472. constrainer (0)
  59473. #ifdef JUCE_DEBUG
  59474. , hasBeenResized (false)
  59475. #endif
  59476. {
  59477. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59478. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  59479. if (addToDesktop_)
  59480. Component::addToDesktop (getDesktopWindowStyleFlags());
  59481. }
  59482. ResizableWindow::ResizableWindow (const String& name,
  59483. const Colour& backgroundColour_,
  59484. const bool addToDesktop_)
  59485. : TopLevelWindow (name, addToDesktop_),
  59486. resizableCorner (0),
  59487. resizableBorder (0),
  59488. contentComponent (0),
  59489. resizeToFitContent (false),
  59490. fullscreen (false),
  59491. lastNonFullScreenPos (50, 50, 256, 256),
  59492. constrainer (0)
  59493. #ifdef JUCE_DEBUG
  59494. , hasBeenResized (false)
  59495. #endif
  59496. {
  59497. setBackgroundColour (backgroundColour_);
  59498. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59499. if (addToDesktop_)
  59500. Component::addToDesktop (getDesktopWindowStyleFlags());
  59501. }
  59502. ResizableWindow::~ResizableWindow()
  59503. {
  59504. deleteAndZero (resizableCorner);
  59505. deleteAndZero (resizableBorder);
  59506. deleteAndZero (contentComponent);
  59507. // have you been adding your own components directly to this window..? tut tut tut.
  59508. // Read the instructions for using a ResizableWindow!
  59509. jassert (getNumChildComponents() == 0);
  59510. }
  59511. int ResizableWindow::getDesktopWindowStyleFlags() const
  59512. {
  59513. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  59514. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  59515. flags |= ComponentPeer::windowIsResizable;
  59516. return flags;
  59517. }
  59518. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  59519. const bool deleteOldOne,
  59520. const bool resizeToFit)
  59521. {
  59522. resizeToFitContent = resizeToFit;
  59523. if (contentComponent != newContentComponent)
  59524. {
  59525. if (deleteOldOne)
  59526. delete contentComponent;
  59527. else
  59528. removeChildComponent (contentComponent);
  59529. contentComponent = newContentComponent;
  59530. Component::addAndMakeVisible (contentComponent);
  59531. }
  59532. if (resizeToFit)
  59533. childBoundsChanged (contentComponent);
  59534. resized(); // must always be called to position the new content comp
  59535. }
  59536. void ResizableWindow::setContentComponentSize (int width, int height)
  59537. {
  59538. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  59539. const BorderSize border (getContentComponentBorder());
  59540. setSize (width + border.getLeftAndRight(),
  59541. height + border.getTopAndBottom());
  59542. }
  59543. const BorderSize ResizableWindow::getBorderThickness()
  59544. {
  59545. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  59546. }
  59547. const BorderSize ResizableWindow::getContentComponentBorder()
  59548. {
  59549. return getBorderThickness();
  59550. }
  59551. void ResizableWindow::moved()
  59552. {
  59553. updateLastPos();
  59554. }
  59555. void ResizableWindow::visibilityChanged()
  59556. {
  59557. TopLevelWindow::visibilityChanged();
  59558. updateLastPos();
  59559. }
  59560. void ResizableWindow::resized()
  59561. {
  59562. if (resizableBorder != 0)
  59563. {
  59564. resizableBorder->setVisible (! isFullScreen());
  59565. resizableBorder->setBorderThickness (getBorderThickness());
  59566. resizableBorder->setSize (getWidth(), getHeight());
  59567. resizableBorder->toBack();
  59568. }
  59569. if (resizableCorner != 0)
  59570. {
  59571. resizableCorner->setVisible (! isFullScreen());
  59572. const int resizerSize = 18;
  59573. resizableCorner->setBounds (getWidth() - resizerSize,
  59574. getHeight() - resizerSize,
  59575. resizerSize, resizerSize);
  59576. }
  59577. if (contentComponent != 0)
  59578. contentComponent->setBoundsInset (getContentComponentBorder());
  59579. updateLastPos();
  59580. #ifdef JUCE_DEBUG
  59581. hasBeenResized = true;
  59582. #endif
  59583. }
  59584. void ResizableWindow::childBoundsChanged (Component* child)
  59585. {
  59586. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  59587. {
  59588. // not going to look very good if this component has a zero size..
  59589. jassert (child->getWidth() > 0);
  59590. jassert (child->getHeight() > 0);
  59591. const BorderSize borders (getContentComponentBorder());
  59592. setSize (child->getWidth() + borders.getLeftAndRight(),
  59593. child->getHeight() + borders.getTopAndBottom());
  59594. }
  59595. }
  59596. void ResizableWindow::activeWindowStatusChanged()
  59597. {
  59598. const BorderSize borders (getContentComponentBorder());
  59599. repaint (0, 0, getWidth(), borders.getTop());
  59600. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  59601. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  59602. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  59603. }
  59604. void ResizableWindow::setResizable (const bool shouldBeResizable,
  59605. const bool useBottomRightCornerResizer)
  59606. {
  59607. if (shouldBeResizable)
  59608. {
  59609. if (useBottomRightCornerResizer)
  59610. {
  59611. deleteAndZero (resizableBorder);
  59612. if (resizableCorner == 0)
  59613. {
  59614. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  59615. resizableCorner->setAlwaysOnTop (true);
  59616. }
  59617. }
  59618. else
  59619. {
  59620. deleteAndZero (resizableCorner);
  59621. if (resizableBorder == 0)
  59622. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  59623. }
  59624. }
  59625. else
  59626. {
  59627. deleteAndZero (resizableCorner);
  59628. deleteAndZero (resizableBorder);
  59629. }
  59630. if (isUsingNativeTitleBar())
  59631. recreateDesktopWindow();
  59632. childBoundsChanged (contentComponent);
  59633. resized();
  59634. }
  59635. bool ResizableWindow::isResizable() const throw()
  59636. {
  59637. return resizableCorner != 0
  59638. || resizableBorder != 0;
  59639. }
  59640. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  59641. const int newMinimumHeight,
  59642. const int newMaximumWidth,
  59643. const int newMaximumHeight) throw()
  59644. {
  59645. // if you've set up a custom constrainer then these settings won't have any effect..
  59646. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  59647. if (constrainer == 0)
  59648. setConstrainer (&defaultConstrainer);
  59649. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  59650. newMaximumWidth, newMaximumHeight);
  59651. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  59652. }
  59653. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  59654. {
  59655. if (constrainer != newConstrainer)
  59656. {
  59657. constrainer = newConstrainer;
  59658. const bool useBottomRightCornerResizer = resizableCorner != 0;
  59659. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  59660. deleteAndZero (resizableCorner);
  59661. deleteAndZero (resizableBorder);
  59662. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59663. ComponentPeer* const peer = getPeer();
  59664. if (peer != 0)
  59665. peer->setConstrainer (newConstrainer);
  59666. }
  59667. }
  59668. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  59669. {
  59670. if (constrainer != 0)
  59671. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  59672. else
  59673. setBounds (x, y, w, h);
  59674. }
  59675. void ResizableWindow::paint (Graphics& g)
  59676. {
  59677. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  59678. getBorderThickness(), *this);
  59679. if (! isFullScreen())
  59680. {
  59681. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  59682. getBorderThickness(), *this);
  59683. }
  59684. #ifdef JUCE_DEBUG
  59685. /* If this fails, then you've probably written a subclass with a resized()
  59686. callback but forgotten to make it call its parent class's resized() method.
  59687. It's important when you override methods like resized(), moved(),
  59688. etc., that you make sure the base class methods also get called.
  59689. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  59690. because your content should all be inside the content component - and it's the
  59691. content component's resized() method that you should be using to do your
  59692. layout.
  59693. */
  59694. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  59695. #endif
  59696. }
  59697. void ResizableWindow::lookAndFeelChanged()
  59698. {
  59699. resized();
  59700. if (isOnDesktop())
  59701. {
  59702. Component::addToDesktop (getDesktopWindowStyleFlags());
  59703. ComponentPeer* const peer = getPeer();
  59704. if (peer != 0)
  59705. peer->setConstrainer (constrainer);
  59706. }
  59707. }
  59708. const Colour ResizableWindow::getBackgroundColour() const throw()
  59709. {
  59710. return findColour (backgroundColourId, false);
  59711. }
  59712. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  59713. {
  59714. Colour backgroundColour (newColour);
  59715. if (! Desktop::canUseSemiTransparentWindows())
  59716. backgroundColour = newColour.withAlpha (1.0f);
  59717. setColour (backgroundColourId, backgroundColour);
  59718. setOpaque (backgroundColour.isOpaque());
  59719. repaint();
  59720. }
  59721. bool ResizableWindow::isFullScreen() const
  59722. {
  59723. if (isOnDesktop())
  59724. {
  59725. ComponentPeer* const peer = getPeer();
  59726. return peer != 0 && peer->isFullScreen();
  59727. }
  59728. return fullscreen;
  59729. }
  59730. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  59731. {
  59732. if (shouldBeFullScreen != isFullScreen())
  59733. {
  59734. updateLastPos();
  59735. fullscreen = shouldBeFullScreen;
  59736. if (isOnDesktop())
  59737. {
  59738. ComponentPeer* const peer = getPeer();
  59739. if (peer != 0)
  59740. {
  59741. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  59742. const Rectangle lastPos (lastNonFullScreenPos);
  59743. peer->setFullScreen (shouldBeFullScreen);
  59744. if (! shouldBeFullScreen)
  59745. setBounds (lastPos);
  59746. }
  59747. else
  59748. {
  59749. jassertfalse
  59750. }
  59751. }
  59752. else
  59753. {
  59754. if (shouldBeFullScreen)
  59755. setBounds (0, 0, getParentWidth(), getParentHeight());
  59756. else
  59757. setBounds (lastNonFullScreenPos);
  59758. }
  59759. resized();
  59760. }
  59761. }
  59762. bool ResizableWindow::isMinimised() const
  59763. {
  59764. ComponentPeer* const peer = getPeer();
  59765. return (peer != 0) && peer->isMinimised();
  59766. }
  59767. void ResizableWindow::setMinimised (const bool shouldMinimise)
  59768. {
  59769. if (shouldMinimise != isMinimised())
  59770. {
  59771. ComponentPeer* const peer = getPeer();
  59772. if (peer != 0)
  59773. {
  59774. updateLastPos();
  59775. peer->setMinimised (shouldMinimise);
  59776. }
  59777. else
  59778. {
  59779. jassertfalse
  59780. }
  59781. }
  59782. }
  59783. void ResizableWindow::updateLastPos()
  59784. {
  59785. if (isShowing() && ! (isFullScreen() || isMinimised()))
  59786. {
  59787. lastNonFullScreenPos = getBounds();
  59788. }
  59789. }
  59790. void ResizableWindow::parentSizeChanged()
  59791. {
  59792. if (isFullScreen() && getParentComponent() != 0)
  59793. {
  59794. setBounds (0, 0, getParentWidth(), getParentHeight());
  59795. }
  59796. }
  59797. const String ResizableWindow::getWindowStateAsString()
  59798. {
  59799. updateLastPos();
  59800. String s;
  59801. if (isFullScreen())
  59802. s << "fs ";
  59803. s << lastNonFullScreenPos.getX() << T(' ')
  59804. << lastNonFullScreenPos.getY() << T(' ')
  59805. << lastNonFullScreenPos.getWidth() << T(' ')
  59806. << lastNonFullScreenPos.getHeight();
  59807. return s;
  59808. }
  59809. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  59810. {
  59811. StringArray tokens;
  59812. tokens.addTokens (s, false);
  59813. tokens.removeEmptyStrings();
  59814. tokens.trim();
  59815. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  59816. const int n = fs ? 1 : 0;
  59817. if (tokens.size() != 4 + n)
  59818. return false;
  59819. Rectangle r (tokens[n].getIntValue(),
  59820. tokens[n + 1].getIntValue(),
  59821. tokens[n + 2].getIntValue(),
  59822. tokens[n + 3].getIntValue());
  59823. if (r.isEmpty())
  59824. return false;
  59825. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  59826. if (! screen.contains (r))
  59827. {
  59828. r.setSize (jmin (r.getWidth(), screen.getWidth()),
  59829. jmin (r.getHeight(), screen.getHeight()));
  59830. r.setPosition (jlimit (screen.getX(), screen.getRight() - r.getWidth(), r.getX()),
  59831. jlimit (screen.getY(), screen.getBottom() - r.getHeight(), r.getY()));
  59832. }
  59833. lastNonFullScreenPos = r;
  59834. if (isOnDesktop())
  59835. {
  59836. ComponentPeer* const peer = getPeer();
  59837. if (peer != 0)
  59838. peer->setNonFullScreenBounds (r);
  59839. }
  59840. setFullScreen (fs);
  59841. if (! fs)
  59842. setBoundsConstrained (r.getX(),
  59843. r.getY(),
  59844. r.getWidth(),
  59845. r.getHeight());
  59846. return true;
  59847. }
  59848. void ResizableWindow::mouseDown (const MouseEvent&)
  59849. {
  59850. if (! isFullScreen())
  59851. dragger.startDraggingComponent (this, constrainer);
  59852. }
  59853. void ResizableWindow::mouseDrag (const MouseEvent& e)
  59854. {
  59855. if (! isFullScreen())
  59856. dragger.dragComponent (this, e);
  59857. }
  59858. #ifdef JUCE_DEBUG
  59859. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  59860. {
  59861. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59862. manages its child components automatically, and if you add your own it'll cause
  59863. trouble. Instead, use setContentComponent() to give it a component which
  59864. will be automatically resized and kept in the right place - then you can add
  59865. subcomponents to the content comp. See the notes for the ResizableWindow class
  59866. for more info.
  59867. If you really know what you're doing and want to avoid this assertion, just call
  59868. Component::addChildComponent directly.
  59869. */
  59870. jassertfalse
  59871. Component::addChildComponent (child, zOrder);
  59872. }
  59873. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  59874. {
  59875. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59876. manages its child components automatically, and if you add your own it'll cause
  59877. trouble. Instead, use setContentComponent() to give it a component which
  59878. will be automatically resized and kept in the right place - then you can add
  59879. subcomponents to the content comp. See the notes for the ResizableWindow class
  59880. for more info.
  59881. If you really know what you're doing and want to avoid this assertion, just call
  59882. Component::addAndMakeVisible directly.
  59883. */
  59884. jassertfalse
  59885. Component::addAndMakeVisible (child, zOrder);
  59886. }
  59887. #endif
  59888. END_JUCE_NAMESPACE
  59889. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  59890. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  59891. BEGIN_JUCE_NAMESPACE
  59892. SplashScreen::SplashScreen()
  59893. : backgroundImage (0),
  59894. isImageInCache (false)
  59895. {
  59896. setOpaque (true);
  59897. }
  59898. SplashScreen::~SplashScreen()
  59899. {
  59900. if (isImageInCache)
  59901. ImageCache::release (backgroundImage);
  59902. else
  59903. delete backgroundImage;
  59904. }
  59905. void SplashScreen::show (const String& title,
  59906. Image* const backgroundImage_,
  59907. const int minimumTimeToDisplayFor,
  59908. const bool useDropShadow,
  59909. const bool removeOnMouseClick)
  59910. {
  59911. backgroundImage = backgroundImage_;
  59912. jassert (backgroundImage_ != 0);
  59913. if (backgroundImage_ != 0)
  59914. {
  59915. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  59916. setOpaque (! backgroundImage_->hasAlphaChannel());
  59917. show (title,
  59918. backgroundImage_->getWidth(),
  59919. backgroundImage_->getHeight(),
  59920. minimumTimeToDisplayFor,
  59921. useDropShadow,
  59922. removeOnMouseClick);
  59923. }
  59924. }
  59925. void SplashScreen::show (const String& title,
  59926. const int width,
  59927. const int height,
  59928. const int minimumTimeToDisplayFor,
  59929. const bool useDropShadow,
  59930. const bool removeOnMouseClick)
  59931. {
  59932. setName (title);
  59933. setAlwaysOnTop (true);
  59934. setVisible (true);
  59935. centreWithSize (width, height);
  59936. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  59937. toFront (false);
  59938. MessageManager::getInstance()->runDispatchLoopUntil (300);
  59939. repaint();
  59940. originalClickCounter = removeOnMouseClick
  59941. ? Desktop::getMouseButtonClickCounter()
  59942. : INT_MAX;
  59943. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  59944. startTimer (50);
  59945. }
  59946. void SplashScreen::paint (Graphics& g)
  59947. {
  59948. if (backgroundImage != 0)
  59949. {
  59950. g.setOpacity (1.0f);
  59951. g.drawImage (backgroundImage,
  59952. 0, 0, getWidth(), getHeight(),
  59953. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  59954. }
  59955. }
  59956. void SplashScreen::timerCallback()
  59957. {
  59958. if (Time::getCurrentTime() > earliestTimeToDelete
  59959. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  59960. {
  59961. delete this;
  59962. }
  59963. }
  59964. END_JUCE_NAMESPACE
  59965. /********* End of inlined file: juce_SplashScreen.cpp *********/
  59966. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59967. BEGIN_JUCE_NAMESPACE
  59968. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  59969. const bool hasProgressBar,
  59970. const bool hasCancelButton,
  59971. const int timeOutMsWhenCancelling_,
  59972. const String& cancelButtonText)
  59973. : Thread ("Juce Progress Window"),
  59974. progress (0.0),
  59975. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  59976. {
  59977. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  59978. .createAlertWindow (title, String::empty, cancelButtonText,
  59979. String::empty, String::empty,
  59980. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  59981. if (hasProgressBar)
  59982. alertWindow->addProgressBarComponent (progress);
  59983. }
  59984. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  59985. {
  59986. stopThread (timeOutMsWhenCancelling);
  59987. delete alertWindow;
  59988. }
  59989. bool ThreadWithProgressWindow::runThread (const int priority)
  59990. {
  59991. startThread (priority);
  59992. startTimer (100);
  59993. {
  59994. const ScopedLock sl (messageLock);
  59995. alertWindow->setMessage (message);
  59996. }
  59997. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  59998. stopThread (timeOutMsWhenCancelling);
  59999. alertWindow->setVisible (false);
  60000. return finishedNaturally;
  60001. }
  60002. void ThreadWithProgressWindow::setProgress (const double newProgress)
  60003. {
  60004. progress = newProgress;
  60005. }
  60006. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  60007. {
  60008. const ScopedLock sl (messageLock);
  60009. message = newStatusMessage;
  60010. }
  60011. void ThreadWithProgressWindow::timerCallback()
  60012. {
  60013. if (! isThreadRunning())
  60014. {
  60015. // thread has finished normally..
  60016. alertWindow->exitModalState (1);
  60017. alertWindow->setVisible (false);
  60018. }
  60019. else
  60020. {
  60021. const ScopedLock sl (messageLock);
  60022. alertWindow->setMessage (message);
  60023. }
  60024. }
  60025. END_JUCE_NAMESPACE
  60026. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  60027. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  60028. BEGIN_JUCE_NAMESPACE
  60029. TooltipWindow::TooltipWindow (Component* const parentComponent,
  60030. const int millisecondsBeforeTipAppears_)
  60031. : Component ("tooltip"),
  60032. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  60033. mouseX (0),
  60034. mouseY (0),
  60035. lastHideTime (0),
  60036. lastComponentUnderMouse (0),
  60037. changedCompsSinceShown (true)
  60038. {
  60039. startTimer (123);
  60040. setAlwaysOnTop (true);
  60041. setOpaque (true);
  60042. if (parentComponent != 0)
  60043. parentComponent->addChildComponent (this);
  60044. }
  60045. TooltipWindow::~TooltipWindow()
  60046. {
  60047. hide();
  60048. }
  60049. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  60050. {
  60051. millisecondsBeforeTipAppears = newTimeMs;
  60052. }
  60053. void TooltipWindow::paint (Graphics& g)
  60054. {
  60055. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  60056. }
  60057. void TooltipWindow::mouseEnter (const MouseEvent&)
  60058. {
  60059. hide();
  60060. }
  60061. void TooltipWindow::showFor (Component* const c, const String& tip)
  60062. {
  60063. jassert (tip.isNotEmpty());
  60064. tipShowing = tip;
  60065. int mx, my;
  60066. Desktop::getMousePosition (mx, my);
  60067. if (getParentComponent() != 0)
  60068. getParentComponent()->globalPositionToRelative (mx, my);
  60069. int x, y, w, h;
  60070. getLookAndFeel().getTooltipSize (tip, w, h);
  60071. if (mx > getParentWidth() / 2)
  60072. x = mx - (w + 12);
  60073. else
  60074. x = mx + 24;
  60075. if (my > getParentHeight() / 2)
  60076. y = my - (h + 6);
  60077. else
  60078. y = my + 6;
  60079. setBounds (x, y, w, h);
  60080. setVisible (true);
  60081. if (getParentComponent() == 0)
  60082. {
  60083. addToDesktop (ComponentPeer::windowHasDropShadow
  60084. | ComponentPeer::windowIsTemporary
  60085. | ComponentPeer::windowIgnoresKeyPresses);
  60086. }
  60087. toFront (false);
  60088. }
  60089. const String TooltipWindow::getTipFor (Component* const c)
  60090. {
  60091. if (c->isValidComponent()
  60092. && Process::isForegroundProcess()
  60093. && ! Component::isMouseButtonDownAnywhere())
  60094. {
  60095. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  60096. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  60097. return ttc->getTooltip();
  60098. }
  60099. return String::empty;
  60100. }
  60101. void TooltipWindow::hide()
  60102. {
  60103. tipShowing = String::empty;
  60104. removeFromDesktop();
  60105. setVisible (false);
  60106. }
  60107. void TooltipWindow::timerCallback()
  60108. {
  60109. const unsigned int now = Time::getApproximateMillisecondCounter();
  60110. Component* const newComp = Component::getComponentUnderMouse();
  60111. const String newTip (getTipFor (newComp));
  60112. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  60113. lastComponentUnderMouse = newComp;
  60114. lastTipUnderMouse = newTip;
  60115. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  60116. const bool mouseWasClicked = clickCount > mouseClicks;
  60117. mouseClicks = clickCount;
  60118. int mx, my;
  60119. Desktop::getMousePosition (mx, my);
  60120. const bool mouseMovedQuickly = (abs (mx - mouseX) + abs (my - mouseY) > 12);
  60121. mouseX = mx;
  60122. mouseY = my;
  60123. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  60124. lastCompChangeTime = now;
  60125. if (isVisible() || now < lastHideTime + 500)
  60126. {
  60127. // if a tip is currently visible (or has just disappeared), update to a new one
  60128. // immediately if needed..
  60129. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  60130. {
  60131. if (isVisible())
  60132. {
  60133. lastHideTime = now;
  60134. hide();
  60135. }
  60136. }
  60137. else if (tipChanged)
  60138. {
  60139. showFor (newComp, newTip);
  60140. }
  60141. }
  60142. else
  60143. {
  60144. // if there isn't currently a tip, but one is needed, only let it
  60145. // appear after a timeout..
  60146. if (newTip.isNotEmpty()
  60147. && newTip != tipShowing
  60148. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  60149. {
  60150. showFor (newComp, newTip);
  60151. }
  60152. }
  60153. }
  60154. END_JUCE_NAMESPACE
  60155. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  60156. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  60157. BEGIN_JUCE_NAMESPACE
  60158. /** Keeps track of the active top level window.
  60159. */
  60160. class TopLevelWindowManager : public Timer,
  60161. public DeletedAtShutdown
  60162. {
  60163. public:
  60164. TopLevelWindowManager()
  60165. : windows (8),
  60166. currentActive (0)
  60167. {
  60168. }
  60169. ~TopLevelWindowManager()
  60170. {
  60171. clearSingletonInstance();
  60172. }
  60173. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  60174. void timerCallback()
  60175. {
  60176. startTimer (jmin (1731, getTimerInterval() * 2));
  60177. TopLevelWindow* active = 0;
  60178. if (Process::isForegroundProcess())
  60179. {
  60180. active = currentActive;
  60181. Component* const c = Component::getCurrentlyFocusedComponent();
  60182. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  60183. if (tlw == 0 && c != 0)
  60184. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  60185. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  60186. if (tlw != 0)
  60187. active = tlw;
  60188. }
  60189. if (active != currentActive)
  60190. {
  60191. currentActive = active;
  60192. for (int i = windows.size(); --i >= 0;)
  60193. {
  60194. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  60195. tlw->setWindowActive (isWindowActive (tlw));
  60196. i = jmin (i, windows.size() - 1);
  60197. }
  60198. Desktop::getInstance().triggerFocusCallback();
  60199. }
  60200. }
  60201. bool addWindow (TopLevelWindow* const w) throw()
  60202. {
  60203. windows.add (w);
  60204. startTimer (10);
  60205. return isWindowActive (w);
  60206. }
  60207. void removeWindow (TopLevelWindow* const w) throw()
  60208. {
  60209. startTimer (10);
  60210. if (currentActive == w)
  60211. currentActive = 0;
  60212. windows.removeValue (w);
  60213. if (windows.size() == 0)
  60214. deleteInstance();
  60215. }
  60216. VoidArray windows;
  60217. private:
  60218. TopLevelWindow* currentActive;
  60219. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  60220. {
  60221. return (tlw == currentActive
  60222. || tlw->isParentOf (currentActive)
  60223. || tlw->hasKeyboardFocus (true))
  60224. && tlw->isShowing();
  60225. }
  60226. TopLevelWindowManager (const TopLevelWindowManager&);
  60227. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  60228. };
  60229. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  60230. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  60231. {
  60232. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  60233. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  60234. }
  60235. TopLevelWindow::TopLevelWindow (const String& name,
  60236. const bool addToDesktop_)
  60237. : Component (name),
  60238. useDropShadow (true),
  60239. useNativeTitleBar (false),
  60240. windowIsActive_ (false),
  60241. shadower (0)
  60242. {
  60243. setOpaque (true);
  60244. if (addToDesktop_)
  60245. Component::addToDesktop (getDesktopWindowStyleFlags());
  60246. else
  60247. setDropShadowEnabled (true);
  60248. setWantsKeyboardFocus (true);
  60249. setBroughtToFrontOnMouseClick (true);
  60250. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  60251. }
  60252. TopLevelWindow::~TopLevelWindow()
  60253. {
  60254. deleteAndZero (shadower);
  60255. TopLevelWindowManager::getInstance()->removeWindow (this);
  60256. }
  60257. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  60258. {
  60259. if (hasKeyboardFocus (true))
  60260. TopLevelWindowManager::getInstance()->timerCallback();
  60261. else
  60262. TopLevelWindowManager::getInstance()->startTimer (10);
  60263. }
  60264. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  60265. {
  60266. if (windowIsActive_ != isNowActive)
  60267. {
  60268. windowIsActive_ = isNowActive;
  60269. activeWindowStatusChanged();
  60270. }
  60271. }
  60272. void TopLevelWindow::activeWindowStatusChanged()
  60273. {
  60274. }
  60275. void TopLevelWindow::parentHierarchyChanged()
  60276. {
  60277. setDropShadowEnabled (useDropShadow);
  60278. }
  60279. void TopLevelWindow::visibilityChanged()
  60280. {
  60281. if (isShowing())
  60282. toFront (true);
  60283. }
  60284. int TopLevelWindow::getDesktopWindowStyleFlags() const
  60285. {
  60286. int flags = ComponentPeer::windowAppearsOnTaskbar;
  60287. if (useDropShadow)
  60288. flags |= ComponentPeer::windowHasDropShadow;
  60289. if (useNativeTitleBar)
  60290. flags |= ComponentPeer::windowHasTitleBar;
  60291. return flags;
  60292. }
  60293. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  60294. {
  60295. useDropShadow = useShadow;
  60296. if (isOnDesktop())
  60297. {
  60298. deleteAndZero (shadower);
  60299. Component::addToDesktop (getDesktopWindowStyleFlags());
  60300. }
  60301. else
  60302. {
  60303. if (useShadow && isOpaque())
  60304. {
  60305. if (shadower == 0)
  60306. {
  60307. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  60308. if (shadower != 0)
  60309. shadower->setOwner (this);
  60310. }
  60311. }
  60312. else
  60313. {
  60314. deleteAndZero (shadower);
  60315. }
  60316. }
  60317. }
  60318. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  60319. {
  60320. if (useNativeTitleBar != useNativeTitleBar_)
  60321. {
  60322. useNativeTitleBar = useNativeTitleBar_;
  60323. recreateDesktopWindow();
  60324. sendLookAndFeelChange();
  60325. }
  60326. }
  60327. void TopLevelWindow::recreateDesktopWindow()
  60328. {
  60329. if (isOnDesktop())
  60330. {
  60331. Component::addToDesktop (getDesktopWindowStyleFlags());
  60332. toFront (true);
  60333. }
  60334. }
  60335. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  60336. {
  60337. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  60338. because this class needs to make sure its layout corresponds with settings like whether
  60339. it's got a native title bar or not.
  60340. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  60341. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  60342. method, then add or remove whatever flags are necessary from this value before returning it.
  60343. */
  60344. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  60345. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  60346. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  60347. if (windowStyleFlags != getDesktopWindowStyleFlags())
  60348. sendLookAndFeelChange();
  60349. }
  60350. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  60351. {
  60352. if (c == 0)
  60353. c = TopLevelWindow::getActiveTopLevelWindow();
  60354. if (c == 0)
  60355. {
  60356. centreWithSize (width, height);
  60357. }
  60358. else
  60359. {
  60360. int x = (c->getWidth() - width) / 2;
  60361. int y = (c->getHeight() - height) / 2;
  60362. c->relativePositionToGlobal (x, y);
  60363. Rectangle parentArea (c->getParentMonitorArea());
  60364. if (getParentComponent() != 0)
  60365. {
  60366. getParentComponent()->globalPositionToRelative (x, y);
  60367. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  60368. }
  60369. parentArea.reduce (12, 12);
  60370. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  60371. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  60372. width, height);
  60373. }
  60374. }
  60375. int TopLevelWindow::getNumTopLevelWindows() throw()
  60376. {
  60377. return TopLevelWindowManager::getInstance()->windows.size();
  60378. }
  60379. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  60380. {
  60381. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  60382. }
  60383. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  60384. {
  60385. TopLevelWindow* best = 0;
  60386. int bestNumTWLParents = -1;
  60387. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  60388. {
  60389. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  60390. if (tlw->isActiveWindow())
  60391. {
  60392. int numTWLParents = 0;
  60393. const Component* c = tlw->getParentComponent();
  60394. while (c != 0)
  60395. {
  60396. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  60397. ++numTWLParents;
  60398. c = c->getParentComponent();
  60399. }
  60400. if (bestNumTWLParents < numTWLParents)
  60401. {
  60402. best = tlw;
  60403. bestNumTWLParents = numTWLParents;
  60404. }
  60405. }
  60406. }
  60407. return best;
  60408. }
  60409. END_JUCE_NAMESPACE
  60410. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  60411. /********* Start of inlined file: juce_Brush.cpp *********/
  60412. BEGIN_JUCE_NAMESPACE
  60413. Brush::Brush() throw()
  60414. {
  60415. }
  60416. Brush::~Brush() throw()
  60417. {
  60418. }
  60419. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  60420. int x, float y1, float y2) throw()
  60421. {
  60422. Path p;
  60423. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  60424. paintPath (context, p, AffineTransform::identity);
  60425. }
  60426. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60427. int y, float x1, float x2) throw()
  60428. {
  60429. Path p;
  60430. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  60431. paintPath (context, p, AffineTransform::identity);
  60432. }
  60433. void Brush::paintLine (LowLevelGraphicsContext& context,
  60434. float x1, float y1, float x2, float y2) throw()
  60435. {
  60436. Path p;
  60437. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  60438. paintPath (context, p, AffineTransform::identity);
  60439. }
  60440. END_JUCE_NAMESPACE
  60441. /********* End of inlined file: juce_Brush.cpp *********/
  60442. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  60443. BEGIN_JUCE_NAMESPACE
  60444. GradientBrush::GradientBrush (const Colour& colour1,
  60445. const float x1,
  60446. const float y1,
  60447. const Colour& colour2,
  60448. const float x2,
  60449. const float y2,
  60450. const bool isRadial) throw()
  60451. : gradient (colour1, x1, y1,
  60452. colour2, x2, y2,
  60453. isRadial)
  60454. {
  60455. }
  60456. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  60457. : gradient (gradient_)
  60458. {
  60459. }
  60460. GradientBrush::~GradientBrush() throw()
  60461. {
  60462. }
  60463. Brush* GradientBrush::createCopy() const throw()
  60464. {
  60465. return new GradientBrush (gradient);
  60466. }
  60467. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  60468. {
  60469. gradient.transform = gradient.transform.followedBy (transform);
  60470. }
  60471. void GradientBrush::multiplyOpacity (const float multiple) throw()
  60472. {
  60473. gradient.multiplyOpacity (multiple);
  60474. }
  60475. bool GradientBrush::isInvisible() const throw()
  60476. {
  60477. return gradient.isInvisible();
  60478. }
  60479. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  60480. const Path& path, const AffineTransform& transform) throw()
  60481. {
  60482. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  60483. }
  60484. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  60485. int x, int y, int w, int h) throw()
  60486. {
  60487. context.fillRectWithGradient (x, y, w, h, gradient);
  60488. }
  60489. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60490. const Image& alphaChannelImage, int imageX, int imageY,
  60491. int x, int y, int w, int h) throw()
  60492. {
  60493. context.saveState();
  60494. if (context.reduceClipRegion (x, y, w, h))
  60495. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  60496. context.restoreState();
  60497. }
  60498. END_JUCE_NAMESPACE
  60499. /********* End of inlined file: juce_GradientBrush.cpp *********/
  60500. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  60501. BEGIN_JUCE_NAMESPACE
  60502. ImageBrush::ImageBrush (Image* const image_,
  60503. const int anchorX_,
  60504. const int anchorY_,
  60505. const float opacity_) throw()
  60506. : image (image_),
  60507. anchorX (anchorX_),
  60508. anchorY (anchorY_),
  60509. opacity (opacity_)
  60510. {
  60511. jassert (image != 0); // not much point creating a brush without an image, is there?
  60512. if (image != 0)
  60513. {
  60514. if (image->getWidth() == 0 || image->getHeight() == 0)
  60515. {
  60516. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  60517. image = 0;
  60518. }
  60519. }
  60520. }
  60521. ImageBrush::~ImageBrush() throw()
  60522. {
  60523. }
  60524. Brush* ImageBrush::createCopy() const throw()
  60525. {
  60526. return new ImageBrush (image, anchorX, anchorY, opacity);
  60527. }
  60528. void ImageBrush::multiplyOpacity (const float multiple) throw()
  60529. {
  60530. opacity *= multiple;
  60531. }
  60532. bool ImageBrush::isInvisible() const throw()
  60533. {
  60534. return opacity == 0.0f;
  60535. }
  60536. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60537. {
  60538. //xxx should probably be smarter and warp the image
  60539. }
  60540. void ImageBrush::getStartXY (int& x, int& y) const throw()
  60541. {
  60542. x -= anchorX;
  60543. y -= anchorY;
  60544. const int iw = image->getWidth();
  60545. const int ih = image->getHeight();
  60546. if (x < 0)
  60547. x = ((x / iw) - 1) * iw;
  60548. else
  60549. x = (x / iw) * iw;
  60550. if (y < 0)
  60551. y = ((y / ih) - 1) * ih;
  60552. else
  60553. y = (y / ih) * ih;
  60554. x += anchorX;
  60555. y += anchorY;
  60556. }
  60557. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  60558. int x, int y, int w, int h) throw()
  60559. {
  60560. context.saveState();
  60561. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60562. {
  60563. const int right = x + w;
  60564. const int bottom = y + h;
  60565. const int iw = image->getWidth();
  60566. const int ih = image->getHeight();
  60567. int startX = x;
  60568. getStartXY (startX, y);
  60569. while (y < bottom)
  60570. {
  60571. x = startX;
  60572. while (x < right)
  60573. {
  60574. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  60575. x += iw;
  60576. }
  60577. y += ih;
  60578. }
  60579. }
  60580. context.restoreState();
  60581. }
  60582. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  60583. const Path& path, const AffineTransform& transform) throw()
  60584. {
  60585. if (image != 0)
  60586. {
  60587. Rectangle clip (context.getClipBounds());
  60588. {
  60589. float x, y, w, h;
  60590. path.getBoundsTransformed (transform, x, y, w, h);
  60591. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  60592. (int) floorf (y),
  60593. 2 + (int) floorf (w),
  60594. 2 + (int) floorf (h)));
  60595. }
  60596. int x = clip.getX();
  60597. int y = clip.getY();
  60598. const int right = clip.getRight();
  60599. const int bottom = clip.getBottom();
  60600. const int iw = image->getWidth();
  60601. const int ih = image->getHeight();
  60602. int startX = x;
  60603. getStartXY (startX, y);
  60604. while (y < bottom)
  60605. {
  60606. x = startX;
  60607. while (x < right)
  60608. {
  60609. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  60610. x += iw;
  60611. }
  60612. y += ih;
  60613. }
  60614. }
  60615. }
  60616. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60617. const Image& alphaChannelImage, int imageX, int imageY,
  60618. int x, int y, int w, int h) throw()
  60619. {
  60620. context.saveState();
  60621. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60622. {
  60623. const Rectangle clip (context.getClipBounds());
  60624. x = clip.getX();
  60625. y = clip.getY();
  60626. const int right = clip.getRight();
  60627. const int bottom = clip.getBottom();
  60628. const int iw = image->getWidth();
  60629. const int ih = image->getHeight();
  60630. int startX = x;
  60631. getStartXY (startX, y);
  60632. while (y < bottom)
  60633. {
  60634. x = startX;
  60635. while (x < right)
  60636. {
  60637. context.fillAlphaChannelWithImage (alphaChannelImage,
  60638. imageX, imageY, *image,
  60639. x, y, opacity);
  60640. x += iw;
  60641. }
  60642. y += ih;
  60643. }
  60644. }
  60645. context.restoreState();
  60646. }
  60647. END_JUCE_NAMESPACE
  60648. /********* End of inlined file: juce_ImageBrush.cpp *********/
  60649. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  60650. BEGIN_JUCE_NAMESPACE
  60651. SolidColourBrush::SolidColourBrush() throw()
  60652. : colour (0xff000000)
  60653. {
  60654. }
  60655. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  60656. : colour (colour_)
  60657. {
  60658. }
  60659. SolidColourBrush::~SolidColourBrush() throw()
  60660. {
  60661. }
  60662. Brush* SolidColourBrush::createCopy() const throw()
  60663. {
  60664. return new SolidColourBrush (colour);
  60665. }
  60666. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60667. {
  60668. }
  60669. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  60670. {
  60671. colour = colour.withMultipliedAlpha (multiple);
  60672. }
  60673. bool SolidColourBrush::isInvisible() const throw()
  60674. {
  60675. return colour.isTransparent();
  60676. }
  60677. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  60678. const Path& path, const AffineTransform& transform) throw()
  60679. {
  60680. if (! colour.isTransparent())
  60681. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  60682. }
  60683. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  60684. int x, int y, int w, int h) throw()
  60685. {
  60686. if (! colour.isTransparent())
  60687. context.fillRectWithColour (x, y, w, h, colour, false);
  60688. }
  60689. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60690. const Image& alphaChannelImage, int imageX, int imageY,
  60691. int x, int y, int w, int h) throw()
  60692. {
  60693. if (! colour.isTransparent())
  60694. {
  60695. context.saveState();
  60696. if (context.reduceClipRegion (x, y, w, h))
  60697. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  60698. context.restoreState();
  60699. }
  60700. }
  60701. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  60702. int x, float y1, float y2) throw()
  60703. {
  60704. context.drawVerticalLine (x, y1, y2, colour);
  60705. }
  60706. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60707. int y, float x1, float x2) throw()
  60708. {
  60709. context.drawHorizontalLine (y, x1, x2, colour);
  60710. }
  60711. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  60712. float x1, float y1, float x2, float y2) throw()
  60713. {
  60714. context.drawLine (x1, y1, x2, y2, colour);
  60715. }
  60716. END_JUCE_NAMESPACE
  60717. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  60718. /********* Start of inlined file: juce_Colour.cpp *********/
  60719. BEGIN_JUCE_NAMESPACE
  60720. static forcedinline uint8 floatAlphaToInt (const float alpha)
  60721. {
  60722. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  60723. }
  60724. static const float oneOver255 = 1.0f / 255.0f;
  60725. Colour::Colour() throw()
  60726. : argb (0)
  60727. {
  60728. }
  60729. Colour::Colour (const Colour& other) throw()
  60730. : argb (other.argb)
  60731. {
  60732. }
  60733. const Colour& Colour::operator= (const Colour& other) throw()
  60734. {
  60735. argb = other.argb;
  60736. return *this;
  60737. }
  60738. bool Colour::operator== (const Colour& other) const throw()
  60739. {
  60740. return argb.getARGB() == other.argb.getARGB();
  60741. }
  60742. bool Colour::operator!= (const Colour& other) const throw()
  60743. {
  60744. return argb.getARGB() != other.argb.getARGB();
  60745. }
  60746. Colour::Colour (const uint32 argb_) throw()
  60747. : argb (argb_)
  60748. {
  60749. }
  60750. Colour::Colour (const uint8 red,
  60751. const uint8 green,
  60752. const uint8 blue) throw()
  60753. {
  60754. argb.setARGB (0xff, red, green, blue);
  60755. }
  60756. const Colour Colour::fromRGB (const uint8 red,
  60757. const uint8 green,
  60758. const uint8 blue) throw()
  60759. {
  60760. return Colour (red, green, blue);
  60761. }
  60762. Colour::Colour (const uint8 red,
  60763. const uint8 green,
  60764. const uint8 blue,
  60765. const uint8 alpha) throw()
  60766. {
  60767. argb.setARGB (alpha, red, green, blue);
  60768. }
  60769. const Colour Colour::fromRGBA (const uint8 red,
  60770. const uint8 green,
  60771. const uint8 blue,
  60772. const uint8 alpha) throw()
  60773. {
  60774. return Colour (red, green, blue, alpha);
  60775. }
  60776. Colour::Colour (const uint8 red,
  60777. const uint8 green,
  60778. const uint8 blue,
  60779. const float alpha) throw()
  60780. {
  60781. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  60782. }
  60783. const Colour Colour::fromRGBAFloat (const uint8 red,
  60784. const uint8 green,
  60785. const uint8 blue,
  60786. const float alpha) throw()
  60787. {
  60788. return Colour (red, green, blue, alpha);
  60789. }
  60790. static void convertHSBtoRGB (float h, float s, float v,
  60791. uint8& r, uint8& g, uint8& b) throw()
  60792. {
  60793. v = jlimit (0.0f, 1.0f, v);
  60794. v *= 255.0f;
  60795. const uint8 intV = (uint8) roundFloatToInt (v);
  60796. if (s <= 0)
  60797. {
  60798. r = intV;
  60799. g = intV;
  60800. b = intV;
  60801. }
  60802. else
  60803. {
  60804. s = jmin (1.0f, s);
  60805. h = jlimit (0.0f, 1.0f, h);
  60806. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  60807. const float f = h - floorf (h);
  60808. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  60809. const float y = v * (1.0f - s * f);
  60810. const float z = v * (1.0f - (s * (1.0f - f)));
  60811. if (h < 1.0f)
  60812. {
  60813. r = intV;
  60814. g = (uint8) roundFloatToInt (z);
  60815. b = x;
  60816. }
  60817. else if (h < 2.0f)
  60818. {
  60819. r = (uint8) roundFloatToInt (y);
  60820. g = intV;
  60821. b = x;
  60822. }
  60823. else if (h < 3.0f)
  60824. {
  60825. r = x;
  60826. g = intV;
  60827. b = (uint8) roundFloatToInt (z);
  60828. }
  60829. else if (h < 4.0f)
  60830. {
  60831. r = x;
  60832. g = (uint8) roundFloatToInt (y);
  60833. b = intV;
  60834. }
  60835. else if (h < 5.0f)
  60836. {
  60837. r = (uint8) roundFloatToInt (z);
  60838. g = x;
  60839. b = intV;
  60840. }
  60841. else if (h < 6.0f)
  60842. {
  60843. r = intV;
  60844. g = x;
  60845. b = (uint8) roundFloatToInt (y);
  60846. }
  60847. else
  60848. {
  60849. r = 0;
  60850. g = 0;
  60851. b = 0;
  60852. }
  60853. }
  60854. }
  60855. Colour::Colour (const float hue,
  60856. const float saturation,
  60857. const float brightness,
  60858. const float alpha) throw()
  60859. {
  60860. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60861. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60862. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  60863. }
  60864. const Colour Colour::fromHSV (const float hue,
  60865. const float saturation,
  60866. const float brightness,
  60867. const float alpha) throw()
  60868. {
  60869. return Colour (hue, saturation, brightness, alpha);
  60870. }
  60871. Colour::Colour (const float hue,
  60872. const float saturation,
  60873. const float brightness,
  60874. const uint8 alpha) throw()
  60875. {
  60876. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60877. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60878. argb.setARGB (alpha, r, g, b);
  60879. }
  60880. Colour::~Colour() throw()
  60881. {
  60882. }
  60883. const PixelARGB Colour::getPixelARGB() const throw()
  60884. {
  60885. PixelARGB p (argb);
  60886. p.premultiply();
  60887. return p;
  60888. }
  60889. uint32 Colour::getARGB() const throw()
  60890. {
  60891. return argb.getARGB();
  60892. }
  60893. bool Colour::isTransparent() const throw()
  60894. {
  60895. return getAlpha() == 0;
  60896. }
  60897. bool Colour::isOpaque() const throw()
  60898. {
  60899. return getAlpha() == 0xff;
  60900. }
  60901. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  60902. {
  60903. PixelARGB newCol (argb);
  60904. newCol.setAlpha (newAlpha);
  60905. return Colour (newCol.getARGB());
  60906. }
  60907. const Colour Colour::withAlpha (const float newAlpha) const throw()
  60908. {
  60909. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  60910. PixelARGB newCol (argb);
  60911. newCol.setAlpha (floatAlphaToInt (newAlpha));
  60912. return Colour (newCol.getARGB());
  60913. }
  60914. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  60915. {
  60916. jassert (alphaMultiplier >= 0);
  60917. PixelARGB newCol (argb);
  60918. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  60919. return Colour (newCol.getARGB());
  60920. }
  60921. const Colour Colour::overlaidWith (const Colour& src) const throw()
  60922. {
  60923. const int destAlpha = getAlpha();
  60924. if (destAlpha > 0)
  60925. {
  60926. const int invA = 0xff - (int) src.getAlpha();
  60927. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  60928. if (resA > 0)
  60929. {
  60930. const int da = (invA * destAlpha) / resA;
  60931. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  60932. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  60933. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  60934. (uint8) resA);
  60935. }
  60936. return *this;
  60937. }
  60938. else
  60939. {
  60940. return src;
  60941. }
  60942. }
  60943. float Colour::getFloatRed() const throw()
  60944. {
  60945. return getRed() * oneOver255;
  60946. }
  60947. float Colour::getFloatGreen() const throw()
  60948. {
  60949. return getGreen() * oneOver255;
  60950. }
  60951. float Colour::getFloatBlue() const throw()
  60952. {
  60953. return getBlue() * oneOver255;
  60954. }
  60955. float Colour::getFloatAlpha() const throw()
  60956. {
  60957. return getAlpha() * oneOver255;
  60958. }
  60959. void Colour::getHSB (float& h, float& s, float& v) const throw()
  60960. {
  60961. const int r = getRed();
  60962. const int g = getGreen();
  60963. const int b = getBlue();
  60964. const int hi = jmax (r, g, b);
  60965. const int lo = jmin (r, g, b);
  60966. if (hi != 0)
  60967. {
  60968. s = (hi - lo) / (float) hi;
  60969. if (s != 0)
  60970. {
  60971. const float invDiff = 1.0f / (hi - lo);
  60972. const float red = (hi - r) * invDiff;
  60973. const float green = (hi - g) * invDiff;
  60974. const float blue = (hi - b) * invDiff;
  60975. if (r == hi)
  60976. h = blue - green;
  60977. else if (g == hi)
  60978. h = 2.0f + red - blue;
  60979. else
  60980. h = 4.0f + green - red;
  60981. h *= 1.0f / 6.0f;
  60982. if (h < 0)
  60983. ++h;
  60984. }
  60985. else
  60986. {
  60987. h = 0;
  60988. }
  60989. }
  60990. else
  60991. {
  60992. s = 0;
  60993. h = 0;
  60994. }
  60995. v = hi * oneOver255;
  60996. }
  60997. float Colour::getHue() const throw()
  60998. {
  60999. float h, s, b;
  61000. getHSB (h, s, b);
  61001. return h;
  61002. }
  61003. const Colour Colour::withHue (const float hue) const throw()
  61004. {
  61005. float h, s, b;
  61006. getHSB (h, s, b);
  61007. return Colour (hue, s, b, getAlpha());
  61008. }
  61009. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  61010. {
  61011. float h, s, b;
  61012. getHSB (h, s, b);
  61013. h += amountToRotate;
  61014. h -= floorf (h);
  61015. return Colour (h, s, b, getAlpha());
  61016. }
  61017. float Colour::getSaturation() const throw()
  61018. {
  61019. float h, s, b;
  61020. getHSB (h, s, b);
  61021. return s;
  61022. }
  61023. const Colour Colour::withSaturation (const float saturation) const throw()
  61024. {
  61025. float h, s, b;
  61026. getHSB (h, s, b);
  61027. return Colour (h, saturation, b, getAlpha());
  61028. }
  61029. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  61030. {
  61031. float h, s, b;
  61032. getHSB (h, s, b);
  61033. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  61034. }
  61035. float Colour::getBrightness() const throw()
  61036. {
  61037. float h, s, b;
  61038. getHSB (h, s, b);
  61039. return b;
  61040. }
  61041. const Colour Colour::withBrightness (const float brightness) const throw()
  61042. {
  61043. float h, s, b;
  61044. getHSB (h, s, b);
  61045. return Colour (h, s, brightness, getAlpha());
  61046. }
  61047. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  61048. {
  61049. float h, s, b;
  61050. getHSB (h, s, b);
  61051. b *= amount;
  61052. if (b > 1.0f)
  61053. b = 1.0f;
  61054. return Colour (h, s, b, getAlpha());
  61055. }
  61056. const Colour Colour::brighter (float amount) const throw()
  61057. {
  61058. amount = 1.0f / (1.0f + amount);
  61059. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  61060. (uint8) (255 - (amount * (255 - getGreen()))),
  61061. (uint8) (255 - (amount * (255 - getBlue()))),
  61062. getAlpha());
  61063. }
  61064. const Colour Colour::darker (float amount) const throw()
  61065. {
  61066. amount = 1.0f / (1.0f + amount);
  61067. return Colour ((uint8) (amount * getRed()),
  61068. (uint8) (amount * getGreen()),
  61069. (uint8) (amount * getBlue()),
  61070. getAlpha());
  61071. }
  61072. const Colour Colour::greyLevel (const float brightness) throw()
  61073. {
  61074. const uint8 level
  61075. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  61076. return Colour (level, level, level);
  61077. }
  61078. const Colour Colour::contrasting (const float amount) const throw()
  61079. {
  61080. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  61081. ? Colours::black
  61082. : Colours::white).withAlpha (amount));
  61083. }
  61084. const Colour Colour::contrasting (const Colour& colour1,
  61085. const Colour& colour2) throw()
  61086. {
  61087. const float b1 = colour1.getBrightness();
  61088. const float b2 = colour2.getBrightness();
  61089. float best = 0.0f;
  61090. float bestDist = 0.0f;
  61091. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  61092. {
  61093. const float d1 = fabsf (i - b1);
  61094. const float d2 = fabsf (i - b2);
  61095. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  61096. if (dist > bestDist)
  61097. {
  61098. best = i;
  61099. bestDist = dist;
  61100. }
  61101. }
  61102. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  61103. .withBrightness (best);
  61104. }
  61105. const String Colour::toString() const throw()
  61106. {
  61107. return String::toHexString ((int) argb.getARGB());
  61108. }
  61109. const Colour Colour::fromString (const String& encodedColourString)
  61110. {
  61111. return Colour ((uint32) encodedColourString.getHexValue32());
  61112. }
  61113. END_JUCE_NAMESPACE
  61114. /********* End of inlined file: juce_Colour.cpp *********/
  61115. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  61116. BEGIN_JUCE_NAMESPACE
  61117. ColourGradient::ColourGradient() throw()
  61118. : colours (4)
  61119. {
  61120. #ifdef JUCE_DEBUG
  61121. x1 = 987654.0f;
  61122. #endif
  61123. }
  61124. ColourGradient::ColourGradient (const Colour& colour1,
  61125. const float x1_,
  61126. const float y1_,
  61127. const Colour& colour2,
  61128. const float x2_,
  61129. const float y2_,
  61130. const bool isRadial_) throw()
  61131. : x1 (x1_),
  61132. y1 (y1_),
  61133. x2 (x2_),
  61134. y2 (y2_),
  61135. isRadial (isRadial_),
  61136. colours (4)
  61137. {
  61138. colours.add (0);
  61139. colours.add (colour1.getARGB());
  61140. colours.add (1 << 16);
  61141. colours.add (colour2.getARGB());
  61142. }
  61143. ColourGradient::~ColourGradient() throw()
  61144. {
  61145. }
  61146. void ColourGradient::clearColours() throw()
  61147. {
  61148. colours.clear();
  61149. }
  61150. void ColourGradient::addColour (const double proportionAlongGradient,
  61151. const Colour& colour) throw()
  61152. {
  61153. // must be within the two end-points
  61154. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  61155. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  61156. int i;
  61157. for (i = 0; i < colours.size(); i += 2)
  61158. if (colours.getUnchecked(i) > pos)
  61159. break;
  61160. colours.insert (i, pos);
  61161. colours.insert (i + 1, colour.getARGB());
  61162. }
  61163. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  61164. {
  61165. for (int i = 1; i < colours.size(); i += 2)
  61166. {
  61167. const Colour c (colours.getUnchecked(i));
  61168. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  61169. }
  61170. }
  61171. int ColourGradient::getNumColours() const throw()
  61172. {
  61173. return colours.size() >> 1;
  61174. }
  61175. double ColourGradient::getColourPosition (const int index) const throw()
  61176. {
  61177. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  61178. }
  61179. const Colour ColourGradient::getColour (const int index) const throw()
  61180. {
  61181. return Colour (colours [(index << 1) + 1]);
  61182. }
  61183. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  61184. {
  61185. #ifdef JUCE_DEBUG
  61186. // trying to use the object without setting its co-ordinates? Have a careful read of
  61187. // the comments for the constructors.
  61188. jassert (x1 != 987654.0f);
  61189. #endif
  61190. const int numColours = colours.size() >> 1;
  61191. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  61192. transform.transformPoint (tx1, ty1);
  61193. transform.transformPoint (tx2, ty2);
  61194. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  61195. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  61196. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  61197. if (numColours >= 2)
  61198. {
  61199. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  61200. PixelARGB pix1 (colours.getUnchecked (1));
  61201. pix1.premultiply();
  61202. int index = 0;
  61203. for (int j = 2; j < colours.size(); j += 2)
  61204. {
  61205. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  61206. PixelARGB pix2 (colours.getUnchecked (j + 1));
  61207. pix2.premultiply();
  61208. for (int i = 0; i < numToDo; ++i)
  61209. {
  61210. jassert (index >= 0 && index < numEntries);
  61211. lookupTable[index] = pix1;
  61212. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  61213. ++index;
  61214. }
  61215. pix1 = pix2;
  61216. }
  61217. while (index < numEntries)
  61218. lookupTable [index++] = pix1;
  61219. }
  61220. else
  61221. {
  61222. jassertfalse // no colours specified!
  61223. }
  61224. return lookupTable;
  61225. }
  61226. bool ColourGradient::isOpaque() const throw()
  61227. {
  61228. for (int i = 1; i < colours.size(); i += 2)
  61229. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  61230. return false;
  61231. return true;
  61232. }
  61233. bool ColourGradient::isInvisible() const throw()
  61234. {
  61235. for (int i = 1; i < colours.size(); i += 2)
  61236. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  61237. return false;
  61238. return true;
  61239. }
  61240. END_JUCE_NAMESPACE
  61241. /********* End of inlined file: juce_ColourGradient.cpp *********/
  61242. /********* Start of inlined file: juce_Colours.cpp *********/
  61243. BEGIN_JUCE_NAMESPACE
  61244. const Colour Colours::transparentBlack (0);
  61245. const Colour Colours::transparentWhite (0x00ffffff);
  61246. const Colour Colours::aliceblue (0xfff0f8ff);
  61247. const Colour Colours::antiquewhite (0xfffaebd7);
  61248. const Colour Colours::aqua (0xff00ffff);
  61249. const Colour Colours::aquamarine (0xff7fffd4);
  61250. const Colour Colours::azure (0xfff0ffff);
  61251. const Colour Colours::beige (0xfff5f5dc);
  61252. const Colour Colours::bisque (0xffffe4c4);
  61253. const Colour Colours::black (0xff000000);
  61254. const Colour Colours::blanchedalmond (0xffffebcd);
  61255. const Colour Colours::blue (0xff0000ff);
  61256. const Colour Colours::blueviolet (0xff8a2be2);
  61257. const Colour Colours::brown (0xffa52a2a);
  61258. const Colour Colours::burlywood (0xffdeb887);
  61259. const Colour Colours::cadetblue (0xff5f9ea0);
  61260. const Colour Colours::chartreuse (0xff7fff00);
  61261. const Colour Colours::chocolate (0xffd2691e);
  61262. const Colour Colours::coral (0xffff7f50);
  61263. const Colour Colours::cornflowerblue (0xff6495ed);
  61264. const Colour Colours::cornsilk (0xfffff8dc);
  61265. const Colour Colours::crimson (0xffdc143c);
  61266. const Colour Colours::cyan (0xff00ffff);
  61267. const Colour Colours::darkblue (0xff00008b);
  61268. const Colour Colours::darkcyan (0xff008b8b);
  61269. const Colour Colours::darkgoldenrod (0xffb8860b);
  61270. const Colour Colours::darkgrey (0xff555555);
  61271. const Colour Colours::darkgreen (0xff006400);
  61272. const Colour Colours::darkkhaki (0xffbdb76b);
  61273. const Colour Colours::darkmagenta (0xff8b008b);
  61274. const Colour Colours::darkolivegreen (0xff556b2f);
  61275. const Colour Colours::darkorange (0xffff8c00);
  61276. const Colour Colours::darkorchid (0xff9932cc);
  61277. const Colour Colours::darkred (0xff8b0000);
  61278. const Colour Colours::darksalmon (0xffe9967a);
  61279. const Colour Colours::darkseagreen (0xff8fbc8f);
  61280. const Colour Colours::darkslateblue (0xff483d8b);
  61281. const Colour Colours::darkslategrey (0xff2f4f4f);
  61282. const Colour Colours::darkturquoise (0xff00ced1);
  61283. const Colour Colours::darkviolet (0xff9400d3);
  61284. const Colour Colours::deeppink (0xffff1493);
  61285. const Colour Colours::deepskyblue (0xff00bfff);
  61286. const Colour Colours::dimgrey (0xff696969);
  61287. const Colour Colours::dodgerblue (0xff1e90ff);
  61288. const Colour Colours::firebrick (0xffb22222);
  61289. const Colour Colours::floralwhite (0xfffffaf0);
  61290. const Colour Colours::forestgreen (0xff228b22);
  61291. const Colour Colours::fuchsia (0xffff00ff);
  61292. const Colour Colours::gainsboro (0xffdcdcdc);
  61293. const Colour Colours::gold (0xffffd700);
  61294. const Colour Colours::goldenrod (0xffdaa520);
  61295. const Colour Colours::grey (0xff808080);
  61296. const Colour Colours::green (0xff008000);
  61297. const Colour Colours::greenyellow (0xffadff2f);
  61298. const Colour Colours::honeydew (0xfff0fff0);
  61299. const Colour Colours::hotpink (0xffff69b4);
  61300. const Colour Colours::indianred (0xffcd5c5c);
  61301. const Colour Colours::indigo (0xff4b0082);
  61302. const Colour Colours::ivory (0xfffffff0);
  61303. const Colour Colours::khaki (0xfff0e68c);
  61304. const Colour Colours::lavender (0xffe6e6fa);
  61305. const Colour Colours::lavenderblush (0xfffff0f5);
  61306. const Colour Colours::lemonchiffon (0xfffffacd);
  61307. const Colour Colours::lightblue (0xffadd8e6);
  61308. const Colour Colours::lightcoral (0xfff08080);
  61309. const Colour Colours::lightcyan (0xffe0ffff);
  61310. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  61311. const Colour Colours::lightgreen (0xff90ee90);
  61312. const Colour Colours::lightgrey (0xffd3d3d3);
  61313. const Colour Colours::lightpink (0xffffb6c1);
  61314. const Colour Colours::lightsalmon (0xffffa07a);
  61315. const Colour Colours::lightseagreen (0xff20b2aa);
  61316. const Colour Colours::lightskyblue (0xff87cefa);
  61317. const Colour Colours::lightslategrey (0xff778899);
  61318. const Colour Colours::lightsteelblue (0xffb0c4de);
  61319. const Colour Colours::lightyellow (0xffffffe0);
  61320. const Colour Colours::lime (0xff00ff00);
  61321. const Colour Colours::limegreen (0xff32cd32);
  61322. const Colour Colours::linen (0xfffaf0e6);
  61323. const Colour Colours::magenta (0xffff00ff);
  61324. const Colour Colours::maroon (0xff800000);
  61325. const Colour Colours::mediumaquamarine (0xff66cdaa);
  61326. const Colour Colours::mediumblue (0xff0000cd);
  61327. const Colour Colours::mediumorchid (0xffba55d3);
  61328. const Colour Colours::mediumpurple (0xff9370db);
  61329. const Colour Colours::mediumseagreen (0xff3cb371);
  61330. const Colour Colours::mediumslateblue (0xff7b68ee);
  61331. const Colour Colours::mediumspringgreen (0xff00fa9a);
  61332. const Colour Colours::mediumturquoise (0xff48d1cc);
  61333. const Colour Colours::mediumvioletred (0xffc71585);
  61334. const Colour Colours::midnightblue (0xff191970);
  61335. const Colour Colours::mintcream (0xfff5fffa);
  61336. const Colour Colours::mistyrose (0xffffe4e1);
  61337. const Colour Colours::navajowhite (0xffffdead);
  61338. const Colour Colours::navy (0xff000080);
  61339. const Colour Colours::oldlace (0xfffdf5e6);
  61340. const Colour Colours::olive (0xff808000);
  61341. const Colour Colours::olivedrab (0xff6b8e23);
  61342. const Colour Colours::orange (0xffffa500);
  61343. const Colour Colours::orangered (0xffff4500);
  61344. const Colour Colours::orchid (0xffda70d6);
  61345. const Colour Colours::palegoldenrod (0xffeee8aa);
  61346. const Colour Colours::palegreen (0xff98fb98);
  61347. const Colour Colours::paleturquoise (0xffafeeee);
  61348. const Colour Colours::palevioletred (0xffdb7093);
  61349. const Colour Colours::papayawhip (0xffffefd5);
  61350. const Colour Colours::peachpuff (0xffffdab9);
  61351. const Colour Colours::peru (0xffcd853f);
  61352. const Colour Colours::pink (0xffffc0cb);
  61353. const Colour Colours::plum (0xffdda0dd);
  61354. const Colour Colours::powderblue (0xffb0e0e6);
  61355. const Colour Colours::purple (0xff800080);
  61356. const Colour Colours::red (0xffff0000);
  61357. const Colour Colours::rosybrown (0xffbc8f8f);
  61358. const Colour Colours::royalblue (0xff4169e1);
  61359. const Colour Colours::saddlebrown (0xff8b4513);
  61360. const Colour Colours::salmon (0xfffa8072);
  61361. const Colour Colours::sandybrown (0xfff4a460);
  61362. const Colour Colours::seagreen (0xff2e8b57);
  61363. const Colour Colours::seashell (0xfffff5ee);
  61364. const Colour Colours::sienna (0xffa0522d);
  61365. const Colour Colours::silver (0xffc0c0c0);
  61366. const Colour Colours::skyblue (0xff87ceeb);
  61367. const Colour Colours::slateblue (0xff6a5acd);
  61368. const Colour Colours::slategrey (0xff708090);
  61369. const Colour Colours::snow (0xfffffafa);
  61370. const Colour Colours::springgreen (0xff00ff7f);
  61371. const Colour Colours::steelblue (0xff4682b4);
  61372. const Colour Colours::tan (0xffd2b48c);
  61373. const Colour Colours::teal (0xff008080);
  61374. const Colour Colours::thistle (0xffd8bfd8);
  61375. const Colour Colours::tomato (0xffff6347);
  61376. const Colour Colours::turquoise (0xff40e0d0);
  61377. const Colour Colours::violet (0xffee82ee);
  61378. const Colour Colours::wheat (0xfff5deb3);
  61379. const Colour Colours::white (0xffffffff);
  61380. const Colour Colours::whitesmoke (0xfff5f5f5);
  61381. const Colour Colours::yellow (0xffffff00);
  61382. const Colour Colours::yellowgreen (0xff9acd32);
  61383. const Colour Colours::findColourForName (const String& colourName,
  61384. const Colour& defaultColour)
  61385. {
  61386. static const int presets[] =
  61387. {
  61388. // (first value is the string's hashcode, second is ARGB)
  61389. 0x05978fff, 0xff000000, /* black */
  61390. 0x06bdcc29, 0xffffffff, /* white */
  61391. 0x002e305a, 0xff0000ff, /* blue */
  61392. 0x00308adf, 0xff808080, /* grey */
  61393. 0x05e0cf03, 0xff008000, /* green */
  61394. 0x0001b891, 0xffff0000, /* red */
  61395. 0xd43c6474, 0xffffff00, /* yellow */
  61396. 0x620886da, 0xfff0f8ff, /* aliceblue */
  61397. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  61398. 0x002dcebc, 0xff00ffff, /* aqua */
  61399. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  61400. 0x0590228f, 0xfff0ffff, /* azure */
  61401. 0x05947fe4, 0xfff5f5dc, /* beige */
  61402. 0xad388e35, 0xffffe4c4, /* bisque */
  61403. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  61404. 0x39129959, 0xff8a2be2, /* blueviolet */
  61405. 0x059a8136, 0xffa52a2a, /* brown */
  61406. 0x89cea8f9, 0xffdeb887, /* burlywood */
  61407. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  61408. 0x6b748956, 0xff7fff00, /* chartreuse */
  61409. 0x2903623c, 0xffd2691e, /* chocolate */
  61410. 0x05a74431, 0xffff7f50, /* coral */
  61411. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  61412. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  61413. 0x3d8c4edf, 0xffdc143c, /* crimson */
  61414. 0x002ed323, 0xff00ffff, /* cyan */
  61415. 0x67cc74d0, 0xff00008b, /* darkblue */
  61416. 0x67cd1799, 0xff008b8b, /* darkcyan */
  61417. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  61418. 0x67cecf55, 0xff555555, /* darkgrey */
  61419. 0x920b194d, 0xff006400, /* darkgreen */
  61420. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  61421. 0x5c293873, 0xff8b008b, /* darkmagenta */
  61422. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  61423. 0xbcfd2524, 0xffff8c00, /* darkorange */
  61424. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  61425. 0x55ee0d5b, 0xff8b0000, /* darkred */
  61426. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  61427. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  61428. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  61429. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  61430. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  61431. 0xc8769375, 0xff9400d3, /* darkviolet */
  61432. 0x25832862, 0xffff1493, /* deeppink */
  61433. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  61434. 0x634c8b67, 0xff696969, /* dimgrey */
  61435. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  61436. 0xef19e3cb, 0xffb22222, /* firebrick */
  61437. 0xb852b195, 0xfffffaf0, /* floralwhite */
  61438. 0xd086fd06, 0xff228b22, /* forestgreen */
  61439. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  61440. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  61441. 0x00308060, 0xffffd700, /* gold */
  61442. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  61443. 0xbab8a537, 0xffadff2f, /* greenyellow */
  61444. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  61445. 0x41892743, 0xffff69b4, /* hotpink */
  61446. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  61447. 0xb969fed2, 0xff4b0082, /* indigo */
  61448. 0x05fef6a9, 0xfffffff0, /* ivory */
  61449. 0x06149302, 0xfff0e68c, /* khaki */
  61450. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  61451. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  61452. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  61453. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  61454. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  61455. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  61456. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  61457. 0xf40157ad, 0xff90ee90, /* lightgreen */
  61458. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  61459. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  61460. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  61461. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  61462. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  61463. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  61464. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  61465. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  61466. 0x0032afd5, 0xff00ff00, /* lime */
  61467. 0x607bbc4e, 0xff32cd32, /* limegreen */
  61468. 0x06234efa, 0xfffaf0e6, /* linen */
  61469. 0x316858a9, 0xffff00ff, /* magenta */
  61470. 0xbf8ca470, 0xff800000, /* maroon */
  61471. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  61472. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  61473. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  61474. 0x07556b71, 0xff9370db, /* mediumpurple */
  61475. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  61476. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  61477. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  61478. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  61479. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  61480. 0x168eb32a, 0xff191970, /* midnightblue */
  61481. 0x4306b960, 0xfff5fffa, /* mintcream */
  61482. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  61483. 0xe97218a6, 0xffffdead, /* navajowhite */
  61484. 0x00337bb6, 0xff000080, /* navy */
  61485. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  61486. 0x064ee1db, 0xff808000, /* olive */
  61487. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  61488. 0xc3de262e, 0xffffa500, /* orange */
  61489. 0x58bebba3, 0xffff4500, /* orangered */
  61490. 0xc3def8a3, 0xffda70d6, /* orchid */
  61491. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  61492. 0x3d9dd619, 0xff98fb98, /* palegreen */
  61493. 0x74022737, 0xffafeeee, /* paleturquoise */
  61494. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  61495. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  61496. 0x93e1b776, 0xffffdab9, /* peachpuff */
  61497. 0x003472f8, 0xffcd853f, /* peru */
  61498. 0x00348176, 0xffffc0cb, /* pink */
  61499. 0x00348d94, 0xffdda0dd, /* plum */
  61500. 0xd036be93, 0xffb0e0e6, /* powderblue */
  61501. 0xc5c507bc, 0xff800080, /* purple */
  61502. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  61503. 0xbd9413e1, 0xff4169e1, /* royalblue */
  61504. 0xf456044f, 0xff8b4513, /* saddlebrown */
  61505. 0xc9c6f66e, 0xfffa8072, /* salmon */
  61506. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  61507. 0x34636c14, 0xff2e8b57, /* seagreen */
  61508. 0x3507fb41, 0xfffff5ee, /* seashell */
  61509. 0xca348772, 0xffa0522d, /* sienna */
  61510. 0xca37d30d, 0xffc0c0c0, /* silver */
  61511. 0x80da74fb, 0xff87ceeb, /* skyblue */
  61512. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  61513. 0x44ab37f8, 0xff708090, /* slategrey */
  61514. 0x0035f183, 0xfffffafa, /* snow */
  61515. 0xd5440d16, 0xff00ff7f, /* springgreen */
  61516. 0x3e1524a5, 0xff4682b4, /* steelblue */
  61517. 0x0001bfa1, 0xffd2b48c, /* tan */
  61518. 0x0036425c, 0xff008080, /* teal */
  61519. 0xafc8858f, 0xffd8bfd8, /* thistle */
  61520. 0xcc41600a, 0xffff6347, /* tomato */
  61521. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  61522. 0xcf57947f, 0xffee82ee, /* violet */
  61523. 0x06bdbae7, 0xfff5deb3, /* wheat */
  61524. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  61525. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  61526. };
  61527. const int hash = colourName.trim().toLowerCase().hashCode();
  61528. for (int i = 0; i < numElementsInArray (presets); i += 2)
  61529. if (presets [i] == hash)
  61530. return Colour (presets [i + 1]);
  61531. return defaultColour;
  61532. }
  61533. END_JUCE_NAMESPACE
  61534. /********* End of inlined file: juce_Colours.cpp *********/
  61535. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  61536. BEGIN_JUCE_NAMESPACE
  61537. EdgeTable::EdgeTable (const int top_,
  61538. const int height_,
  61539. const OversamplingLevel oversampling_,
  61540. const int expectedEdgesPerLine) throw()
  61541. : top (top_),
  61542. height (height_),
  61543. maxEdgesPerLine (expectedEdgesPerLine),
  61544. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  61545. oversampling (oversampling_)
  61546. {
  61547. table = (int*) juce_calloc ((height << (int)oversampling_)
  61548. * lineStrideElements * sizeof (int));
  61549. }
  61550. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  61551. : table (0)
  61552. {
  61553. operator= (other);
  61554. }
  61555. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  61556. {
  61557. juce_free (table);
  61558. top = other.top;
  61559. height = other.height;
  61560. maxEdgesPerLine = other.maxEdgesPerLine;
  61561. lineStrideElements = other.lineStrideElements;
  61562. oversampling = other.oversampling;
  61563. const int tableSize = (height << (int)oversampling)
  61564. * lineStrideElements * sizeof (int);
  61565. table = (int*) juce_malloc (tableSize);
  61566. memcpy (table, other.table, tableSize);
  61567. return *this;
  61568. }
  61569. EdgeTable::~EdgeTable() throw()
  61570. {
  61571. juce_free (table);
  61572. }
  61573. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  61574. {
  61575. if (newNumEdgesPerLine != maxEdgesPerLine)
  61576. {
  61577. maxEdgesPerLine = newNumEdgesPerLine;
  61578. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  61579. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  61580. * newLineStrideElements * sizeof (int));
  61581. for (int i = 0; i < (height << (int) oversampling); ++i)
  61582. {
  61583. const int* srcLine = table + lineStrideElements * i;
  61584. int* dstLine = newTable + newLineStrideElements * i;
  61585. int num = *srcLine++;
  61586. *dstLine++ = num;
  61587. num <<= 1;
  61588. while (--num >= 0)
  61589. *dstLine++ = *srcLine++;
  61590. }
  61591. juce_free (table);
  61592. table = newTable;
  61593. lineStrideElements = newLineStrideElements;
  61594. }
  61595. }
  61596. void EdgeTable::optimiseTable() throw()
  61597. {
  61598. int maxLineElements = 0;
  61599. for (int i = height; --i >= 0;)
  61600. maxLineElements = jmax (maxLineElements,
  61601. table [i * lineStrideElements]);
  61602. remapTableForNumEdges (maxLineElements);
  61603. }
  61604. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  61605. {
  61606. jassert (y >= 0 && y < (height << oversampling))
  61607. int* lineStart = table + lineStrideElements * y;
  61608. int n = lineStart[0];
  61609. if (n >= maxEdgesPerLine)
  61610. {
  61611. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  61612. jassert (n < maxEdgesPerLine);
  61613. lineStart = table + lineStrideElements * y;
  61614. }
  61615. n <<= 1;
  61616. int* const line = lineStart + 1;
  61617. while (n > 0)
  61618. {
  61619. const int cx = line [n - 2];
  61620. if (cx <= x)
  61621. break;
  61622. line [n] = cx;
  61623. line [n + 1] = line [n - 1];
  61624. n -= 2;
  61625. }
  61626. line [n] = x;
  61627. line [n + 1] = winding;
  61628. lineStart[0]++;
  61629. }
  61630. void EdgeTable::addPath (const Path& path,
  61631. const AffineTransform& transform) throw()
  61632. {
  61633. const int windingAmount = 256 / (1 << (int) oversampling);
  61634. const float timesOversampling = (float) (1 << (int) oversampling);
  61635. const int bottomLimit = (height << (int) oversampling);
  61636. PathFlatteningIterator iter (path, transform);
  61637. while (iter.next())
  61638. {
  61639. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  61640. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  61641. if (y1 != y2)
  61642. {
  61643. const double x1 = 256.0 * iter.x1;
  61644. const double x2 = 256.0 * iter.x2;
  61645. const double multiplier = (x2 - x1) / (y2 - y1);
  61646. const int oldY1 = y1;
  61647. int winding;
  61648. if (y1 > y2)
  61649. {
  61650. swapVariables (y1, y2);
  61651. winding = windingAmount;
  61652. }
  61653. else
  61654. {
  61655. winding = -windingAmount;
  61656. }
  61657. jassert (y1 < y2);
  61658. if (y1 < 0)
  61659. y1 = 0;
  61660. if (y2 > bottomLimit)
  61661. y2 = bottomLimit;
  61662. while (y1 < y2)
  61663. {
  61664. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  61665. y1,
  61666. winding);
  61667. ++y1;
  61668. }
  61669. }
  61670. }
  61671. if (! path.isUsingNonZeroWinding())
  61672. {
  61673. // if it's an alternate-winding path, we need to go through and
  61674. // make sure all the windings are alternating.
  61675. int* lineStart = table;
  61676. for (int i = height << (int) oversampling; --i >= 0;)
  61677. {
  61678. int* line = lineStart;
  61679. lineStart += lineStrideElements;
  61680. int num = *line;
  61681. while (--num >= 0)
  61682. {
  61683. line += 2;
  61684. *line = abs (*line);
  61685. if (--num >= 0)
  61686. {
  61687. line += 2;
  61688. *line = -abs (*line);
  61689. }
  61690. }
  61691. }
  61692. }
  61693. }
  61694. END_JUCE_NAMESPACE
  61695. /********* End of inlined file: juce_EdgeTable.cpp *********/
  61696. /********* Start of inlined file: juce_Graphics.cpp *********/
  61697. BEGIN_JUCE_NAMESPACE
  61698. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  61699. #define MINIMUM_COORD -0x3fffffff
  61700. #define MAXIMUM_COORD 0x3fffffff
  61701. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61702. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61703. jassert ((int) x >= MINIMUM_COORD \
  61704. && (int) x <= MAXIMUM_COORD \
  61705. && (int) y >= MINIMUM_COORD \
  61706. && (int) y <= MAXIMUM_COORD \
  61707. && (int) w >= MINIMUM_COORD \
  61708. && (int) w <= MAXIMUM_COORD \
  61709. && (int) h >= MINIMUM_COORD \
  61710. && (int) h <= MAXIMUM_COORD);
  61711. LowLevelGraphicsContext::LowLevelGraphicsContext()
  61712. {
  61713. }
  61714. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  61715. {
  61716. }
  61717. Graphics::Graphics (Image& imageToDrawOnto) throw()
  61718. : context (imageToDrawOnto.createLowLevelContext()),
  61719. ownsContext (true),
  61720. state (new GraphicsState()),
  61721. saveStatePending (false)
  61722. {
  61723. }
  61724. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  61725. : context (internalContext),
  61726. ownsContext (false),
  61727. state (new GraphicsState()),
  61728. saveStatePending (false)
  61729. {
  61730. }
  61731. Graphics::~Graphics() throw()
  61732. {
  61733. delete state;
  61734. if (ownsContext)
  61735. delete context;
  61736. }
  61737. void Graphics::resetToDefaultState() throw()
  61738. {
  61739. setColour (Colours::black);
  61740. state->font.resetToDefaultState();
  61741. state->quality = defaultQuality;
  61742. }
  61743. bool Graphics::isVectorDevice() const throw()
  61744. {
  61745. return context->isVectorDevice();
  61746. }
  61747. bool Graphics::reduceClipRegion (const int x, const int y,
  61748. const int w, const int h) throw()
  61749. {
  61750. saveStateIfPending();
  61751. return context->reduceClipRegion (x, y, w, h);
  61752. }
  61753. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  61754. {
  61755. saveStateIfPending();
  61756. return context->reduceClipRegion (clipRegion);
  61757. }
  61758. void Graphics::excludeClipRegion (const int x, const int y,
  61759. const int w, const int h) throw()
  61760. {
  61761. saveStateIfPending();
  61762. context->excludeClipRegion (x, y, w, h);
  61763. }
  61764. bool Graphics::isClipEmpty() const throw()
  61765. {
  61766. return context->isClipEmpty();
  61767. }
  61768. const Rectangle Graphics::getClipBounds() const throw()
  61769. {
  61770. return context->getClipBounds();
  61771. }
  61772. void Graphics::saveState() throw()
  61773. {
  61774. saveStateIfPending();
  61775. saveStatePending = true;
  61776. }
  61777. void Graphics::restoreState() throw()
  61778. {
  61779. if (saveStatePending)
  61780. {
  61781. saveStatePending = false;
  61782. }
  61783. else
  61784. {
  61785. const int stackSize = stateStack.size();
  61786. if (stackSize > 0)
  61787. {
  61788. context->restoreState();
  61789. delete state;
  61790. state = stateStack.getUnchecked (stackSize - 1);
  61791. stateStack.removeLast (1, false);
  61792. }
  61793. else
  61794. {
  61795. // Trying to call restoreState() more times than you've called saveState() !
  61796. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  61797. jassertfalse
  61798. }
  61799. }
  61800. }
  61801. void Graphics::saveStateIfPending() throw()
  61802. {
  61803. if (saveStatePending)
  61804. {
  61805. saveStatePending = false;
  61806. context->saveState();
  61807. stateStack.add (new GraphicsState (*state));
  61808. }
  61809. }
  61810. void Graphics::setOrigin (const int newOriginX,
  61811. const int newOriginY) throw()
  61812. {
  61813. saveStateIfPending();
  61814. context->setOrigin (newOriginX, newOriginY);
  61815. }
  61816. bool Graphics::clipRegionIntersects (const int x, const int y,
  61817. const int w, const int h) const throw()
  61818. {
  61819. return context->clipRegionIntersects (x, y, w, h);
  61820. }
  61821. void Graphics::setColour (const Colour& newColour) throw()
  61822. {
  61823. saveStateIfPending();
  61824. state->colour = newColour;
  61825. deleteAndZero (state->brush);
  61826. }
  61827. const Colour& Graphics::getCurrentColour() const throw()
  61828. {
  61829. return state->colour;
  61830. }
  61831. void Graphics::setOpacity (const float newOpacity) throw()
  61832. {
  61833. saveStateIfPending();
  61834. state->colour = state->colour.withAlpha (newOpacity);
  61835. }
  61836. void Graphics::setBrush (const Brush* const newBrush) throw()
  61837. {
  61838. saveStateIfPending();
  61839. delete state->brush;
  61840. if (newBrush != 0)
  61841. state->brush = newBrush->createCopy();
  61842. else
  61843. state->brush = 0;
  61844. }
  61845. Graphics::GraphicsState::GraphicsState() throw()
  61846. : colour (Colours::black),
  61847. brush (0),
  61848. quality (defaultQuality)
  61849. {
  61850. }
  61851. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  61852. : colour (other.colour),
  61853. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  61854. font (other.font),
  61855. quality (other.quality)
  61856. {
  61857. }
  61858. Graphics::GraphicsState::~GraphicsState() throw()
  61859. {
  61860. delete brush;
  61861. }
  61862. void Graphics::setFont (const Font& newFont) throw()
  61863. {
  61864. saveStateIfPending();
  61865. state->font = newFont;
  61866. }
  61867. void Graphics::setFont (const float newFontHeight,
  61868. const int newFontStyleFlags) throw()
  61869. {
  61870. saveStateIfPending();
  61871. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  61872. }
  61873. const Font& Graphics::getCurrentFont() const throw()
  61874. {
  61875. return state->font;
  61876. }
  61877. void Graphics::drawSingleLineText (const String& text,
  61878. const int startX,
  61879. const int baselineY) const throw()
  61880. {
  61881. if (text.isNotEmpty()
  61882. && startX < context->getClipBounds().getRight())
  61883. {
  61884. GlyphArrangement arr;
  61885. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  61886. arr.draw (*this);
  61887. }
  61888. }
  61889. void Graphics::drawTextAsPath (const String& text,
  61890. const AffineTransform& transform) const throw()
  61891. {
  61892. if (text.isNotEmpty())
  61893. {
  61894. GlyphArrangement arr;
  61895. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  61896. arr.draw (*this, transform);
  61897. }
  61898. }
  61899. void Graphics::drawMultiLineText (const String& text,
  61900. const int startX,
  61901. const int baselineY,
  61902. const int maximumLineWidth) const throw()
  61903. {
  61904. if (text.isNotEmpty()
  61905. && startX < context->getClipBounds().getRight())
  61906. {
  61907. GlyphArrangement arr;
  61908. arr.addJustifiedText (state->font, text,
  61909. (float) startX, (float) baselineY, (float) maximumLineWidth,
  61910. Justification::left);
  61911. arr.draw (*this);
  61912. }
  61913. }
  61914. void Graphics::drawText (const String& text,
  61915. const int x,
  61916. const int y,
  61917. const int width,
  61918. const int height,
  61919. const Justification& justificationType,
  61920. const bool useEllipsesIfTooBig) const throw()
  61921. {
  61922. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  61923. {
  61924. GlyphArrangement arr;
  61925. arr.addCurtailedLineOfText (state->font, text,
  61926. 0.0f, 0.0f, (float)width,
  61927. useEllipsesIfTooBig);
  61928. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  61929. (float) x, (float) y,
  61930. (float) width, (float) height,
  61931. justificationType);
  61932. arr.draw (*this);
  61933. }
  61934. }
  61935. void Graphics::drawFittedText (const String& text,
  61936. const int x,
  61937. const int y,
  61938. const int width,
  61939. const int height,
  61940. const Justification& justification,
  61941. const int maximumNumberOfLines,
  61942. const float minimumHorizontalScale) const throw()
  61943. {
  61944. if (text.isNotEmpty()
  61945. && width > 0 && height > 0
  61946. && context->clipRegionIntersects (x, y, width, height))
  61947. {
  61948. GlyphArrangement arr;
  61949. arr.addFittedText (state->font, text,
  61950. (float) x, (float) y,
  61951. (float) width, (float) height,
  61952. justification,
  61953. maximumNumberOfLines,
  61954. minimumHorizontalScale);
  61955. arr.draw (*this);
  61956. }
  61957. }
  61958. void Graphics::fillRect (int x,
  61959. int y,
  61960. int width,
  61961. int height) const throw()
  61962. {
  61963. // passing in a silly number can cause maths problems in rendering!
  61964. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61965. SolidColourBrush colourBrush (state->colour);
  61966. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  61967. }
  61968. void Graphics::fillRect (const Rectangle& r) const throw()
  61969. {
  61970. fillRect (r.getX(),
  61971. r.getY(),
  61972. r.getWidth(),
  61973. r.getHeight());
  61974. }
  61975. void Graphics::fillRect (const float x,
  61976. const float y,
  61977. const float width,
  61978. const float height) const throw()
  61979. {
  61980. // passing in a silly number can cause maths problems in rendering!
  61981. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61982. Path p;
  61983. p.addRectangle (x, y, width, height);
  61984. fillPath (p);
  61985. }
  61986. void Graphics::setPixel (int x, int y) const throw()
  61987. {
  61988. if (context->clipRegionIntersects (x, y, 1, 1))
  61989. {
  61990. SolidColourBrush colourBrush (state->colour);
  61991. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  61992. }
  61993. }
  61994. void Graphics::fillAll() const throw()
  61995. {
  61996. fillRect (context->getClipBounds());
  61997. }
  61998. void Graphics::fillAll (const Colour& colourToUse) const throw()
  61999. {
  62000. if (! colourToUse.isTransparent())
  62001. {
  62002. const Rectangle clip (context->getClipBounds());
  62003. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  62004. colourToUse, false);
  62005. }
  62006. }
  62007. void Graphics::fillPath (const Path& path,
  62008. const AffineTransform& transform) const throw()
  62009. {
  62010. if ((! context->isClipEmpty()) && ! path.isEmpty())
  62011. {
  62012. SolidColourBrush colourBrush (state->colour);
  62013. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  62014. }
  62015. }
  62016. void Graphics::strokePath (const Path& path,
  62017. const PathStrokeType& strokeType,
  62018. const AffineTransform& transform) const throw()
  62019. {
  62020. if ((! state->colour.isTransparent()) || state->brush != 0)
  62021. {
  62022. Path stroke;
  62023. strokeType.createStrokedPath (stroke, path, transform);
  62024. fillPath (stroke);
  62025. }
  62026. }
  62027. void Graphics::drawRect (const int x,
  62028. const int y,
  62029. const int width,
  62030. const int height,
  62031. const int lineThickness) const throw()
  62032. {
  62033. // passing in a silly number can cause maths problems in rendering!
  62034. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62035. SolidColourBrush colourBrush (state->colour);
  62036. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  62037. b.paintRectangle (*context, x, y, width, lineThickness);
  62038. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  62039. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  62040. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  62041. }
  62042. void Graphics::drawRect (const float x,
  62043. const float y,
  62044. const float width,
  62045. const float height,
  62046. const float lineThickness) const throw()
  62047. {
  62048. // passing in a silly number can cause maths problems in rendering!
  62049. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62050. Path p;
  62051. p.addRectangle (x, y, width, lineThickness);
  62052. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  62053. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  62054. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  62055. fillPath (p);
  62056. }
  62057. void Graphics::drawRect (const Rectangle& r,
  62058. const int lineThickness) const throw()
  62059. {
  62060. drawRect (r.getX(), r.getY(),
  62061. r.getWidth(), r.getHeight(),
  62062. lineThickness);
  62063. }
  62064. void Graphics::drawBevel (const int x,
  62065. const int y,
  62066. const int width,
  62067. const int height,
  62068. const int bevelThickness,
  62069. const Colour& topLeftColour,
  62070. const Colour& bottomRightColour,
  62071. const bool useGradient,
  62072. const bool sharpEdgeOnOutside) const throw()
  62073. {
  62074. // passing in a silly number can cause maths problems in rendering!
  62075. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62076. if (clipRegionIntersects (x, y, width, height))
  62077. {
  62078. const float oldOpacity = state->colour.getFloatAlpha();
  62079. const float ramp = oldOpacity / bevelThickness;
  62080. for (int i = bevelThickness; --i >= 0;)
  62081. {
  62082. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  62083. : oldOpacity;
  62084. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  62085. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  62086. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  62087. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  62088. }
  62089. }
  62090. }
  62091. void Graphics::fillEllipse (const float x,
  62092. const float y,
  62093. const float width,
  62094. const float height) const throw()
  62095. {
  62096. // passing in a silly number can cause maths problems in rendering!
  62097. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62098. Path p;
  62099. p.addEllipse (x, y, width, height);
  62100. fillPath (p);
  62101. }
  62102. void Graphics::drawEllipse (const float x,
  62103. const float y,
  62104. const float width,
  62105. const float height,
  62106. const float lineThickness) const throw()
  62107. {
  62108. // passing in a silly number can cause maths problems in rendering!
  62109. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62110. Path p;
  62111. p.addEllipse (x, y, width, height);
  62112. strokePath (p, PathStrokeType (lineThickness));
  62113. }
  62114. void Graphics::fillRoundedRectangle (const float x,
  62115. const float y,
  62116. const float width,
  62117. const float height,
  62118. const float cornerSize) const throw()
  62119. {
  62120. // passing in a silly number can cause maths problems in rendering!
  62121. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62122. Path p;
  62123. p.addRoundedRectangle (x, y, width, height, cornerSize);
  62124. fillPath (p);
  62125. }
  62126. void Graphics::fillRoundedRectangle (const Rectangle& r,
  62127. const float cornerSize) const throw()
  62128. {
  62129. fillRoundedRectangle ((float) r.getX(),
  62130. (float) r.getY(),
  62131. (float) r.getWidth(),
  62132. (float) r.getHeight(),
  62133. cornerSize);
  62134. }
  62135. void Graphics::drawRoundedRectangle (const float x,
  62136. const float y,
  62137. const float width,
  62138. const float height,
  62139. const float cornerSize,
  62140. const float lineThickness) const throw()
  62141. {
  62142. // passing in a silly number can cause maths problems in rendering!
  62143. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  62144. Path p;
  62145. p.addRoundedRectangle (x, y, width, height, cornerSize);
  62146. strokePath (p, PathStrokeType (lineThickness));
  62147. }
  62148. void Graphics::drawRoundedRectangle (const Rectangle& r,
  62149. const float cornerSize,
  62150. const float lineThickness) const throw()
  62151. {
  62152. drawRoundedRectangle ((float) r.getX(),
  62153. (float) r.getY(),
  62154. (float) r.getWidth(),
  62155. (float) r.getHeight(),
  62156. cornerSize, lineThickness);
  62157. }
  62158. void Graphics::drawArrow (const float startX,
  62159. const float startY,
  62160. const float endX,
  62161. const float endY,
  62162. const float lineThickness,
  62163. const float arrowheadWidth,
  62164. const float arrowheadLength) const throw()
  62165. {
  62166. Path p;
  62167. p.addArrow (startX, startY, endX, endY,
  62168. lineThickness, arrowheadWidth, arrowheadLength);
  62169. fillPath (p);
  62170. }
  62171. void Graphics::fillCheckerBoard (int x, int y,
  62172. int width, int height,
  62173. const int checkWidth,
  62174. const int checkHeight,
  62175. const Colour& colour1,
  62176. const Colour& colour2) const throw()
  62177. {
  62178. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  62179. if (checkWidth > 0 && checkHeight > 0)
  62180. {
  62181. if (colour1 == colour2)
  62182. {
  62183. context->fillRectWithColour (x, y, width, height, colour1, false);
  62184. }
  62185. else
  62186. {
  62187. const Rectangle clip (context->getClipBounds());
  62188. const int right = jmin (x + width, clip.getRight());
  62189. const int bottom = jmin (y + height, clip.getBottom());
  62190. int cy = 0;
  62191. while (y < bottom)
  62192. {
  62193. int cx = cy;
  62194. for (int xx = x; xx < right; xx += checkWidth)
  62195. context->fillRectWithColour (xx, y,
  62196. jmin (checkWidth, right - xx),
  62197. jmin (checkHeight, bottom - y),
  62198. ((cx++ & 1) == 0) ? colour1 : colour2,
  62199. false);
  62200. ++cy;
  62201. y += checkHeight;
  62202. }
  62203. }
  62204. }
  62205. }
  62206. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  62207. {
  62208. SolidColourBrush colourBrush (state->colour);
  62209. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  62210. }
  62211. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  62212. {
  62213. SolidColourBrush colourBrush (state->colour);
  62214. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  62215. }
  62216. void Graphics::drawLine (float x1, float y1,
  62217. float x2, float y2) const throw()
  62218. {
  62219. if (! context->isClipEmpty())
  62220. {
  62221. SolidColourBrush colourBrush (state->colour);
  62222. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  62223. }
  62224. }
  62225. void Graphics::drawLine (const float startX,
  62226. const float startY,
  62227. const float endX,
  62228. const float endY,
  62229. const float lineThickness) const throw()
  62230. {
  62231. Path p;
  62232. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  62233. fillPath (p);
  62234. }
  62235. void Graphics::drawLine (const Line& line) const throw()
  62236. {
  62237. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  62238. }
  62239. void Graphics::drawLine (const Line& line,
  62240. const float lineThickness) const throw()
  62241. {
  62242. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  62243. }
  62244. void Graphics::drawDashedLine (const float startX,
  62245. const float startY,
  62246. const float endX,
  62247. const float endY,
  62248. const float* const dashLengths,
  62249. const int numDashLengths,
  62250. const float lineThickness) const throw()
  62251. {
  62252. const double dx = endX - startX;
  62253. const double dy = endY - startY;
  62254. const double totalLen = juce_hypot (dx, dy);
  62255. if (totalLen >= 0.5)
  62256. {
  62257. const double onePixAlpha = 1.0 / totalLen;
  62258. double alpha = 0.0;
  62259. float x = startX;
  62260. float y = startY;
  62261. int n = 0;
  62262. while (alpha < 1.0f)
  62263. {
  62264. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  62265. n = n % numDashLengths;
  62266. const float oldX = x;
  62267. const float oldY = y;
  62268. x = (float) (startX + dx * alpha);
  62269. y = (float) (startY + dy * alpha);
  62270. if ((n & 1) != 0)
  62271. {
  62272. if (lineThickness != 1.0f)
  62273. drawLine (oldX, oldY, x, y, lineThickness);
  62274. else
  62275. drawLine (oldX, oldY, x, y);
  62276. }
  62277. }
  62278. }
  62279. }
  62280. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  62281. {
  62282. saveStateIfPending();
  62283. state->quality = newQuality;
  62284. }
  62285. void Graphics::drawImageAt (const Image* const imageToDraw,
  62286. const int topLeftX,
  62287. const int topLeftY,
  62288. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62289. {
  62290. if (imageToDraw != 0)
  62291. {
  62292. const int imageW = imageToDraw->getWidth();
  62293. const int imageH = imageToDraw->getHeight();
  62294. drawImage (imageToDraw,
  62295. topLeftX, topLeftY, imageW, imageH,
  62296. 0, 0, imageW, imageH,
  62297. fillAlphaChannelWithCurrentBrush);
  62298. }
  62299. }
  62300. void Graphics::drawImageWithin (const Image* const imageToDraw,
  62301. const int destX,
  62302. const int destY,
  62303. const int destW,
  62304. const int destH,
  62305. const RectanglePlacement& placementWithinTarget,
  62306. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62307. {
  62308. // passing in a silly number can cause maths problems in rendering!
  62309. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  62310. if (imageToDraw != 0)
  62311. {
  62312. const int imageW = imageToDraw->getWidth();
  62313. const int imageH = imageToDraw->getHeight();
  62314. if (imageW > 0 && imageH > 0)
  62315. {
  62316. double newX = 0.0, newY = 0.0;
  62317. double newW = imageW;
  62318. double newH = imageH;
  62319. placementWithinTarget.applyTo (newX, newY, newW, newH,
  62320. destX, destY, destW, destH);
  62321. if (newW > 0 && newH > 0)
  62322. {
  62323. drawImage (imageToDraw,
  62324. roundDoubleToInt (newX), roundDoubleToInt (newY),
  62325. roundDoubleToInt (newW), roundDoubleToInt (newH),
  62326. 0, 0, imageW, imageH,
  62327. fillAlphaChannelWithCurrentBrush);
  62328. }
  62329. }
  62330. }
  62331. }
  62332. void Graphics::drawImage (const Image* const imageToDraw,
  62333. int dx, int dy, int dw, int dh,
  62334. int sx, int sy, int sw, int sh,
  62335. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62336. {
  62337. // passing in a silly number can cause maths problems in rendering!
  62338. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  62339. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  62340. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  62341. return;
  62342. if (sw == dw && sh == dh)
  62343. {
  62344. if (sx < 0)
  62345. {
  62346. dx -= sx;
  62347. dw += sx;
  62348. sw += sx;
  62349. sx = 0;
  62350. }
  62351. if (sx + sw > imageToDraw->getWidth())
  62352. {
  62353. const int amount = sx + sw - imageToDraw->getWidth();
  62354. dw -= amount;
  62355. sw -= amount;
  62356. }
  62357. if (sy < 0)
  62358. {
  62359. dy -= sy;
  62360. dh += sy;
  62361. sh += sy;
  62362. sy = 0;
  62363. }
  62364. if (sy + sh > imageToDraw->getHeight())
  62365. {
  62366. const int amount = sy + sh - imageToDraw->getHeight();
  62367. dh -= amount;
  62368. sh -= amount;
  62369. }
  62370. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62371. return;
  62372. if (fillAlphaChannelWithCurrentBrush)
  62373. {
  62374. SolidColourBrush colourBrush (state->colour);
  62375. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62376. .paintAlphaChannel (*context, *imageToDraw,
  62377. dx - sx, dy - sy,
  62378. dx, dy,
  62379. dw, dh);
  62380. }
  62381. else
  62382. {
  62383. context->blendImage (*imageToDraw,
  62384. dx, dy, dw, dh, sx, sy,
  62385. state->colour.getFloatAlpha());
  62386. }
  62387. }
  62388. else
  62389. {
  62390. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62391. return;
  62392. if (fillAlphaChannelWithCurrentBrush)
  62393. {
  62394. if (imageToDraw->isRGB())
  62395. {
  62396. fillRect (dx, dy, dw, dh);
  62397. }
  62398. else
  62399. {
  62400. int tx = dx;
  62401. int ty = dy;
  62402. int tw = dw;
  62403. int th = dh;
  62404. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62405. {
  62406. Image temp (imageToDraw->getFormat(), tw, th, true);
  62407. Graphics g (temp);
  62408. g.setImageResamplingQuality (state->quality);
  62409. g.setOrigin (dx - tx, dy - ty);
  62410. g.drawImage (imageToDraw,
  62411. 0, 0, dw, dh,
  62412. sx, sy, sw, sh,
  62413. false);
  62414. SolidColourBrush colourBrush (state->colour);
  62415. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62416. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62417. }
  62418. }
  62419. }
  62420. else
  62421. {
  62422. context->blendImageRescaling (*imageToDraw,
  62423. dx, dy, dw, dh,
  62424. sx, sy, sw, sh,
  62425. state->colour.getFloatAlpha(),
  62426. state->quality);
  62427. }
  62428. }
  62429. }
  62430. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  62431. int sourceClipX,
  62432. int sourceClipY,
  62433. int sourceClipWidth,
  62434. int sourceClipHeight,
  62435. const AffineTransform& transform,
  62436. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62437. {
  62438. if (imageToDraw != 0
  62439. && (! context->isClipEmpty())
  62440. && ! transform.isSingularity())
  62441. {
  62442. if (transform.isIdentity())
  62443. {
  62444. drawImage (imageToDraw,
  62445. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62446. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62447. fillAlphaChannelWithCurrentBrush);
  62448. }
  62449. else if (fillAlphaChannelWithCurrentBrush)
  62450. {
  62451. Path p;
  62452. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  62453. (float) sourceClipWidth, (float) sourceClipHeight);
  62454. p.applyTransform (transform);
  62455. float dx, dy, dw, dh;
  62456. p.getBounds (dx, dy, dw, dh);
  62457. int tx = (int) dx;
  62458. int ty = (int) dy;
  62459. int tw = roundFloatToInt (dw) + 2;
  62460. int th = roundFloatToInt (dh) + 2;
  62461. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62462. {
  62463. Image temp (imageToDraw->getFormat(), tw, th, true);
  62464. Graphics g (temp);
  62465. g.setImageResamplingQuality (state->quality);
  62466. g.drawImageTransformed (imageToDraw,
  62467. sourceClipX,
  62468. sourceClipY,
  62469. sourceClipWidth,
  62470. sourceClipHeight,
  62471. transform.translated ((float) -tx, (float) -ty),
  62472. false);
  62473. SolidColourBrush colourBrush (state->colour);
  62474. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62475. }
  62476. }
  62477. else
  62478. {
  62479. context->blendImageWarping (*imageToDraw,
  62480. sourceClipX,
  62481. sourceClipY,
  62482. sourceClipWidth,
  62483. sourceClipHeight,
  62484. transform,
  62485. state->colour.getFloatAlpha(),
  62486. state->quality);
  62487. }
  62488. }
  62489. }
  62490. END_JUCE_NAMESPACE
  62491. /********* End of inlined file: juce_Graphics.cpp *********/
  62492. /********* Start of inlined file: juce_Justification.cpp *********/
  62493. BEGIN_JUCE_NAMESPACE
  62494. Justification::Justification (const Justification& other) throw()
  62495. : flags (other.flags)
  62496. {
  62497. }
  62498. const Justification& Justification::operator= (const Justification& other) throw()
  62499. {
  62500. flags = other.flags;
  62501. return *this;
  62502. }
  62503. int Justification::getOnlyVerticalFlags() const throw()
  62504. {
  62505. return flags & (top | bottom | verticallyCentred);
  62506. }
  62507. int Justification::getOnlyHorizontalFlags() const throw()
  62508. {
  62509. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  62510. }
  62511. void Justification::applyToRectangle (int& x, int& y,
  62512. const int w, const int h,
  62513. const int spaceX, const int spaceY,
  62514. const int spaceW, const int spaceH) const throw()
  62515. {
  62516. if ((flags & horizontallyCentred) != 0)
  62517. {
  62518. x = spaceX + ((spaceW - w) >> 1);
  62519. }
  62520. else if ((flags & right) != 0)
  62521. {
  62522. x = spaceX + spaceW - w;
  62523. }
  62524. else
  62525. {
  62526. x = spaceX;
  62527. }
  62528. if ((flags & verticallyCentred) != 0)
  62529. {
  62530. y = spaceY + ((spaceH - h) >> 1);
  62531. }
  62532. else if ((flags & bottom) != 0)
  62533. {
  62534. y = spaceY + spaceH - h;
  62535. }
  62536. else
  62537. {
  62538. y = spaceY;
  62539. }
  62540. }
  62541. END_JUCE_NAMESPACE
  62542. /********* End of inlined file: juce_Justification.cpp *********/
  62543. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62544. BEGIN_JUCE_NAMESPACE
  62545. #if JUCE_MSVC
  62546. #pragma warning (disable: 4996) // deprecated sprintf warning
  62547. #endif
  62548. // this will throw an assertion if you try to draw something that's not
  62549. // possible in postscript
  62550. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  62551. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  62552. #define notPossibleInPostscriptAssert jassertfalse
  62553. #else
  62554. #define notPossibleInPostscriptAssert
  62555. #endif
  62556. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  62557. const String& documentTitle,
  62558. const int totalWidth_,
  62559. const int totalHeight_)
  62560. : out (resultingPostScript),
  62561. totalWidth (totalWidth_),
  62562. totalHeight (totalHeight_),
  62563. xOffset (0),
  62564. yOffset (0),
  62565. needToClip (true)
  62566. {
  62567. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  62568. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  62569. out << "%!PS-Adobe-3.0 EPSF-3.0"
  62570. "\n%%BoundingBox: 0 0 600 824"
  62571. "\n%%Pages: 0"
  62572. "\n%%Creator: Raw Material Software JUCE"
  62573. "\n%%Title: " << documentTitle <<
  62574. "\n%%CreationDate: none"
  62575. "\n%%LanguageLevel: 2"
  62576. "\n%%EndComments"
  62577. "\n%%BeginProlog"
  62578. "\n%%BeginResource: JRes"
  62579. "\n/bd {bind def} bind def"
  62580. "\n/c {setrgbcolor} bd"
  62581. "\n/m {moveto} bd"
  62582. "\n/l {lineto} bd"
  62583. "\n/rl {rlineto} bd"
  62584. "\n/ct {curveto} bd"
  62585. "\n/cp {closepath} bd"
  62586. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  62587. "\n/doclip {initclip newpath} bd"
  62588. "\n/endclip {clip newpath} bd"
  62589. "\n%%EndResource"
  62590. "\n%%EndProlog"
  62591. "\n%%BeginSetup"
  62592. "\n%%EndSetup"
  62593. "\n%%Page: 1 1"
  62594. "\n%%BeginPageSetup"
  62595. "\n%%EndPageSetup\n\n"
  62596. << "40 800 translate\n"
  62597. << scale << ' ' << scale << " scale\n\n";
  62598. }
  62599. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  62600. {
  62601. delete clip;
  62602. }
  62603. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  62604. {
  62605. return true;
  62606. }
  62607. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  62608. {
  62609. if (x != 0 || y != 0)
  62610. {
  62611. xOffset += x;
  62612. yOffset += y;
  62613. needToClip = true;
  62614. }
  62615. }
  62616. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  62617. {
  62618. needToClip = true;
  62619. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62620. }
  62621. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62622. {
  62623. needToClip = true;
  62624. return clip->clipTo (clipRegion);
  62625. }
  62626. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  62627. {
  62628. needToClip = true;
  62629. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62630. }
  62631. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62632. {
  62633. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62634. }
  62635. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  62636. {
  62637. return clip->getBounds().translated (-xOffset, -yOffset);
  62638. }
  62639. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  62640. {
  62641. return clip->isEmpty();
  62642. }
  62643. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  62644. const int xOffset_, const int yOffset_)
  62645. : clip (clip_),
  62646. xOffset (xOffset_),
  62647. yOffset (yOffset_)
  62648. {
  62649. }
  62650. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  62651. {
  62652. delete clip;
  62653. }
  62654. void LowLevelGraphicsPostScriptRenderer::saveState()
  62655. {
  62656. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62657. }
  62658. void LowLevelGraphicsPostScriptRenderer::restoreState()
  62659. {
  62660. SavedState* const top = stateStack.getLast();
  62661. if (top != 0)
  62662. {
  62663. clip->swapWith (*top->clip);
  62664. xOffset = top->xOffset;
  62665. yOffset = top->yOffset;
  62666. stateStack.removeLast();
  62667. needToClip = true;
  62668. }
  62669. else
  62670. {
  62671. jassertfalse // trying to pop with an empty stack!
  62672. }
  62673. }
  62674. void LowLevelGraphicsPostScriptRenderer::writeClip()
  62675. {
  62676. if (needToClip)
  62677. {
  62678. needToClip = false;
  62679. out << "doclip ";
  62680. int itemsOnLine = 0;
  62681. for (RectangleList::Iterator i (*clip); i.next();)
  62682. {
  62683. if (++itemsOnLine == 6)
  62684. {
  62685. itemsOnLine = 0;
  62686. out << '\n';
  62687. }
  62688. const Rectangle& r = *i.getRectangle();
  62689. out << r.getX() << ' ' << -r.getY() << ' '
  62690. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  62691. }
  62692. out << "endclip\n";
  62693. }
  62694. }
  62695. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  62696. {
  62697. Colour c (Colours::white.overlaidWith (colour));
  62698. if (lastColour != c)
  62699. {
  62700. lastColour = c;
  62701. out << String (c.getFloatRed(), 3) << ' '
  62702. << String (c.getFloatGreen(), 3) << ' '
  62703. << String (c.getFloatBlue(), 3) << " c\n";
  62704. }
  62705. }
  62706. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  62707. {
  62708. out << String (x, 2) << ' '
  62709. << String (-y, 2) << ' ';
  62710. }
  62711. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  62712. {
  62713. out << "newpath ";
  62714. float lastX = 0.0f;
  62715. float lastY = 0.0f;
  62716. int itemsOnLine = 0;
  62717. Path::Iterator i (path);
  62718. while (i.next())
  62719. {
  62720. if (++itemsOnLine == 4)
  62721. {
  62722. itemsOnLine = 0;
  62723. out << '\n';
  62724. }
  62725. switch (i.elementType)
  62726. {
  62727. case Path::Iterator::startNewSubPath:
  62728. writeXY (i.x1, i.y1);
  62729. lastX = i.x1;
  62730. lastY = i.y1;
  62731. out << "m ";
  62732. break;
  62733. case Path::Iterator::lineTo:
  62734. writeXY (i.x1, i.y1);
  62735. lastX = i.x1;
  62736. lastY = i.y1;
  62737. out << "l ";
  62738. break;
  62739. case Path::Iterator::quadraticTo:
  62740. {
  62741. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  62742. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  62743. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  62744. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  62745. writeXY (cp1x, cp1y);
  62746. writeXY (cp2x, cp2y);
  62747. writeXY (i.x2, i.y2);
  62748. out << "ct ";
  62749. lastX = i.x2;
  62750. lastY = i.y2;
  62751. }
  62752. break;
  62753. case Path::Iterator::cubicTo:
  62754. writeXY (i.x1, i.y1);
  62755. writeXY (i.x2, i.y2);
  62756. writeXY (i.x3, i.y3);
  62757. out << "ct ";
  62758. lastX = i.x3;
  62759. lastY = i.y3;
  62760. break;
  62761. case Path::Iterator::closePath:
  62762. out << "cp ";
  62763. break;
  62764. default:
  62765. jassertfalse
  62766. break;
  62767. }
  62768. }
  62769. out << '\n';
  62770. }
  62771. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  62772. {
  62773. out << "[ "
  62774. << trans.mat00 << ' '
  62775. << trans.mat10 << ' '
  62776. << trans.mat01 << ' '
  62777. << trans.mat11 << ' '
  62778. << trans.mat02 << ' '
  62779. << trans.mat12 << " ] concat ";
  62780. }
  62781. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  62782. {
  62783. writeClip();
  62784. writeColour (colour);
  62785. x += xOffset;
  62786. y += yOffset;
  62787. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  62788. }
  62789. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62790. {
  62791. Path p;
  62792. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62793. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  62794. }
  62795. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62796. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  62797. {
  62798. writeClip();
  62799. Path p (path);
  62800. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62801. writePath (p);
  62802. writeColour (colour);
  62803. out << "fill\n";
  62804. }
  62805. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  62806. {
  62807. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  62808. // postscript can't do semi-transparent ones.
  62809. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62810. writeClip();
  62811. out << "gsave ";
  62812. {
  62813. Path p (path);
  62814. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62815. writePath (p);
  62816. out << "clip\n";
  62817. }
  62818. int numColours = 256;
  62819. PixelARGB* const colours = gradient.createLookupTable (numColours);
  62820. for (int i = numColours; --i >= 0;)
  62821. colours[i].unpremultiply();
  62822. const Rectangle bounds (clip->getBounds());
  62823. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  62824. // time-being, this just fills it with the average colour..
  62825. writeColour (Colour (colours [numColours / 2].getARGB()));
  62826. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  62827. juce_free (colours);
  62828. out << "grestore\n";
  62829. }
  62830. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62831. const Image& sourceImage,
  62832. int imageX, int imageY,
  62833. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  62834. {
  62835. writeClip();
  62836. out << "gsave ";
  62837. Path p (path);
  62838. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  62839. writePath (p);
  62840. out << "clip\n";
  62841. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  62842. out << "grestore\n";
  62843. }
  62844. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  62845. {
  62846. x += xOffset;
  62847. y += yOffset;
  62848. writeClip();
  62849. writeColour (colour);
  62850. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62851. }
  62852. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  62853. {
  62854. imageX += xOffset;
  62855. imageY += yOffset;
  62856. writeClip();
  62857. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62858. }
  62859. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  62860. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  62861. {
  62862. alphaImageX += xOffset;
  62863. alphaImageY += yOffset;
  62864. fillerImageX += xOffset;
  62865. fillerImageY += yOffset;
  62866. writeClip();
  62867. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62868. }
  62869. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  62870. int dx, int dy, int dw, int dh,
  62871. int sx, int sy, int sw, int sh,
  62872. float alpha,
  62873. const Graphics::ResamplingQuality quality)
  62874. {
  62875. if (sw > 0 && sh > 0)
  62876. {
  62877. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  62878. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  62879. if (sw == dw && sh == dh)
  62880. {
  62881. blendImage (sourceImage,
  62882. dx, dy, dw, dh,
  62883. sx, sy, alpha);
  62884. }
  62885. else
  62886. {
  62887. blendImageWarping (sourceImage,
  62888. sx, sy, sw, sh,
  62889. AffineTransform::scale (dw / (float) sw,
  62890. dh / (float) sh)
  62891. .translated ((float) (dx - sx),
  62892. (float) (dy - sy)),
  62893. alpha,
  62894. quality);
  62895. }
  62896. }
  62897. }
  62898. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62899. {
  62900. blendImageWarping (sourceImage,
  62901. sx, sy, dw, dh,
  62902. AffineTransform::translation ((float) dx, (float) dy),
  62903. opacity, Graphics::highResamplingQuality);
  62904. }
  62905. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  62906. const int sx, const int sy,
  62907. const int maxW, const int maxH) const
  62908. {
  62909. out << "{<\n";
  62910. const int w = jmin (maxW, im.getWidth());
  62911. const int h = jmin (maxH, im.getHeight());
  62912. int charsOnLine = 0;
  62913. int lineStride, pixelStride;
  62914. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  62915. Colour pixel;
  62916. for (int y = h; --y >= 0;)
  62917. {
  62918. for (int x = 0; x < w; ++x)
  62919. {
  62920. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  62921. if (x >= sx && y >= sy)
  62922. {
  62923. if (im.isARGB())
  62924. {
  62925. PixelARGB p (*(const PixelARGB*) pixelData);
  62926. p.unpremultiply();
  62927. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  62928. }
  62929. else if (im.isRGB())
  62930. {
  62931. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  62932. }
  62933. else
  62934. {
  62935. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  62936. }
  62937. }
  62938. else
  62939. {
  62940. pixel = Colours::transparentWhite;
  62941. }
  62942. char colourString [16];
  62943. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  62944. out << (const char*) colourString;
  62945. charsOnLine += 3;
  62946. if (charsOnLine > 100)
  62947. {
  62948. out << '\n';
  62949. charsOnLine = 0;
  62950. }
  62951. }
  62952. }
  62953. im.releasePixelDataReadOnly (data);
  62954. out << "\n>}\n";
  62955. }
  62956. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  62957. int srcClipX, int srcClipY,
  62958. int srcClipW, int srcClipH,
  62959. const AffineTransform& t,
  62960. float /*opacity*/,
  62961. const Graphics::ResamplingQuality /*quality*/)
  62962. {
  62963. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  62964. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  62965. writeClip();
  62966. out << "gsave ";
  62967. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  62968. .scaled (1.0f, -1.0f));
  62969. RectangleList imageClip;
  62970. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  62971. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  62972. out << "newpath ";
  62973. int itemsOnLine = 0;
  62974. for (RectangleList::Iterator i (imageClip); i.next();)
  62975. {
  62976. if (++itemsOnLine == 6)
  62977. {
  62978. out << '\n';
  62979. itemsOnLine = 0;
  62980. }
  62981. const Rectangle& r = *i.getRectangle();
  62982. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  62983. }
  62984. out << " clip newpath\n";
  62985. out << w << ' ' << h << " scale\n";
  62986. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  62987. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  62988. out << "false 3 colorimage grestore\n";
  62989. needToClip = true;
  62990. }
  62991. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62992. {
  62993. Path p;
  62994. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  62995. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  62996. }
  62997. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62998. {
  62999. drawLine (x, top, x, bottom, col);
  63000. }
  63001. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  63002. {
  63003. drawLine (left, y, right, y, col);
  63004. }
  63005. END_JUCE_NAMESPACE
  63006. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  63007. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  63008. BEGIN_JUCE_NAMESPACE
  63009. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  63010. #define JUCE_USE_SSE_INSTRUCTIONS 1
  63011. #endif
  63012. #if JUCE_DEBUG && JUCE_MSVC
  63013. #pragma warning (disable: 4714)
  63014. #endif
  63015. #define MINIMUM_COORD -0x3fffffff
  63016. #define MAXIMUM_COORD 0x3fffffff
  63017. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  63018. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  63019. jassert ((int) x >= MINIMUM_COORD \
  63020. && (int) x <= MAXIMUM_COORD \
  63021. && (int) y >= MINIMUM_COORD \
  63022. && (int) y <= MAXIMUM_COORD \
  63023. && (int) w >= 0 \
  63024. && (int) w < MAXIMUM_COORD \
  63025. && (int) h >= 0 \
  63026. && (int) h < MAXIMUM_COORD);
  63027. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63028. {
  63029. const PixelARGB blendColour (colour.getPixelARGB());
  63030. if (w < 32)
  63031. {
  63032. while (--h >= 0)
  63033. {
  63034. PixelRGB* dest = (PixelRGB*) pixels;
  63035. for (int i = w; --i >= 0;)
  63036. (dest++)->set (blendColour);
  63037. pixels += stride;
  63038. }
  63039. }
  63040. else
  63041. {
  63042. // for wider fills, it's worth using some optimisations..
  63043. const uint8 r = blendColour.getRed();
  63044. const uint8 g = blendColour.getGreen();
  63045. const uint8 b = blendColour.getBlue();
  63046. if (r == g && r == b) // if all the component values are the same, we can cheat..
  63047. {
  63048. while (--h >= 0)
  63049. {
  63050. memset (pixels, r, w * 3);
  63051. pixels += stride;
  63052. }
  63053. }
  63054. else
  63055. {
  63056. PixelRGB filler [4];
  63057. filler[0].set (blendColour);
  63058. filler[1].set (blendColour);
  63059. filler[2].set (blendColour);
  63060. filler[3].set (blendColour);
  63061. const int* const intFiller = (const int*) filler;
  63062. while (--h >= 0)
  63063. {
  63064. uint8* dest = (uint8*) pixels;
  63065. int i = w;
  63066. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  63067. {
  63068. ((PixelRGB*) dest)->set (blendColour);
  63069. dest += 3;
  63070. --i;
  63071. }
  63072. while (i >= 4)
  63073. {
  63074. ((int*) dest) [0] = intFiller[0];
  63075. ((int*) dest) [1] = intFiller[1];
  63076. ((int*) dest) [2] = intFiller[2];
  63077. dest += 12;
  63078. i -= 4;
  63079. }
  63080. while (--i >= 0)
  63081. {
  63082. ((PixelRGB*) dest)->set (blendColour);
  63083. dest += 3;
  63084. }
  63085. pixels += stride;
  63086. }
  63087. }
  63088. }
  63089. }
  63090. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63091. {
  63092. const PixelARGB blendColour (colour.getPixelARGB());
  63093. while (--h >= 0)
  63094. {
  63095. PixelARGB* const dest = (PixelARGB*) pixels;
  63096. for (int i = 0; i < w; ++i)
  63097. dest[i] = blendColour;
  63098. pixels += stride;
  63099. }
  63100. }
  63101. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63102. {
  63103. if (colour.isOpaque())
  63104. {
  63105. replaceRectRGB (pixels, w, h, stride, colour);
  63106. }
  63107. else
  63108. {
  63109. const PixelARGB blendColour (colour.getPixelARGB());
  63110. const int alpha = blendColour.getAlpha();
  63111. if (alpha <= 0)
  63112. return;
  63113. #if JUCE_USE_SSE_INSTRUCTIONS
  63114. if (SystemStats::hasSSE())
  63115. {
  63116. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  63117. | (int64) ((blendColour.getGreen() << 16)
  63118. | blendColour.getBlue());
  63119. const int invAlpha = 0xff - alpha;
  63120. int64 aaaa = (invAlpha << 16) | invAlpha;
  63121. aaaa = (aaaa << 16) | aaaa;
  63122. #ifndef JUCE_GCC
  63123. __asm
  63124. {
  63125. movq mm1, aaaa
  63126. movq mm2, rgb0
  63127. pxor mm7, mm7
  63128. }
  63129. while (--h >= 0)
  63130. {
  63131. __asm
  63132. {
  63133. mov edx, pixels
  63134. mov ebx, w
  63135. pixloop:
  63136. prefetchnta [edx]
  63137. mov ax, [edx + 1]
  63138. shl eax, 8
  63139. mov al, [edx]
  63140. movd mm0, eax
  63141. punpcklbw mm0, mm7
  63142. pmullw mm0, mm1
  63143. psrlw mm0, 8
  63144. paddw mm0, mm2
  63145. packuswb mm0, mm7
  63146. movd eax, mm0
  63147. mov [edx], al
  63148. inc edx
  63149. shr eax, 8
  63150. mov [edx], ax
  63151. add edx, 2
  63152. dec ebx
  63153. jg pixloop
  63154. }
  63155. pixels += stride;
  63156. }
  63157. __asm emms
  63158. #else
  63159. __asm__ __volatile__ (
  63160. "\tpush %%ebx \n"
  63161. "\tmovq %[aaaa], %%mm1 \n"
  63162. "\tmovq %[rgb0], %%mm2 \n"
  63163. "\tpxor %%mm7, %%mm7 \n"
  63164. ".lineLoop2: \n"
  63165. "\tmovl %%esi,%%edx \n"
  63166. "\tmovl %[w], %%ebx \n"
  63167. ".pixLoop2: \n"
  63168. "\tprefetchnta (%%edx) \n"
  63169. "\tmov (%%edx), %%ax \n"
  63170. "\tshl $8, %%eax \n"
  63171. "\tmov 2(%%edx), %%al \n"
  63172. "\tmovd %%eax, %%mm0 \n"
  63173. "\tpunpcklbw %%mm7, %%mm0 \n"
  63174. "\tpmullw %%mm1, %%mm0 \n"
  63175. "\tpsrlw $8, %%mm0 \n"
  63176. "\tpaddw %%mm2, %%mm0 \n"
  63177. "\tpackuswb %%mm7, %%mm0 \n"
  63178. "\tmovd %%mm0, %%eax \n"
  63179. "\tmovb %%al, (%%edx) \n"
  63180. "\tinc %%edx \n"
  63181. "\tshr $8, %%eax \n"
  63182. "\tmovw %%ax, (%%edx) \n"
  63183. "\tadd $2, %%edx \n"
  63184. "\tdec %%ebx \n"
  63185. "\tjg .pixLoop2 \n"
  63186. "\tadd %%edi, %%esi \n"
  63187. "\tdec %%ecx \n"
  63188. "\tjg .lineLoop2 \n"
  63189. "\tpop %%ebx \n"
  63190. "\temms \n"
  63191. : /* No output registers */
  63192. : [aaaa] "m" (aaaa), /* Input registers */
  63193. [rgb0] "m" (rgb0),
  63194. [w] "m" (w),
  63195. "c" (h),
  63196. [stride] "D" (stride),
  63197. [pixels] "S" (pixels)
  63198. : "cc", "eax", "edx", "memory" /* Clobber list */
  63199. );
  63200. #endif
  63201. }
  63202. else
  63203. #endif
  63204. {
  63205. while (--h >= 0)
  63206. {
  63207. PixelRGB* dest = (PixelRGB*) pixels;
  63208. for (int i = w; --i >= 0;)
  63209. (dest++)->blend (blendColour);
  63210. pixels += stride;
  63211. }
  63212. }
  63213. }
  63214. }
  63215. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63216. {
  63217. if (colour.isOpaque())
  63218. {
  63219. replaceRectARGB (pixels, w, h, stride, colour);
  63220. }
  63221. else
  63222. {
  63223. const PixelARGB blendColour (colour.getPixelARGB());
  63224. const int alpha = blendColour.getAlpha();
  63225. if (alpha <= 0)
  63226. return;
  63227. while (--h >= 0)
  63228. {
  63229. PixelARGB* dest = (PixelARGB*) pixels;
  63230. for (int i = w; --i >= 0;)
  63231. (dest++)->blend (blendColour);
  63232. pixels += stride;
  63233. }
  63234. }
  63235. }
  63236. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  63237. const uint8* alphaValues, const int w, int h,
  63238. const int pixelStride, const int lineStride,
  63239. const Colour& colour) throw()
  63240. {
  63241. const PixelARGB srcPix (colour.getPixelARGB());
  63242. while (--h >= 0)
  63243. {
  63244. PixelARGB* dest = (PixelARGB*) destPixel;
  63245. const uint8* src = alphaValues;
  63246. int i = w;
  63247. while (--i >= 0)
  63248. {
  63249. unsigned int srcAlpha = *src;
  63250. src += pixelStride;
  63251. if (srcAlpha > 0)
  63252. dest->blend (srcPix, srcAlpha);
  63253. ++dest;
  63254. }
  63255. alphaValues += lineStride;
  63256. destPixel += imageStride;
  63257. }
  63258. }
  63259. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  63260. const uint8* alphaValues, int const width, int height,
  63261. const int pixelStride, const int lineStride,
  63262. const Colour& colour) throw()
  63263. {
  63264. const PixelARGB srcPix (colour.getPixelARGB());
  63265. while (--height >= 0)
  63266. {
  63267. PixelRGB* dest = (PixelRGB*) destPixel;
  63268. const uint8* src = alphaValues;
  63269. int i = width;
  63270. while (--i >= 0)
  63271. {
  63272. unsigned int srcAlpha = *src;
  63273. src += pixelStride;
  63274. if (srcAlpha > 0)
  63275. dest->blend (srcPix, srcAlpha);
  63276. ++dest;
  63277. }
  63278. alphaValues += lineStride;
  63279. destPixel += imageStride;
  63280. }
  63281. }
  63282. template <class PixelType>
  63283. class SolidColourEdgeTableRenderer
  63284. {
  63285. uint8* const data;
  63286. const int stride;
  63287. PixelType* linePixels;
  63288. PixelARGB sourceColour;
  63289. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  63290. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  63291. public:
  63292. SolidColourEdgeTableRenderer (uint8* const data_,
  63293. const int stride_,
  63294. const Colour& colour) throw()
  63295. : data (data_),
  63296. stride (stride_),
  63297. sourceColour (colour.getPixelARGB())
  63298. {
  63299. }
  63300. forcedinline void setEdgeTableYPos (const int y) throw()
  63301. {
  63302. linePixels = (PixelType*) (data + stride * y);
  63303. }
  63304. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63305. {
  63306. linePixels[x].blend (sourceColour, alphaLevel);
  63307. }
  63308. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63309. {
  63310. PixelARGB p (sourceColour);
  63311. p.multiplyAlpha (alphaLevel);
  63312. PixelType* dest = linePixels + x;
  63313. if (p.getAlpha() < 0xff)
  63314. {
  63315. do
  63316. {
  63317. dest->blend (p);
  63318. ++dest;
  63319. } while (--width > 0);
  63320. }
  63321. else
  63322. {
  63323. do
  63324. {
  63325. dest->set (p);
  63326. ++dest;
  63327. } while (--width > 0);
  63328. }
  63329. }
  63330. };
  63331. class AlphaBitmapRenderer
  63332. {
  63333. uint8* data;
  63334. int stride;
  63335. uint8* lineStart;
  63336. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  63337. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  63338. public:
  63339. AlphaBitmapRenderer (uint8* const data_,
  63340. const int stride_) throw()
  63341. : data (data_),
  63342. stride (stride_)
  63343. {
  63344. }
  63345. forcedinline void setEdgeTableYPos (const int y) throw()
  63346. {
  63347. lineStart = data + (stride * y);
  63348. }
  63349. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63350. {
  63351. lineStart [x] = (uint8) alphaLevel;
  63352. }
  63353. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63354. {
  63355. uint8* d = lineStart + x;
  63356. while (--width >= 0)
  63357. *d++ = (uint8) alphaLevel;
  63358. }
  63359. };
  63360. static const int numScaleBits = 12;
  63361. class LinearGradientPixelGenerator
  63362. {
  63363. const PixelARGB* const lookupTable;
  63364. const int numEntries;
  63365. PixelARGB linePix;
  63366. int start, scale;
  63367. double grad, yTerm;
  63368. bool vertical, horizontal;
  63369. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  63370. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  63371. public:
  63372. LinearGradientPixelGenerator (const ColourGradient& gradient,
  63373. const PixelARGB* const lookupTable_, const int numEntries_)
  63374. : lookupTable (lookupTable_),
  63375. numEntries (numEntries_)
  63376. {
  63377. jassert (numEntries_ >= 0);
  63378. float x1 = gradient.x1;
  63379. float y1 = gradient.y1;
  63380. float x2 = gradient.x2;
  63381. float y2 = gradient.y2;
  63382. if (! gradient.transform.isIdentity())
  63383. {
  63384. Line l (x2, y2, x1, y1);
  63385. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  63386. float x3 = p3.getX();
  63387. float y3 = p3.getY();
  63388. gradient.transform.transformPoint (x1, y1);
  63389. gradient.transform.transformPoint (x2, y2);
  63390. gradient.transform.transformPoint (x3, y3);
  63391. Line l2 (x2, y2, x3, y3);
  63392. float prop = l2.findNearestPointTo (x1, y1);
  63393. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  63394. x2 = newP2.getX();
  63395. y2 = newP2.getY();
  63396. }
  63397. vertical = fabs (x1 - x2) < 0.001f;
  63398. horizontal = fabs (y1 - y2) < 0.001f;
  63399. if (vertical)
  63400. {
  63401. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  63402. start = roundDoubleToInt (y1 * scale);
  63403. }
  63404. else if (horizontal)
  63405. {
  63406. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  63407. start = roundDoubleToInt (x1 * scale);
  63408. }
  63409. else
  63410. {
  63411. grad = (y2 - y1) / (double) (x1 - x2);
  63412. yTerm = y1 - x1 / grad;
  63413. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  63414. grad *= scale;
  63415. }
  63416. }
  63417. forcedinline void setY (const int y) throw()
  63418. {
  63419. if (vertical)
  63420. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  63421. else if (! horizontal)
  63422. start = roundDoubleToInt ((y - yTerm) * grad);
  63423. }
  63424. forcedinline const PixelARGB getPixel (const int x) const throw()
  63425. {
  63426. if (vertical)
  63427. return linePix;
  63428. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  63429. }
  63430. };
  63431. class RadialGradientPixelGenerator
  63432. {
  63433. protected:
  63434. const PixelARGB* const lookupTable;
  63435. const int numEntries;
  63436. const double gx1, gy1;
  63437. double maxDist, invScale;
  63438. double dy;
  63439. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  63440. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  63441. public:
  63442. RadialGradientPixelGenerator (const ColourGradient& gradient,
  63443. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63444. : lookupTable (lookupTable_),
  63445. numEntries (numEntries_),
  63446. gx1 (gradient.x1),
  63447. gy1 (gradient.y1)
  63448. {
  63449. jassert (numEntries_ >= 0);
  63450. const float dx = gradient.x1 - gradient.x2;
  63451. const float dy = gradient.y1 - gradient.y2;
  63452. maxDist = dx * dx + dy * dy;
  63453. invScale = (numEntries + 1) / sqrt (maxDist);
  63454. }
  63455. forcedinline void setY (const int y) throw()
  63456. {
  63457. dy = y - gy1;
  63458. dy *= dy;
  63459. }
  63460. forcedinline const PixelARGB getPixel (const int px) const throw()
  63461. {
  63462. double x = px - gx1;
  63463. x *= x;
  63464. x += dy;
  63465. if (x >= maxDist)
  63466. return lookupTable [numEntries];
  63467. else
  63468. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63469. }
  63470. };
  63471. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  63472. {
  63473. double tM10, tM00, lineYM01, lineYM11;
  63474. AffineTransform inverseTransform;
  63475. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  63476. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  63477. public:
  63478. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  63479. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63480. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  63481. inverseTransform (gradient.transform.inverted())
  63482. {
  63483. tM10 = inverseTransform.mat10;
  63484. tM00 = inverseTransform.mat00;
  63485. }
  63486. forcedinline void setY (const int y) throw()
  63487. {
  63488. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  63489. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  63490. }
  63491. forcedinline const PixelARGB getPixel (const int px) const throw()
  63492. {
  63493. double x = px;
  63494. const double y = tM10 * x + lineYM11;
  63495. x = tM00 * x + lineYM01;
  63496. x *= x;
  63497. x += y * y;
  63498. if (x >= maxDist)
  63499. return lookupTable [numEntries];
  63500. else
  63501. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63502. }
  63503. };
  63504. template <class PixelType, class GradientType>
  63505. class GradientEdgeTableRenderer : public GradientType
  63506. {
  63507. uint8* const data;
  63508. const int stride;
  63509. PixelType* linePixels;
  63510. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  63511. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  63512. public:
  63513. GradientEdgeTableRenderer (uint8* const data_,
  63514. const int stride_,
  63515. const ColourGradient& gradient,
  63516. const PixelARGB* const lookupTable, const int numEntries) throw()
  63517. : GradientType (gradient, lookupTable, numEntries - 1),
  63518. data (data_),
  63519. stride (stride_)
  63520. {
  63521. }
  63522. forcedinline void setEdgeTableYPos (const int y) throw()
  63523. {
  63524. linePixels = (PixelType*) (data + stride * y);
  63525. GradientType::setY (y);
  63526. }
  63527. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63528. {
  63529. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  63530. }
  63531. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  63532. {
  63533. PixelType* dest = linePixels + x;
  63534. if (alphaLevel < 0xff)
  63535. {
  63536. do
  63537. {
  63538. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  63539. } while (--width > 0);
  63540. }
  63541. else
  63542. {
  63543. do
  63544. {
  63545. (dest++)->blend (GradientType::getPixel (x++));
  63546. } while (--width > 0);
  63547. }
  63548. }
  63549. };
  63550. template <class DestPixelType, class SrcPixelType>
  63551. class ImageFillEdgeTableRenderer
  63552. {
  63553. uint8* const destImageData;
  63554. const uint8* srcImageData;
  63555. int stride, srcStride, extraAlpha;
  63556. DestPixelType* linePixels;
  63557. SrcPixelType* sourceLineStart;
  63558. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  63559. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  63560. public:
  63561. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  63562. const int stride_,
  63563. const uint8* srcImageData_,
  63564. const int srcStride_,
  63565. int extraAlpha_,
  63566. SrcPixelType*) throw() // dummy param to avoid compiler error
  63567. : destImageData (destImageData_),
  63568. srcImageData (srcImageData_),
  63569. stride (stride_),
  63570. srcStride (srcStride_),
  63571. extraAlpha (extraAlpha_)
  63572. {
  63573. }
  63574. forcedinline void setEdgeTableYPos (int y) throw()
  63575. {
  63576. linePixels = (DestPixelType*) (destImageData + stride * y);
  63577. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  63578. }
  63579. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  63580. {
  63581. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63582. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  63583. }
  63584. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  63585. {
  63586. DestPixelType* dest = linePixels + x;
  63587. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63588. if (alphaLevel < 0xfe)
  63589. {
  63590. do
  63591. {
  63592. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  63593. } while (--width > 0);
  63594. }
  63595. else
  63596. {
  63597. do
  63598. {
  63599. dest++ ->blend (sourceLineStart [x++]);
  63600. } while (--width > 0);
  63601. }
  63602. }
  63603. };
  63604. static void blendRowOfPixels (PixelARGB* dst,
  63605. const PixelRGB* src,
  63606. int width) throw()
  63607. {
  63608. while (--width >= 0)
  63609. (dst++)->set (*src++);
  63610. }
  63611. static void blendRowOfPixels (PixelRGB* dst,
  63612. const PixelRGB* src,
  63613. int width) throw()
  63614. {
  63615. memcpy (dst, src, 3 * width);
  63616. }
  63617. static void blendRowOfPixels (PixelRGB* dst,
  63618. const PixelARGB* src,
  63619. int width) throw()
  63620. {
  63621. while (--width >= 0)
  63622. (dst++)->blend (*src++);
  63623. }
  63624. static void blendRowOfPixels (PixelARGB* dst,
  63625. const PixelARGB* src,
  63626. int width) throw()
  63627. {
  63628. while (--width >= 0)
  63629. (dst++)->blend (*src++);
  63630. }
  63631. static void blendRowOfPixels (PixelARGB* dst,
  63632. const PixelRGB* src,
  63633. int width,
  63634. const uint8 alpha) throw()
  63635. {
  63636. while (--width >= 0)
  63637. (dst++)->blend (*src++, alpha);
  63638. }
  63639. static void blendRowOfPixels (PixelRGB* dst,
  63640. const PixelRGB* src,
  63641. int width,
  63642. const uint8 alpha) throw()
  63643. {
  63644. uint8* d = (uint8*) dst;
  63645. const uint8* s = (const uint8*) src;
  63646. const int inverseAlpha = 0xff - alpha;
  63647. while (--width >= 0)
  63648. {
  63649. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  63650. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  63651. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  63652. d += 3;
  63653. s += 3;
  63654. }
  63655. }
  63656. static void blendRowOfPixels (PixelRGB* dst,
  63657. const PixelARGB* src,
  63658. int width,
  63659. const uint8 alpha) throw()
  63660. {
  63661. while (--width >= 0)
  63662. (dst++)->blend (*src++, alpha);
  63663. }
  63664. static void blendRowOfPixels (PixelARGB* dst,
  63665. const PixelARGB* src,
  63666. int width,
  63667. const uint8 alpha) throw()
  63668. {
  63669. while (--width >= 0)
  63670. (dst++)->blend (*src++, alpha);
  63671. }
  63672. template <class DestPixelType, class SrcPixelType>
  63673. static void overlayImage (DestPixelType* dest,
  63674. const int destStride,
  63675. const SrcPixelType* src,
  63676. const int srcStride,
  63677. const int width,
  63678. int height,
  63679. const uint8 alpha) throw()
  63680. {
  63681. if (alpha < 0xff)
  63682. {
  63683. while (--height >= 0)
  63684. {
  63685. blendRowOfPixels (dest, src, width, alpha);
  63686. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63687. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63688. }
  63689. }
  63690. else
  63691. {
  63692. while (--height >= 0)
  63693. {
  63694. blendRowOfPixels (dest, src, width);
  63695. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63696. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63697. }
  63698. }
  63699. }
  63700. template <class DestPixelType, class SrcPixelType>
  63701. static void transformedImageRender (Image& destImage,
  63702. const Image& sourceImage,
  63703. const int destClipX, const int destClipY,
  63704. const int destClipW, const int destClipH,
  63705. const int srcClipX, const int srcClipY,
  63706. const int srcClipWidth, const int srcClipHeight,
  63707. double srcX, double srcY,
  63708. const double lineDX, const double lineDY,
  63709. const double pixelDX, const double pixelDY,
  63710. const uint8 alpha,
  63711. const Graphics::ResamplingQuality quality,
  63712. DestPixelType*,
  63713. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  63714. // parameters of the templated classes to
  63715. // make it use the correct instance of this function..
  63716. {
  63717. int destStride, destPixelStride;
  63718. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  63719. int srcStride, srcPixelStride;
  63720. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  63721. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  63722. {
  63723. if (alpha == 255)
  63724. {
  63725. for (int y = 0; y < destClipH; ++y)
  63726. {
  63727. double sx = srcX;
  63728. double sy = srcY;
  63729. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63730. for (int x = destClipW; --x >= 0;)
  63731. {
  63732. const int ix = ((int) sx) - srcClipX;
  63733. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63734. {
  63735. const int iy = ((int) sy) - srcClipY;
  63736. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63737. {
  63738. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63739. dest->set (*src);
  63740. }
  63741. }
  63742. ++dest;
  63743. sx += pixelDX;
  63744. sy += pixelDY;
  63745. }
  63746. srcX += lineDX;
  63747. srcY += lineDY;
  63748. }
  63749. }
  63750. else
  63751. {
  63752. for (int y = 0; y < destClipH; ++y)
  63753. {
  63754. double sx = srcX;
  63755. double sy = srcY;
  63756. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63757. for (int x = destClipW; --x >= 0;)
  63758. {
  63759. const int ix = ((int) sx) - srcClipX;
  63760. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63761. {
  63762. const int iy = ((int) sy) - srcClipY;
  63763. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63764. {
  63765. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63766. dest->blend (*src, alpha);
  63767. }
  63768. }
  63769. ++dest;
  63770. sx += pixelDX;
  63771. sy += pixelDY;
  63772. }
  63773. srcX += lineDX;
  63774. srcY += lineDY;
  63775. }
  63776. }
  63777. }
  63778. else
  63779. {
  63780. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  63781. for (int y = 0; y < destClipH; ++y)
  63782. {
  63783. double sx = srcX - (srcClipWidth == destClipW ? 0.0 : 0.5);
  63784. double sy = srcY - (srcClipHeight == destClipH ? 0.0 : 0.5);
  63785. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63786. for (int x = 0; x < destClipW; ++x)
  63787. {
  63788. const double fx = floor (sx);
  63789. const double fy = floor (sy);
  63790. const int ix = roundDoubleToInt (fx) - srcClipX;
  63791. const int iy = roundDoubleToInt (fy) - srcClipY;
  63792. if (ix < srcClipWidth && iy < srcClipHeight)
  63793. {
  63794. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  63795. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63796. if (iy >= 0)
  63797. {
  63798. if (ix >= 0)
  63799. p1.set (src[0]);
  63800. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63801. p2.set (src[1]);
  63802. }
  63803. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  63804. {
  63805. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63806. if (ix >= 0)
  63807. p3.set (src[0]);
  63808. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63809. p4.set (src[1]);
  63810. }
  63811. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  63812. p1.tween (p2, dx);
  63813. p3.tween (p4, dx);
  63814. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  63815. if (p1.getAlpha() > 0)
  63816. dest->blend (p1, alpha);
  63817. }
  63818. ++dest;
  63819. sx += pixelDX;
  63820. sy += pixelDY;
  63821. }
  63822. srcX += lineDX;
  63823. srcY += lineDY;
  63824. }
  63825. }
  63826. destImage.releasePixelDataReadWrite (destPixels);
  63827. sourceImage.releasePixelDataReadOnly (srcPixels);
  63828. }
  63829. template <class SrcPixelType, class DestPixelType>
  63830. static void renderAlphaMap (DestPixelType* destPixels,
  63831. int destStride,
  63832. SrcPixelType* srcPixels,
  63833. int srcStride,
  63834. const uint8* alphaValues,
  63835. const int lineStride, const int pixelStride,
  63836. int width, int height,
  63837. const int extraAlpha) throw()
  63838. {
  63839. while (--height >= 0)
  63840. {
  63841. SrcPixelType* srcPix = srcPixels;
  63842. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  63843. DestPixelType* destPix = destPixels;
  63844. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  63845. const uint8* alpha = alphaValues;
  63846. alphaValues += lineStride;
  63847. if (extraAlpha < 0x100)
  63848. {
  63849. for (int i = width; --i >= 0;)
  63850. {
  63851. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  63852. alpha += pixelStride;
  63853. }
  63854. }
  63855. else
  63856. {
  63857. for (int i = width; --i >= 0;)
  63858. {
  63859. destPix++ ->blend (*srcPix++, *alpha);
  63860. alpha += pixelStride;
  63861. }
  63862. }
  63863. }
  63864. }
  63865. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  63866. : image (image_),
  63867. xOffset (0),
  63868. yOffset (0),
  63869. stateStack (20)
  63870. {
  63871. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  63872. }
  63873. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  63874. {
  63875. delete clip;
  63876. }
  63877. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  63878. {
  63879. return false;
  63880. }
  63881. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  63882. {
  63883. xOffset += x;
  63884. yOffset += y;
  63885. }
  63886. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  63887. {
  63888. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  63889. }
  63890. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  63891. {
  63892. RectangleList temp (clipRegion);
  63893. temp.offsetAll (xOffset, yOffset);
  63894. return clip->clipTo (temp);
  63895. }
  63896. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  63897. {
  63898. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  63899. }
  63900. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  63901. {
  63902. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  63903. }
  63904. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  63905. {
  63906. return clip->getBounds().translated (-xOffset, -yOffset);
  63907. }
  63908. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  63909. {
  63910. return clip->isEmpty();
  63911. }
  63912. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  63913. const int xOffset_, const int yOffset_)
  63914. : clip (clip_),
  63915. xOffset (xOffset_),
  63916. yOffset (yOffset_)
  63917. {
  63918. }
  63919. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  63920. {
  63921. delete clip;
  63922. }
  63923. void LowLevelGraphicsSoftwareRenderer::saveState()
  63924. {
  63925. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  63926. }
  63927. void LowLevelGraphicsSoftwareRenderer::restoreState()
  63928. {
  63929. SavedState* const top = stateStack.getLast();
  63930. if (top != 0)
  63931. {
  63932. clip->swapWith (*top->clip);
  63933. xOffset = top->xOffset;
  63934. yOffset = top->yOffset;
  63935. stateStack.removeLast();
  63936. }
  63937. else
  63938. {
  63939. jassertfalse // trying to pop with an empty stack!
  63940. }
  63941. }
  63942. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63943. {
  63944. x += xOffset;
  63945. y += yOffset;
  63946. for (RectangleList::Iterator i (*clip); i.next();)
  63947. {
  63948. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  63949. }
  63950. }
  63951. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  63952. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63953. {
  63954. if (clipRect.intersectRectangle (x, y, w, h))
  63955. {
  63956. int stride, pixelStride;
  63957. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63958. if (image.getFormat() == Image::RGB)
  63959. {
  63960. if (replaceExistingContents)
  63961. replaceRectRGB (pixels, w, h, stride, colour);
  63962. else
  63963. blendRectRGB (pixels, w, h, stride, colour);
  63964. }
  63965. else if (image.getFormat() == Image::ARGB)
  63966. {
  63967. if (replaceExistingContents)
  63968. replaceRectARGB (pixels, w, h, stride, colour);
  63969. else
  63970. blendRectARGB (pixels, w, h, stride, colour);
  63971. }
  63972. else
  63973. {
  63974. jassertfalse // not done!
  63975. }
  63976. image.releasePixelDataReadWrite (pixels);
  63977. }
  63978. }
  63979. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  63980. {
  63981. Path p;
  63982. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  63983. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  63984. }
  63985. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  63986. const Path& path, const AffineTransform& transform,
  63987. int& x, int& y, int& w, int& h) const
  63988. {
  63989. float tx, ty, tw, th;
  63990. path.getBoundsTransformed (transform, tx, ty, tw, th);
  63991. x = roundDoubleToInt (tx) - 1;
  63992. y = roundDoubleToInt (ty) - 1;
  63993. w = roundDoubleToInt (tw) + 2;
  63994. h = roundDoubleToInt (th) + 2;
  63995. // seems like this operation is using some crazy out-of-range numbers..
  63996. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  63997. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  63998. }
  63999. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  64000. const Colour& colour, EdgeTable::OversamplingLevel quality)
  64001. {
  64002. for (RectangleList::Iterator i (*clip); i.next();)
  64003. {
  64004. const Rectangle& r = *i.getRectangle();
  64005. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  64006. }
  64007. }
  64008. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  64009. const Colour& colour, EdgeTable::OversamplingLevel quality)
  64010. {
  64011. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64012. int cx, cy, cw, ch;
  64013. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  64014. {
  64015. EdgeTable edgeTable (0, ch, quality);
  64016. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  64017. int stride, pixelStride;
  64018. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  64019. if (image.getFormat() == Image::RGB)
  64020. {
  64021. jassert (pixelStride == 3);
  64022. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  64023. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64024. }
  64025. else if (image.getFormat() == Image::ARGB)
  64026. {
  64027. jassert (pixelStride == 4);
  64028. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  64029. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64030. }
  64031. else if (image.getFormat() == Image::SingleChannel)
  64032. {
  64033. jassert (pixelStride == 1);
  64034. AlphaBitmapRenderer renderer (pixels, stride);
  64035. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64036. }
  64037. image.releasePixelDataReadWrite (pixels);
  64038. }
  64039. }
  64040. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  64041. {
  64042. for (RectangleList::Iterator i (*clip); i.next();)
  64043. {
  64044. const Rectangle& r = *i.getRectangle();
  64045. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64046. path, t, gradient, quality);
  64047. }
  64048. }
  64049. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  64050. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  64051. {
  64052. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64053. int cx, cy, cw, ch;
  64054. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  64055. {
  64056. int stride, pixelStride;
  64057. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  64058. ColourGradient g2 (gradient);
  64059. const bool isIdentity = g2.transform.isIdentity();
  64060. if (isIdentity)
  64061. {
  64062. g2.x1 += xOffset - cx;
  64063. g2.x2 += xOffset - cx;
  64064. g2.y1 += yOffset - cy;
  64065. g2.y2 += yOffset - cy;
  64066. }
  64067. else
  64068. {
  64069. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  64070. (float) (yOffset - cy));
  64071. }
  64072. int numLookupEntries;
  64073. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  64074. jassert (numLookupEntries > 0);
  64075. EdgeTable edgeTable (0, ch, quality);
  64076. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  64077. if (image.getFormat() == Image::RGB)
  64078. {
  64079. jassert (pixelStride == 3);
  64080. if (g2.isRadial)
  64081. {
  64082. if (isIdentity)
  64083. {
  64084. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64085. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64086. }
  64087. else
  64088. {
  64089. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64090. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64091. }
  64092. }
  64093. else
  64094. {
  64095. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64096. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64097. }
  64098. }
  64099. else if (image.getFormat() == Image::ARGB)
  64100. {
  64101. jassert (pixelStride == 4);
  64102. if (g2.isRadial)
  64103. {
  64104. if (isIdentity)
  64105. {
  64106. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64107. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64108. }
  64109. else
  64110. {
  64111. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64112. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64113. }
  64114. }
  64115. else
  64116. {
  64117. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  64118. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  64119. }
  64120. }
  64121. else if (image.getFormat() == Image::SingleChannel)
  64122. {
  64123. jassertfalse // not done!
  64124. }
  64125. juce_free (lookupTable);
  64126. image.releasePixelDataReadWrite (pixels);
  64127. }
  64128. }
  64129. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  64130. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  64131. {
  64132. imageX += xOffset;
  64133. imageY += yOffset;
  64134. for (RectangleList::Iterator i (*clip); i.next();)
  64135. {
  64136. const Rectangle& r = *i.getRectangle();
  64137. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64138. path, transform, sourceImage, imageX, imageY, opacity, quality);
  64139. }
  64140. }
  64141. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  64142. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  64143. {
  64144. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  64145. {
  64146. EdgeTable edgeTable (0, h, quality);
  64147. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  64148. int stride, pixelStride;
  64149. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  64150. int srcStride, srcPixelStride;
  64151. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  64152. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  64153. if (image.getFormat() == Image::RGB)
  64154. {
  64155. if (sourceImage.getFormat() == Image::RGB)
  64156. {
  64157. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  64158. srcPix, srcStride,
  64159. alpha, (PixelRGB*) 0);
  64160. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64161. }
  64162. else if (sourceImage.getFormat() == Image::ARGB)
  64163. {
  64164. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  64165. srcPix, srcStride,
  64166. alpha, (PixelARGB*) 0);
  64167. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64168. }
  64169. else
  64170. {
  64171. jassertfalse // not done!
  64172. }
  64173. }
  64174. else if (image.getFormat() == Image::ARGB)
  64175. {
  64176. if (sourceImage.getFormat() == Image::RGB)
  64177. {
  64178. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  64179. srcPix, srcStride,
  64180. alpha, (PixelRGB*) 0);
  64181. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64182. }
  64183. else if (sourceImage.getFormat() == Image::ARGB)
  64184. {
  64185. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  64186. srcPix, srcStride,
  64187. alpha, (PixelARGB*) 0);
  64188. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64189. }
  64190. else
  64191. {
  64192. jassertfalse // not done!
  64193. }
  64194. }
  64195. else
  64196. {
  64197. jassertfalse // not done!
  64198. }
  64199. sourceImage.releasePixelDataReadOnly (srcPix);
  64200. image.releasePixelDataReadWrite (pixels);
  64201. }
  64202. }
  64203. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  64204. {
  64205. x += xOffset;
  64206. y += yOffset;
  64207. for (RectangleList::Iterator i (*clip); i.next();)
  64208. {
  64209. const Rectangle& r = *i.getRectangle();
  64210. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64211. clipImage, x, y, colour);
  64212. }
  64213. }
  64214. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  64215. {
  64216. int w = clipImage.getWidth();
  64217. int h = clipImage.getHeight();
  64218. int sx = 0;
  64219. int sy = 0;
  64220. if (x < clipX)
  64221. {
  64222. sx = clipX - x;
  64223. w -= clipX - x;
  64224. x = clipX;
  64225. }
  64226. if (y < clipY)
  64227. {
  64228. sy = clipY - y;
  64229. h -= clipY - y;
  64230. y = clipY;
  64231. }
  64232. if (x + w > clipX + clipW)
  64233. w = clipX + clipW - x;
  64234. if (y + h > clipY + clipH)
  64235. h = clipY + clipH - y;
  64236. if (w > 0 && h > 0)
  64237. {
  64238. int stride, alphaStride, pixelStride;
  64239. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  64240. const uint8* const alphaValues
  64241. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  64242. #if JUCE_BIG_ENDIAN
  64243. const uint8* const alphas = alphaValues;
  64244. #else
  64245. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  64246. #endif
  64247. if (image.getFormat() == Image::RGB)
  64248. {
  64249. blendAlphaMapRGB (pixels, stride,
  64250. alphas, w, h,
  64251. pixelStride, alphaStride,
  64252. colour);
  64253. }
  64254. else if (image.getFormat() == Image::ARGB)
  64255. {
  64256. blendAlphaMapARGB (pixels, stride,
  64257. alphas, w, h,
  64258. pixelStride, alphaStride,
  64259. colour);
  64260. }
  64261. else
  64262. {
  64263. jassertfalse // not done!
  64264. }
  64265. clipImage.releasePixelDataReadOnly (alphaValues);
  64266. image.releasePixelDataReadWrite (pixels);
  64267. }
  64268. }
  64269. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  64270. {
  64271. imageX += xOffset;
  64272. imageY += yOffset;
  64273. for (RectangleList::Iterator i (*clip); i.next();)
  64274. {
  64275. const Rectangle& r = *i.getRectangle();
  64276. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64277. alphaChannelImage, imageX, imageY, gradient);
  64278. }
  64279. }
  64280. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  64281. const Image& alphaChannelImage,
  64282. int imageX, int imageY, const ColourGradient& gradient)
  64283. {
  64284. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  64285. {
  64286. ColourGradient g2 (gradient);
  64287. g2.x1 += xOffset - x;
  64288. g2.x2 += xOffset - x;
  64289. g2.y1 += yOffset - y;
  64290. g2.y2 += yOffset - y;
  64291. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  64292. LowLevelGraphicsSoftwareRenderer tempG (temp);
  64293. tempG.fillRectWithGradient (0, 0, w, h, g2);
  64294. clippedFillAlphaChannelWithImage (x, y, w, h,
  64295. alphaChannelImage, imageX, imageY,
  64296. temp, x, y, 1.0f);
  64297. }
  64298. }
  64299. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  64300. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64301. {
  64302. alphaImageX += xOffset;
  64303. alphaImageY += yOffset;
  64304. fillerImageX += xOffset;
  64305. fillerImageY += yOffset;
  64306. for (RectangleList::Iterator i (*clip); i.next();)
  64307. {
  64308. const Rectangle& r = *i.getRectangle();
  64309. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64310. alphaImage, alphaImageX, alphaImageY,
  64311. fillerImage, fillerImageX, fillerImageY, opacity);
  64312. }
  64313. }
  64314. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  64315. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64316. {
  64317. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  64318. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  64319. {
  64320. int dstStride, dstPixStride;
  64321. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  64322. int srcStride, srcPixStride;
  64323. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  64324. int maskStride, maskPixStride;
  64325. const uint8* const alpha
  64326. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  64327. #if JUCE_BIG_ENDIAN
  64328. const uint8* const alphaValues = alpha;
  64329. #else
  64330. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  64331. #endif
  64332. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  64333. if (image.getFormat() == Image::RGB)
  64334. {
  64335. if (fillerImage.getFormat() == Image::RGB)
  64336. {
  64337. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64338. }
  64339. else if (fillerImage.getFormat() == Image::ARGB)
  64340. {
  64341. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64342. }
  64343. else
  64344. {
  64345. jassertfalse // not done!
  64346. }
  64347. }
  64348. else if (image.getFormat() == Image::ARGB)
  64349. {
  64350. if (fillerImage.getFormat() == Image::RGB)
  64351. {
  64352. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64353. }
  64354. else if (fillerImage.getFormat() == Image::ARGB)
  64355. {
  64356. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64357. }
  64358. else
  64359. {
  64360. jassertfalse // not done!
  64361. }
  64362. }
  64363. else
  64364. {
  64365. jassertfalse // not done!
  64366. }
  64367. alphaImage.releasePixelDataReadOnly (alphaValues);
  64368. fillerImage.releasePixelDataReadOnly (srcPix);
  64369. image.releasePixelDataReadWrite (dstPix);
  64370. }
  64371. }
  64372. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64373. {
  64374. dx += xOffset;
  64375. dy += yOffset;
  64376. for (RectangleList::Iterator i (*clip); i.next();)
  64377. {
  64378. const Rectangle& r = *i.getRectangle();
  64379. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64380. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  64381. }
  64382. }
  64383. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  64384. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64385. {
  64386. if (dx < clipX)
  64387. {
  64388. sx += clipX - dx;
  64389. dw -= clipX - dx;
  64390. dx = clipX;
  64391. }
  64392. if (dy < clipY)
  64393. {
  64394. sy += clipY - dy;
  64395. dh -= clipY - dy;
  64396. dy = clipY;
  64397. }
  64398. if (dx + dw > clipX + clipW)
  64399. dw = clipX + clipW - dx;
  64400. if (dy + dh > clipY + clipH)
  64401. dh = clipY + clipH - dy;
  64402. if (dw <= 0 || dh <= 0)
  64403. return;
  64404. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64405. if (alpha == 0)
  64406. return;
  64407. int dstStride, dstPixelStride;
  64408. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  64409. int srcStride, srcPixelStride;
  64410. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  64411. if (image.getFormat() == Image::ARGB)
  64412. {
  64413. if (sourceImage.getFormat() == Image::ARGB)
  64414. {
  64415. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64416. (PixelARGB*) srcPixels, srcStride,
  64417. dw, dh, alpha);
  64418. }
  64419. else if (sourceImage.getFormat() == Image::RGB)
  64420. {
  64421. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64422. (PixelRGB*) srcPixels, srcStride,
  64423. dw, dh, alpha);
  64424. }
  64425. else
  64426. {
  64427. jassertfalse
  64428. }
  64429. }
  64430. else if (image.getFormat() == Image::RGB)
  64431. {
  64432. if (sourceImage.getFormat() == Image::ARGB)
  64433. {
  64434. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64435. (PixelARGB*) srcPixels, srcStride,
  64436. dw, dh, alpha);
  64437. }
  64438. else if (sourceImage.getFormat() == Image::RGB)
  64439. {
  64440. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64441. (PixelRGB*) srcPixels, srcStride,
  64442. dw, dh, alpha);
  64443. }
  64444. else
  64445. {
  64446. jassertfalse
  64447. }
  64448. }
  64449. else
  64450. {
  64451. jassertfalse
  64452. }
  64453. image.releasePixelDataReadWrite (dstPixels);
  64454. sourceImage.releasePixelDataReadOnly (srcPixels);
  64455. }
  64456. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  64457. int dx, int dy, int dw, int dh,
  64458. int sx, int sy, int sw, int sh,
  64459. float alpha,
  64460. const Graphics::ResamplingQuality quality)
  64461. {
  64462. if (sw > 0 && sh > 0)
  64463. {
  64464. if (sw == dw && sh == dh)
  64465. {
  64466. blendImage (sourceImage,
  64467. dx, dy, dw, dh,
  64468. sx, sy, alpha);
  64469. }
  64470. else
  64471. {
  64472. blendImageWarping (sourceImage,
  64473. sx, sy, sw, sh,
  64474. AffineTransform::translation ((float) -sx,
  64475. (float) -sy)
  64476. .scaled (dw / (float) sw,
  64477. dh / (float) sh)
  64478. .translated ((float) dx,
  64479. (float) dy),
  64480. alpha,
  64481. quality);
  64482. }
  64483. }
  64484. }
  64485. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  64486. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64487. const AffineTransform& t,
  64488. float opacity,
  64489. const Graphics::ResamplingQuality quality)
  64490. {
  64491. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64492. for (RectangleList::Iterator i (*clip); i.next();)
  64493. {
  64494. const Rectangle& r = *i.getRectangle();
  64495. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64496. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  64497. transform, opacity, quality);
  64498. }
  64499. }
  64500. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  64501. const Image& sourceImage,
  64502. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64503. const AffineTransform& transform,
  64504. float opacity,
  64505. const Graphics::ResamplingQuality quality)
  64506. {
  64507. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  64508. {
  64509. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  64510. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  64511. if (srcClipW <= 0 || srcClipH <= 0)
  64512. return;
  64513. jassert (srcClipX >= 0 && srcClipY >= 0);
  64514. Path imageBounds;
  64515. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  64516. imageBounds.applyTransform (transform);
  64517. float imX, imY, imW, imH;
  64518. imageBounds.getBounds (imX, imY, imW, imH);
  64519. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  64520. (int) floorf (imX),
  64521. (int) floorf (imY),
  64522. 1 + roundDoubleToInt (imW),
  64523. 1 + roundDoubleToInt (imH)))
  64524. {
  64525. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64526. float srcX1 = (float) destClipX;
  64527. float srcY1 = (float) destClipY;
  64528. float srcX2 = (float) (destClipX + destClipW);
  64529. float srcY2 = srcY1;
  64530. float srcX3 = srcX1;
  64531. float srcY3 = (float) (destClipY + destClipH);
  64532. AffineTransform inverse (transform.inverted());
  64533. inverse.transformPoint (srcX1, srcY1);
  64534. inverse.transformPoint (srcX2, srcY2);
  64535. inverse.transformPoint (srcX3, srcY3);
  64536. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  64537. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  64538. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  64539. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  64540. if (image.getFormat() == Image::ARGB)
  64541. {
  64542. if (sourceImage.getFormat() == Image::ARGB)
  64543. {
  64544. transformedImageRender (image, sourceImage,
  64545. destClipX, destClipY, destClipW, destClipH,
  64546. srcClipX, srcClipY, srcClipW, srcClipH,
  64547. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64548. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  64549. }
  64550. else if (sourceImage.getFormat() == Image::RGB)
  64551. {
  64552. transformedImageRender (image, sourceImage,
  64553. destClipX, destClipY, destClipW, destClipH,
  64554. srcClipX, srcClipY, srcClipW, srcClipH,
  64555. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64556. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  64557. }
  64558. else
  64559. {
  64560. jassertfalse
  64561. }
  64562. }
  64563. else if (image.getFormat() == Image::RGB)
  64564. {
  64565. if (sourceImage.getFormat() == Image::ARGB)
  64566. {
  64567. transformedImageRender (image, sourceImage,
  64568. destClipX, destClipY, destClipW, destClipH,
  64569. srcClipX, srcClipY, srcClipW, srcClipH,
  64570. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64571. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  64572. }
  64573. else if (sourceImage.getFormat() == Image::RGB)
  64574. {
  64575. transformedImageRender (image, sourceImage,
  64576. destClipX, destClipY, destClipW, destClipH,
  64577. srcClipX, srcClipY, srcClipW, srcClipH,
  64578. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64579. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  64580. }
  64581. else
  64582. {
  64583. jassertfalse
  64584. }
  64585. }
  64586. else
  64587. {
  64588. jassertfalse
  64589. }
  64590. }
  64591. }
  64592. }
  64593. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  64594. {
  64595. x1 += xOffset;
  64596. y1 += yOffset;
  64597. x2 += xOffset;
  64598. y2 += yOffset;
  64599. for (RectangleList::Iterator i (*clip); i.next();)
  64600. {
  64601. const Rectangle& r = *i.getRectangle();
  64602. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64603. x1, y1, x2, y2, colour);
  64604. }
  64605. }
  64606. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  64607. {
  64608. if (clipW > 0 && clipH > 0)
  64609. {
  64610. if (x1 == x2)
  64611. {
  64612. if (y2 < y1)
  64613. swapVariables (y1, y2);
  64614. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  64615. }
  64616. else if (y1 == y2)
  64617. {
  64618. if (x2 < x1)
  64619. swapVariables (x1, x2);
  64620. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  64621. }
  64622. else
  64623. {
  64624. double gradient = (y2 - y1) / (x2 - x1);
  64625. if (fabs (gradient) > 1.0)
  64626. {
  64627. gradient = 1.0 / gradient;
  64628. int y = roundDoubleToInt (y1);
  64629. const int startY = y;
  64630. int endY = roundDoubleToInt (y2);
  64631. if (y > endY)
  64632. swapVariables (y, endY);
  64633. while (y < endY)
  64634. {
  64635. const double x = x1 + gradient * (y - startY);
  64636. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  64637. ++y;
  64638. }
  64639. }
  64640. else
  64641. {
  64642. int x = roundDoubleToInt (x1);
  64643. const int startX = x;
  64644. int endX = roundDoubleToInt (x2);
  64645. if (x > endX)
  64646. swapVariables (x, endX);
  64647. while (x < endX)
  64648. {
  64649. const double y = y1 + gradient * (x - startX);
  64650. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  64651. ++x;
  64652. }
  64653. }
  64654. }
  64655. }
  64656. }
  64657. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  64658. {
  64659. for (RectangleList::Iterator i (*clip); i.next();)
  64660. {
  64661. const Rectangle& r = *i.getRectangle();
  64662. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64663. x + xOffset, top + yOffset, bottom + yOffset, col);
  64664. }
  64665. }
  64666. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  64667. const int x, double top, double bottom, const Colour& col)
  64668. {
  64669. jassert (top <= bottom);
  64670. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  64671. && top < clipY + clipH
  64672. && bottom > clipY
  64673. && clipW > 0)
  64674. {
  64675. if (top < clipY)
  64676. top = clipY;
  64677. if (bottom > clipY + clipH)
  64678. bottom = clipY + clipH;
  64679. if (bottom > top)
  64680. drawVertical (x, top, bottom, col);
  64681. }
  64682. }
  64683. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  64684. {
  64685. for (RectangleList::Iterator i (*clip); i.next();)
  64686. {
  64687. const Rectangle& r = *i.getRectangle();
  64688. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64689. y + yOffset, left + xOffset, right + xOffset, col);
  64690. }
  64691. }
  64692. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  64693. const int y, double left, double right, const Colour& col)
  64694. {
  64695. jassert (left <= right);
  64696. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  64697. && left < clipX + clipW
  64698. && right > clipX
  64699. && clipW > 0)
  64700. {
  64701. if (left < clipX)
  64702. left = clipX;
  64703. if (right > clipX + clipW)
  64704. right = clipX + clipW;
  64705. if (right > left)
  64706. drawHorizontal (y, left, right, col);
  64707. }
  64708. }
  64709. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  64710. const double top,
  64711. const double bottom,
  64712. const Colour& col)
  64713. {
  64714. int wholeStart = (int) top;
  64715. const int wholeEnd = (int) bottom;
  64716. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64717. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64718. if (totalPixels <= 0)
  64719. return;
  64720. int lineStride, dstPixelStride;
  64721. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  64722. uint8* dest = dstPixels;
  64723. PixelARGB colour (col.getPixelARGB());
  64724. if (wholeEnd == wholeStart)
  64725. {
  64726. if (image.getFormat() == Image::ARGB)
  64727. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64728. else if (image.getFormat() == Image::RGB)
  64729. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64730. else
  64731. {
  64732. jassertfalse
  64733. }
  64734. }
  64735. else
  64736. {
  64737. if (image.getFormat() == Image::ARGB)
  64738. {
  64739. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64740. ++wholeStart;
  64741. dest += lineStride;
  64742. if (colour.getAlpha() == 0xff)
  64743. {
  64744. while (wholeEnd > wholeStart)
  64745. {
  64746. ((PixelARGB*) dest)->set (colour);
  64747. ++wholeStart;
  64748. dest += lineStride;
  64749. }
  64750. }
  64751. else
  64752. {
  64753. while (wholeEnd > wholeStart)
  64754. {
  64755. ((PixelARGB*) dest)->blend (colour);
  64756. ++wholeStart;
  64757. dest += lineStride;
  64758. }
  64759. }
  64760. if (lastAlpha > 0)
  64761. {
  64762. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64763. }
  64764. }
  64765. else if (image.getFormat() == Image::RGB)
  64766. {
  64767. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64768. ++wholeStart;
  64769. dest += lineStride;
  64770. if (colour.getAlpha() == 0xff)
  64771. {
  64772. while (wholeEnd > wholeStart)
  64773. {
  64774. ((PixelRGB*) dest)->set (colour);
  64775. ++wholeStart;
  64776. dest += lineStride;
  64777. }
  64778. }
  64779. else
  64780. {
  64781. while (wholeEnd > wholeStart)
  64782. {
  64783. ((PixelRGB*) dest)->blend (colour);
  64784. ++wholeStart;
  64785. dest += lineStride;
  64786. }
  64787. }
  64788. if (lastAlpha > 0)
  64789. {
  64790. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64791. }
  64792. }
  64793. else
  64794. {
  64795. jassertfalse
  64796. }
  64797. }
  64798. image.releasePixelDataReadWrite (dstPixels);
  64799. }
  64800. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  64801. const double top,
  64802. const double bottom,
  64803. const Colour& col)
  64804. {
  64805. int wholeStart = (int) top;
  64806. const int wholeEnd = (int) bottom;
  64807. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64808. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64809. if (totalPixels <= 0)
  64810. return;
  64811. int lineStride, dstPixelStride;
  64812. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  64813. uint8* dest = dstPixels;
  64814. PixelARGB colour (col.getPixelARGB());
  64815. if (wholeEnd == wholeStart)
  64816. {
  64817. if (image.getFormat() == Image::ARGB)
  64818. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64819. else if (image.getFormat() == Image::RGB)
  64820. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64821. else
  64822. {
  64823. jassertfalse
  64824. }
  64825. }
  64826. else
  64827. {
  64828. if (image.getFormat() == Image::ARGB)
  64829. {
  64830. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64831. dest += dstPixelStride;
  64832. ++wholeStart;
  64833. if (colour.getAlpha() == 0xff)
  64834. {
  64835. while (wholeEnd > wholeStart)
  64836. {
  64837. ((PixelARGB*) dest)->set (colour);
  64838. dest += dstPixelStride;
  64839. ++wholeStart;
  64840. }
  64841. }
  64842. else
  64843. {
  64844. while (wholeEnd > wholeStart)
  64845. {
  64846. ((PixelARGB*) dest)->blend (colour);
  64847. dest += dstPixelStride;
  64848. ++wholeStart;
  64849. }
  64850. }
  64851. if (lastAlpha > 0)
  64852. {
  64853. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64854. }
  64855. }
  64856. else if (image.getFormat() == Image::RGB)
  64857. {
  64858. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64859. dest += dstPixelStride;
  64860. ++wholeStart;
  64861. if (colour.getAlpha() == 0xff)
  64862. {
  64863. while (wholeEnd > wholeStart)
  64864. {
  64865. ((PixelRGB*) dest)->set (colour);
  64866. dest += dstPixelStride;
  64867. ++wholeStart;
  64868. }
  64869. }
  64870. else
  64871. {
  64872. while (wholeEnd > wholeStart)
  64873. {
  64874. ((PixelRGB*) dest)->blend (colour);
  64875. dest += dstPixelStride;
  64876. ++wholeStart;
  64877. }
  64878. }
  64879. if (lastAlpha > 0)
  64880. {
  64881. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64882. }
  64883. }
  64884. else
  64885. {
  64886. jassertfalse
  64887. }
  64888. }
  64889. image.releasePixelDataReadWrite (dstPixels);
  64890. }
  64891. END_JUCE_NAMESPACE
  64892. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  64893. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  64894. BEGIN_JUCE_NAMESPACE
  64895. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  64896. : flags (other.flags)
  64897. {
  64898. }
  64899. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  64900. {
  64901. flags = other.flags;
  64902. return *this;
  64903. }
  64904. void RectanglePlacement::applyTo (double& x, double& y,
  64905. double& w, double& h,
  64906. const double dx, const double dy,
  64907. const double dw, const double dh) const throw()
  64908. {
  64909. if (w == 0 || h == 0)
  64910. return;
  64911. if ((flags & stretchToFit) != 0)
  64912. {
  64913. x = dx;
  64914. y = dy;
  64915. w = dw;
  64916. h = dh;
  64917. }
  64918. else
  64919. {
  64920. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  64921. : jmin (dw / w, dh / h);
  64922. if ((flags & onlyReduceInSize) != 0)
  64923. scale = jmin (scale, 1.0);
  64924. if ((flags & onlyIncreaseInSize) != 0)
  64925. scale = jmax (scale, 1.0);
  64926. w *= scale;
  64927. h *= scale;
  64928. if ((flags & xLeft) != 0)
  64929. x = dx;
  64930. else if ((flags & xRight) != 0)
  64931. x = dx + dw - w;
  64932. else
  64933. x = dx + (dw - w) * 0.5;
  64934. if ((flags & yTop) != 0)
  64935. y = dy;
  64936. else if ((flags & yBottom) != 0)
  64937. y = dy + dh - h;
  64938. else
  64939. y = dy + (dh - h) * 0.5;
  64940. }
  64941. }
  64942. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  64943. float w, float h,
  64944. const float dx, const float dy,
  64945. const float dw, const float dh) const throw()
  64946. {
  64947. if (w == 0 || h == 0)
  64948. return AffineTransform::identity;
  64949. const float scaleX = dw / w;
  64950. const float scaleY = dh / h;
  64951. if ((flags & stretchToFit) != 0)
  64952. return AffineTransform::translation (-x, -y)
  64953. .scaled (scaleX, scaleY)
  64954. .translated (dx, dy);
  64955. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  64956. : jmin (scaleX, scaleY);
  64957. if ((flags & onlyReduceInSize) != 0)
  64958. scale = jmin (scale, 1.0f);
  64959. if ((flags & onlyIncreaseInSize) != 0)
  64960. scale = jmax (scale, 1.0f);
  64961. w *= scale;
  64962. h *= scale;
  64963. float newX = dx;
  64964. if ((flags & xRight) != 0)
  64965. newX += dw - w; // right
  64966. else if ((flags & xLeft) == 0)
  64967. newX += (dw - w) / 2.0f; // centre
  64968. float newY = dy;
  64969. if ((flags & yBottom) != 0)
  64970. newY += dh - h; // bottom
  64971. else if ((flags & yTop) == 0)
  64972. newY += (dh - h) / 2.0f; // centre
  64973. return AffineTransform::translation (-x, -y)
  64974. .scaled (scale, scale)
  64975. .translated (newX, newY);
  64976. }
  64977. END_JUCE_NAMESPACE
  64978. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  64979. /********* Start of inlined file: juce_Drawable.cpp *********/
  64980. BEGIN_JUCE_NAMESPACE
  64981. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  64982. const AffineTransform& transform_,
  64983. const float opacity_) throw()
  64984. : g (g_),
  64985. transform (transform_),
  64986. opacity (opacity_)
  64987. {
  64988. }
  64989. Drawable::Drawable()
  64990. {
  64991. }
  64992. Drawable::~Drawable()
  64993. {
  64994. }
  64995. void Drawable::draw (Graphics& g,
  64996. const AffineTransform& transform) const
  64997. {
  64998. const RenderingContext context (g, transform, g.getCurrentColour().getFloatAlpha());
  64999. render (context);
  65000. }
  65001. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  65002. {
  65003. draw (g, AffineTransform::translation (x, y));
  65004. }
  65005. void Drawable::drawWithin (Graphics& g,
  65006. const int destX,
  65007. const int destY,
  65008. const int destW,
  65009. const int destH,
  65010. const RectanglePlacement& placement) const
  65011. {
  65012. if (destW > 0 && destH > 0)
  65013. {
  65014. float x, y, w, h;
  65015. getBounds (x, y, w, h);
  65016. draw (g, placement.getTransformToFit (x, y, w, h,
  65017. (float) destX, (float) destY,
  65018. (float) destW, (float) destH));
  65019. }
  65020. }
  65021. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  65022. {
  65023. Drawable* result = 0;
  65024. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  65025. if (image != 0)
  65026. {
  65027. DrawableImage* const di = new DrawableImage();
  65028. di->setImage (image, true);
  65029. result = di;
  65030. }
  65031. else
  65032. {
  65033. const String asString (String::createStringFromData (data, numBytes));
  65034. XmlDocument doc (asString);
  65035. XmlElement* const outer = doc.getDocumentElement (true);
  65036. if (outer != 0 && outer->hasTagName (T("svg")))
  65037. {
  65038. XmlElement* const svg = doc.getDocumentElement();
  65039. if (svg != 0)
  65040. {
  65041. result = Drawable::createFromSVG (*svg);
  65042. delete svg;
  65043. }
  65044. }
  65045. delete outer;
  65046. }
  65047. return result;
  65048. }
  65049. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  65050. {
  65051. MemoryBlock mb;
  65052. dataSource.readIntoMemoryBlock (mb);
  65053. return createFromImageData (mb.getData(), mb.getSize());
  65054. }
  65055. Drawable* Drawable::createFromImageFile (const File& file)
  65056. {
  65057. FileInputStream* fin = file.createInputStream();
  65058. if (fin == 0)
  65059. return 0;
  65060. Drawable* d = createFromImageDataStream (*fin);
  65061. delete fin;
  65062. return d;
  65063. }
  65064. Drawable* Drawable::readFromBinaryStream (InputStream& input)
  65065. {
  65066. char header[8];
  65067. if (input.read (header, sizeof (header)) != sizeof (header))
  65068. return 0;
  65069. DrawableComposite* result = 0;
  65070. if (memcmp (header, "JuceDrw1", sizeof (header)) == 0)
  65071. {
  65072. result = new DrawableComposite();
  65073. if (! result->readBinary (input))
  65074. deleteAndZero (result);
  65075. }
  65076. return result;
  65077. }
  65078. bool Drawable::writeToBinaryStream (OutputStream& output) const
  65079. {
  65080. output.write ("JuceDrw1", 8);
  65081. return writeBinary (output);
  65082. }
  65083. Drawable* Drawable::readFromXml (const XmlElement& xml)
  65084. {
  65085. DrawableComposite* result = 0;
  65086. if (xml.hasTagName (T("JuceDrawable")))
  65087. {
  65088. result = new DrawableComposite();
  65089. if (! result->readXml (xml))
  65090. deleteAndZero (result);
  65091. }
  65092. return result;
  65093. }
  65094. XmlElement* Drawable::createXml() const
  65095. {
  65096. if (dynamic_cast <const DrawableComposite*> (this) == 0)
  65097. {
  65098. DrawableComposite tempDC;
  65099. tempDC.insertDrawable (const_cast <Drawable*> (this));
  65100. XmlElement* result = tempDC.createXml();
  65101. tempDC.removeDrawable (0, false);
  65102. return result;
  65103. }
  65104. else
  65105. {
  65106. XmlElement* e = new XmlElement (T("JuceDrawable"));
  65107. writeXml (*e);
  65108. return e;
  65109. }
  65110. }
  65111. END_JUCE_NAMESPACE
  65112. /********* End of inlined file: juce_Drawable.cpp *********/
  65113. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  65114. BEGIN_JUCE_NAMESPACE
  65115. DrawableComposite::DrawableComposite()
  65116. {
  65117. }
  65118. DrawableComposite::~DrawableComposite()
  65119. {
  65120. }
  65121. void DrawableComposite::insertDrawable (Drawable* drawable,
  65122. const AffineTransform& transform,
  65123. const int index)
  65124. {
  65125. if (drawable != 0)
  65126. {
  65127. if (! drawables.contains (drawable))
  65128. {
  65129. drawables.insert (index, drawable);
  65130. if (transform.isIdentity())
  65131. transforms.insert (index, 0);
  65132. else
  65133. transforms.insert (index, new AffineTransform (transform));
  65134. }
  65135. else
  65136. {
  65137. jassertfalse // trying to add a drawable that's already in here!
  65138. }
  65139. }
  65140. }
  65141. void DrawableComposite::insertDrawable (const Drawable& drawable,
  65142. const AffineTransform& transform,
  65143. const int index)
  65144. {
  65145. insertDrawable (drawable.createCopy(), transform, index);
  65146. }
  65147. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  65148. {
  65149. drawables.remove (index, deleteDrawable);
  65150. transforms.remove (index);
  65151. }
  65152. void DrawableComposite::bringToFront (const int index)
  65153. {
  65154. if (index >= 0 && index < drawables.size() - 1)
  65155. {
  65156. drawables.move (index, -1);
  65157. transforms.move (index, -1);
  65158. }
  65159. }
  65160. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  65161. {
  65162. if (drawables.size() > 0 && context.opacity > 0)
  65163. {
  65164. if (context.opacity >= 1.0f || drawables.size() == 1)
  65165. {
  65166. Drawable::RenderingContext contextCopy (context);
  65167. for (int i = 0; i < drawables.size(); ++i)
  65168. {
  65169. const AffineTransform* const t = transforms.getUnchecked(i);
  65170. contextCopy.transform = (t == 0) ? context.transform
  65171. : t->followedBy (context.transform);
  65172. drawables.getUnchecked(i)->render (contextCopy);
  65173. }
  65174. }
  65175. else
  65176. {
  65177. // To correctly render a whole composite layer with an overall transparency,
  65178. // we need to render everything opaquely into a temp buffer, then blend that
  65179. // with the target opacity...
  65180. const Rectangle clipBounds (context.g.getClipBounds());
  65181. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  65182. {
  65183. Graphics tempG (tempImage);
  65184. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  65185. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  65186. render (tempContext);
  65187. }
  65188. context.g.setOpacity (context.opacity);
  65189. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  65190. }
  65191. }
  65192. }
  65193. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  65194. {
  65195. Path totalPath;
  65196. for (int i = 0; i < drawables.size(); ++i)
  65197. {
  65198. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  65199. if (width > 0.0f && height > 0.0f)
  65200. {
  65201. Path outline;
  65202. outline.addRectangle (x, y, width, height);
  65203. const AffineTransform* const t = transforms.getUnchecked(i);
  65204. if (t == 0)
  65205. totalPath.addPath (outline);
  65206. else
  65207. totalPath.addPath (outline, *t);
  65208. }
  65209. }
  65210. totalPath.getBounds (x, y, width, height);
  65211. }
  65212. bool DrawableComposite::hitTest (float x, float y) const
  65213. {
  65214. for (int i = 0; i < drawables.size(); ++i)
  65215. {
  65216. float tx = x;
  65217. float ty = y;
  65218. const AffineTransform* const t = transforms.getUnchecked(i);
  65219. if (t != 0)
  65220. t->inverted().transformPoint (tx, ty);
  65221. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  65222. return true;
  65223. }
  65224. return false;
  65225. }
  65226. Drawable* DrawableComposite::createCopy() const
  65227. {
  65228. DrawableComposite* const dc = new DrawableComposite();
  65229. for (int i = 0; i < drawables.size(); ++i)
  65230. {
  65231. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  65232. const AffineTransform* const t = transforms.getUnchecked(i);
  65233. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  65234. }
  65235. return dc;
  65236. }
  65237. const char juce_drawableCompositeTransformFlag = 't';
  65238. const char juce_drawableCompositeBinaryType = 'C';
  65239. const char juce_drawablePathBinaryType = 'P';
  65240. const char juce_drawableImageBinaryType = 'I';
  65241. const char juce_drawableTextBinaryType = 'T';
  65242. bool DrawableComposite::readBinary (InputStream& input)
  65243. {
  65244. AffineTransform transform;
  65245. while (! input.isExhausted())
  65246. {
  65247. const int n = input.readByte();
  65248. if (n == 0)
  65249. break;
  65250. if (n == juce_drawableCompositeTransformFlag)
  65251. {
  65252. float f[6];
  65253. for (int i = 0; i < 6; ++i)
  65254. f[i] = input.readFloat();
  65255. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65256. }
  65257. else
  65258. {
  65259. Drawable* d = 0;
  65260. switch (n)
  65261. {
  65262. case juce_drawableCompositeBinaryType: d = new DrawableComposite(); break;
  65263. case juce_drawablePathBinaryType: d = new DrawablePath(); break;
  65264. case juce_drawableImageBinaryType: d = new DrawableImage(); break;
  65265. case juce_drawableTextBinaryType: d = new DrawableText(); break;
  65266. default: jassertfalse; return false;
  65267. }
  65268. d->setName (input.readString());
  65269. if (! d->readBinary (input))
  65270. {
  65271. delete d;
  65272. return false;
  65273. }
  65274. insertDrawable (d, transform);
  65275. transform = AffineTransform::identity;
  65276. }
  65277. }
  65278. return true;
  65279. }
  65280. bool DrawableComposite::writeBinary (OutputStream& output) const
  65281. {
  65282. for (int i = 0; i < drawables.size(); ++i)
  65283. {
  65284. AffineTransform* transform = transforms.getUnchecked(i);
  65285. if (transform != 0)
  65286. {
  65287. output.writeByte (juce_drawableCompositeTransformFlag);
  65288. output.writeFloat (transform->mat00);
  65289. output.writeFloat (transform->mat01);
  65290. output.writeFloat (transform->mat02);
  65291. output.writeFloat (transform->mat10);
  65292. output.writeFloat (transform->mat11);
  65293. output.writeFloat (transform->mat12);
  65294. }
  65295. Drawable* const d = drawables.getUnchecked(i);
  65296. char typeFlag;
  65297. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65298. typeFlag = juce_drawableCompositeBinaryType;
  65299. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65300. typeFlag = juce_drawablePathBinaryType;
  65301. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65302. typeFlag = juce_drawableImageBinaryType;
  65303. else if (dynamic_cast <DrawableText*> (d) != 0)
  65304. typeFlag = juce_drawableTextBinaryType;
  65305. else
  65306. {
  65307. jassertfalse;
  65308. continue;
  65309. }
  65310. output.writeByte (typeFlag);
  65311. output.writeString (d->getName());
  65312. d->writeBinary (output);
  65313. }
  65314. output.writeByte (0);
  65315. return true;
  65316. }
  65317. const tchar* juce_drawableCompositeXmlTag = T("Group");
  65318. const tchar* juce_drawablePathXmlTag = T("Path");
  65319. const tchar* juce_drawableImageXmlTag = T("Image");
  65320. const tchar* juce_drawableTextXmlTag = T("Text");
  65321. bool DrawableComposite::readXml (const XmlElement& xml)
  65322. {
  65323. forEachXmlChildElement (xml, e)
  65324. {
  65325. Drawable* d = 0;
  65326. if (e->hasTagName (juce_drawableCompositeXmlTag))
  65327. d = new DrawableComposite();
  65328. else if (e->hasTagName (juce_drawablePathXmlTag))
  65329. d = new DrawablePath();
  65330. else if (e->hasTagName (juce_drawableImageXmlTag))
  65331. d = new DrawableImage();
  65332. else if (e->hasTagName (juce_drawableTextXmlTag))
  65333. d = new DrawableText();
  65334. else
  65335. {
  65336. jassertfalse;
  65337. return false;
  65338. }
  65339. d->setName (e->getStringAttribute (T("id")));
  65340. if (! d->readXml (*e))
  65341. {
  65342. jassertfalse;
  65343. delete d;
  65344. return false;
  65345. }
  65346. AffineTransform transform;
  65347. const String transformAtt (e->getStringAttribute (T("transform")));
  65348. if (transformAtt.isNotEmpty())
  65349. {
  65350. StringArray tokens;
  65351. tokens.addTokens (transformAtt.trim(), false);
  65352. tokens.removeEmptyStrings (true);
  65353. if (tokens.size() == 6)
  65354. {
  65355. float f[6];
  65356. for (int i = 0; i < 6; ++i)
  65357. f[i] = (float) tokens[i].getDoubleValue();
  65358. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65359. }
  65360. }
  65361. insertDrawable (d, transform);
  65362. }
  65363. return true;
  65364. }
  65365. void DrawableComposite::writeXml (XmlElement& xml) const
  65366. {
  65367. for (int i = 0; i < drawables.size(); ++i)
  65368. {
  65369. XmlElement* e = 0;
  65370. Drawable* const d = drawables.getUnchecked(i);
  65371. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65372. e = new XmlElement (juce_drawableCompositeXmlTag);
  65373. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65374. e = new XmlElement (juce_drawablePathXmlTag);
  65375. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65376. e = new XmlElement (juce_drawableImageXmlTag);
  65377. else if (dynamic_cast <DrawableText*> (d) != 0)
  65378. e = new XmlElement (juce_drawableTextXmlTag);
  65379. else
  65380. {
  65381. jassertfalse;
  65382. continue;
  65383. }
  65384. AffineTransform* transform = transforms.getUnchecked(i);
  65385. if (transform != 0)
  65386. {
  65387. String t;
  65388. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  65389. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  65390. e->setAttribute (T("transform"), t);
  65391. }
  65392. if (d->getName().isNotEmpty())
  65393. e->setAttribute (T("id"), d->getName());
  65394. d->writeXml (*e);
  65395. xml.addChildElement (e);
  65396. }
  65397. }
  65398. END_JUCE_NAMESPACE
  65399. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  65400. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  65401. BEGIN_JUCE_NAMESPACE
  65402. DrawableImage::DrawableImage()
  65403. : image (0),
  65404. canDeleteImage (false),
  65405. opacity (1.0f),
  65406. overlayColour (0x00000000)
  65407. {
  65408. }
  65409. DrawableImage::~DrawableImage()
  65410. {
  65411. clearImage();
  65412. }
  65413. void DrawableImage::clearImage()
  65414. {
  65415. if (canDeleteImage && image != 0)
  65416. {
  65417. if (ImageCache::isImageInCache (image))
  65418. ImageCache::release (image);
  65419. else
  65420. delete image;
  65421. }
  65422. image = 0;
  65423. }
  65424. void DrawableImage::setImage (const Image& imageToCopy)
  65425. {
  65426. clearImage();
  65427. image = new Image (imageToCopy);
  65428. canDeleteImage = true;
  65429. }
  65430. void DrawableImage::setImage (Image* imageToUse,
  65431. const bool releaseWhenNotNeeded)
  65432. {
  65433. clearImage();
  65434. image = imageToUse;
  65435. canDeleteImage = releaseWhenNotNeeded;
  65436. }
  65437. void DrawableImage::setOpacity (const float newOpacity)
  65438. {
  65439. opacity = newOpacity;
  65440. }
  65441. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  65442. {
  65443. overlayColour = newOverlayColour;
  65444. }
  65445. void DrawableImage::render (const Drawable::RenderingContext& context) const
  65446. {
  65447. if (image != 0)
  65448. {
  65449. if (opacity > 0.0f && ! overlayColour.isOpaque())
  65450. {
  65451. context.g.setOpacity (context.opacity * opacity);
  65452. context.g.drawImageTransformed (image,
  65453. 0, 0, image->getWidth(), image->getHeight(),
  65454. context.transform, false);
  65455. }
  65456. if (! overlayColour.isTransparent())
  65457. {
  65458. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  65459. context.g.drawImageTransformed (image,
  65460. 0, 0, image->getWidth(), image->getHeight(),
  65461. context.transform, true);
  65462. }
  65463. }
  65464. }
  65465. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  65466. {
  65467. x = 0.0f;
  65468. y = 0.0f;
  65469. width = 0.0f;
  65470. height = 0.0f;
  65471. if (image != 0)
  65472. {
  65473. width = (float) image->getWidth();
  65474. height = (float) image->getHeight();
  65475. }
  65476. }
  65477. bool DrawableImage::hitTest (float x, float y) const
  65478. {
  65479. return image != 0
  65480. && x >= 0.0f
  65481. && y >= 0.0f
  65482. && x < image->getWidth()
  65483. && y < image->getHeight()
  65484. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  65485. }
  65486. Drawable* DrawableImage::createCopy() const
  65487. {
  65488. DrawableImage* const di = new DrawableImage();
  65489. di->opacity = opacity;
  65490. di->overlayColour = overlayColour;
  65491. if (image != 0)
  65492. {
  65493. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  65494. {
  65495. di->setImage (*image);
  65496. }
  65497. else
  65498. {
  65499. ImageCache::incReferenceCount (image);
  65500. di->setImage (image, true);
  65501. }
  65502. }
  65503. return di;
  65504. }
  65505. bool DrawableImage::readBinary (InputStream& input)
  65506. {
  65507. opacity = input.readFloat();
  65508. overlayColour = Colour (input.readInt());
  65509. const int dataLen = input.readInt();
  65510. if (dataLen > 0)
  65511. {
  65512. MemoryBlock imageData;
  65513. input.readIntoMemoryBlock (imageData, dataLen);
  65514. Image* im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65515. if (im == 0)
  65516. return false;
  65517. setImage (im, true);
  65518. }
  65519. return true;
  65520. }
  65521. bool DrawableImage::writeBinary (OutputStream& output) const
  65522. {
  65523. MemoryOutputStream imageData;
  65524. if (image != 0)
  65525. {
  65526. PNGImageFormat pngFormat;
  65527. if (! pngFormat.writeImageToStream (*image, imageData))
  65528. return false;
  65529. }
  65530. output.writeFloat (opacity);
  65531. output.writeInt (overlayColour.getARGB());
  65532. output.writeInt (imageData.getDataSize());
  65533. output.write (imageData.getData(), imageData.getDataSize());
  65534. return true;
  65535. }
  65536. bool DrawableImage::readXml (const XmlElement& xml)
  65537. {
  65538. opacity = (float) xml.getDoubleAttribute (T("opacity"), 1.0);
  65539. overlayColour = Colour (xml.getStringAttribute (T("overlay"), T("0")).getHexValue32());
  65540. MemoryBlock imageData;
  65541. if (imageData.fromBase64Encoding (xml.getAllSubText()))
  65542. {
  65543. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65544. if (im == 0)
  65545. return false;
  65546. setImage (im, true);
  65547. }
  65548. return true;
  65549. }
  65550. void DrawableImage::writeXml (XmlElement& xml) const
  65551. {
  65552. if (opacity < 1.0f)
  65553. xml.setAttribute (T("opacity"), (double) opacity);
  65554. if (! overlayColour.isTransparent())
  65555. xml.setAttribute (T("overlay"), String::toHexString ((int) overlayColour.getARGB()));
  65556. if (image != 0)
  65557. {
  65558. MemoryOutputStream imageData;
  65559. PNGImageFormat pngFormat;
  65560. if (pngFormat.writeImageToStream (*image, imageData))
  65561. {
  65562. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  65563. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  65564. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  65565. xml.addTextElement (base64);
  65566. }
  65567. }
  65568. }
  65569. END_JUCE_NAMESPACE
  65570. /********* End of inlined file: juce_DrawableImage.cpp *********/
  65571. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  65572. BEGIN_JUCE_NAMESPACE
  65573. DrawablePath::DrawablePath()
  65574. : fillBrush (new SolidColourBrush (Colours::black)),
  65575. strokeBrush (0),
  65576. strokeType (0.0f)
  65577. {
  65578. }
  65579. DrawablePath::~DrawablePath()
  65580. {
  65581. delete fillBrush;
  65582. delete strokeBrush;
  65583. }
  65584. void DrawablePath::setPath (const Path& newPath)
  65585. {
  65586. path = newPath;
  65587. updateOutline();
  65588. }
  65589. void DrawablePath::setSolidFill (const Colour& newColour)
  65590. {
  65591. delete fillBrush;
  65592. fillBrush = new SolidColourBrush (newColour);
  65593. }
  65594. void DrawablePath::setFillBrush (const Brush& newBrush)
  65595. {
  65596. delete fillBrush;
  65597. fillBrush = newBrush.createCopy();
  65598. }
  65599. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  65600. {
  65601. strokeType = PathStrokeType (thickness);
  65602. delete strokeBrush;
  65603. strokeBrush = new SolidColourBrush (colour);
  65604. updateOutline();
  65605. }
  65606. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  65607. {
  65608. strokeType = strokeType_;
  65609. delete strokeBrush;
  65610. strokeBrush = newStrokeBrush.createCopy();
  65611. updateOutline();
  65612. }
  65613. void DrawablePath::render (const Drawable::RenderingContext& context) const
  65614. {
  65615. {
  65616. Brush* const tempBrush = fillBrush->createCopy();
  65617. tempBrush->applyTransform (context.transform);
  65618. tempBrush->multiplyOpacity (context.opacity);
  65619. context.g.setBrush (tempBrush);
  65620. context.g.fillPath (path, context.transform);
  65621. delete tempBrush;
  65622. }
  65623. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  65624. {
  65625. Brush* const tempBrush = strokeBrush->createCopy();
  65626. tempBrush->applyTransform (context.transform);
  65627. tempBrush->multiplyOpacity (context.opacity);
  65628. context.g.setBrush (tempBrush);
  65629. context.g.fillPath (outline, context.transform);
  65630. delete tempBrush;
  65631. }
  65632. }
  65633. void DrawablePath::updateOutline()
  65634. {
  65635. outline.clear();
  65636. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  65637. }
  65638. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  65639. {
  65640. if (strokeType.getStrokeThickness() > 0.0f)
  65641. outline.getBounds (x, y, width, height);
  65642. else
  65643. path.getBounds (x, y, width, height);
  65644. }
  65645. bool DrawablePath::hitTest (float x, float y) const
  65646. {
  65647. return path.contains (x, y)
  65648. || outline.contains (x, y);
  65649. }
  65650. Drawable* DrawablePath::createCopy() const
  65651. {
  65652. DrawablePath* const dp = new DrawablePath();
  65653. dp->path = path;
  65654. dp->setFillBrush (*fillBrush);
  65655. if (strokeBrush != 0)
  65656. dp->setOutline (strokeType, *strokeBrush);
  65657. return dp;
  65658. }
  65659. static Brush* readBrushFromBinary (InputStream& input)
  65660. {
  65661. switch (input.readByte())
  65662. {
  65663. case 1:
  65664. return new SolidColourBrush (Colour ((uint32) input.readInt()));
  65665. case 2:
  65666. {
  65667. ColourGradient gradient;
  65668. gradient.x1 = input.readFloat();
  65669. gradient.y1 = input.readFloat();
  65670. gradient.x2 = input.readFloat();
  65671. gradient.y2 = input.readFloat();
  65672. gradient.isRadial = input.readByte() != 0;
  65673. const int numColours = input.readCompressedInt();
  65674. for (int i = 0; i < numColours; ++i)
  65675. {
  65676. double proportion = (double) input.readFloat();
  65677. const Colour colour ((uint32) input.readInt());
  65678. gradient.addColour (proportion, colour);
  65679. }
  65680. return new GradientBrush (gradient);
  65681. }
  65682. case 3:
  65683. {
  65684. jassertfalse; //xxx TODO
  65685. return new ImageBrush (0, 0, 0, 0);
  65686. }
  65687. default:
  65688. break;
  65689. }
  65690. return 0;
  65691. }
  65692. static void writeBrushToBinary (OutputStream& output, const Brush* const brush)
  65693. {
  65694. if (brush == 0)
  65695. {
  65696. output.writeByte (0);
  65697. return;
  65698. }
  65699. const SolidColourBrush* cb;
  65700. const GradientBrush* gb;
  65701. const ImageBrush* ib;
  65702. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65703. {
  65704. output.writeByte (1);
  65705. output.writeInt ((int) cb->getColour().getARGB());
  65706. }
  65707. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65708. {
  65709. output.writeByte (2);
  65710. const ColourGradient& g = gb->getGradient();
  65711. output.writeFloat (g.x1);
  65712. output.writeFloat (g.y1);
  65713. output.writeFloat (g.x2);
  65714. output.writeFloat (g.y2);
  65715. output.writeByte (g.isRadial ? 1 : 0);
  65716. output.writeCompressedInt (g.getNumColours());
  65717. for (int i = 0; i < g.getNumColours(); ++i)
  65718. {
  65719. output.writeFloat ((float) g.getColourPosition (i));
  65720. output.writeInt ((int) g.getColour (i).getARGB());
  65721. }
  65722. }
  65723. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65724. {
  65725. output.writeByte (3);
  65726. jassertfalse; //xxx TODO
  65727. }
  65728. }
  65729. static Brush* readBrushFromXml (const XmlElement* xml)
  65730. {
  65731. if (xml == 0)
  65732. return 0;
  65733. const String type (xml->getStringAttribute (T("type")));
  65734. if (type.equalsIgnoreCase (T("solid")))
  65735. return new SolidColourBrush (Colour ((uint32) xml->getStringAttribute (T("colour"), T("ff000000")).getHexValue32()));
  65736. if (type.equalsIgnoreCase (T("gradient")))
  65737. {
  65738. ColourGradient gradient;
  65739. gradient.x1 = (float) xml->getDoubleAttribute (T("x1"));
  65740. gradient.y1 = (float) xml->getDoubleAttribute (T("y1"));
  65741. gradient.x2 = (float) xml->getDoubleAttribute (T("x2"));
  65742. gradient.y2 = (float) xml->getDoubleAttribute (T("y2"));
  65743. gradient.isRadial = xml->getBoolAttribute (T("radial"), false);
  65744. StringArray colours;
  65745. colours.addTokens (xml->getStringAttribute (T("colours")), false);
  65746. for (int i = 0; i < colours.size() / 2; ++i)
  65747. gradient.addColour (colours[i * 2].getDoubleValue(),
  65748. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  65749. return new GradientBrush (gradient);
  65750. }
  65751. if (type.equalsIgnoreCase (T("image")))
  65752. {
  65753. jassertfalse; //xxx TODO
  65754. return new ImageBrush (0, 0, 0, 0);
  65755. }
  65756. return 0;
  65757. }
  65758. static XmlElement* writeBrushToXml (const String& tagName, const Brush* brush)
  65759. {
  65760. if (brush == 0)
  65761. return 0;
  65762. XmlElement* const xml = new XmlElement (tagName);
  65763. const SolidColourBrush* cb;
  65764. const GradientBrush* gb;
  65765. const ImageBrush* ib;
  65766. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65767. {
  65768. xml->setAttribute (T("type"), T("solid"));
  65769. xml->setAttribute (T("colour"), String::toHexString ((int) cb->getColour().getARGB()));
  65770. }
  65771. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65772. {
  65773. xml->setAttribute (T("type"), T("gradient"));
  65774. const ColourGradient& g = gb->getGradient();
  65775. xml->setAttribute (T("x1"), g.x1);
  65776. xml->setAttribute (T("y1"), g.y1);
  65777. xml->setAttribute (T("x2"), g.x2);
  65778. xml->setAttribute (T("y2"), g.y2);
  65779. xml->setAttribute (T("radial"), g.isRadial);
  65780. String s;
  65781. for (int i = 0; i < g.getNumColours(); ++i)
  65782. s << " " << g.getColourPosition (i) << " " << String::toHexString ((int) g.getColour(i).getARGB());
  65783. xml->setAttribute (T("colours"), s.trimStart());
  65784. }
  65785. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65786. {
  65787. xml->setAttribute (T("type"), T("image"));
  65788. jassertfalse; //xxx TODO
  65789. }
  65790. return xml;
  65791. }
  65792. bool DrawablePath::readBinary (InputStream& input)
  65793. {
  65794. delete fillBrush;
  65795. fillBrush = readBrushFromBinary (input);
  65796. delete strokeBrush;
  65797. strokeBrush = readBrushFromBinary (input);
  65798. const float strokeThickness = input.readFloat();
  65799. const int jointStyle = input.readByte();
  65800. const int endStyle = input.readByte();
  65801. strokeType = PathStrokeType (strokeThickness,
  65802. jointStyle == 1 ? PathStrokeType::curved
  65803. : (jointStyle == 2 ? PathStrokeType::beveled
  65804. : PathStrokeType::mitered),
  65805. endStyle == 1 ? PathStrokeType::square
  65806. : (endStyle == 2 ? PathStrokeType::rounded
  65807. : PathStrokeType::butt));
  65808. const int pathSize = input.readInt();
  65809. MemoryBlock pathData;
  65810. input.readIntoMemoryBlock (pathData, pathSize);
  65811. if (pathData.getSize() != pathSize)
  65812. return false;
  65813. path.clear();
  65814. path.loadPathFromData ((const uint8*) pathData.getData(), pathSize);
  65815. updateOutline();
  65816. return true;
  65817. }
  65818. bool DrawablePath::writeBinary (OutputStream& output) const
  65819. {
  65820. writeBrushToBinary (output, fillBrush);
  65821. writeBrushToBinary (output, strokeBrush);
  65822. output.writeFloat (strokeType.getStrokeThickness());
  65823. output.writeByte (strokeType.getJointStyle() == PathStrokeType::mitered ? 0
  65824. : (strokeType.getJointStyle() == PathStrokeType::curved ? 1 : 2));
  65825. output.writeByte (strokeType.getEndStyle() == PathStrokeType::butt ? 0
  65826. : (strokeType.getEndStyle() == PathStrokeType::square ? 1 : 2));
  65827. MemoryOutputStream out;
  65828. path.writePathToStream (out);
  65829. output.writeInt (out.getDataSize());
  65830. output.write (out.getData(), out.getDataSize());
  65831. return true;
  65832. }
  65833. bool DrawablePath::readXml (const XmlElement& xml)
  65834. {
  65835. delete fillBrush;
  65836. fillBrush = readBrushFromXml (xml.getChildByName (T("fill")));
  65837. delete strokeBrush;
  65838. strokeBrush = readBrushFromXml (xml.getChildByName (T("stroke")));
  65839. const String jointStyle (xml.getStringAttribute (T("jointStyle"), String::empty));
  65840. const String endStyle (xml.getStringAttribute (T("capStyle"), String::empty));
  65841. strokeType = PathStrokeType ((float) xml.getDoubleAttribute (T("strokeWidth"), 0.0),
  65842. jointStyle.equalsIgnoreCase (T("curved")) ? PathStrokeType::curved
  65843. : (jointStyle.equalsIgnoreCase (T("bevel")) ? PathStrokeType::beveled
  65844. : PathStrokeType::mitered),
  65845. endStyle.equalsIgnoreCase (T("square")) ? PathStrokeType::square
  65846. : (endStyle.equalsIgnoreCase (T("round")) ? PathStrokeType::rounded
  65847. : PathStrokeType::butt));
  65848. path.clear();
  65849. path.restoreFromString (xml.getAllSubText());
  65850. updateOutline();
  65851. return true;
  65852. }
  65853. void DrawablePath::writeXml (XmlElement& xml) const
  65854. {
  65855. xml.addChildElement (writeBrushToXml (T("fill"), fillBrush));
  65856. xml.addChildElement (writeBrushToXml (T("stroke"), strokeBrush));
  65857. xml.setAttribute (T("strokeWidth"), (double) strokeType.getStrokeThickness());
  65858. xml.setAttribute (T("jointStyle"),
  65859. strokeType.getJointStyle() == PathStrokeType::mitered ? T("miter")
  65860. : (strokeType.getJointStyle() == PathStrokeType::curved ? T("curved") : T("bevel")));
  65861. xml.setAttribute (T("capStyle"),
  65862. strokeType.getEndStyle() == PathStrokeType::butt ? T("butt")
  65863. : (strokeType.getEndStyle() == PathStrokeType::square ? T("square") : T("round")));
  65864. xml.addTextElement (path.toString());
  65865. }
  65866. END_JUCE_NAMESPACE
  65867. /********* End of inlined file: juce_DrawablePath.cpp *********/
  65868. /********* Start of inlined file: juce_DrawableText.cpp *********/
  65869. BEGIN_JUCE_NAMESPACE
  65870. DrawableText::DrawableText()
  65871. : colour (Colours::white)
  65872. {
  65873. }
  65874. DrawableText::~DrawableText()
  65875. {
  65876. }
  65877. void DrawableText::setText (const GlyphArrangement& newText)
  65878. {
  65879. text = newText;
  65880. }
  65881. void DrawableText::setText (const String& newText, const Font& fontToUse)
  65882. {
  65883. text.clear();
  65884. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  65885. }
  65886. void DrawableText::setColour (const Colour& newColour)
  65887. {
  65888. colour = newColour;
  65889. }
  65890. void DrawableText::render (const Drawable::RenderingContext& context) const
  65891. {
  65892. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  65893. text.draw (context.g, context.transform);
  65894. }
  65895. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  65896. {
  65897. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  65898. width -= x;
  65899. height -= y;
  65900. }
  65901. bool DrawableText::hitTest (float x, float y) const
  65902. {
  65903. return text.findGlyphIndexAt (x, y) >= 0;
  65904. }
  65905. Drawable* DrawableText::createCopy() const
  65906. {
  65907. DrawableText* const dt = new DrawableText();
  65908. dt->text = text;
  65909. dt->colour = colour;
  65910. return dt;
  65911. }
  65912. bool DrawableText::readBinary (InputStream& input)
  65913. {
  65914. jassertfalse; //xxx TODO
  65915. return false;
  65916. }
  65917. bool DrawableText::writeBinary (OutputStream& output) const
  65918. {
  65919. jassertfalse; //xxx TODO
  65920. return false;
  65921. }
  65922. bool DrawableText::readXml (const XmlElement& xml)
  65923. {
  65924. jassertfalse; //xxx TODO
  65925. return false;
  65926. }
  65927. void DrawableText::writeXml (XmlElement& xml) const
  65928. {
  65929. jassertfalse; //xxx TODO
  65930. }
  65931. END_JUCE_NAMESPACE
  65932. /********* End of inlined file: juce_DrawableText.cpp *********/
  65933. /********* Start of inlined file: juce_SVGParser.cpp *********/
  65934. BEGIN_JUCE_NAMESPACE
  65935. class SVGState
  65936. {
  65937. public:
  65938. SVGState (const XmlElement* const topLevel)
  65939. : topLevelXml (topLevel),
  65940. x (0), y (0),
  65941. width (512), height (512),
  65942. viewBoxW (0), viewBoxH (0)
  65943. {
  65944. }
  65945. ~SVGState()
  65946. {
  65947. }
  65948. Drawable* parseSVGElement (const XmlElement& xml)
  65949. {
  65950. if (! xml.hasTagName (T("svg")))
  65951. return 0;
  65952. DrawableComposite* const drawable = new DrawableComposite();
  65953. drawable->setName (xml.getStringAttribute (T("id")));
  65954. SVGState newState (*this);
  65955. if (xml.hasAttribute (T("transform")))
  65956. newState.addTransform (xml);
  65957. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  65958. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  65959. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  65960. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  65961. if (xml.hasAttribute (T("viewBox")))
  65962. {
  65963. const String viewParams (xml.getStringAttribute (T("viewBox")));
  65964. int i = 0;
  65965. float vx, vy, vw, vh;
  65966. if (parseCoords (viewParams, vx, vy, i, true)
  65967. && parseCoords (viewParams, vw, vh, i, true)
  65968. && vw > 0
  65969. && vh > 0)
  65970. {
  65971. newState.viewBoxW = vw;
  65972. newState.viewBoxH = vh;
  65973. int placementFlags = 0;
  65974. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  65975. if (aspect.containsIgnoreCase (T("none")))
  65976. {
  65977. placementFlags = RectanglePlacement::stretchToFit;
  65978. }
  65979. else
  65980. {
  65981. if (aspect.containsIgnoreCase (T("slice")))
  65982. placementFlags |= RectanglePlacement::fillDestination;
  65983. if (aspect.containsIgnoreCase (T("xMin")))
  65984. placementFlags |= RectanglePlacement::xLeft;
  65985. else if (aspect.containsIgnoreCase (T("xMax")))
  65986. placementFlags |= RectanglePlacement::xRight;
  65987. else
  65988. placementFlags |= RectanglePlacement::xMid;
  65989. if (aspect.containsIgnoreCase (T("yMin")))
  65990. placementFlags |= RectanglePlacement::yTop;
  65991. else if (aspect.containsIgnoreCase (T("yMax")))
  65992. placementFlags |= RectanglePlacement::yBottom;
  65993. else
  65994. placementFlags |= RectanglePlacement::yMid;
  65995. }
  65996. const RectanglePlacement placement (placementFlags);
  65997. newState.transform
  65998. = placement.getTransformToFit (vx, vy, vw, vh,
  65999. 0.0f, 0.0f, newState.width, newState.height)
  66000. .followedBy (newState.transform);
  66001. }
  66002. }
  66003. else
  66004. {
  66005. if (viewBoxW == 0)
  66006. newState.viewBoxW = newState.width;
  66007. if (viewBoxH == 0)
  66008. newState.viewBoxH = newState.height;
  66009. }
  66010. newState.parseSubElements (xml, drawable);
  66011. return drawable;
  66012. }
  66013. private:
  66014. const XmlElement* const topLevelXml;
  66015. float x, y, width, height, viewBoxW, viewBoxH;
  66016. AffineTransform transform;
  66017. String cssStyleText;
  66018. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  66019. {
  66020. forEachXmlChildElement (xml, e)
  66021. {
  66022. Drawable* d = 0;
  66023. if (e->hasTagName (T("g")))
  66024. d = parseGroupElement (*e);
  66025. else if (e->hasTagName (T("svg")))
  66026. d = parseSVGElement (*e);
  66027. else if (e->hasTagName (T("path")))
  66028. d = parsePath (*e);
  66029. else if (e->hasTagName (T("rect")))
  66030. d = parseRect (*e);
  66031. else if (e->hasTagName (T("circle")))
  66032. d = parseCircle (*e);
  66033. else if (e->hasTagName (T("ellipse")))
  66034. d = parseEllipse (*e);
  66035. else if (e->hasTagName (T("line")))
  66036. d = parseLine (*e);
  66037. else if (e->hasTagName (T("polyline")))
  66038. d = parsePolygon (*e, true);
  66039. else if (e->hasTagName (T("polygon")))
  66040. d = parsePolygon (*e, false);
  66041. else if (e->hasTagName (T("text")))
  66042. d = parseText (*e);
  66043. else if (e->hasTagName (T("switch")))
  66044. d = parseSwitch (*e);
  66045. else if (e->hasTagName (T("style")))
  66046. parseCSSStyle (*e);
  66047. parentDrawable->insertDrawable (d);
  66048. }
  66049. }
  66050. DrawableComposite* parseSwitch (const XmlElement& xml)
  66051. {
  66052. const XmlElement* const group = xml.getChildByName (T("g"));
  66053. if (group != 0)
  66054. return parseGroupElement (*group);
  66055. return 0;
  66056. }
  66057. DrawableComposite* parseGroupElement (const XmlElement& xml)
  66058. {
  66059. DrawableComposite* const drawable = new DrawableComposite();
  66060. drawable->setName (xml.getStringAttribute (T("id")));
  66061. if (xml.hasAttribute (T("transform")))
  66062. {
  66063. SVGState newState (*this);
  66064. newState.addTransform (xml);
  66065. newState.parseSubElements (xml, drawable);
  66066. }
  66067. else
  66068. {
  66069. parseSubElements (xml, drawable);
  66070. }
  66071. return drawable;
  66072. }
  66073. Drawable* parsePath (const XmlElement& xml) const
  66074. {
  66075. const String d (xml.getStringAttribute (T("d")).trimStart());
  66076. Path path;
  66077. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  66078. path.setUsingNonZeroWinding (false);
  66079. int index = 0;
  66080. float lastX = 0, lastY = 0;
  66081. float lastX2 = 0, lastY2 = 0;
  66082. tchar lastCommandChar = 0;
  66083. bool carryOn = true;
  66084. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  66085. for (;;)
  66086. {
  66087. float x, y, x2, y2, x3, y3;
  66088. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  66089. if (validCommandChars.containsChar (d[index]))
  66090. lastCommandChar = d [index++];
  66091. switch (lastCommandChar)
  66092. {
  66093. case T('M'):
  66094. case T('m'):
  66095. case T('L'):
  66096. case T('l'):
  66097. if (parseCoords (d, x, y, index, false))
  66098. {
  66099. if (isRelative)
  66100. {
  66101. x += lastX;
  66102. y += lastY;
  66103. }
  66104. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  66105. path.startNewSubPath (x, y);
  66106. else
  66107. path.lineTo (x, y);
  66108. lastX2 = lastX;
  66109. lastY2 = lastY;
  66110. lastX = x;
  66111. lastY = y;
  66112. }
  66113. else
  66114. {
  66115. ++index;
  66116. }
  66117. break;
  66118. case T('H'):
  66119. case T('h'):
  66120. if (parseCoord (d, x, index, false, true))
  66121. {
  66122. if (isRelative)
  66123. x += lastX;
  66124. path.lineTo (x, lastY);
  66125. lastX2 = lastX;
  66126. lastX = x;
  66127. }
  66128. else
  66129. {
  66130. ++index;
  66131. }
  66132. break;
  66133. case T('V'):
  66134. case T('v'):
  66135. if (parseCoord (d, y, index, false, false))
  66136. {
  66137. if (isRelative)
  66138. y += lastY;
  66139. path.lineTo (lastX, y);
  66140. lastY2 = lastY;
  66141. lastY = y;
  66142. }
  66143. else
  66144. {
  66145. ++index;
  66146. }
  66147. break;
  66148. case T('C'):
  66149. case T('c'):
  66150. if (parseCoords (d, x, y, index, false)
  66151. && parseCoords (d, x2, y2, index, false)
  66152. && parseCoords (d, x3, y3, index, false))
  66153. {
  66154. if (isRelative)
  66155. {
  66156. x += lastX;
  66157. y += lastY;
  66158. x2 += lastX;
  66159. y2 += lastY;
  66160. x3 += lastX;
  66161. y3 += lastY;
  66162. }
  66163. path.cubicTo (x, y, x2, y2, x3, y3);
  66164. lastX2 = x2;
  66165. lastY2 = y2;
  66166. lastX = x3;
  66167. lastY = y3;
  66168. }
  66169. else
  66170. {
  66171. ++index;
  66172. }
  66173. break;
  66174. case T('S'):
  66175. case T('s'):
  66176. if (parseCoords (d, x, y, index, false)
  66177. && parseCoords (d, x3, y3, index, false))
  66178. {
  66179. if (isRelative)
  66180. {
  66181. x += lastX;
  66182. y += lastY;
  66183. x3 += lastX;
  66184. y3 += lastY;
  66185. }
  66186. x2 = lastX + (lastX - lastX2);
  66187. y2 = lastY + (lastY - lastY2);
  66188. path.cubicTo (x2, y2, x, y, x3, y3);
  66189. lastX2 = x;
  66190. lastY2 = y;
  66191. lastX = x3;
  66192. lastY = y3;
  66193. }
  66194. else
  66195. {
  66196. ++index;
  66197. }
  66198. break;
  66199. case T('Q'):
  66200. case T('q'):
  66201. if (parseCoords (d, x, y, index, false)
  66202. && parseCoords (d, x2, y2, index, false))
  66203. {
  66204. if (isRelative)
  66205. {
  66206. x += lastX;
  66207. y += lastY;
  66208. x2 += lastX;
  66209. y2 += lastY;
  66210. }
  66211. path.quadraticTo (x, y, x2, y2);
  66212. lastX2 = x;
  66213. lastY2 = y;
  66214. lastX = x2;
  66215. lastY = y2;
  66216. }
  66217. else
  66218. {
  66219. ++index;
  66220. }
  66221. break;
  66222. case T('T'):
  66223. case T('t'):
  66224. if (parseCoords (d, x, y, index, false))
  66225. {
  66226. if (isRelative)
  66227. {
  66228. x += lastX;
  66229. y += lastY;
  66230. }
  66231. x2 = lastX + (lastX - lastX2);
  66232. y2 = lastY + (lastY - lastY2);
  66233. path.quadraticTo (x2, y2, x, y);
  66234. lastX2 = x2;
  66235. lastY2 = y2;
  66236. lastX = x;
  66237. lastY = y;
  66238. }
  66239. else
  66240. {
  66241. ++index;
  66242. }
  66243. break;
  66244. case T('A'):
  66245. case T('a'):
  66246. if (parseCoords (d, x, y, index, false))
  66247. {
  66248. String num;
  66249. if (parseNextNumber (d, num, index, false))
  66250. {
  66251. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  66252. if (parseNextNumber (d, num, index, false))
  66253. {
  66254. const bool largeArc = num.getIntValue() != 0;
  66255. if (parseNextNumber (d, num, index, false))
  66256. {
  66257. const bool sweep = num.getIntValue() != 0;
  66258. if (parseCoords (d, x2, y2, index, false))
  66259. {
  66260. if (isRelative)
  66261. {
  66262. x2 += lastX;
  66263. y2 += lastY;
  66264. }
  66265. if (lastX != x2 || lastY != y2)
  66266. {
  66267. double centreX, centreY, startAngle, deltaAngle;
  66268. double rx = x, ry = y;
  66269. endpointToCentreParameters (lastX, lastY, x2, y2,
  66270. angle, largeArc, sweep,
  66271. rx, ry, centreX, centreY,
  66272. startAngle, deltaAngle);
  66273. path.addCentredArc ((float) centreX, (float) centreY,
  66274. (float) rx, (float) ry,
  66275. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  66276. false);
  66277. path.lineTo (x2, y2);
  66278. }
  66279. lastX2 = lastX;
  66280. lastY2 = lastY;
  66281. lastX = x2;
  66282. lastY = y2;
  66283. }
  66284. }
  66285. }
  66286. }
  66287. }
  66288. else
  66289. {
  66290. ++index;
  66291. }
  66292. break;
  66293. case T('Z'):
  66294. case T('z'):
  66295. path.closeSubPath();
  66296. while (CharacterFunctions::isWhitespace (d [index]))
  66297. ++index;
  66298. break;
  66299. default:
  66300. carryOn = false;
  66301. break;
  66302. }
  66303. if (! carryOn)
  66304. break;
  66305. }
  66306. return parseShape (xml, path);
  66307. }
  66308. Drawable* parseRect (const XmlElement& xml) const
  66309. {
  66310. Path rect;
  66311. const bool hasRX = xml.hasAttribute (T("rx"));
  66312. const bool hasRY = xml.hasAttribute (T("ry"));
  66313. if (hasRX || hasRY)
  66314. {
  66315. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66316. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66317. if (! hasRX)
  66318. rx = ry;
  66319. else if (! hasRY)
  66320. ry = rx;
  66321. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66322. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66323. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66324. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  66325. rx, ry);
  66326. }
  66327. else
  66328. {
  66329. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66330. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66331. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66332. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  66333. }
  66334. return parseShape (xml, rect);
  66335. }
  66336. Drawable* parseCircle (const XmlElement& xml) const
  66337. {
  66338. Path circle;
  66339. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66340. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66341. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  66342. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  66343. return parseShape (xml, circle);
  66344. }
  66345. Drawable* parseEllipse (const XmlElement& xml) const
  66346. {
  66347. Path ellipse;
  66348. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66349. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66350. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66351. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66352. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  66353. return parseShape (xml, ellipse);
  66354. }
  66355. Drawable* parseLine (const XmlElement& xml) const
  66356. {
  66357. Path line;
  66358. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  66359. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  66360. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  66361. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  66362. line.startNewSubPath (x1, y1);
  66363. line.lineTo (x2, y2);
  66364. return parseShape (xml, line);
  66365. }
  66366. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  66367. {
  66368. const String points (xml.getStringAttribute (T("points")));
  66369. Path path;
  66370. int index = 0;
  66371. float x, y;
  66372. if (parseCoords (points, x, y, index, true))
  66373. {
  66374. float firstX = x;
  66375. float firstY = y;
  66376. float lastX = 0, lastY = 0;
  66377. path.startNewSubPath (x, y);
  66378. while (parseCoords (points, x, y, index, true))
  66379. {
  66380. lastX = x;
  66381. lastY = y;
  66382. path.lineTo (x, y);
  66383. }
  66384. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  66385. path.closeSubPath();
  66386. }
  66387. return parseShape (xml, path);
  66388. }
  66389. Drawable* parseShape (const XmlElement& xml, Path& path,
  66390. const bool parseTransform = true) const
  66391. {
  66392. if (parseTransform && xml.hasAttribute (T("transform")))
  66393. {
  66394. SVGState newState (*this);
  66395. newState.addTransform (xml);
  66396. return newState.parseShape (xml, path, false);
  66397. }
  66398. DrawablePath* dp = new DrawablePath();
  66399. dp->setName (xml.getStringAttribute (T("id")));
  66400. dp->setSolidFill (Colours::transparentBlack);
  66401. path.applyTransform (transform);
  66402. dp->setPath (path);
  66403. Path::Iterator iter (path);
  66404. bool containsClosedSubPath = false;
  66405. while (iter.next())
  66406. {
  66407. if (iter.elementType == Path::Iterator::closePath)
  66408. {
  66409. containsClosedSubPath = true;
  66410. break;
  66411. }
  66412. }
  66413. Brush* const fillBrush
  66414. = getBrushForFill (path,
  66415. getStyleAttribute (&xml, T("fill")),
  66416. getStyleAttribute (&xml, T("fill-opacity")),
  66417. getStyleAttribute (&xml, T("opacity")),
  66418. containsClosedSubPath ? Colours::black
  66419. : Colours::transparentBlack);
  66420. if (fillBrush != 0)
  66421. {
  66422. if (! fillBrush->isInvisible())
  66423. {
  66424. fillBrush->applyTransform (transform);
  66425. dp->setFillBrush (*fillBrush);
  66426. }
  66427. delete fillBrush;
  66428. }
  66429. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  66430. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  66431. {
  66432. Brush* const strokeBrush
  66433. = getBrushForFill (path, strokeType,
  66434. getStyleAttribute (&xml, T("stroke-opacity")),
  66435. getStyleAttribute (&xml, T("opacity")),
  66436. Colours::transparentBlack);
  66437. if (strokeBrush != 0)
  66438. {
  66439. const PathStrokeType stroke (getStrokeFor (&xml));
  66440. if (! strokeBrush->isInvisible())
  66441. {
  66442. strokeBrush->applyTransform (transform);
  66443. dp->setOutline (stroke, *strokeBrush);
  66444. }
  66445. delete strokeBrush;
  66446. }
  66447. }
  66448. return dp;
  66449. }
  66450. const XmlElement* findLinkedElement (const XmlElement* e) const
  66451. {
  66452. const String id (e->getStringAttribute (T("xlink:href")));
  66453. if (! id.startsWithChar (T('#')))
  66454. return 0;
  66455. return findElementForId (topLevelXml, id.substring (1));
  66456. }
  66457. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  66458. {
  66459. if (fillXml == 0)
  66460. return;
  66461. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  66462. {
  66463. int index = 0;
  66464. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  66465. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  66466. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  66467. double offset = e->getDoubleAttribute (T("offset"));
  66468. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  66469. offset *= 0.01;
  66470. cg.addColour (jlimit (0.0, 1.0, offset), col);
  66471. }
  66472. }
  66473. Brush* getBrushForFill (const Path& path,
  66474. const String& fill,
  66475. const String& fillOpacity,
  66476. const String& overallOpacity,
  66477. const Colour& defaultColour) const
  66478. {
  66479. float opacity = 1.0f;
  66480. if (overallOpacity.isNotEmpty())
  66481. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  66482. if (fillOpacity.isNotEmpty())
  66483. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  66484. if (fill.startsWithIgnoreCase (T("url")))
  66485. {
  66486. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  66487. .upToLastOccurrenceOf (T(")"), false, false).trim());
  66488. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  66489. if (fillXml != 0
  66490. && (fillXml->hasTagName (T("linearGradient"))
  66491. || fillXml->hasTagName (T("radialGradient"))))
  66492. {
  66493. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  66494. ColourGradient cg;
  66495. addGradientStopsIn (cg, inheritedFrom);
  66496. addGradientStopsIn (cg, fillXml);
  66497. if (cg.getNumColours() > 0)
  66498. {
  66499. cg.addColour (0.0, cg.getColour (0));
  66500. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  66501. }
  66502. else
  66503. {
  66504. cg.addColour (0.0, Colours::black);
  66505. cg.addColour (1.0, Colours::black);
  66506. }
  66507. if (overallOpacity.isNotEmpty())
  66508. cg.multiplyOpacity (overallOpacity.getFloatValue());
  66509. jassert (cg.getNumColours() > 0);
  66510. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  66511. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  66512. float width = viewBoxW;
  66513. float height = viewBoxH;
  66514. float dx = 0.0;
  66515. float dy = 0.0;
  66516. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  66517. if (! userSpace)
  66518. path.getBounds (dx, dy, width, height);
  66519. if (cg.isRadial)
  66520. {
  66521. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  66522. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  66523. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  66524. cg.x2 = cg.x1 + radius;
  66525. cg.y2 = cg.y1;
  66526. //xxx (the fx, fy focal point isn't handled properly here..)
  66527. }
  66528. else
  66529. {
  66530. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  66531. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  66532. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  66533. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  66534. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  66535. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  66536. }
  66537. return new GradientBrush (cg);
  66538. }
  66539. }
  66540. if (fill.equalsIgnoreCase (T("none")))
  66541. return new SolidColourBrush (Colours::transparentBlack);
  66542. int i = 0;
  66543. Colour colour (parseColour (fill, i, defaultColour));
  66544. colour = colour.withMultipliedAlpha (opacity);
  66545. return new SolidColourBrush (colour);
  66546. }
  66547. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  66548. {
  66549. const String width (getStyleAttribute (xml, T("stroke-width")));
  66550. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  66551. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  66552. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  66553. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  66554. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  66555. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  66556. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  66557. if (join.equalsIgnoreCase (T("round")))
  66558. joinStyle = PathStrokeType::curved;
  66559. else if (join.equalsIgnoreCase (T("bevel")))
  66560. joinStyle = PathStrokeType::beveled;
  66561. if (cap.equalsIgnoreCase (T("round")))
  66562. capStyle = PathStrokeType::rounded;
  66563. else if (cap.equalsIgnoreCase (T("square")))
  66564. capStyle = PathStrokeType::square;
  66565. float ox = 0.0f, oy = 0.0f;
  66566. transform.transformPoint (ox, oy);
  66567. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  66568. transform.transformPoint (x, y);
  66569. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  66570. joinStyle, capStyle);
  66571. }
  66572. Drawable* parseText (const XmlElement& xml)
  66573. {
  66574. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  66575. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  66576. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  66577. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  66578. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  66579. //xxx not done text yet!
  66580. forEachXmlChildElement (xml, e)
  66581. {
  66582. if (e->isTextElement())
  66583. {
  66584. const String text (e->getText());
  66585. Path path;
  66586. Drawable* s = parseShape (*e, path);
  66587. delete s;
  66588. }
  66589. else if (e->hasTagName (T("tspan")))
  66590. {
  66591. Drawable* s = parseText (*e);
  66592. delete s;
  66593. }
  66594. }
  66595. return 0;
  66596. }
  66597. void addTransform (const XmlElement& xml)
  66598. {
  66599. transform = parseTransform (xml.getStringAttribute (T("transform")))
  66600. .followedBy (transform);
  66601. }
  66602. bool parseCoord (const String& s, float& value, int& index,
  66603. const bool allowUnits, const bool isX) const
  66604. {
  66605. String number;
  66606. if (! parseNextNumber (s, number, index, allowUnits))
  66607. {
  66608. value = 0;
  66609. return false;
  66610. }
  66611. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  66612. return true;
  66613. }
  66614. bool parseCoords (const String& s, float& x, float& y,
  66615. int& index, const bool allowUnits) const
  66616. {
  66617. return parseCoord (s, x, index, allowUnits, true)
  66618. && parseCoord (s, y, index, allowUnits, false);
  66619. }
  66620. float getCoordLength (const String& s, const float sizeForProportions) const
  66621. {
  66622. float n = s.getFloatValue();
  66623. const int len = s.length();
  66624. if (len > 2)
  66625. {
  66626. const float dpi = 96.0f;
  66627. const tchar n1 = s [len - 2];
  66628. const tchar n2 = s [len - 1];
  66629. if (n1 == T('i') && n2 == T('n'))
  66630. n *= dpi;
  66631. else if (n1 == T('m') && n2 == T('m'))
  66632. n *= dpi / 25.4f;
  66633. else if (n1 == T('c') && n2 == T('m'))
  66634. n *= dpi / 2.54f;
  66635. else if (n1 == T('p') && n2 == T('c'))
  66636. n *= 15.0f;
  66637. else if (n2 == T('%'))
  66638. n *= 0.01f * sizeForProportions;
  66639. }
  66640. return n;
  66641. }
  66642. void getCoordList (Array <float>& coords, const String& list,
  66643. const bool allowUnits, const bool isX) const
  66644. {
  66645. int index = 0;
  66646. float value;
  66647. while (parseCoord (list, value, index, allowUnits, isX))
  66648. coords.add (value);
  66649. }
  66650. void parseCSSStyle (const XmlElement& xml)
  66651. {
  66652. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  66653. }
  66654. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  66655. const String& defaultValue = String::empty) const
  66656. {
  66657. if (xml->hasAttribute (attributeName))
  66658. return xml->getStringAttribute (attributeName, defaultValue);
  66659. const String styleAtt (xml->getStringAttribute (T("style")));
  66660. if (styleAtt.isNotEmpty())
  66661. {
  66662. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  66663. if (value.isNotEmpty())
  66664. return value;
  66665. }
  66666. else if (xml->hasAttribute (T("class")))
  66667. {
  66668. const String className (T(".") + xml->getStringAttribute (T("class")));
  66669. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  66670. if (index < 0)
  66671. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  66672. if (index >= 0)
  66673. {
  66674. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  66675. if (openBracket > index)
  66676. {
  66677. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  66678. if (closeBracket > openBracket)
  66679. {
  66680. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  66681. if (value.isNotEmpty())
  66682. return value;
  66683. }
  66684. }
  66685. }
  66686. }
  66687. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66688. if (xml != 0)
  66689. return getStyleAttribute (xml, attributeName, defaultValue);
  66690. return defaultValue;
  66691. }
  66692. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  66693. {
  66694. if (xml->hasAttribute (attributeName))
  66695. return xml->getStringAttribute (attributeName);
  66696. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66697. if (xml != 0)
  66698. return getInheritedAttribute (xml, attributeName);
  66699. return String::empty;
  66700. }
  66701. static bool isIdentifierChar (const tchar c)
  66702. {
  66703. return CharacterFunctions::isLetter (c) || c == T('-');
  66704. }
  66705. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  66706. {
  66707. int i = 0;
  66708. for (;;)
  66709. {
  66710. i = list.indexOf (i, attributeName);
  66711. if (i < 0)
  66712. break;
  66713. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  66714. && ! isIdentifierChar (list [i + attributeName.length()]))
  66715. {
  66716. i = list.indexOfChar (i, T(':'));
  66717. if (i < 0)
  66718. break;
  66719. int end = list.indexOfChar (i, T(';'));
  66720. if (end < 0)
  66721. end = 0x7ffff;
  66722. return list.substring (i + 1, end).trim();
  66723. }
  66724. ++i;
  66725. }
  66726. return defaultValue;
  66727. }
  66728. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  66729. {
  66730. const tchar* const s = (const tchar*) source;
  66731. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66732. ++index;
  66733. int start = index;
  66734. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  66735. ++index;
  66736. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  66737. ++index;
  66738. if ((s[index] == T('e') || s[index] == T('E'))
  66739. && (CharacterFunctions::isDigit (s[index + 1])
  66740. || s[index + 1] == T('-')
  66741. || s[index + 1] == T('+')))
  66742. {
  66743. index += 2;
  66744. while (CharacterFunctions::isDigit (s[index]))
  66745. ++index;
  66746. }
  66747. if (allowUnits)
  66748. {
  66749. while (CharacterFunctions::isLetter (s[index]))
  66750. ++index;
  66751. }
  66752. if (index == start)
  66753. return false;
  66754. value = String (s + start, index - start);
  66755. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66756. ++index;
  66757. return true;
  66758. }
  66759. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  66760. {
  66761. if (s [index] == T('#'))
  66762. {
  66763. uint32 hex [6];
  66764. zeromem (hex, sizeof (hex));
  66765. int numChars = 0;
  66766. for (int i = 6; --i >= 0;)
  66767. {
  66768. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  66769. if (hexValue >= 0)
  66770. hex [numChars++] = hexValue;
  66771. else
  66772. break;
  66773. }
  66774. if (numChars <= 3)
  66775. return Colour ((uint8) (hex [0] * 0x11),
  66776. (uint8) (hex [1] * 0x11),
  66777. (uint8) (hex [2] * 0x11));
  66778. else
  66779. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  66780. (uint8) ((hex [2] << 4) + hex [3]),
  66781. (uint8) ((hex [4] << 4) + hex [5]));
  66782. }
  66783. else if (s [index] == T('r')
  66784. && s [index + 1] == T('g')
  66785. && s [index + 2] == T('b'))
  66786. {
  66787. const int openBracket = s.indexOfChar (index, T('('));
  66788. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  66789. if (openBracket >= 3 && closeBracket > openBracket)
  66790. {
  66791. index = closeBracket;
  66792. StringArray tokens;
  66793. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  66794. tokens.trim();
  66795. tokens.removeEmptyStrings();
  66796. if (tokens[0].containsChar (T('%')))
  66797. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  66798. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  66799. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  66800. else
  66801. return Colour ((uint8) tokens[0].getIntValue(),
  66802. (uint8) tokens[1].getIntValue(),
  66803. (uint8) tokens[2].getIntValue());
  66804. }
  66805. }
  66806. return Colours::findColourForName (s, defaultColour);
  66807. }
  66808. static const AffineTransform parseTransform (String t)
  66809. {
  66810. AffineTransform result;
  66811. while (t.isNotEmpty())
  66812. {
  66813. StringArray tokens;
  66814. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  66815. .upToFirstOccurrenceOf (T(")"), false, false),
  66816. T(", "), 0);
  66817. tokens.removeEmptyStrings (true);
  66818. float numbers [6];
  66819. for (int i = 0; i < 6; ++i)
  66820. numbers[i] = tokens[i].getFloatValue();
  66821. AffineTransform trans;
  66822. if (t.startsWithIgnoreCase (T("matrix")))
  66823. {
  66824. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  66825. numbers[1], numbers[3], numbers[5]);
  66826. }
  66827. else if (t.startsWithIgnoreCase (T("translate")))
  66828. {
  66829. trans = trans.translated (numbers[0], numbers[1]);
  66830. }
  66831. else if (t.startsWithIgnoreCase (T("scale")))
  66832. {
  66833. if (tokens.size() == 1)
  66834. trans = trans.scaled (numbers[0], numbers[0]);
  66835. else
  66836. trans = trans.scaled (numbers[0], numbers[1]);
  66837. }
  66838. else if (t.startsWithIgnoreCase (T("rotate")))
  66839. {
  66840. if (tokens.size() != 3)
  66841. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  66842. else
  66843. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  66844. numbers[1], numbers[2]);
  66845. }
  66846. else if (t.startsWithIgnoreCase (T("skewX")))
  66847. {
  66848. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  66849. 0.0f, 1.0f, 0.0f);
  66850. }
  66851. else if (t.startsWithIgnoreCase (T("skewY")))
  66852. {
  66853. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  66854. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  66855. }
  66856. result = trans.followedBy (result);
  66857. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  66858. }
  66859. return result;
  66860. }
  66861. static void endpointToCentreParameters (const double x1, const double y1,
  66862. const double x2, const double y2,
  66863. const double angle,
  66864. const bool largeArc, const bool sweep,
  66865. double& rx, double& ry,
  66866. double& centreX, double& centreY,
  66867. double& startAngle, double& deltaAngle)
  66868. {
  66869. const double midX = (x1 - x2) * 0.5;
  66870. const double midY = (y1 - y2) * 0.5;
  66871. const double cosAngle = cos (angle);
  66872. const double sinAngle = sin (angle);
  66873. const double xp = cosAngle * midX + sinAngle * midY;
  66874. const double yp = cosAngle * midY - sinAngle * midX;
  66875. const double xp2 = xp * xp;
  66876. const double yp2 = yp * yp;
  66877. double rx2 = rx * rx;
  66878. double ry2 = ry * ry;
  66879. const double s = (xp2 / rx2) + (yp2 / ry2);
  66880. double c;
  66881. if (s <= 1.0)
  66882. {
  66883. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  66884. / (( rx2 * yp2) + (ry2 * xp2))));
  66885. if (largeArc == sweep)
  66886. c = -c;
  66887. }
  66888. else
  66889. {
  66890. const double s2 = sqrt (s);
  66891. rx *= s2;
  66892. ry *= s2;
  66893. rx2 = rx * rx;
  66894. ry2 = ry * ry;
  66895. c = 0;
  66896. }
  66897. const double cpx = ((rx * yp) / ry) * c;
  66898. const double cpy = ((-ry * xp) / rx) * c;
  66899. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  66900. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  66901. const double ux = (xp - cpx) / rx;
  66902. const double uy = (yp - cpy) / ry;
  66903. const double vx = (-xp - cpx) / rx;
  66904. const double vy = (-yp - cpy) / ry;
  66905. const double length = juce_hypot (ux, uy);
  66906. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  66907. if (uy < 0)
  66908. startAngle = -startAngle;
  66909. startAngle += double_Pi * 0.5;
  66910. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  66911. / (length * juce_hypot (vx, vy))));
  66912. if ((ux * vy) - (uy * vx) < 0)
  66913. deltaAngle = -deltaAngle;
  66914. if (sweep)
  66915. {
  66916. if (deltaAngle < 0)
  66917. deltaAngle += double_Pi * 2.0;
  66918. }
  66919. else
  66920. {
  66921. if (deltaAngle > 0)
  66922. deltaAngle -= double_Pi * 2.0;
  66923. }
  66924. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  66925. }
  66926. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  66927. {
  66928. forEachXmlChildElement (*parent, e)
  66929. {
  66930. if (e->compareAttribute (T("id"), id))
  66931. return e;
  66932. const XmlElement* const found = findElementForId (e, id);
  66933. if (found != 0)
  66934. return found;
  66935. }
  66936. return 0;
  66937. }
  66938. const SVGState& operator= (const SVGState&);
  66939. };
  66940. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  66941. {
  66942. SVGState state (&svgDocument);
  66943. return state.parseSVGElement (svgDocument);
  66944. }
  66945. END_JUCE_NAMESPACE
  66946. /********* End of inlined file: juce_SVGParser.cpp *********/
  66947. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  66948. BEGIN_JUCE_NAMESPACE
  66949. #if JUCE_MSVC
  66950. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  66951. #endif
  66952. DropShadowEffect::DropShadowEffect()
  66953. : offsetX (0),
  66954. offsetY (0),
  66955. radius (4),
  66956. opacity (0.6f)
  66957. {
  66958. }
  66959. DropShadowEffect::~DropShadowEffect()
  66960. {
  66961. }
  66962. void DropShadowEffect::setShadowProperties (const float newRadius,
  66963. const float newOpacity,
  66964. const int newShadowOffsetX,
  66965. const int newShadowOffsetY)
  66966. {
  66967. radius = jmax (1.1f, newRadius);
  66968. offsetX = newShadowOffsetX;
  66969. offsetY = newShadowOffsetY;
  66970. opacity = newOpacity;
  66971. }
  66972. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  66973. {
  66974. const int w = image.getWidth();
  66975. const int h = image.getHeight();
  66976. int lineStride, pixelStride;
  66977. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  66978. Image shadowImage (Image::SingleChannel, w, h, false);
  66979. int destStride, destPixelStride;
  66980. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  66981. const int filter = roundFloatToInt (63.0f / radius);
  66982. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  66983. for (int x = w; --x >= 0;)
  66984. {
  66985. int shadowAlpha = 0;
  66986. const PixelARGB* src = srcPixels + x;
  66987. uint8* shadowPix = shadowChannel + x;
  66988. for (int y = h; --y >= 0;)
  66989. {
  66990. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  66991. *shadowPix = (uint8) shadowAlpha;
  66992. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  66993. shadowPix += destStride;
  66994. }
  66995. }
  66996. for (int y = h; --y >= 0;)
  66997. {
  66998. int shadowAlpha = 0;
  66999. uint8* shadowPix = shadowChannel + y * destStride;
  67000. for (int x = w; --x >= 0;)
  67001. {
  67002. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  67003. *shadowPix++ = (uint8) shadowAlpha;
  67004. }
  67005. }
  67006. image.releasePixelDataReadOnly (srcPixels);
  67007. shadowImage.releasePixelDataReadWrite (shadowChannel);
  67008. g.setColour (Colours::black.withAlpha (opacity));
  67009. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  67010. g.setOpacity (1.0f);
  67011. g.drawImageAt (&image, 0, 0);
  67012. }
  67013. END_JUCE_NAMESPACE
  67014. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  67015. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  67016. BEGIN_JUCE_NAMESPACE
  67017. GlowEffect::GlowEffect()
  67018. : radius (2.0f),
  67019. colour (Colours::white)
  67020. {
  67021. }
  67022. GlowEffect::~GlowEffect()
  67023. {
  67024. }
  67025. void GlowEffect::setGlowProperties (const float newRadius,
  67026. const Colour& newColour)
  67027. {
  67028. radius = newRadius;
  67029. colour = newColour;
  67030. }
  67031. void GlowEffect::applyEffect (Image& image, Graphics& g)
  67032. {
  67033. const int w = image.getWidth();
  67034. const int h = image.getHeight();
  67035. Image temp (image.getFormat(), w, h, true);
  67036. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  67037. blurKernel.createGaussianBlur (radius);
  67038. blurKernel.rescaleAllValues (radius);
  67039. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  67040. g.setColour (colour);
  67041. g.drawImageAt (&temp, 0, 0, true);
  67042. g.setOpacity (1.0f);
  67043. g.drawImageAt (&image, 0, 0, false);
  67044. }
  67045. END_JUCE_NAMESPACE
  67046. /********* End of inlined file: juce_GlowEffect.cpp *********/
  67047. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  67048. BEGIN_JUCE_NAMESPACE
  67049. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  67050. : opacity (opacity_)
  67051. {
  67052. }
  67053. ReduceOpacityEffect::~ReduceOpacityEffect()
  67054. {
  67055. }
  67056. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  67057. {
  67058. opacity = jlimit (0.0f, 1.0f, newOpacity);
  67059. }
  67060. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  67061. {
  67062. g.setOpacity (opacity);
  67063. g.drawImageAt (&image, 0, 0);
  67064. }
  67065. END_JUCE_NAMESPACE
  67066. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  67067. /********* Start of inlined file: juce_Font.cpp *********/
  67068. BEGIN_JUCE_NAMESPACE
  67069. static const float minFontHeight = 0.1f;
  67070. static const float maxFontHeight = 10000.0f;
  67071. static const float defaultFontHeight = 14.0f;
  67072. Font::Font() throw()
  67073. : typefaceName (Typeface::defaultTypefaceNameSans),
  67074. height (defaultFontHeight),
  67075. horizontalScale (1.0f),
  67076. kerning (0),
  67077. ascent (0),
  67078. styleFlags (Font::plain)
  67079. {
  67080. }
  67081. void Font::resetToDefaultState() throw()
  67082. {
  67083. typefaceName = Typeface::defaultTypefaceNameSans;
  67084. height = defaultFontHeight;
  67085. horizontalScale = 1.0f;
  67086. kerning = 0;
  67087. ascent = 0;
  67088. styleFlags = Font::plain;
  67089. typeface = 0;
  67090. }
  67091. Font::Font (const float fontHeight,
  67092. const int styleFlags_) throw()
  67093. : typefaceName (Typeface::defaultTypefaceNameSans),
  67094. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  67095. horizontalScale (1.0f),
  67096. kerning (0),
  67097. ascent (0),
  67098. styleFlags (styleFlags_)
  67099. {
  67100. }
  67101. Font::Font (const String& typefaceName_,
  67102. const float fontHeight,
  67103. const int styleFlags_) throw()
  67104. : typefaceName (typefaceName_),
  67105. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  67106. horizontalScale (1.0f),
  67107. kerning (0),
  67108. ascent (0),
  67109. styleFlags (styleFlags_)
  67110. {
  67111. }
  67112. Font::Font (const Font& other) throw()
  67113. : typefaceName (other.typefaceName),
  67114. height (other.height),
  67115. horizontalScale (other.horizontalScale),
  67116. kerning (other.kerning),
  67117. ascent (other.ascent),
  67118. styleFlags (other.styleFlags),
  67119. typeface (other.typeface)
  67120. {
  67121. }
  67122. const Font& Font::operator= (const Font& other) throw()
  67123. {
  67124. if (this != &other)
  67125. {
  67126. typefaceName = other.typefaceName;
  67127. height = other.height;
  67128. styleFlags = other.styleFlags;
  67129. horizontalScale = other.horizontalScale;
  67130. kerning = other.kerning;
  67131. ascent = other.ascent;
  67132. typeface = other.typeface;
  67133. }
  67134. return *this;
  67135. }
  67136. Font::~Font() throw()
  67137. {
  67138. }
  67139. Font::Font (const Typeface& face) throw()
  67140. : height (11.0f),
  67141. horizontalScale (1.0f),
  67142. kerning (0),
  67143. ascent (0),
  67144. styleFlags (plain)
  67145. {
  67146. typefaceName = face.getName();
  67147. setBold (face.isBold());
  67148. setItalic (face.isItalic());
  67149. typeface = new Typeface (face);
  67150. }
  67151. bool Font::operator== (const Font& other) const throw()
  67152. {
  67153. return height == other.height
  67154. && horizontalScale == other.horizontalScale
  67155. && kerning == other.kerning
  67156. && styleFlags == other.styleFlags
  67157. && typefaceName == other.typefaceName;
  67158. }
  67159. bool Font::operator!= (const Font& other) const throw()
  67160. {
  67161. return ! operator== (other);
  67162. }
  67163. void Font::setTypefaceName (const String& faceName) throw()
  67164. {
  67165. typefaceName = faceName;
  67166. typeface = 0;
  67167. ascent = 0;
  67168. }
  67169. static String fallbackFont;
  67170. const String Font::getFallbackFontName() throw()
  67171. {
  67172. return fallbackFont;
  67173. }
  67174. void Font::setFallbackFontName (const String& name) throw()
  67175. {
  67176. fallbackFont = name;
  67177. }
  67178. void Font::setHeight (float newHeight) throw()
  67179. {
  67180. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  67181. }
  67182. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  67183. {
  67184. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  67185. horizontalScale *= (height / newHeight);
  67186. height = newHeight;
  67187. }
  67188. void Font::setStyleFlags (const int newFlags) throw()
  67189. {
  67190. if (styleFlags != newFlags)
  67191. {
  67192. styleFlags = newFlags;
  67193. typeface = 0;
  67194. ascent = 0;
  67195. }
  67196. }
  67197. void Font::setSizeAndStyle (const float newHeight,
  67198. const int newStyleFlags,
  67199. const float newHorizontalScale,
  67200. const float newKerningAmount) throw()
  67201. {
  67202. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  67203. horizontalScale = newHorizontalScale;
  67204. kerning = newKerningAmount;
  67205. setStyleFlags (newStyleFlags);
  67206. }
  67207. void Font::setHorizontalScale (const float scaleFactor) throw()
  67208. {
  67209. horizontalScale = scaleFactor;
  67210. }
  67211. void Font::setExtraKerningFactor (const float extraKerning) throw()
  67212. {
  67213. kerning = extraKerning;
  67214. }
  67215. void Font::setBold (const bool shouldBeBold) throw()
  67216. {
  67217. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  67218. : (styleFlags & ~bold));
  67219. }
  67220. bool Font::isBold() const throw()
  67221. {
  67222. return (styleFlags & bold) != 0;
  67223. }
  67224. void Font::setItalic (const bool shouldBeItalic) throw()
  67225. {
  67226. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  67227. : (styleFlags & ~italic));
  67228. }
  67229. bool Font::isItalic() const throw()
  67230. {
  67231. return (styleFlags & italic) != 0;
  67232. }
  67233. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  67234. {
  67235. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  67236. : (styleFlags & ~underlined));
  67237. }
  67238. bool Font::isUnderlined() const throw()
  67239. {
  67240. return (styleFlags & underlined) != 0;
  67241. }
  67242. float Font::getAscent() const throw()
  67243. {
  67244. if (ascent == 0)
  67245. ascent = getTypeface()->getAscent();
  67246. return height * ascent;
  67247. }
  67248. float Font::getDescent() const throw()
  67249. {
  67250. return height - getAscent();
  67251. }
  67252. int Font::getStringWidth (const String& text) const throw()
  67253. {
  67254. return roundFloatToInt (getStringWidthFloat (text));
  67255. }
  67256. float Font::getStringWidthFloat (const String& text) const throw()
  67257. {
  67258. float x = 0.0f;
  67259. if (text.isNotEmpty())
  67260. {
  67261. Typeface* const typeface = getTypeface();
  67262. const juce_wchar* t = (const juce_wchar*) text;
  67263. do
  67264. {
  67265. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  67266. if (glyph != 0)
  67267. x += kerning + glyph->getHorizontalSpacing (*t);
  67268. }
  67269. while (*t != 0);
  67270. x *= height;
  67271. x *= horizontalScale;
  67272. }
  67273. return x;
  67274. }
  67275. Typeface* Font::getTypeface() const throw()
  67276. {
  67277. if (typeface == 0)
  67278. typeface = Typeface::getTypefaceFor (*this);
  67279. return typeface;
  67280. }
  67281. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  67282. {
  67283. const StringArray names (findAllTypefaceNames());
  67284. for (int i = 0; i < names.size(); ++i)
  67285. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  67286. }
  67287. END_JUCE_NAMESPACE
  67288. /********* End of inlined file: juce_Font.cpp *********/
  67289. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  67290. BEGIN_JUCE_NAMESPACE
  67291. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  67292. class FontGlyphAlphaMap
  67293. {
  67294. public:
  67295. bool draw (const Graphics& g, float x, const float y) const throw()
  67296. {
  67297. if (bitmap1 == 0)
  67298. return false;
  67299. x += xOrigin;
  67300. const float xFloor = floorf (x);
  67301. const int intX = (int) xFloor;
  67302. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  67303. intX, (int) floorf (y + yOrigin), true);
  67304. return true;
  67305. }
  67306. juce_UseDebuggingNewOperator
  67307. private:
  67308. Image* bitmap1;
  67309. Image* bitmap2;
  67310. float xOrigin, yOrigin;
  67311. int lastAccessCount;
  67312. Typeface::Ptr typeface;
  67313. float height, horizontalScale;
  67314. juce_wchar character;
  67315. friend class GlyphCache;
  67316. FontGlyphAlphaMap() throw()
  67317. : bitmap1 (0),
  67318. bitmap2 (0),
  67319. lastAccessCount (0),
  67320. height (0),
  67321. horizontalScale (0),
  67322. character (0)
  67323. {
  67324. }
  67325. ~FontGlyphAlphaMap() throw()
  67326. {
  67327. delete bitmap1;
  67328. delete bitmap2;
  67329. }
  67330. class AlphaBitmapRenderer
  67331. {
  67332. uint8* const data;
  67333. const int stride;
  67334. uint8* lineStart;
  67335. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  67336. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  67337. public:
  67338. AlphaBitmapRenderer (uint8* const data_,
  67339. const int stride_) throw()
  67340. : data (data_),
  67341. stride (stride_)
  67342. {
  67343. }
  67344. forcedinline void setEdgeTableYPos (const int y) throw()
  67345. {
  67346. lineStart = data + (stride * y);
  67347. }
  67348. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67349. {
  67350. lineStart [x] = (uint8) alphaLevel;
  67351. }
  67352. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  67353. {
  67354. uint8* d = lineStart + x;
  67355. while (--width >= 0)
  67356. *d++ = (uint8) alphaLevel;
  67357. }
  67358. };
  67359. Image* createAlphaMapFromPath (const Path& path,
  67360. float& topLeftX, float& topLeftY,
  67361. float xScale, float yScale,
  67362. const float subPixelOffsetX) throw()
  67363. {
  67364. Image* im = 0;
  67365. float px, py, pw, ph;
  67366. path.getBounds (px, py, pw, ph);
  67367. topLeftX = floorf (px * xScale);
  67368. topLeftY = floorf (py * yScale);
  67369. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  67370. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  67371. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  67372. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  67373. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  67374. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  67375. int stride, pixelStride;
  67376. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  67377. jassert (pixelStride == 1);
  67378. AlphaBitmapRenderer renderer (pixels, stride);
  67379. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  67380. im->releasePixelDataReadWrite (pixels);
  67381. return im;
  67382. }
  67383. void generate (Typeface* const face,
  67384. const juce_wchar character_,
  67385. const float fontHeight,
  67386. const float fontHorizontalScale) throw()
  67387. {
  67388. character = character_;
  67389. typeface = face;
  67390. height = fontHeight;
  67391. horizontalScale = fontHorizontalScale;
  67392. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  67393. deleteAndZero (bitmap1);
  67394. deleteAndZero (bitmap2);
  67395. const float fontHScale = fontHeight * fontHorizontalScale;
  67396. if (glyphPath != 0 && ! glyphPath->isEmpty())
  67397. {
  67398. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  67399. if (fontHScale < 24.0f)
  67400. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  67401. }
  67402. else
  67403. {
  67404. xOrigin = yOrigin = 0;
  67405. }
  67406. }
  67407. };
  67408. static const int defaultNumGlyphsToCache = 120;
  67409. class GlyphCache;
  67410. static GlyphCache* cacheInstance = 0;
  67411. class GlyphCache : private DeletedAtShutdown
  67412. {
  67413. public:
  67414. static GlyphCache* getInstance() throw()
  67415. {
  67416. if (cacheInstance == 0)
  67417. cacheInstance = new GlyphCache();
  67418. return cacheInstance;
  67419. }
  67420. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  67421. const float fontHeight,
  67422. const float fontHorizontalScale,
  67423. const juce_wchar character) throw()
  67424. {
  67425. ++accessCounter;
  67426. int oldestCounter = INT_MAX;
  67427. int oldestIndex = 0;
  67428. for (int i = numGlyphs; --i >= 0;)
  67429. {
  67430. FontGlyphAlphaMap& g = glyphs[i];
  67431. if (g.character == character
  67432. && g.height == fontHeight
  67433. && g.typeface->hashCode() == typeface->hashCode()
  67434. && g.horizontalScale == fontHorizontalScale)
  67435. {
  67436. g.lastAccessCount = accessCounter;
  67437. ++hits;
  67438. return g;
  67439. }
  67440. if (oldestCounter > g.lastAccessCount)
  67441. {
  67442. oldestCounter = g.lastAccessCount;
  67443. oldestIndex = i;
  67444. }
  67445. }
  67446. ++misses;
  67447. if (hits + misses > (numGlyphs << 4))
  67448. {
  67449. if (misses * 2 > hits)
  67450. setCacheSize (numGlyphs + 32);
  67451. hits = 0;
  67452. misses = 0;
  67453. oldestIndex = 0;
  67454. }
  67455. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  67456. oldest.lastAccessCount = accessCounter;
  67457. oldest.generate (typeface,
  67458. character,
  67459. fontHeight,
  67460. fontHorizontalScale);
  67461. return oldest;
  67462. }
  67463. void setCacheSize (const int num) throw()
  67464. {
  67465. if (numGlyphs != num)
  67466. {
  67467. numGlyphs = num;
  67468. if (glyphs != 0)
  67469. delete[] glyphs;
  67470. glyphs = new FontGlyphAlphaMap [numGlyphs];
  67471. hits = 0;
  67472. misses = 0;
  67473. }
  67474. }
  67475. juce_UseDebuggingNewOperator
  67476. private:
  67477. FontGlyphAlphaMap* glyphs;
  67478. int numGlyphs, accessCounter;
  67479. int hits, misses;
  67480. GlyphCache() throw()
  67481. : glyphs (0),
  67482. numGlyphs (0),
  67483. accessCounter (0)
  67484. {
  67485. setCacheSize (defaultNumGlyphsToCache);
  67486. }
  67487. ~GlyphCache() throw()
  67488. {
  67489. delete[] glyphs;
  67490. jassert (cacheInstance == this);
  67491. cacheInstance = 0;
  67492. }
  67493. GlyphCache (const GlyphCache&);
  67494. const GlyphCache& operator= (const GlyphCache&);
  67495. };
  67496. PositionedGlyph::PositionedGlyph() throw()
  67497. {
  67498. }
  67499. void PositionedGlyph::draw (const Graphics& g) const throw()
  67500. {
  67501. if (! glyphInfo->isWhitespace())
  67502. {
  67503. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  67504. {
  67505. const FontGlyphAlphaMap& alphaMap
  67506. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  67507. fontHeight,
  67508. fontHorizontalScale,
  67509. getCharacter());
  67510. alphaMap.draw (g, x, y);
  67511. }
  67512. else
  67513. {
  67514. // that's a bit of a dodgy size, isn't it??
  67515. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  67516. draw (g, AffineTransform::identity);
  67517. }
  67518. }
  67519. }
  67520. void PositionedGlyph::draw (const Graphics& g,
  67521. const AffineTransform& transform) const throw()
  67522. {
  67523. if (! glyphInfo->isWhitespace())
  67524. {
  67525. g.fillPath (glyphInfo->getPath(),
  67526. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67527. .translated (x, y)
  67528. .followedBy (transform));
  67529. }
  67530. }
  67531. void PositionedGlyph::createPath (Path& path) const throw()
  67532. {
  67533. if (! glyphInfo->isWhitespace())
  67534. {
  67535. path.addPath (glyphInfo->getPath(),
  67536. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67537. .translated (x, y));
  67538. }
  67539. }
  67540. bool PositionedGlyph::hitTest (float px, float py) const throw()
  67541. {
  67542. if (px >= getLeft() && px < getRight()
  67543. && py >= getTop() && py < getBottom()
  67544. && fontHeight > 0.0f
  67545. && ! glyphInfo->isWhitespace())
  67546. {
  67547. AffineTransform::translation (-x, -y)
  67548. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  67549. .transformPoint (px, py);
  67550. return glyphInfo->getPath().contains (px, py);
  67551. }
  67552. return false;
  67553. }
  67554. void PositionedGlyph::moveBy (const float deltaX,
  67555. const float deltaY) throw()
  67556. {
  67557. x += deltaX;
  67558. y += deltaY;
  67559. }
  67560. GlyphArrangement::GlyphArrangement() throw()
  67561. : numGlyphs (0),
  67562. numAllocated (0),
  67563. glyphs (0)
  67564. {
  67565. }
  67566. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  67567. : numGlyphs (0),
  67568. numAllocated (0),
  67569. glyphs (0)
  67570. {
  67571. addGlyphArrangement (other);
  67572. }
  67573. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  67574. {
  67575. if (this != &other)
  67576. {
  67577. clear();
  67578. addGlyphArrangement (other);
  67579. }
  67580. return *this;
  67581. }
  67582. GlyphArrangement::~GlyphArrangement() throw()
  67583. {
  67584. clear();
  67585. juce_free (glyphs);
  67586. }
  67587. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  67588. {
  67589. if (numAllocated <= minGlyphs)
  67590. {
  67591. numAllocated = minGlyphs + 2;
  67592. if (glyphs == 0)
  67593. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  67594. else
  67595. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  67596. }
  67597. }
  67598. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  67599. {
  67600. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  67601. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67602. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  67603. }
  67604. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  67605. {
  67606. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67607. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  67608. }
  67609. void GlyphArrangement::clear() throw()
  67610. {
  67611. for (int i = numGlyphs; --i >= 0;)
  67612. decGlyphRefCount (i);
  67613. numGlyphs = 0;
  67614. }
  67615. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  67616. {
  67617. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  67618. return glyphs [index];
  67619. }
  67620. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  67621. {
  67622. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  67623. memcpy (glyphs + numGlyphs, other.glyphs,
  67624. other.numGlyphs * sizeof (PositionedGlyph));
  67625. for (int i = other.numGlyphs; --i >= 0;)
  67626. incGlyphRefCount (numGlyphs++);
  67627. }
  67628. void GlyphArrangement::removeLast() throw()
  67629. {
  67630. if (numGlyphs > 0)
  67631. decGlyphRefCount (--numGlyphs);
  67632. }
  67633. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  67634. {
  67635. jassert (startIndex >= 0);
  67636. if (startIndex < 0)
  67637. startIndex = 0;
  67638. if (num < 0 || startIndex + num >= numGlyphs)
  67639. {
  67640. while (numGlyphs > startIndex)
  67641. removeLast();
  67642. }
  67643. else if (num > 0)
  67644. {
  67645. int i;
  67646. for (i = startIndex; i < startIndex + num; ++i)
  67647. decGlyphRefCount (i);
  67648. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  67649. {
  67650. glyphs [startIndex] = glyphs [startIndex + num];
  67651. ++startIndex;
  67652. }
  67653. numGlyphs -= num;
  67654. }
  67655. }
  67656. void GlyphArrangement::addLineOfText (const Font& font,
  67657. const String& text,
  67658. const float xOffset,
  67659. const float yOffset) throw()
  67660. {
  67661. addCurtailedLineOfText (font, text,
  67662. xOffset, yOffset,
  67663. 1.0e10f, false);
  67664. }
  67665. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  67666. const String& text,
  67667. float xOffset,
  67668. const float yOffset,
  67669. const float maxWidthPixels,
  67670. const bool useEllipsis) throw()
  67671. {
  67672. const int textLen = text.length();
  67673. if (textLen > 0)
  67674. {
  67675. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  67676. Typeface* const typeface = font.getTypeface();
  67677. const float fontHeight = font.getHeight();
  67678. const float ascent = font.getAscent();
  67679. const float fontHorizontalScale = font.getHorizontalScale();
  67680. const float heightTimesScale = fontHorizontalScale * fontHeight;
  67681. const float kerningFactor = font.getExtraKerningFactor();
  67682. const float startX = xOffset;
  67683. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  67684. for (int i = 0; i < textLen; ++i)
  67685. {
  67686. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  67687. if (glyph != 0)
  67688. {
  67689. jassert (numAllocated > numGlyphs);
  67690. ensureNumGlyphsAllocated (numGlyphs);
  67691. PositionedGlyph& pg = glyphs [numGlyphs];
  67692. pg.glyphInfo = glyph;
  67693. pg.x = xOffset;
  67694. pg.y = yOffset;
  67695. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  67696. pg.fontHeight = fontHeight;
  67697. pg.fontAscent = ascent;
  67698. pg.fontHorizontalScale = fontHorizontalScale;
  67699. pg.isUnderlined = font.isUnderlined();
  67700. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  67701. if (xOffset - startX > maxWidthPixels + 1.0f)
  67702. {
  67703. // curtail the string if it's too wide..
  67704. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  67705. appendEllipsis (font, startX + maxWidthPixels);
  67706. break;
  67707. }
  67708. else
  67709. {
  67710. if (glyph->getTypeface() != 0)
  67711. glyph->getTypeface()->incReferenceCount();
  67712. ++numGlyphs;
  67713. }
  67714. }
  67715. }
  67716. }
  67717. }
  67718. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  67719. {
  67720. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  67721. if (dotGlyph != 0)
  67722. {
  67723. if (numGlyphs > 0)
  67724. {
  67725. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  67726. const float fontHeight = glyph.fontHeight;
  67727. const float fontHorizontalScale = glyph.fontHorizontalScale;
  67728. const float fontAscent = glyph.fontAscent;
  67729. const float dx = fontHeight * fontHorizontalScale
  67730. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  67731. float xOffset = 0.0f, yOffset = 0.0f;
  67732. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  67733. {
  67734. removeLast();
  67735. jassert (numAllocated > numGlyphs);
  67736. PositionedGlyph& pg = glyphs [numGlyphs];
  67737. xOffset = pg.x;
  67738. yOffset = pg.y;
  67739. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  67740. break;
  67741. }
  67742. for (int i = 3; --i >= 0;)
  67743. {
  67744. jassert (numAllocated > numGlyphs);
  67745. ensureNumGlyphsAllocated (numGlyphs);
  67746. PositionedGlyph& pg = glyphs [numGlyphs];
  67747. pg.glyphInfo = dotGlyph;
  67748. pg.x = xOffset;
  67749. pg.y = yOffset;
  67750. pg.w = dx;
  67751. pg.fontHeight = fontHeight;
  67752. pg.fontAscent = fontAscent;
  67753. pg.fontHorizontalScale = fontHorizontalScale;
  67754. pg.isUnderlined = font.isUnderlined();
  67755. xOffset += dx;
  67756. if (dotGlyph->getTypeface() != 0)
  67757. dotGlyph->getTypeface()->incReferenceCount();
  67758. ++numGlyphs;
  67759. }
  67760. }
  67761. }
  67762. }
  67763. void GlyphArrangement::addJustifiedText (const Font& font,
  67764. const String& text,
  67765. float x, float y,
  67766. const float maxLineWidth,
  67767. const Justification& horizontalLayout) throw()
  67768. {
  67769. int lineStartIndex = numGlyphs;
  67770. addLineOfText (font, text, x, y);
  67771. const float originalY = y;
  67772. while (lineStartIndex < numGlyphs)
  67773. {
  67774. int i = lineStartIndex;
  67775. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  67776. ++i;
  67777. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  67778. int lastWordBreakIndex = -1;
  67779. while (i < numGlyphs)
  67780. {
  67781. PositionedGlyph& pg = glyphs[i];
  67782. const juce_wchar c = pg.getCharacter();
  67783. if (c == T('\r') || c == T('\n'))
  67784. {
  67785. ++i;
  67786. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  67787. ++i;
  67788. break;
  67789. }
  67790. else if (pg.isWhitespace())
  67791. {
  67792. lastWordBreakIndex = i + 1;
  67793. }
  67794. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  67795. {
  67796. if (lastWordBreakIndex >= 0)
  67797. i = lastWordBreakIndex;
  67798. break;
  67799. }
  67800. ++i;
  67801. }
  67802. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  67803. float currentLineEndX = currentLineStartX;
  67804. for (int j = i; --j >= lineStartIndex;)
  67805. {
  67806. if (! glyphs[j].isWhitespace())
  67807. {
  67808. currentLineEndX = glyphs[j].getRight();
  67809. break;
  67810. }
  67811. }
  67812. float deltaX = 0.0f;
  67813. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  67814. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  67815. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  67816. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  67817. else if (horizontalLayout.testFlags (Justification::right))
  67818. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  67819. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  67820. x + deltaX - currentLineStartX, y - originalY);
  67821. lineStartIndex = i;
  67822. y += font.getHeight();
  67823. }
  67824. }
  67825. void GlyphArrangement::addFittedText (const Font& f,
  67826. const String& text,
  67827. float x, float y,
  67828. float width, float height,
  67829. const Justification& layout,
  67830. int maximumLines,
  67831. const float minimumHorizontalScale) throw()
  67832. {
  67833. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  67834. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  67835. if (text.containsAnyOf (T("\r\n")))
  67836. {
  67837. GlyphArrangement ga;
  67838. ga.addJustifiedText (f, text, x, y, width, layout);
  67839. float l, t, r, b;
  67840. ga.getBoundingBox (0, -1, l, t, r, b, false);
  67841. float dy = y - t;
  67842. if (layout.testFlags (Justification::verticallyCentred))
  67843. dy += (height - (b - t)) * 0.5f;
  67844. else if (layout.testFlags (Justification::bottom))
  67845. dy += height - (b - t);
  67846. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  67847. addGlyphArrangement (ga);
  67848. return;
  67849. }
  67850. int startIndex = numGlyphs;
  67851. addLineOfText (f, text.trim(), x, y);
  67852. if (numGlyphs > startIndex)
  67853. {
  67854. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67855. if (lineWidth <= 0)
  67856. return;
  67857. if (lineWidth * minimumHorizontalScale < width)
  67858. {
  67859. if (lineWidth > width)
  67860. {
  67861. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  67862. width / lineWidth);
  67863. }
  67864. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67865. x, y, width, height, layout);
  67866. }
  67867. else if (maximumLines <= 1)
  67868. {
  67869. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  67870. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  67871. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  67872. removeLast();
  67873. appendEllipsis (f, x + width);
  67874. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67875. x, y, width, height, layout);
  67876. }
  67877. else
  67878. {
  67879. Font font (f);
  67880. String txt (text.trim());
  67881. const int length = txt.length();
  67882. int numLines = 1;
  67883. const int originalStartIndex = startIndex;
  67884. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  67885. maximumLines = 1;
  67886. maximumLines = jmin (maximumLines, length);
  67887. while (numLines < maximumLines)
  67888. {
  67889. ++numLines;
  67890. const float newFontHeight = height / (float)numLines;
  67891. if (newFontHeight < 8.0f)
  67892. break;
  67893. if (newFontHeight < font.getHeight())
  67894. {
  67895. font.setHeight (newFontHeight);
  67896. while (numGlyphs > startIndex)
  67897. removeLast();
  67898. addLineOfText (font, txt, x, y);
  67899. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67900. }
  67901. if (numLines > lineWidth / width)
  67902. break;
  67903. }
  67904. if (numLines < 1)
  67905. numLines = 1;
  67906. float lineY = y;
  67907. float widthPerLine = lineWidth / numLines;
  67908. int lastLineStartIndex = 0;
  67909. for (int line = 0; line < numLines; ++line)
  67910. {
  67911. int i = startIndex;
  67912. lastLineStartIndex = i;
  67913. float lineStartX = glyphs[startIndex].getLeft();
  67914. while (i < numGlyphs)
  67915. {
  67916. lineWidth = (glyphs[i].getRight() - lineStartX);
  67917. if (lineWidth > widthPerLine)
  67918. {
  67919. // got to a point where the line's too long, so skip forward to find a
  67920. // good place to break it..
  67921. const int searchStartIndex = i;
  67922. while (i < numGlyphs)
  67923. {
  67924. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  67925. {
  67926. if (glyphs[i].isWhitespace()
  67927. || glyphs[i].getCharacter() == T('-'))
  67928. {
  67929. ++i;
  67930. break;
  67931. }
  67932. }
  67933. else
  67934. {
  67935. // can't find a suitable break, so try looking backwards..
  67936. i = searchStartIndex;
  67937. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  67938. {
  67939. if (glyphs[i - back].isWhitespace()
  67940. || glyphs[i - back].getCharacter() == T('-'))
  67941. {
  67942. i -= back - 1;
  67943. break;
  67944. }
  67945. }
  67946. break;
  67947. }
  67948. ++i;
  67949. }
  67950. break;
  67951. }
  67952. ++i;
  67953. }
  67954. int wsStart = i;
  67955. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  67956. --wsStart;
  67957. int wsEnd = i;
  67958. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  67959. ++wsEnd;
  67960. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  67961. i = jmax (wsStart, startIndex + 1);
  67962. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  67963. if (lineWidth > width)
  67964. {
  67965. stretchRangeOfGlyphs (startIndex, i - startIndex,
  67966. width / lineWidth);
  67967. }
  67968. justifyGlyphs (startIndex, i - startIndex,
  67969. x, lineY, width, font.getHeight(),
  67970. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67971. startIndex = i;
  67972. lineY += font.getHeight();
  67973. if (startIndex >= numGlyphs)
  67974. break;
  67975. }
  67976. if (startIndex < numGlyphs)
  67977. {
  67978. while (numGlyphs > startIndex)
  67979. removeLast();
  67980. if (startIndex - originalStartIndex > 4)
  67981. {
  67982. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  67983. appendEllipsis (font, lineStartX + width);
  67984. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  67985. if (lineWidth > width)
  67986. {
  67987. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67988. width / lineWidth);
  67989. }
  67990. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67991. x, lineY - font.getHeight(), width, font.getHeight(),
  67992. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67993. }
  67994. startIndex = numGlyphs;
  67995. }
  67996. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  67997. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  67998. }
  67999. }
  68000. }
  68001. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  68002. const float dx, const float dy) throw()
  68003. {
  68004. jassert (startIndex >= 0);
  68005. if (dx != 0.0f || dy != 0.0f)
  68006. {
  68007. if (num < 0 || startIndex + num > numGlyphs)
  68008. num = numGlyphs - startIndex;
  68009. while (--num >= 0)
  68010. {
  68011. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  68012. glyphs [startIndex++].moveBy (dx, dy);
  68013. }
  68014. }
  68015. }
  68016. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  68017. const float horizontalScaleFactor) throw()
  68018. {
  68019. jassert (startIndex >= 0);
  68020. if (num < 0 || startIndex + num > numGlyphs)
  68021. num = numGlyphs - startIndex;
  68022. if (num > 0)
  68023. {
  68024. const float xAnchor = glyphs[startIndex].getLeft();
  68025. while (--num >= 0)
  68026. {
  68027. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  68028. PositionedGlyph& pg = glyphs[startIndex++];
  68029. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  68030. pg.fontHorizontalScale *= horizontalScaleFactor;
  68031. pg.w *= horizontalScaleFactor;
  68032. }
  68033. }
  68034. }
  68035. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  68036. float& left,
  68037. float& top,
  68038. float& right,
  68039. float& bottom,
  68040. const bool includeWhitespace) const throw()
  68041. {
  68042. jassert (startIndex >= 0);
  68043. if (num < 0 || startIndex + num > numGlyphs)
  68044. num = numGlyphs - startIndex;
  68045. left = 0.0f;
  68046. top = 0.0f;
  68047. right = 0.0f;
  68048. bottom = 0.0f;
  68049. bool isFirst = true;
  68050. while (--num >= 0)
  68051. {
  68052. const PositionedGlyph& pg = glyphs [startIndex++];
  68053. if (includeWhitespace || ! pg.isWhitespace())
  68054. {
  68055. if (isFirst)
  68056. {
  68057. isFirst = false;
  68058. left = pg.getLeft();
  68059. top = pg.getTop();
  68060. right = pg.getRight();
  68061. bottom = pg.getBottom();
  68062. }
  68063. else
  68064. {
  68065. left = jmin (left, pg.getLeft());
  68066. top = jmin (top, pg.getTop());
  68067. right = jmax (right, pg.getRight());
  68068. bottom = jmax (bottom, pg.getBottom());
  68069. }
  68070. }
  68071. }
  68072. }
  68073. void GlyphArrangement::justifyGlyphs (const int startIndex,
  68074. const int num,
  68075. const float x, const float y,
  68076. const float width, const float height,
  68077. const Justification& justification) throw()
  68078. {
  68079. jassert (num >= 0 && startIndex >= 0);
  68080. if (numGlyphs > 0 && num > 0)
  68081. {
  68082. float left, top, right, bottom;
  68083. getBoundingBox (startIndex, num, left, top, right, bottom,
  68084. ! justification.testFlags (Justification::horizontallyJustified
  68085. | Justification::horizontallyCentred));
  68086. float deltaX = 0.0f;
  68087. if (justification.testFlags (Justification::horizontallyJustified))
  68088. deltaX = x - left;
  68089. else if (justification.testFlags (Justification::horizontallyCentred))
  68090. deltaX = x + (width - (right - left)) * 0.5f - left;
  68091. else if (justification.testFlags (Justification::right))
  68092. deltaX = (x + width) - right;
  68093. else
  68094. deltaX = x - left;
  68095. float deltaY = 0.0f;
  68096. if (justification.testFlags (Justification::top))
  68097. deltaY = y - top;
  68098. else if (justification.testFlags (Justification::bottom))
  68099. deltaY = (y + height) - bottom;
  68100. else
  68101. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  68102. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  68103. if (justification.testFlags (Justification::horizontallyJustified))
  68104. {
  68105. int lineStart = 0;
  68106. float baseY = glyphs [startIndex].getBaselineY();
  68107. int i;
  68108. for (i = 0; i < num; ++i)
  68109. {
  68110. const float glyphY = glyphs [startIndex + i].getBaselineY();
  68111. if (glyphY != baseY)
  68112. {
  68113. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  68114. lineStart = i;
  68115. baseY = glyphY;
  68116. }
  68117. }
  68118. if (i > lineStart)
  68119. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  68120. }
  68121. }
  68122. }
  68123. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  68124. {
  68125. if (start + num < numGlyphs
  68126. && glyphs [start + num - 1].getCharacter() != T('\r')
  68127. && glyphs [start + num - 1].getCharacter() != T('\n'))
  68128. {
  68129. int numSpaces = 0;
  68130. int spacesAtEnd = 0;
  68131. for (int i = 0; i < num; ++i)
  68132. {
  68133. if (glyphs [start + i].isWhitespace())
  68134. {
  68135. ++spacesAtEnd;
  68136. ++numSpaces;
  68137. }
  68138. else
  68139. {
  68140. spacesAtEnd = 0;
  68141. }
  68142. }
  68143. numSpaces -= spacesAtEnd;
  68144. if (numSpaces > 0)
  68145. {
  68146. const float startX = glyphs [start].getLeft();
  68147. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  68148. const float extraPaddingBetweenWords
  68149. = (targetWidth - (endX - startX)) / (float) numSpaces;
  68150. float deltaX = 0.0f;
  68151. for (int i = 0; i < num; ++i)
  68152. {
  68153. glyphs [start + i].moveBy (deltaX, 0.0);
  68154. if (glyphs [start + i].isWhitespace())
  68155. deltaX += extraPaddingBetweenWords;
  68156. }
  68157. }
  68158. }
  68159. }
  68160. void GlyphArrangement::draw (const Graphics& g) const throw()
  68161. {
  68162. for (int i = 0; i < numGlyphs; ++i)
  68163. {
  68164. glyphs[i].draw (g);
  68165. if (glyphs[i].isUnderlined)
  68166. {
  68167. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  68168. juce_wchar nextChar = 0;
  68169. if (i < numGlyphs - 1
  68170. && glyphs[i + 1].y == glyphs[i].y)
  68171. {
  68172. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  68173. }
  68174. g.fillRect (glyphs[i].x,
  68175. glyphs[i].y + lineThickness * 2.0f,
  68176. glyphs[i].fontHeight
  68177. * glyphs[i].fontHorizontalScale
  68178. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  68179. lineThickness);
  68180. }
  68181. }
  68182. }
  68183. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  68184. {
  68185. for (int i = 0; i < numGlyphs; ++i)
  68186. {
  68187. glyphs[i].draw (g, transform);
  68188. if (glyphs[i].isUnderlined)
  68189. {
  68190. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  68191. juce_wchar nextChar = 0;
  68192. if (i < numGlyphs - 1
  68193. && glyphs[i + 1].y == glyphs[i].y)
  68194. {
  68195. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  68196. }
  68197. Path p;
  68198. p.addLineSegment (glyphs[i].x,
  68199. glyphs[i].y + lineThickness * 2.5f,
  68200. glyphs[i].x + glyphs[i].fontHeight
  68201. * glyphs[i].fontHorizontalScale
  68202. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  68203. glyphs[i].y + lineThickness * 2.5f,
  68204. lineThickness);
  68205. g.fillPath (p, transform);
  68206. }
  68207. }
  68208. }
  68209. void GlyphArrangement::createPath (Path& path) const throw()
  68210. {
  68211. for (int i = 0; i < numGlyphs; ++i)
  68212. glyphs[i].createPath (path);
  68213. }
  68214. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  68215. {
  68216. for (int i = 0; i < numGlyphs; ++i)
  68217. if (glyphs[i].hitTest (x, y))
  68218. return i;
  68219. return -1;
  68220. }
  68221. END_JUCE_NAMESPACE
  68222. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  68223. /********* Start of inlined file: juce_TextLayout.cpp *********/
  68224. BEGIN_JUCE_NAMESPACE
  68225. class TextLayoutToken
  68226. {
  68227. public:
  68228. String text;
  68229. Font font;
  68230. int x, y, w, h;
  68231. int line, lineHeight;
  68232. bool isWhitespace, isNewLine;
  68233. TextLayoutToken (const String& t,
  68234. const Font& f,
  68235. const bool isWhitespace_) throw()
  68236. : text (t),
  68237. font (f),
  68238. x(0),
  68239. y(0),
  68240. isWhitespace (isWhitespace_)
  68241. {
  68242. w = font.getStringWidth (t);
  68243. h = roundFloatToInt (f.getHeight());
  68244. isNewLine = t.containsAnyOf (T("\r\n"));
  68245. }
  68246. TextLayoutToken (const TextLayoutToken& other) throw()
  68247. : text (other.text),
  68248. font (other.font),
  68249. x (other.x),
  68250. y (other.y),
  68251. w (other.w),
  68252. h (other.h),
  68253. line (other.line),
  68254. lineHeight (other.lineHeight),
  68255. isWhitespace (other.isWhitespace),
  68256. isNewLine (other.isNewLine)
  68257. {
  68258. }
  68259. ~TextLayoutToken() throw()
  68260. {
  68261. }
  68262. void draw (Graphics& g,
  68263. const int xOffset,
  68264. const int yOffset) throw()
  68265. {
  68266. if (! isWhitespace)
  68267. {
  68268. g.setFont (font);
  68269. g.drawSingleLineText (text.trimEnd(),
  68270. xOffset + x,
  68271. yOffset + y + (lineHeight - h)
  68272. + roundFloatToInt (font.getAscent()));
  68273. }
  68274. }
  68275. juce_UseDebuggingNewOperator
  68276. };
  68277. TextLayout::TextLayout() throw()
  68278. : tokens (64),
  68279. totalLines (0)
  68280. {
  68281. }
  68282. TextLayout::TextLayout (const String& text,
  68283. const Font& font) throw()
  68284. : tokens (64),
  68285. totalLines (0)
  68286. {
  68287. appendText (text, font);
  68288. }
  68289. TextLayout::TextLayout (const TextLayout& other) throw()
  68290. : tokens (64),
  68291. totalLines (0)
  68292. {
  68293. *this = other;
  68294. }
  68295. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  68296. {
  68297. if (this != &other)
  68298. {
  68299. clear();
  68300. totalLines = other.totalLines;
  68301. for (int i = 0; i < other.tokens.size(); ++i)
  68302. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  68303. }
  68304. return *this;
  68305. }
  68306. TextLayout::~TextLayout() throw()
  68307. {
  68308. clear();
  68309. }
  68310. void TextLayout::clear() throw()
  68311. {
  68312. for (int i = tokens.size(); --i >= 0;)
  68313. {
  68314. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68315. delete t;
  68316. }
  68317. tokens.clear();
  68318. totalLines = 0;
  68319. }
  68320. void TextLayout::appendText (const String& text,
  68321. const Font& font) throw()
  68322. {
  68323. const tchar* t = text;
  68324. String currentString;
  68325. int lastCharType = 0;
  68326. for (;;)
  68327. {
  68328. const tchar c = *t++;
  68329. if (c == 0)
  68330. break;
  68331. int charType;
  68332. if (c == T('\r') || c == T('\n'))
  68333. {
  68334. charType = 0;
  68335. }
  68336. else if (CharacterFunctions::isWhitespace (c))
  68337. {
  68338. charType = 2;
  68339. }
  68340. else
  68341. {
  68342. charType = 1;
  68343. }
  68344. if (charType == 0 || charType != lastCharType)
  68345. {
  68346. if (currentString.isNotEmpty())
  68347. {
  68348. tokens.add (new TextLayoutToken (currentString, font,
  68349. lastCharType == 2 || lastCharType == 0));
  68350. }
  68351. currentString = String::charToString (c);
  68352. if (c == T('\r') && *t == T('\n'))
  68353. currentString += *t++;
  68354. }
  68355. else
  68356. {
  68357. currentString += c;
  68358. }
  68359. lastCharType = charType;
  68360. }
  68361. if (currentString.isNotEmpty())
  68362. tokens.add (new TextLayoutToken (currentString,
  68363. font,
  68364. lastCharType == 2));
  68365. }
  68366. void TextLayout::setText (const String& text, const Font& font) throw()
  68367. {
  68368. clear();
  68369. appendText (text, font);
  68370. }
  68371. void TextLayout::layout (int maxWidth,
  68372. const Justification& justification,
  68373. const bool attemptToBalanceLineLengths) throw()
  68374. {
  68375. if (attemptToBalanceLineLengths)
  68376. {
  68377. const int originalW = maxWidth;
  68378. int bestWidth = maxWidth;
  68379. float bestLineProportion = 0.0f;
  68380. while (maxWidth > originalW / 2)
  68381. {
  68382. layout (maxWidth, justification, false);
  68383. if (getNumLines() <= 1)
  68384. return;
  68385. const int lastLineW = getLineWidth (getNumLines() - 1);
  68386. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  68387. const float prop = lastLineW / (float) lastButOneLineW;
  68388. if (prop > 0.9f)
  68389. return;
  68390. if (prop > bestLineProportion)
  68391. {
  68392. bestLineProportion = prop;
  68393. bestWidth = maxWidth;
  68394. }
  68395. maxWidth -= 10;
  68396. }
  68397. layout (bestWidth, justification, false);
  68398. }
  68399. else
  68400. {
  68401. int x = 0;
  68402. int y = 0;
  68403. int h = 0;
  68404. totalLines = 0;
  68405. int i;
  68406. for (i = 0; i < tokens.size(); ++i)
  68407. {
  68408. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68409. t->x = x;
  68410. t->y = y;
  68411. t->line = totalLines;
  68412. x += t->w;
  68413. h = jmax (h, t->h);
  68414. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  68415. if (nextTok == 0)
  68416. break;
  68417. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  68418. {
  68419. // finished a line, so go back and update the heights of the things on it
  68420. for (int j = i; j >= 0; --j)
  68421. {
  68422. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  68423. if (tok->line == totalLines)
  68424. tok->lineHeight = h;
  68425. else
  68426. break;
  68427. }
  68428. x = 0;
  68429. y += h;
  68430. h = 0;
  68431. ++totalLines;
  68432. }
  68433. }
  68434. // finished a line, so go back and update the heights of the things on it
  68435. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  68436. {
  68437. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  68438. if (t->line == totalLines)
  68439. t->lineHeight = h;
  68440. else
  68441. break;
  68442. }
  68443. ++totalLines;
  68444. if (! justification.testFlags (Justification::left))
  68445. {
  68446. int totalW = getWidth();
  68447. for (i = totalLines; --i >= 0;)
  68448. {
  68449. const int lineW = getLineWidth (i);
  68450. int dx = 0;
  68451. if (justification.testFlags (Justification::horizontallyCentred))
  68452. dx = (totalW - lineW) / 2;
  68453. else if (justification.testFlags (Justification::right))
  68454. dx = totalW - lineW;
  68455. for (int j = tokens.size(); --j >= 0;)
  68456. {
  68457. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  68458. if (t->line == i)
  68459. t->x += dx;
  68460. }
  68461. }
  68462. }
  68463. }
  68464. }
  68465. int TextLayout::getLineWidth (const int lineNumber) const throw()
  68466. {
  68467. int maxW = 0;
  68468. for (int i = tokens.size(); --i >= 0;)
  68469. {
  68470. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68471. if (t->line == lineNumber && ! t->isWhitespace)
  68472. maxW = jmax (maxW, t->x + t->w);
  68473. }
  68474. return maxW;
  68475. }
  68476. int TextLayout::getWidth() const throw()
  68477. {
  68478. int maxW = 0;
  68479. for (int i = tokens.size(); --i >= 0;)
  68480. {
  68481. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68482. if (! t->isWhitespace)
  68483. maxW = jmax (maxW, t->x + t->w);
  68484. }
  68485. return maxW;
  68486. }
  68487. int TextLayout::getHeight() const throw()
  68488. {
  68489. int maxH = 0;
  68490. for (int i = tokens.size(); --i >= 0;)
  68491. {
  68492. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68493. if (! t->isWhitespace)
  68494. maxH = jmax (maxH, t->y + t->h);
  68495. }
  68496. return maxH;
  68497. }
  68498. void TextLayout::draw (Graphics& g,
  68499. const int xOffset,
  68500. const int yOffset) const throw()
  68501. {
  68502. for (int i = tokens.size(); --i >= 0;)
  68503. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  68504. }
  68505. void TextLayout::drawWithin (Graphics& g,
  68506. int x, int y, int w, int h,
  68507. const Justification& justification) const throw()
  68508. {
  68509. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  68510. x, y, w, h);
  68511. draw (g, x, y);
  68512. }
  68513. END_JUCE_NAMESPACE
  68514. /********* End of inlined file: juce_TextLayout.cpp *********/
  68515. /********* Start of inlined file: juce_Typeface.cpp *********/
  68516. BEGIN_JUCE_NAMESPACE
  68517. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  68518. const Path& shape,
  68519. const float horizontalSeparation,
  68520. Typeface* const typeface_) throw()
  68521. : character (character_),
  68522. path (shape),
  68523. width (horizontalSeparation),
  68524. typeface (typeface_)
  68525. {
  68526. }
  68527. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  68528. {
  68529. }
  68530. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  68531. {
  68532. if (subsequentCharacter != 0)
  68533. {
  68534. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  68535. const int numPairs = getNumKerningPairs();
  68536. for (int i = 0; i < numPairs; ++i)
  68537. if (pairs [i].character2 == subsequentCharacter)
  68538. return width + pairs [i].kerningAmount;
  68539. }
  68540. return width;
  68541. }
  68542. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  68543. const float extraKerningAmount) throw()
  68544. {
  68545. const int numPairs = getNumKerningPairs();
  68546. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  68547. KerningPair& p = getKerningPair (numPairs);
  68548. p.character2 = subsequentCharacter;
  68549. p.kerningAmount = extraKerningAmount;
  68550. }
  68551. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  68552. {
  68553. return ((KerningPair*) kerningPairs.getData()) [index];
  68554. }
  68555. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  68556. {
  68557. return kerningPairs.getSize() / sizeof (KerningPair);
  68558. }
  68559. const tchar* Typeface::defaultTypefaceNameSans = T("<Sans-Serif>");
  68560. const tchar* Typeface::defaultTypefaceNameSerif = T("<Serif>");
  68561. const tchar* Typeface::defaultTypefaceNameMono = T("<Monospaced>");
  68562. Typeface::Typeface() throw()
  68563. : hash (0),
  68564. isFullyPopulated (false)
  68565. {
  68566. zeromem (lookupTable, sizeof (lookupTable));
  68567. }
  68568. Typeface::Typeface (const Typeface& other)
  68569. : typefaceName (other.typefaceName),
  68570. ascent (other.ascent),
  68571. bold (other.bold),
  68572. italic (other.italic),
  68573. isFullyPopulated (other.isFullyPopulated),
  68574. defaultCharacter (other.defaultCharacter)
  68575. {
  68576. zeromem (lookupTable, sizeof (lookupTable));
  68577. for (int i = 0; i < other.glyphs.size(); ++i)
  68578. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68579. updateHashCode();
  68580. }
  68581. Typeface::Typeface (const String& faceName,
  68582. const bool bold,
  68583. const bool italic)
  68584. : isFullyPopulated (false)
  68585. {
  68586. zeromem (lookupTable, sizeof (lookupTable));
  68587. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  68588. updateHashCode();
  68589. }
  68590. Typeface::~Typeface()
  68591. {
  68592. clear();
  68593. }
  68594. const Typeface& Typeface::operator= (const Typeface& other) throw()
  68595. {
  68596. if (this != &other)
  68597. {
  68598. clear();
  68599. typefaceName = other.typefaceName;
  68600. ascent = other.ascent;
  68601. bold = other.bold;
  68602. italic = other.italic;
  68603. isFullyPopulated = other.isFullyPopulated;
  68604. defaultCharacter = other.defaultCharacter;
  68605. for (int i = 0; i < other.glyphs.size(); ++i)
  68606. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68607. updateHashCode();
  68608. }
  68609. return *this;
  68610. }
  68611. void Typeface::updateHashCode() throw()
  68612. {
  68613. hash = typefaceName.hashCode();
  68614. if (bold)
  68615. hash ^= 0xffff;
  68616. if (italic)
  68617. hash ^= 0xffff0000;
  68618. }
  68619. void Typeface::clear() throw()
  68620. {
  68621. zeromem (lookupTable, sizeof (lookupTable));
  68622. typefaceName = String::empty;
  68623. bold = false;
  68624. italic = false;
  68625. for (int i = glyphs.size(); --i >= 0;)
  68626. {
  68627. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  68628. delete g;
  68629. }
  68630. glyphs.clear();
  68631. updateHashCode();
  68632. }
  68633. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  68634. {
  68635. zeromem (lookupTable, sizeof (lookupTable));
  68636. isFullyPopulated = true;
  68637. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  68638. BufferedInputStream in (&gzin, 32768, false);
  68639. typefaceName = in.readString();
  68640. bold = in.readBool();
  68641. italic = in.readBool();
  68642. ascent = in.readFloat();
  68643. defaultCharacter = (juce_wchar) in.readShort();
  68644. int i, numChars = in.readInt();
  68645. for (i = 0; i < numChars; ++i)
  68646. {
  68647. const juce_wchar c = (juce_wchar) in.readShort();
  68648. const float width = in.readFloat();
  68649. Path p;
  68650. p.loadPathFromStream (in);
  68651. addGlyph (c, p, width);
  68652. }
  68653. const int numKerningPairs = in.readInt();
  68654. for (i = 0; i < numKerningPairs; ++i)
  68655. {
  68656. const juce_wchar char1 = (juce_wchar) in.readShort();
  68657. const juce_wchar char2 = (juce_wchar) in.readShort();
  68658. addKerningPair (char1, char2, in.readFloat());
  68659. }
  68660. updateHashCode();
  68661. }
  68662. void Typeface::serialise (OutputStream& outputStream)
  68663. {
  68664. GZIPCompressorOutputStream out (&outputStream);
  68665. out.writeString (typefaceName);
  68666. out.writeBool (bold);
  68667. out.writeBool (italic);
  68668. out.writeFloat (ascent);
  68669. out.writeShort ((short) (unsigned short) defaultCharacter);
  68670. out.writeInt (glyphs.size());
  68671. int i, numKerningPairs = 0;
  68672. for (i = 0; i < glyphs.size(); ++i)
  68673. {
  68674. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68675. out.writeShort ((short) (unsigned short) g.character);
  68676. out.writeFloat (g.width);
  68677. g.path.writePathToStream (out);
  68678. numKerningPairs += g.getNumKerningPairs();
  68679. }
  68680. out.writeInt (numKerningPairs);
  68681. for (i = 0; i < glyphs.size(); ++i)
  68682. {
  68683. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68684. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  68685. {
  68686. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  68687. out.writeShort ((short) (unsigned short) g.character);
  68688. out.writeShort ((short) (unsigned short) p.character2);
  68689. out.writeFloat (p.kerningAmount);
  68690. }
  68691. }
  68692. }
  68693. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  68694. {
  68695. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  68696. if (g != 0)
  68697. return &(g->path);
  68698. else
  68699. return 0;
  68700. }
  68701. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  68702. {
  68703. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  68704. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  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. return g;
  68710. }
  68711. if ((! isFullyPopulated)
  68712. && findAndAddSystemGlyph (character))
  68713. {
  68714. for (int i = 0; i < glyphs.size(); ++i)
  68715. {
  68716. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68717. if (g->character == character)
  68718. return g;
  68719. }
  68720. }
  68721. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  68722. {
  68723. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  68724. if (spaceGlyph != 0)
  68725. {
  68726. // Add a copy of the empty glyph, mapped onto this character
  68727. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  68728. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68729. }
  68730. return spaceGlyph;
  68731. }
  68732. else if (character != defaultCharacter)
  68733. {
  68734. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  68735. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  68736. if (fallbackTypeface != 0 && fallbackTypeface != this)
  68737. return fallbackTypeface->getGlyph (character);
  68738. return getGlyph (defaultCharacter);
  68739. }
  68740. return 0;
  68741. }
  68742. void Typeface::addGlyph (const juce_wchar character,
  68743. const Path& path,
  68744. const float horizontalSpacing) throw()
  68745. {
  68746. #ifdef JUCE_DEBUG
  68747. for (int i = 0; i < glyphs.size(); ++i)
  68748. {
  68749. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68750. if (g->character == character)
  68751. jassertfalse;
  68752. }
  68753. #endif
  68754. if (((unsigned int) character) < 128)
  68755. lookupTable [character] = (short) glyphs.size();
  68756. glyphs.add (new TypefaceGlyphInfo (character,
  68757. path,
  68758. horizontalSpacing,
  68759. this));
  68760. }
  68761. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  68762. {
  68763. if (glyphInfoToCopy != 0)
  68764. {
  68765. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  68766. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  68767. TypefaceGlyphInfo* const newOne
  68768. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  68769. glyphInfoToCopy->path,
  68770. glyphInfoToCopy->width,
  68771. this);
  68772. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  68773. glyphs.add (newOne);
  68774. }
  68775. }
  68776. void Typeface::addKerningPair (const juce_wchar char1,
  68777. const juce_wchar char2,
  68778. const float extraAmount) throw()
  68779. {
  68780. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  68781. if (g != 0)
  68782. g->addKerningPair (char2, extraAmount);
  68783. }
  68784. void Typeface::setName (const String& name) throw()
  68785. {
  68786. typefaceName = name;
  68787. updateHashCode();
  68788. }
  68789. void Typeface::setAscent (const float newAscent) throw()
  68790. {
  68791. ascent = newAscent;
  68792. }
  68793. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  68794. {
  68795. defaultCharacter = newDefaultCharacter;
  68796. }
  68797. void Typeface::setBold (const bool shouldBeBold) throw()
  68798. {
  68799. bold = shouldBeBold;
  68800. updateHashCode();
  68801. }
  68802. void Typeface::setItalic (const bool shouldBeItalic) throw()
  68803. {
  68804. italic = shouldBeItalic;
  68805. updateHashCode();
  68806. }
  68807. class TypefaceCache;
  68808. static TypefaceCache* typefaceCacheInstance = 0;
  68809. void clearUpDefaultFontNames() throw(); // in juce_LookAndFeel.cpp
  68810. class TypefaceCache : private DeletedAtShutdown
  68811. {
  68812. private:
  68813. struct CachedFace
  68814. {
  68815. CachedFace() throw()
  68816. : lastUsageCount (0),
  68817. flags (0)
  68818. {
  68819. }
  68820. String typefaceName;
  68821. int lastUsageCount;
  68822. int flags;
  68823. Typeface::Ptr typeFace;
  68824. };
  68825. int counter;
  68826. OwnedArray <CachedFace> faces;
  68827. TypefaceCache (const TypefaceCache&);
  68828. const TypefaceCache& operator= (const TypefaceCache&);
  68829. public:
  68830. TypefaceCache (int numToCache = 10)
  68831. : counter (1),
  68832. faces (2)
  68833. {
  68834. while (--numToCache >= 0)
  68835. {
  68836. CachedFace* const face = new CachedFace();
  68837. face->typeFace = new Typeface();
  68838. faces.add (face);
  68839. }
  68840. }
  68841. ~TypefaceCache()
  68842. {
  68843. faces.clear();
  68844. jassert (typefaceCacheInstance == this);
  68845. typefaceCacheInstance = 0;
  68846. clearUpDefaultFontNames();
  68847. }
  68848. static TypefaceCache* getInstance() throw()
  68849. {
  68850. if (typefaceCacheInstance == 0)
  68851. typefaceCacheInstance = new TypefaceCache();
  68852. return typefaceCacheInstance;
  68853. }
  68854. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  68855. {
  68856. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  68857. int i;
  68858. for (i = faces.size(); --i >= 0;)
  68859. {
  68860. CachedFace* const face = faces.getUnchecked(i);
  68861. if (face->flags == flags
  68862. && face->typefaceName == font.getTypefaceName())
  68863. {
  68864. face->lastUsageCount = ++counter;
  68865. return face->typeFace;
  68866. }
  68867. }
  68868. int replaceIndex = 0;
  68869. int bestLastUsageCount = INT_MAX;
  68870. for (i = faces.size(); --i >= 0;)
  68871. {
  68872. const int lu = faces.getUnchecked(i)->lastUsageCount;
  68873. if (bestLastUsageCount > lu)
  68874. {
  68875. bestLastUsageCount = lu;
  68876. replaceIndex = i;
  68877. }
  68878. }
  68879. CachedFace* const face = faces.getUnchecked (replaceIndex);
  68880. face->typefaceName = font.getTypefaceName();
  68881. face->flags = flags;
  68882. face->lastUsageCount = ++counter;
  68883. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  68884. return face->typeFace;
  68885. }
  68886. };
  68887. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  68888. {
  68889. return TypefaceCache::getInstance()->findTypefaceFor (font);
  68890. }
  68891. END_JUCE_NAMESPACE
  68892. /********* End of inlined file: juce_Typeface.cpp *********/
  68893. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  68894. BEGIN_JUCE_NAMESPACE
  68895. AffineTransform::AffineTransform() throw()
  68896. : mat00 (1.0f),
  68897. mat01 (0),
  68898. mat02 (0),
  68899. mat10 (0),
  68900. mat11 (1.0f),
  68901. mat12 (0)
  68902. {
  68903. }
  68904. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  68905. : mat00 (other.mat00),
  68906. mat01 (other.mat01),
  68907. mat02 (other.mat02),
  68908. mat10 (other.mat10),
  68909. mat11 (other.mat11),
  68910. mat12 (other.mat12)
  68911. {
  68912. }
  68913. AffineTransform::AffineTransform (const float mat00_,
  68914. const float mat01_,
  68915. const float mat02_,
  68916. const float mat10_,
  68917. const float mat11_,
  68918. const float mat12_) throw()
  68919. : mat00 (mat00_),
  68920. mat01 (mat01_),
  68921. mat02 (mat02_),
  68922. mat10 (mat10_),
  68923. mat11 (mat11_),
  68924. mat12 (mat12_)
  68925. {
  68926. }
  68927. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  68928. {
  68929. mat00 = other.mat00;
  68930. mat01 = other.mat01;
  68931. mat02 = other.mat02;
  68932. mat10 = other.mat10;
  68933. mat11 = other.mat11;
  68934. mat12 = other.mat12;
  68935. return *this;
  68936. }
  68937. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  68938. {
  68939. return mat00 == other.mat00
  68940. && mat01 == other.mat01
  68941. && mat02 == other.mat02
  68942. && mat10 == other.mat10
  68943. && mat11 == other.mat11
  68944. && mat12 == other.mat12;
  68945. }
  68946. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  68947. {
  68948. return ! operator== (other);
  68949. }
  68950. bool AffineTransform::isIdentity() const throw()
  68951. {
  68952. return (mat01 == 0)
  68953. && (mat02 == 0)
  68954. && (mat10 == 0)
  68955. && (mat12 == 0)
  68956. && (mat00 == 1.0f)
  68957. && (mat11 == 1.0f);
  68958. }
  68959. const AffineTransform AffineTransform::identity;
  68960. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  68961. {
  68962. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  68963. other.mat00 * mat01 + other.mat01 * mat11,
  68964. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  68965. other.mat10 * mat00 + other.mat11 * mat10,
  68966. other.mat10 * mat01 + other.mat11 * mat11,
  68967. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  68968. }
  68969. const AffineTransform AffineTransform::followedBy (const float omat00,
  68970. const float omat01,
  68971. const float omat02,
  68972. const float omat10,
  68973. const float omat11,
  68974. const float omat12) const throw()
  68975. {
  68976. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  68977. omat00 * mat01 + omat01 * mat11,
  68978. omat00 * mat02 + omat01 * mat12 + omat02,
  68979. omat10 * mat00 + omat11 * mat10,
  68980. omat10 * mat01 + omat11 * mat11,
  68981. omat10 * mat02 + omat11 * mat12 + omat12);
  68982. }
  68983. const AffineTransform AffineTransform::translated (const float dx,
  68984. const float dy) const throw()
  68985. {
  68986. return followedBy (1.0f, 0, dx,
  68987. 0, 1.0f, dy);
  68988. }
  68989. const AffineTransform AffineTransform::translation (const float dx,
  68990. const float dy) throw()
  68991. {
  68992. return AffineTransform (1.0f, 0, dx,
  68993. 0, 1.0f, dy);
  68994. }
  68995. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  68996. {
  68997. const float cosRad = cosf (rad);
  68998. const float sinRad = sinf (rad);
  68999. return followedBy (cosRad, -sinRad, 0,
  69000. sinRad, cosRad, 0);
  69001. }
  69002. const AffineTransform AffineTransform::rotation (const float rad) throw()
  69003. {
  69004. const float cosRad = cosf (rad);
  69005. const float sinRad = sinf (rad);
  69006. return AffineTransform (cosRad, -sinRad, 0,
  69007. sinRad, cosRad, 0);
  69008. }
  69009. const AffineTransform AffineTransform::rotated (const float angle,
  69010. const float pivotX,
  69011. const float pivotY) const throw()
  69012. {
  69013. return translated (-pivotX, -pivotY)
  69014. .rotated (angle)
  69015. .translated (pivotX, pivotY);
  69016. }
  69017. const AffineTransform AffineTransform::rotation (const float angle,
  69018. const float pivotX,
  69019. const float pivotY) throw()
  69020. {
  69021. return translation (-pivotX, -pivotY)
  69022. .rotated (angle)
  69023. .translated (pivotX, pivotY);
  69024. }
  69025. const AffineTransform AffineTransform::scaled (const float factorX,
  69026. const float factorY) const throw()
  69027. {
  69028. return followedBy (factorX, 0, 0,
  69029. 0, factorY, 0);
  69030. }
  69031. const AffineTransform AffineTransform::scale (const float factorX,
  69032. const float factorY) throw()
  69033. {
  69034. return AffineTransform (factorX, 0, 0,
  69035. 0, factorY, 0);
  69036. }
  69037. const AffineTransform AffineTransform::sheared (const float shearX,
  69038. const float shearY) const throw()
  69039. {
  69040. return followedBy (1.0f, shearX, 0,
  69041. shearY, 1.0f, 0);
  69042. }
  69043. const AffineTransform AffineTransform::inverted() const throw()
  69044. {
  69045. double determinant = (mat00 * mat11 - mat10 * mat01);
  69046. if (determinant != 0.0)
  69047. {
  69048. determinant = 1.0 / determinant;
  69049. const float dst00 = (float) (mat11 * determinant);
  69050. const float dst10 = (float) (-mat10 * determinant);
  69051. const float dst01 = (float) (-mat01 * determinant);
  69052. const float dst11 = (float) (mat00 * determinant);
  69053. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  69054. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  69055. }
  69056. else
  69057. {
  69058. // singularity..
  69059. return *this;
  69060. }
  69061. }
  69062. bool AffineTransform::isSingularity() const throw()
  69063. {
  69064. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  69065. }
  69066. void AffineTransform::transformPoint (float& x,
  69067. float& y) const throw()
  69068. {
  69069. const float oldX = x;
  69070. x = mat00 * oldX + mat01 * y + mat02;
  69071. y = mat10 * oldX + mat11 * y + mat12;
  69072. }
  69073. void AffineTransform::transformPoint (double& x,
  69074. double& y) const throw()
  69075. {
  69076. const double oldX = x;
  69077. x = mat00 * oldX + mat01 * y + mat02;
  69078. y = mat10 * oldX + mat11 * y + mat12;
  69079. }
  69080. END_JUCE_NAMESPACE
  69081. /********* End of inlined file: juce_AffineTransform.cpp *********/
  69082. /********* Start of inlined file: juce_BorderSize.cpp *********/
  69083. BEGIN_JUCE_NAMESPACE
  69084. BorderSize::BorderSize() throw()
  69085. : top (0),
  69086. left (0),
  69087. bottom (0),
  69088. right (0)
  69089. {
  69090. }
  69091. BorderSize::BorderSize (const BorderSize& other) throw()
  69092. : top (other.top),
  69093. left (other.left),
  69094. bottom (other.bottom),
  69095. right (other.right)
  69096. {
  69097. }
  69098. BorderSize::BorderSize (const int topGap,
  69099. const int leftGap,
  69100. const int bottomGap,
  69101. const int rightGap) throw()
  69102. : top (topGap),
  69103. left (leftGap),
  69104. bottom (bottomGap),
  69105. right (rightGap)
  69106. {
  69107. }
  69108. BorderSize::BorderSize (const int allGaps) throw()
  69109. : top (allGaps),
  69110. left (allGaps),
  69111. bottom (allGaps),
  69112. right (allGaps)
  69113. {
  69114. }
  69115. BorderSize::~BorderSize() throw()
  69116. {
  69117. }
  69118. void BorderSize::setTop (const int newTopGap) throw()
  69119. {
  69120. top = newTopGap;
  69121. }
  69122. void BorderSize::setLeft (const int newLeftGap) throw()
  69123. {
  69124. left = newLeftGap;
  69125. }
  69126. void BorderSize::setBottom (const int newBottomGap) throw()
  69127. {
  69128. bottom = newBottomGap;
  69129. }
  69130. void BorderSize::setRight (const int newRightGap) throw()
  69131. {
  69132. right = newRightGap;
  69133. }
  69134. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  69135. {
  69136. return Rectangle (r.getX() + left,
  69137. r.getY() + top,
  69138. r.getWidth() - (left + right),
  69139. r.getHeight() - (top + bottom));
  69140. }
  69141. void BorderSize::subtractFrom (Rectangle& r) const throw()
  69142. {
  69143. r.setBounds (r.getX() + left,
  69144. r.getY() + top,
  69145. r.getWidth() - (left + right),
  69146. r.getHeight() - (top + bottom));
  69147. }
  69148. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  69149. {
  69150. return Rectangle (r.getX() - left,
  69151. r.getY() - top,
  69152. r.getWidth() + (left + right),
  69153. r.getHeight() + (top + bottom));
  69154. }
  69155. void BorderSize::addTo (Rectangle& r) const throw()
  69156. {
  69157. r.setBounds (r.getX() - left,
  69158. r.getY() - top,
  69159. r.getWidth() + (left + right),
  69160. r.getHeight() + (top + bottom));
  69161. }
  69162. bool BorderSize::operator== (const BorderSize& other) const throw()
  69163. {
  69164. return top == other.top
  69165. && left == other.left
  69166. && bottom == other.bottom
  69167. && right == other.right;
  69168. }
  69169. bool BorderSize::operator!= (const BorderSize& other) const throw()
  69170. {
  69171. return ! operator== (other);
  69172. }
  69173. END_JUCE_NAMESPACE
  69174. /********* End of inlined file: juce_BorderSize.cpp *********/
  69175. /********* Start of inlined file: juce_Line.cpp *********/
  69176. BEGIN_JUCE_NAMESPACE
  69177. static bool juce_lineIntersection (const float x1, const float y1,
  69178. const float x2, const float y2,
  69179. const float x3, const float y3,
  69180. const float x4, const float y4,
  69181. float& intersectionX,
  69182. float& intersectionY) throw()
  69183. {
  69184. if (x2 != x3 || y2 != y3)
  69185. {
  69186. const float dx1 = x2 - x1;
  69187. const float dy1 = y2 - y1;
  69188. const float dx2 = x4 - x3;
  69189. const float dy2 = y4 - y3;
  69190. const float divisor = dx1 * dy2 - dx2 * dy1;
  69191. if (divisor == 0)
  69192. {
  69193. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  69194. {
  69195. if (dy1 == 0 && dy2 != 0)
  69196. {
  69197. const float along = (y1 - y3) / dy2;
  69198. intersectionX = x3 + along * dx2;
  69199. intersectionY = y1;
  69200. return along >= 0 && along <= 1.0f;
  69201. }
  69202. else if (dy2 == 0 && dy1 != 0)
  69203. {
  69204. const float along = (y3 - y1) / dy1;
  69205. intersectionX = x1 + along * dx1;
  69206. intersectionY = y3;
  69207. return along >= 0 && along <= 1.0f;
  69208. }
  69209. else if (dx1 == 0 && dx2 != 0)
  69210. {
  69211. const float along = (x1 - x3) / dx2;
  69212. intersectionX = x1;
  69213. intersectionY = y3 + along * dy2;
  69214. return along >= 0 && along <= 1.0f;
  69215. }
  69216. else if (dx2 == 0 && dx1 != 0)
  69217. {
  69218. const float along = (x3 - x1) / dx1;
  69219. intersectionX = x3;
  69220. intersectionY = y1 + along * dy1;
  69221. return along >= 0 && along <= 1.0f;
  69222. }
  69223. }
  69224. intersectionX = 0.5f * (x2 + x3);
  69225. intersectionY = 0.5f * (y2 + y3);
  69226. return false;
  69227. }
  69228. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  69229. intersectionX = x1 + along1 * dx1;
  69230. intersectionY = y1 + along1 * dy1;
  69231. if (along1 < 0 || along1 > 1.0f)
  69232. return false;
  69233. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  69234. return along2 >= 0 && along2 <= 1.0f;
  69235. }
  69236. intersectionX = x2;
  69237. intersectionY = y2;
  69238. return true;
  69239. }
  69240. Line::Line() throw()
  69241. : startX (0.0f),
  69242. startY (0.0f),
  69243. endX (0.0f),
  69244. endY (0.0f)
  69245. {
  69246. }
  69247. Line::Line (const Line& other) throw()
  69248. : startX (other.startX),
  69249. startY (other.startY),
  69250. endX (other.endX),
  69251. endY (other.endY)
  69252. {
  69253. }
  69254. Line::Line (const float startX_, const float startY_,
  69255. const float endX_, const float endY_) throw()
  69256. : startX (startX_),
  69257. startY (startY_),
  69258. endX (endX_),
  69259. endY (endY_)
  69260. {
  69261. }
  69262. Line::Line (const Point& start,
  69263. const Point& end) throw()
  69264. : startX (start.getX()),
  69265. startY (start.getY()),
  69266. endX (end.getX()),
  69267. endY (end.getY())
  69268. {
  69269. }
  69270. const Line& Line::operator= (const Line& other) throw()
  69271. {
  69272. startX = other.startX;
  69273. startY = other.startY;
  69274. endX = other.endX;
  69275. endY = other.endY;
  69276. return *this;
  69277. }
  69278. Line::~Line() throw()
  69279. {
  69280. }
  69281. const Point Line::getStart() const throw()
  69282. {
  69283. return Point (startX, startY);
  69284. }
  69285. const Point Line::getEnd() const throw()
  69286. {
  69287. return Point (endX, endY);
  69288. }
  69289. void Line::setStart (const float newStartX,
  69290. const float newStartY) throw()
  69291. {
  69292. startX = newStartX;
  69293. startY = newStartY;
  69294. }
  69295. void Line::setStart (const Point& newStart) throw()
  69296. {
  69297. startX = newStart.getX();
  69298. startY = newStart.getY();
  69299. }
  69300. void Line::setEnd (const float newEndX,
  69301. const float newEndY) throw()
  69302. {
  69303. endX = newEndX;
  69304. endY = newEndY;
  69305. }
  69306. void Line::setEnd (const Point& newEnd) throw()
  69307. {
  69308. endX = newEnd.getX();
  69309. endY = newEnd.getY();
  69310. }
  69311. bool Line::operator== (const Line& other) const throw()
  69312. {
  69313. return startX == other.startX
  69314. && startY == other.startY
  69315. && endX == other.endX
  69316. && endY == other.endY;
  69317. }
  69318. bool Line::operator!= (const Line& other) const throw()
  69319. {
  69320. return startX != other.startX
  69321. || startY != other.startY
  69322. || endX != other.endX
  69323. || endY != other.endY;
  69324. }
  69325. void Line::applyTransform (const AffineTransform& transform) throw()
  69326. {
  69327. transform.transformPoint (startX, startY);
  69328. transform.transformPoint (endX, endY);
  69329. }
  69330. float Line::getLength() const throw()
  69331. {
  69332. return (float) juce_hypot (startX - endX,
  69333. startY - endY);
  69334. }
  69335. float Line::getAngle() const throw()
  69336. {
  69337. return atan2f (endX - startX,
  69338. endY - startY);
  69339. }
  69340. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  69341. {
  69342. const float alpha = distanceFromStart / getLength();
  69343. return Point (startX + (endX - startX) * alpha,
  69344. startY + (endY - startY) * alpha);
  69345. }
  69346. const Point Line::getPointAlongLine (const float offsetX,
  69347. const float offsetY) const throw()
  69348. {
  69349. const float dx = endX - startX;
  69350. const float dy = endY - startY;
  69351. const double length = juce_hypot (dx, dy);
  69352. if (length == 0)
  69353. return Point (startX, startY);
  69354. else
  69355. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  69356. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  69357. }
  69358. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  69359. {
  69360. return Point (startX + (endX - startX) * alpha,
  69361. startY + (endY - startY) * alpha);
  69362. }
  69363. float Line::getDistanceFromLine (const float x,
  69364. const float y) const throw()
  69365. {
  69366. const double dx = endX - startX;
  69367. const double dy = endY - startY;
  69368. const double length = dx * dx + dy * dy;
  69369. if (length > 0)
  69370. {
  69371. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  69372. if (prop >= 0.0f && prop < 1.0f)
  69373. {
  69374. return (float) juce_hypot (x - (startX + prop * dx),
  69375. y - (startY + prop * dy));
  69376. }
  69377. }
  69378. return (float) jmin (juce_hypot (x - startX, y - startY),
  69379. juce_hypot (x - endX, y - endY));
  69380. }
  69381. float Line::findNearestPointTo (const float x,
  69382. const float y) const throw()
  69383. {
  69384. const double dx = endX - startX;
  69385. const double dy = endY - startY;
  69386. const double length = dx * dx + dy * dy;
  69387. if (length <= 0.0)
  69388. return 0.0f;
  69389. return jlimit (0.0f, 1.0f,
  69390. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  69391. }
  69392. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  69393. {
  69394. const float length = getLength();
  69395. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  69396. getEnd());
  69397. }
  69398. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  69399. {
  69400. const float length = getLength();
  69401. return Line (getStart(),
  69402. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  69403. }
  69404. bool Line::clipToPath (const Path& path,
  69405. const bool keepSectionOutsidePath) throw()
  69406. {
  69407. const bool startInside = path.contains (startX, startY);
  69408. const bool endInside = path.contains (endX, endY);
  69409. if (startInside == endInside)
  69410. {
  69411. if (keepSectionOutsidePath != startInside)
  69412. {
  69413. // entirely outside the path
  69414. return false;
  69415. }
  69416. else
  69417. {
  69418. // entirely inside the path
  69419. startX = 0.0f;
  69420. startY = 0.0f;
  69421. endX = 0.0f;
  69422. endY = 0.0f;
  69423. return true;
  69424. }
  69425. }
  69426. else
  69427. {
  69428. bool changed = false;
  69429. PathFlatteningIterator iter (path, AffineTransform::identity);
  69430. while (iter.next())
  69431. {
  69432. float ix, iy;
  69433. if (intersects (Line (iter.x1, iter.y1,
  69434. iter.x2, iter.y2),
  69435. ix, iy))
  69436. {
  69437. if ((startInside && keepSectionOutsidePath)
  69438. || (endInside && ! keepSectionOutsidePath))
  69439. {
  69440. setStart (ix, iy);
  69441. }
  69442. else
  69443. {
  69444. setEnd (ix, iy);
  69445. }
  69446. changed = true;
  69447. }
  69448. }
  69449. return changed;
  69450. }
  69451. }
  69452. bool Line::intersects (const Line& line,
  69453. float& intersectionX,
  69454. float& intersectionY) const throw()
  69455. {
  69456. return juce_lineIntersection (startX, startY,
  69457. endX, endY,
  69458. line.startX, line.startY,
  69459. line.endX, line.endY,
  69460. intersectionX,
  69461. intersectionY);
  69462. }
  69463. bool Line::isVertical() const throw()
  69464. {
  69465. return startX == endX;
  69466. }
  69467. bool Line::isHorizontal() const throw()
  69468. {
  69469. return startY == endY;
  69470. }
  69471. bool Line::isPointAbove (const float x, const float y) const throw()
  69472. {
  69473. return startX != endX
  69474. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  69475. }
  69476. END_JUCE_NAMESPACE
  69477. /********* End of inlined file: juce_Line.cpp *********/
  69478. /********* Start of inlined file: juce_Path.cpp *********/
  69479. BEGIN_JUCE_NAMESPACE
  69480. // tests that some co-ords aren't NaNs
  69481. #define CHECK_COORDS_ARE_VALID(x, y) \
  69482. jassert (x == x && y == y);
  69483. const float Path::lineMarker = 100001.0f;
  69484. const float Path::moveMarker = 100002.0f;
  69485. const float Path::quadMarker = 100003.0f;
  69486. const float Path::cubicMarker = 100004.0f;
  69487. const float Path::closeSubPathMarker = 100005.0f;
  69488. static const int defaultGranularity = 32;
  69489. Path::Path() throw()
  69490. : ArrayAllocationBase <float> (defaultGranularity),
  69491. numElements (0),
  69492. pathXMin (0),
  69493. pathXMax (0),
  69494. pathYMin (0),
  69495. pathYMax (0),
  69496. useNonZeroWinding (true)
  69497. {
  69498. }
  69499. Path::~Path() throw()
  69500. {
  69501. }
  69502. Path::Path (const Path& other) throw()
  69503. : ArrayAllocationBase <float> (defaultGranularity),
  69504. numElements (other.numElements),
  69505. pathXMin (other.pathXMin),
  69506. pathXMax (other.pathXMax),
  69507. pathYMin (other.pathYMin),
  69508. pathYMax (other.pathYMax),
  69509. useNonZeroWinding (other.useNonZeroWinding)
  69510. {
  69511. if (numElements > 0)
  69512. {
  69513. setAllocatedSize (numElements);
  69514. memcpy (elements, other.elements, numElements * sizeof (float));
  69515. }
  69516. }
  69517. const Path& Path::operator= (const Path& other) throw()
  69518. {
  69519. if (this != &other)
  69520. {
  69521. ensureAllocatedSize (other.numElements);
  69522. numElements = other.numElements;
  69523. pathXMin = other.pathXMin;
  69524. pathXMax = other.pathXMax;
  69525. pathYMin = other.pathYMin;
  69526. pathYMax = other.pathYMax;
  69527. useNonZeroWinding = other.useNonZeroWinding;
  69528. if (numElements > 0)
  69529. memcpy (elements, other.elements, numElements * sizeof (float));
  69530. }
  69531. return *this;
  69532. }
  69533. void Path::clear() throw()
  69534. {
  69535. numElements = 0;
  69536. pathXMin = 0;
  69537. pathYMin = 0;
  69538. pathYMax = 0;
  69539. pathXMax = 0;
  69540. }
  69541. void Path::swapWithPath (Path& other)
  69542. {
  69543. swapVariables <int> (this->numAllocated, other.numAllocated);
  69544. swapVariables <float*> (this->elements, other.elements);
  69545. swapVariables <int> (this->numElements, other.numElements);
  69546. swapVariables <float> (this->pathXMin, other.pathXMin);
  69547. swapVariables <float> (this->pathXMax, other.pathXMax);
  69548. swapVariables <float> (this->pathYMin, other.pathYMin);
  69549. swapVariables <float> (this->pathYMax, other.pathYMax);
  69550. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  69551. }
  69552. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  69553. {
  69554. useNonZeroWinding = isNonZero;
  69555. }
  69556. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  69557. const bool preserveProportions) throw()
  69558. {
  69559. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  69560. }
  69561. bool Path::isEmpty() const throw()
  69562. {
  69563. int i = 0;
  69564. while (i < numElements)
  69565. {
  69566. const float type = elements [i++];
  69567. if (type == moveMarker)
  69568. {
  69569. i += 2;
  69570. }
  69571. else if (type == lineMarker
  69572. || type == quadMarker
  69573. || type == cubicMarker)
  69574. {
  69575. return false;
  69576. }
  69577. }
  69578. return true;
  69579. }
  69580. void Path::getBounds (float& x, float& y,
  69581. float& w, float& h) const throw()
  69582. {
  69583. x = pathXMin;
  69584. y = pathYMin;
  69585. w = pathXMax - pathXMin;
  69586. h = pathYMax - pathYMin;
  69587. }
  69588. void Path::getBoundsTransformed (const AffineTransform& transform,
  69589. float& x, float& y,
  69590. float& w, float& h) const throw()
  69591. {
  69592. float x1 = pathXMin;
  69593. float y1 = pathYMin;
  69594. transform.transformPoint (x1, y1);
  69595. float x2 = pathXMax;
  69596. float y2 = pathYMin;
  69597. transform.transformPoint (x2, y2);
  69598. float x3 = pathXMin;
  69599. float y3 = pathYMax;
  69600. transform.transformPoint (x3, y3);
  69601. float x4 = pathXMax;
  69602. float y4 = pathYMax;
  69603. transform.transformPoint (x4, y4);
  69604. x = jmin (x1, x2, x3, x4);
  69605. y = jmin (y1, y2, y3, y4);
  69606. w = jmax (x1, x2, x3, x4) - x;
  69607. h = jmax (y1, y2, y3, y4) - y;
  69608. }
  69609. void Path::startNewSubPath (const float x,
  69610. const float y) throw()
  69611. {
  69612. CHECK_COORDS_ARE_VALID (x, y);
  69613. if (numElements == 0)
  69614. {
  69615. pathXMin = pathXMax = x;
  69616. pathYMin = pathYMax = y;
  69617. }
  69618. else
  69619. {
  69620. pathXMin = jmin (pathXMin, x);
  69621. pathXMax = jmax (pathXMax, x);
  69622. pathYMin = jmin (pathYMin, y);
  69623. pathYMax = jmax (pathYMax, y);
  69624. }
  69625. ensureAllocatedSize (numElements + 3);
  69626. elements [numElements++] = moveMarker;
  69627. elements [numElements++] = x;
  69628. elements [numElements++] = y;
  69629. }
  69630. void Path::lineTo (const float x, const float y) throw()
  69631. {
  69632. CHECK_COORDS_ARE_VALID (x, y);
  69633. if (numElements == 0)
  69634. startNewSubPath (0, 0);
  69635. ensureAllocatedSize (numElements + 3);
  69636. elements [numElements++] = lineMarker;
  69637. elements [numElements++] = x;
  69638. elements [numElements++] = y;
  69639. pathXMin = jmin (pathXMin, x);
  69640. pathXMax = jmax (pathXMax, x);
  69641. pathYMin = jmin (pathYMin, y);
  69642. pathYMax = jmax (pathYMax, y);
  69643. }
  69644. void Path::quadraticTo (const float x1, const float y1,
  69645. const float x2, const float y2) throw()
  69646. {
  69647. CHECK_COORDS_ARE_VALID (x1, y1);
  69648. CHECK_COORDS_ARE_VALID (x2, y2);
  69649. if (numElements == 0)
  69650. startNewSubPath (0, 0);
  69651. ensureAllocatedSize (numElements + 5);
  69652. elements [numElements++] = quadMarker;
  69653. elements [numElements++] = x1;
  69654. elements [numElements++] = y1;
  69655. elements [numElements++] = x2;
  69656. elements [numElements++] = y2;
  69657. pathXMin = jmin (pathXMin, x1, x2);
  69658. pathXMax = jmax (pathXMax, x1, x2);
  69659. pathYMin = jmin (pathYMin, y1, y2);
  69660. pathYMax = jmax (pathYMax, y1, y2);
  69661. }
  69662. void Path::cubicTo (const float x1, const float y1,
  69663. const float x2, const float y2,
  69664. const float x3, const float y3) throw()
  69665. {
  69666. CHECK_COORDS_ARE_VALID (x1, y1);
  69667. CHECK_COORDS_ARE_VALID (x2, y2);
  69668. CHECK_COORDS_ARE_VALID (x3, y3);
  69669. if (numElements == 0)
  69670. startNewSubPath (0, 0);
  69671. ensureAllocatedSize (numElements + 7);
  69672. elements [numElements++] = cubicMarker;
  69673. elements [numElements++] = x1;
  69674. elements [numElements++] = y1;
  69675. elements [numElements++] = x2;
  69676. elements [numElements++] = y2;
  69677. elements [numElements++] = x3;
  69678. elements [numElements++] = y3;
  69679. pathXMin = jmin (pathXMin, x1, x2, x3);
  69680. pathXMax = jmax (pathXMax, x1, x2, x3);
  69681. pathYMin = jmin (pathYMin, y1, y2, y3);
  69682. pathYMax = jmax (pathYMax, y1, y2, y3);
  69683. }
  69684. void Path::closeSubPath() throw()
  69685. {
  69686. if (numElements > 0
  69687. && elements [numElements - 1] != closeSubPathMarker)
  69688. {
  69689. ensureAllocatedSize (numElements + 1);
  69690. elements [numElements++] = closeSubPathMarker;
  69691. }
  69692. }
  69693. const Point Path::getCurrentPosition() const
  69694. {
  69695. int i = numElements - 1;
  69696. if (i > 0 && elements[i] == closeSubPathMarker)
  69697. {
  69698. while (i >= 0)
  69699. {
  69700. if (elements[i] == moveMarker)
  69701. {
  69702. i += 2;
  69703. break;
  69704. }
  69705. --i;
  69706. }
  69707. }
  69708. if (i > 0)
  69709. return Point (elements [i - 1], elements [i]);
  69710. return Point (0.0f, 0.0f);
  69711. }
  69712. void Path::addRectangle (const float x, const float y,
  69713. const float w, const float h) throw()
  69714. {
  69715. startNewSubPath (x, y + h);
  69716. lineTo (x, y);
  69717. lineTo (x + w, y);
  69718. lineTo (x + w, y + h);
  69719. closeSubPath();
  69720. }
  69721. void Path::addRoundedRectangle (const float x, const float y,
  69722. const float w, const float h,
  69723. float csx,
  69724. float csy) throw()
  69725. {
  69726. csx = jmin (csx, w * 0.5f);
  69727. csy = jmin (csy, h * 0.5f);
  69728. const float cs45x = csx * 0.45f;
  69729. const float cs45y = csy * 0.45f;
  69730. const float x2 = x + w;
  69731. const float y2 = y + h;
  69732. startNewSubPath (x + csx, y);
  69733. lineTo (x2 - csx, y);
  69734. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  69735. lineTo (x2, y2 - csy);
  69736. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  69737. lineTo (x + csx, y2);
  69738. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  69739. lineTo (x, y + csy);
  69740. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  69741. closeSubPath();
  69742. }
  69743. void Path::addRoundedRectangle (const float x, const float y,
  69744. const float w, const float h,
  69745. float cs) throw()
  69746. {
  69747. addRoundedRectangle (x, y, w, h, cs, cs);
  69748. }
  69749. void Path::addTriangle (const float x1, const float y1,
  69750. const float x2, const float y2,
  69751. const float x3, const float y3) throw()
  69752. {
  69753. startNewSubPath (x1, y1);
  69754. lineTo (x2, y2);
  69755. lineTo (x3, y3);
  69756. closeSubPath();
  69757. }
  69758. void Path::addQuadrilateral (const float x1, const float y1,
  69759. const float x2, const float y2,
  69760. const float x3, const float y3,
  69761. const float x4, const float y4) throw()
  69762. {
  69763. startNewSubPath (x1, y1);
  69764. lineTo (x2, y2);
  69765. lineTo (x3, y3);
  69766. lineTo (x4, y4);
  69767. closeSubPath();
  69768. }
  69769. void Path::addEllipse (const float x, const float y,
  69770. const float w, const float h) throw()
  69771. {
  69772. const float hw = w * 0.5f;
  69773. const float hw55 = hw * 0.55f;
  69774. const float hh = h * 0.5f;
  69775. const float hh45 = hh * 0.55f;
  69776. const float cx = x + hw;
  69777. const float cy = y + hh;
  69778. startNewSubPath (cx, cy - hh);
  69779. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  69780. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  69781. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  69782. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  69783. closeSubPath();
  69784. }
  69785. void Path::addArc (const float x, const float y,
  69786. const float w, const float h,
  69787. const float fromRadians,
  69788. const float toRadians,
  69789. const bool startAsNewSubPath) throw()
  69790. {
  69791. const float radiusX = w / 2.0f;
  69792. const float radiusY = h / 2.0f;
  69793. addCentredArc (x + radiusX,
  69794. y + radiusY,
  69795. radiusX, radiusY,
  69796. 0.0f,
  69797. fromRadians, toRadians,
  69798. startAsNewSubPath);
  69799. }
  69800. static const float ellipseAngularIncrement = 0.05f;
  69801. void Path::addCentredArc (const float centreX, const float centreY,
  69802. const float radiusX, const float radiusY,
  69803. const float rotationOfEllipse,
  69804. const float fromRadians,
  69805. const float toRadians,
  69806. const bool startAsNewSubPath) throw()
  69807. {
  69808. if (radiusX > 0.0f && radiusY > 0.0f)
  69809. {
  69810. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  69811. float angle = fromRadians;
  69812. if (startAsNewSubPath)
  69813. {
  69814. float x = centreX + radiusX * sinf (angle);
  69815. float y = centreY - radiusY * cosf (angle);
  69816. if (rotationOfEllipse != 0)
  69817. rotation.transformPoint (x, y);
  69818. startNewSubPath (x, y);
  69819. }
  69820. if (fromRadians < toRadians)
  69821. {
  69822. if (startAsNewSubPath)
  69823. angle += ellipseAngularIncrement;
  69824. while (angle < toRadians)
  69825. {
  69826. float x = centreX + radiusX * sinf (angle);
  69827. float y = centreY - radiusY * cosf (angle);
  69828. if (rotationOfEllipse != 0)
  69829. rotation.transformPoint (x, y);
  69830. lineTo (x, y);
  69831. angle += ellipseAngularIncrement;
  69832. }
  69833. }
  69834. else
  69835. {
  69836. if (startAsNewSubPath)
  69837. angle -= ellipseAngularIncrement;
  69838. while (angle > toRadians)
  69839. {
  69840. float x = centreX + radiusX * sinf (angle);
  69841. float y = centreY - radiusY * cosf (angle);
  69842. if (rotationOfEllipse != 0)
  69843. rotation.transformPoint (x, y);
  69844. lineTo (x, y);
  69845. angle -= ellipseAngularIncrement;
  69846. }
  69847. }
  69848. float x = centreX + radiusX * sinf (toRadians);
  69849. float y = centreY - radiusY * cosf (toRadians);
  69850. if (rotationOfEllipse != 0)
  69851. rotation.transformPoint (x, y);
  69852. lineTo (x, y);
  69853. }
  69854. }
  69855. void Path::addPieSegment (const float x, const float y,
  69856. const float width, const float height,
  69857. const float fromRadians,
  69858. const float toRadians,
  69859. const float innerCircleProportionalSize)
  69860. {
  69861. float hw = width * 0.5f;
  69862. float hh = height * 0.5f;
  69863. const float centreX = x + hw;
  69864. const float centreY = y + hh;
  69865. startNewSubPath (centreX + hw * sinf (fromRadians),
  69866. centreY - hh * cosf (fromRadians));
  69867. addArc (x, y, width, height, fromRadians, toRadians);
  69868. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  69869. {
  69870. closeSubPath();
  69871. if (innerCircleProportionalSize > 0)
  69872. {
  69873. hw *= innerCircleProportionalSize;
  69874. hh *= innerCircleProportionalSize;
  69875. startNewSubPath (centreX + hw * sinf (toRadians),
  69876. centreY - hh * cosf (toRadians));
  69877. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69878. toRadians, fromRadians);
  69879. }
  69880. }
  69881. else
  69882. {
  69883. if (innerCircleProportionalSize > 0)
  69884. {
  69885. hw *= innerCircleProportionalSize;
  69886. hh *= innerCircleProportionalSize;
  69887. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69888. toRadians, fromRadians);
  69889. }
  69890. else
  69891. {
  69892. lineTo (centreX, centreY);
  69893. }
  69894. }
  69895. closeSubPath();
  69896. }
  69897. static void perpendicularOffset (const float x1, const float y1,
  69898. const float x2, const float y2,
  69899. const float offsetX, const float offsetY,
  69900. float& resultX, float& resultY) throw()
  69901. {
  69902. const float dx = x2 - x1;
  69903. const float dy = y2 - y1;
  69904. const float len = juce_hypotf (dx, dy);
  69905. if (len == 0)
  69906. {
  69907. resultX = x1;
  69908. resultY = y1;
  69909. }
  69910. else
  69911. {
  69912. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  69913. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  69914. }
  69915. }
  69916. void Path::addLineSegment (const float startX, const float startY,
  69917. const float endX, const float endY,
  69918. float lineThickness) throw()
  69919. {
  69920. lineThickness *= 0.5f;
  69921. float x, y;
  69922. perpendicularOffset (startX, startY, endX, endY,
  69923. 0, lineThickness, x, y);
  69924. startNewSubPath (x, y);
  69925. perpendicularOffset (startX, startY, endX, endY,
  69926. 0, -lineThickness, x, y);
  69927. lineTo (x, y);
  69928. perpendicularOffset (endX, endY, startX, startY,
  69929. 0, lineThickness, x, y);
  69930. lineTo (x, y);
  69931. perpendicularOffset (endX, endY, startX, startY,
  69932. 0, -lineThickness, x, y);
  69933. lineTo (x, y);
  69934. closeSubPath();
  69935. }
  69936. void Path::addArrow (const float startX, const float startY,
  69937. const float endX, const float endY,
  69938. float lineThickness,
  69939. float arrowheadWidth,
  69940. float arrowheadLength) throw()
  69941. {
  69942. lineThickness *= 0.5f;
  69943. arrowheadWidth *= 0.5f;
  69944. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  69945. startY - endY));
  69946. float x, y;
  69947. perpendicularOffset (startX, startY, endX, endY,
  69948. 0, lineThickness, x, y);
  69949. startNewSubPath (x, y);
  69950. perpendicularOffset (startX, startY, endX, endY,
  69951. 0, -lineThickness, x, y);
  69952. lineTo (x, y);
  69953. perpendicularOffset (endX, endY, startX, startY,
  69954. arrowheadLength, lineThickness, x, y);
  69955. lineTo (x, y);
  69956. perpendicularOffset (endX, endY, startX, startY,
  69957. arrowheadLength, arrowheadWidth, x, y);
  69958. lineTo (x, y);
  69959. perpendicularOffset (endX, endY, startX, startY,
  69960. 0, 0, x, y);
  69961. lineTo (x, y);
  69962. perpendicularOffset (endX, endY, startX, startY,
  69963. arrowheadLength, -arrowheadWidth, x, y);
  69964. lineTo (x, y);
  69965. perpendicularOffset (endX, endY, startX, startY,
  69966. arrowheadLength, -lineThickness, x, y);
  69967. lineTo (x, y);
  69968. closeSubPath();
  69969. }
  69970. void Path::addStar (const float centreX,
  69971. const float centreY,
  69972. const int numberOfPoints,
  69973. const float innerRadius,
  69974. const float outerRadius,
  69975. const float startAngle)
  69976. {
  69977. jassert (numberOfPoints > 1); // this would be silly.
  69978. if (numberOfPoints > 1)
  69979. {
  69980. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  69981. for (int i = 0; i < numberOfPoints; ++i)
  69982. {
  69983. float angle = startAngle + i * angleBetweenPoints;
  69984. const float x = centreX + outerRadius * sinf (angle);
  69985. const float y = centreY - outerRadius * cosf (angle);
  69986. if (i == 0)
  69987. startNewSubPath (x, y);
  69988. else
  69989. lineTo (x, y);
  69990. angle += angleBetweenPoints * 0.5f;
  69991. lineTo (centreX + innerRadius * sinf (angle),
  69992. centreY - innerRadius * cosf (angle));
  69993. }
  69994. closeSubPath();
  69995. }
  69996. }
  69997. void Path::addBubble (float x, float y,
  69998. float w, float h,
  69999. float cs,
  70000. float tipX,
  70001. float tipY,
  70002. int whichSide,
  70003. float arrowPos,
  70004. float arrowWidth)
  70005. {
  70006. if (w > 1.0f && h > 1.0f)
  70007. {
  70008. cs = jmin (cs, w * 0.5f, h * 0.5f);
  70009. const float cs2 = 2.0f * cs;
  70010. startNewSubPath (x + cs, y);
  70011. if (whichSide == 0)
  70012. {
  70013. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  70014. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  70015. lineTo (arrowX1, y);
  70016. lineTo (tipX, tipY);
  70017. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  70018. }
  70019. lineTo (x + w - cs, y);
  70020. if (cs > 0.0f)
  70021. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  70022. if (whichSide == 3)
  70023. {
  70024. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  70025. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  70026. lineTo (x + w, arrowY1);
  70027. lineTo (tipX, tipY);
  70028. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  70029. }
  70030. lineTo (x + w, y + h - cs);
  70031. if (cs > 0.0f)
  70032. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  70033. if (whichSide == 2)
  70034. {
  70035. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  70036. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  70037. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  70038. lineTo (tipX, tipY);
  70039. lineTo (arrowX1, y + h);
  70040. }
  70041. lineTo (x + cs, y + h);
  70042. if (cs > 0.0f)
  70043. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  70044. if (whichSide == 1)
  70045. {
  70046. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  70047. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  70048. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  70049. lineTo (tipX, tipY);
  70050. lineTo (x, arrowY1);
  70051. }
  70052. lineTo (x, y + cs);
  70053. if (cs > 0.0f)
  70054. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  70055. closeSubPath();
  70056. }
  70057. }
  70058. void Path::addPath (const Path& other) throw()
  70059. {
  70060. int i = 0;
  70061. while (i < other.numElements)
  70062. {
  70063. const float type = other.elements [i++];
  70064. if (type == moveMarker)
  70065. {
  70066. startNewSubPath (other.elements [i],
  70067. other.elements [i + 1]);
  70068. i += 2;
  70069. }
  70070. else if (type == lineMarker)
  70071. {
  70072. lineTo (other.elements [i],
  70073. other.elements [i + 1]);
  70074. i += 2;
  70075. }
  70076. else if (type == quadMarker)
  70077. {
  70078. quadraticTo (other.elements [i],
  70079. other.elements [i + 1],
  70080. other.elements [i + 2],
  70081. other.elements [i + 3]);
  70082. i += 4;
  70083. }
  70084. else if (type == cubicMarker)
  70085. {
  70086. cubicTo (other.elements [i],
  70087. other.elements [i + 1],
  70088. other.elements [i + 2],
  70089. other.elements [i + 3],
  70090. other.elements [i + 4],
  70091. other.elements [i + 5]);
  70092. i += 6;
  70093. }
  70094. else if (type == closeSubPathMarker)
  70095. {
  70096. closeSubPath();
  70097. }
  70098. else
  70099. {
  70100. // something's gone wrong with the element list!
  70101. jassertfalse
  70102. }
  70103. }
  70104. }
  70105. void Path::addPath (const Path& other,
  70106. const AffineTransform& transformToApply) throw()
  70107. {
  70108. int i = 0;
  70109. while (i < other.numElements)
  70110. {
  70111. const float type = other.elements [i++];
  70112. if (type == closeSubPathMarker)
  70113. {
  70114. closeSubPath();
  70115. }
  70116. else
  70117. {
  70118. float x = other.elements [i++];
  70119. float y = other.elements [i++];
  70120. transformToApply.transformPoint (x, y);
  70121. if (type == moveMarker)
  70122. {
  70123. startNewSubPath (x, y);
  70124. }
  70125. else if (type == lineMarker)
  70126. {
  70127. lineTo (x, y);
  70128. }
  70129. else if (type == quadMarker)
  70130. {
  70131. float x2 = other.elements [i++];
  70132. float y2 = other.elements [i++];
  70133. transformToApply.transformPoint (x2, y2);
  70134. quadraticTo (x, y, x2, y2);
  70135. }
  70136. else if (type == cubicMarker)
  70137. {
  70138. float x2 = other.elements [i++];
  70139. float y2 = other.elements [i++];
  70140. float x3 = other.elements [i++];
  70141. float y3 = other.elements [i++];
  70142. transformToApply.transformPoint (x2, y2);
  70143. transformToApply.transformPoint (x3, y3);
  70144. cubicTo (x, y, x2, y2, x3, y3);
  70145. }
  70146. else
  70147. {
  70148. // something's gone wrong with the element list!
  70149. jassertfalse
  70150. }
  70151. }
  70152. }
  70153. }
  70154. void Path::applyTransform (const AffineTransform& transform) throw()
  70155. {
  70156. int i = 0;
  70157. pathYMin = pathXMin = 0;
  70158. pathYMax = pathXMax = 0;
  70159. bool setMaxMin = false;
  70160. while (i < numElements)
  70161. {
  70162. const float type = elements [i++];
  70163. if (type == moveMarker)
  70164. {
  70165. transform.transformPoint (elements [i],
  70166. elements [i + 1]);
  70167. if (setMaxMin)
  70168. {
  70169. pathXMin = jmin (pathXMin, elements [i]);
  70170. pathXMax = jmax (pathXMax, elements [i]);
  70171. pathYMin = jmin (pathYMin, elements [i + 1]);
  70172. pathYMax = jmax (pathYMax, elements [i + 1]);
  70173. }
  70174. else
  70175. {
  70176. pathXMin = pathXMax = elements [i];
  70177. pathYMin = pathYMax = elements [i + 1];
  70178. setMaxMin = true;
  70179. }
  70180. i += 2;
  70181. }
  70182. else if (type == lineMarker)
  70183. {
  70184. transform.transformPoint (elements [i],
  70185. elements [i + 1]);
  70186. pathXMin = jmin (pathXMin, elements [i]);
  70187. pathXMax = jmax (pathXMax, elements [i]);
  70188. pathYMin = jmin (pathYMin, elements [i + 1]);
  70189. pathYMax = jmax (pathYMax, elements [i + 1]);
  70190. i += 2;
  70191. }
  70192. else if (type == quadMarker)
  70193. {
  70194. transform.transformPoint (elements [i],
  70195. elements [i + 1]);
  70196. transform.transformPoint (elements [i + 2],
  70197. elements [i + 3]);
  70198. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  70199. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  70200. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  70201. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  70202. i += 4;
  70203. }
  70204. else if (type == cubicMarker)
  70205. {
  70206. transform.transformPoint (elements [i],
  70207. elements [i + 1]);
  70208. transform.transformPoint (elements [i + 2],
  70209. elements [i + 3]);
  70210. transform.transformPoint (elements [i + 4],
  70211. elements [i + 5]);
  70212. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  70213. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  70214. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  70215. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  70216. i += 6;
  70217. }
  70218. }
  70219. }
  70220. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  70221. const float w, const float h,
  70222. const bool preserveProportions,
  70223. const Justification& justification) const throw()
  70224. {
  70225. float sx, sy, sw, sh;
  70226. getBounds (sx, sy, sw, sh);
  70227. if (preserveProportions)
  70228. {
  70229. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  70230. return AffineTransform::identity;
  70231. float newW, newH;
  70232. const float srcRatio = sh / sw;
  70233. if (srcRatio > h / w)
  70234. {
  70235. newW = h / srcRatio;
  70236. newH = h;
  70237. }
  70238. else
  70239. {
  70240. newW = w;
  70241. newH = w * srcRatio;
  70242. }
  70243. float newXCentre = x;
  70244. float newYCentre = y;
  70245. if (justification.testFlags (Justification::left))
  70246. newXCentre += newW * 0.5f;
  70247. else if (justification.testFlags (Justification::right))
  70248. newXCentre += w - newW * 0.5f;
  70249. else
  70250. newXCentre += w * 0.5f;
  70251. if (justification.testFlags (Justification::top))
  70252. newYCentre += newH * 0.5f;
  70253. else if (justification.testFlags (Justification::bottom))
  70254. newYCentre += h - newH * 0.5f;
  70255. else
  70256. newYCentre += h * 0.5f;
  70257. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  70258. .scaled (newW / sw, newH / sh)
  70259. .translated (newXCentre, newYCentre);
  70260. }
  70261. else
  70262. {
  70263. return AffineTransform::translation (-sx, -sy)
  70264. .scaled (w / sw, h / sh)
  70265. .translated (x, y);
  70266. }
  70267. }
  70268. bool Path::contains (const float x, const float y, const float tolerence) const throw()
  70269. {
  70270. if (x <= pathXMin || x >= pathXMax
  70271. || y <= pathYMin || y >= pathYMax)
  70272. return false;
  70273. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70274. int positiveCrossings = 0;
  70275. int negativeCrossings = 0;
  70276. while (i.next())
  70277. {
  70278. if ((i.y1 <= y && i.y2 > y)
  70279. || (i.y2 <= y && i.y1 > y))
  70280. {
  70281. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  70282. if (intersectX <= x)
  70283. {
  70284. if (i.y1 < i.y2)
  70285. ++positiveCrossings;
  70286. else
  70287. ++negativeCrossings;
  70288. }
  70289. }
  70290. }
  70291. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  70292. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  70293. }
  70294. bool Path::intersectsLine (const float x1, const float y1,
  70295. const float x2, const float y2,
  70296. const float tolerence) throw()
  70297. {
  70298. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70299. const Line line1 (x1, y1, x2, y2);
  70300. while (i.next())
  70301. {
  70302. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  70303. float ix, iy;
  70304. if (line1.intersects (line2, ix, iy))
  70305. return true;
  70306. }
  70307. return false;
  70308. }
  70309. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  70310. {
  70311. if (cornerRadius <= 0.01f)
  70312. return *this;
  70313. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  70314. int n = 0;
  70315. bool lastWasLine = false, firstWasLine = false;
  70316. Path p;
  70317. while (n < numElements)
  70318. {
  70319. const float type = elements [n++];
  70320. if (type == moveMarker)
  70321. {
  70322. indexOfPathStart = p.numElements;
  70323. indexOfPathStartThis = n - 1;
  70324. const float x = elements [n++];
  70325. const float y = elements [n++];
  70326. p.startNewSubPath (x, y);
  70327. lastWasLine = false;
  70328. firstWasLine = (elements [n] == lineMarker);
  70329. }
  70330. else if (type == lineMarker || type == closeSubPathMarker)
  70331. {
  70332. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  70333. if (type == lineMarker)
  70334. {
  70335. endX = elements [n++];
  70336. endY = elements [n++];
  70337. if (n > 8)
  70338. {
  70339. startX = elements [n - 8];
  70340. startY = elements [n - 7];
  70341. joinX = elements [n - 5];
  70342. joinY = elements [n - 4];
  70343. }
  70344. }
  70345. else
  70346. {
  70347. endX = elements [indexOfPathStartThis + 1];
  70348. endY = elements [indexOfPathStartThis + 2];
  70349. if (n > 6)
  70350. {
  70351. startX = elements [n - 6];
  70352. startY = elements [n - 5];
  70353. joinX = elements [n - 3];
  70354. joinY = elements [n - 2];
  70355. }
  70356. }
  70357. if (lastWasLine)
  70358. {
  70359. const double len1 = juce_hypot (startX - joinX,
  70360. startY - joinY);
  70361. if (len1 > 0)
  70362. {
  70363. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70364. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70365. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70366. }
  70367. const double len2 = juce_hypot (endX - joinX,
  70368. endY - joinY);
  70369. if (len2 > 0)
  70370. {
  70371. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70372. p.quadraticTo (joinX, joinY,
  70373. (float) (joinX + (endX - joinX) * propNeeded),
  70374. (float) (joinY + (endY - joinY) * propNeeded));
  70375. }
  70376. p.lineTo (endX, endY);
  70377. }
  70378. else if (type == lineMarker)
  70379. {
  70380. p.lineTo (endX, endY);
  70381. lastWasLine = true;
  70382. }
  70383. if (type == closeSubPathMarker)
  70384. {
  70385. if (firstWasLine)
  70386. {
  70387. startX = elements [n - 3];
  70388. startY = elements [n - 2];
  70389. joinX = endX;
  70390. joinY = endY;
  70391. endX = elements [indexOfPathStartThis + 4];
  70392. endY = elements [indexOfPathStartThis + 5];
  70393. const double len1 = juce_hypot (startX - joinX,
  70394. startY - joinY);
  70395. if (len1 > 0)
  70396. {
  70397. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70398. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70399. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70400. }
  70401. const double len2 = juce_hypot (endX - joinX,
  70402. endY - joinY);
  70403. if (len2 > 0)
  70404. {
  70405. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70406. endX = (float) (joinX + (endX - joinX) * propNeeded);
  70407. endY = (float) (joinY + (endY - joinY) * propNeeded);
  70408. p.quadraticTo (joinX, joinY, endX, endY);
  70409. p.elements [indexOfPathStart + 1] = endX;
  70410. p.elements [indexOfPathStart + 2] = endY;
  70411. }
  70412. }
  70413. p.closeSubPath();
  70414. }
  70415. }
  70416. else if (type == quadMarker)
  70417. {
  70418. lastWasLine = false;
  70419. const float x1 = elements [n++];
  70420. const float y1 = elements [n++];
  70421. const float x2 = elements [n++];
  70422. const float y2 = elements [n++];
  70423. p.quadraticTo (x1, y1, x2, y2);
  70424. }
  70425. else if (type == cubicMarker)
  70426. {
  70427. lastWasLine = false;
  70428. const float x1 = elements [n++];
  70429. const float y1 = elements [n++];
  70430. const float x2 = elements [n++];
  70431. const float y2 = elements [n++];
  70432. const float x3 = elements [n++];
  70433. const float y3 = elements [n++];
  70434. p.cubicTo (x1, y1, x2, y2, x3, y3);
  70435. }
  70436. }
  70437. return p;
  70438. }
  70439. void Path::loadPathFromStream (InputStream& source)
  70440. {
  70441. while (! source.isExhausted())
  70442. {
  70443. switch (source.readByte())
  70444. {
  70445. case 'm':
  70446. {
  70447. const float x = source.readFloat();
  70448. const float y = source.readFloat();
  70449. startNewSubPath (x, y);
  70450. break;
  70451. }
  70452. case 'l':
  70453. {
  70454. const float x = source.readFloat();
  70455. const float y = source.readFloat();
  70456. lineTo (x, y);
  70457. break;
  70458. }
  70459. case 'q':
  70460. {
  70461. const float x1 = source.readFloat();
  70462. const float y1 = source.readFloat();
  70463. const float x2 = source.readFloat();
  70464. const float y2 = source.readFloat();
  70465. quadraticTo (x1, y1, x2, y2);
  70466. break;
  70467. }
  70468. case 'b':
  70469. {
  70470. const float x1 = source.readFloat();
  70471. const float y1 = source.readFloat();
  70472. const float x2 = source.readFloat();
  70473. const float y2 = source.readFloat();
  70474. const float x3 = source.readFloat();
  70475. const float y3 = source.readFloat();
  70476. cubicTo (x1, y1, x2, y2, x3, y3);
  70477. break;
  70478. }
  70479. case 'c':
  70480. closeSubPath();
  70481. break;
  70482. case 'n':
  70483. useNonZeroWinding = true;
  70484. break;
  70485. case 'z':
  70486. useNonZeroWinding = false;
  70487. break;
  70488. case 'e':
  70489. return; // end of path marker
  70490. default:
  70491. jassertfalse // illegal char in the stream
  70492. break;
  70493. }
  70494. }
  70495. }
  70496. void Path::loadPathFromData (const unsigned char* const data,
  70497. const int numberOfBytes) throw()
  70498. {
  70499. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  70500. loadPathFromStream (in);
  70501. }
  70502. void Path::writePathToStream (OutputStream& dest) const
  70503. {
  70504. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  70505. int i = 0;
  70506. while (i < numElements)
  70507. {
  70508. const float type = elements [i++];
  70509. if (type == moveMarker)
  70510. {
  70511. dest.writeByte ('m');
  70512. dest.writeFloat (elements [i++]);
  70513. dest.writeFloat (elements [i++]);
  70514. }
  70515. else if (type == lineMarker)
  70516. {
  70517. dest.writeByte ('l');
  70518. dest.writeFloat (elements [i++]);
  70519. dest.writeFloat (elements [i++]);
  70520. }
  70521. else if (type == quadMarker)
  70522. {
  70523. dest.writeByte ('q');
  70524. dest.writeFloat (elements [i++]);
  70525. dest.writeFloat (elements [i++]);
  70526. dest.writeFloat (elements [i++]);
  70527. dest.writeFloat (elements [i++]);
  70528. }
  70529. else if (type == cubicMarker)
  70530. {
  70531. dest.writeByte ('b');
  70532. dest.writeFloat (elements [i++]);
  70533. dest.writeFloat (elements [i++]);
  70534. dest.writeFloat (elements [i++]);
  70535. dest.writeFloat (elements [i++]);
  70536. dest.writeFloat (elements [i++]);
  70537. dest.writeFloat (elements [i++]);
  70538. }
  70539. else if (type == closeSubPathMarker)
  70540. {
  70541. dest.writeByte ('c');
  70542. }
  70543. }
  70544. dest.writeByte ('e'); // marks the end-of-path
  70545. }
  70546. const String Path::toString() const
  70547. {
  70548. String s;
  70549. s.preallocateStorage (numElements * 4);
  70550. if (! useNonZeroWinding)
  70551. s << T("a ");
  70552. int i = 0;
  70553. float lastMarker = 0.0f;
  70554. while (i < numElements)
  70555. {
  70556. const float marker = elements [i++];
  70557. tchar markerChar = 0;
  70558. int numCoords = 0;
  70559. if (marker == moveMarker)
  70560. {
  70561. markerChar = T('m');
  70562. numCoords = 2;
  70563. }
  70564. else if (marker == lineMarker)
  70565. {
  70566. markerChar = T('l');
  70567. numCoords = 2;
  70568. }
  70569. else if (marker == quadMarker)
  70570. {
  70571. markerChar = T('q');
  70572. numCoords = 4;
  70573. }
  70574. else if (marker == cubicMarker)
  70575. {
  70576. markerChar = T('c');
  70577. numCoords = 6;
  70578. }
  70579. else
  70580. {
  70581. jassert (marker == closeSubPathMarker);
  70582. markerChar = T('z');
  70583. }
  70584. if (marker != lastMarker)
  70585. {
  70586. s << markerChar << T(' ');
  70587. lastMarker = marker;
  70588. }
  70589. while (--numCoords >= 0 && i < numElements)
  70590. {
  70591. String n (elements [i++], 3);
  70592. while (n.endsWithChar (T('0')))
  70593. n = n.dropLastCharacters (1);
  70594. if (n.endsWithChar (T('.')))
  70595. n = n.dropLastCharacters (1);
  70596. s << n << T(' ');
  70597. }
  70598. }
  70599. return s.trimEnd();
  70600. }
  70601. static const String nextToken (const tchar*& t)
  70602. {
  70603. while (CharacterFunctions::isWhitespace (*t))
  70604. ++t;
  70605. const tchar* const start = t;
  70606. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  70607. ++t;
  70608. const int length = (int) (t - start);
  70609. while (CharacterFunctions::isWhitespace (*t))
  70610. ++t;
  70611. return String (start, length);
  70612. }
  70613. void Path::restoreFromString (const String& stringVersion)
  70614. {
  70615. clear();
  70616. setUsingNonZeroWinding (true);
  70617. const tchar* t = stringVersion;
  70618. tchar marker = T('m');
  70619. int numValues = 2;
  70620. float values [6];
  70621. while (*t != 0)
  70622. {
  70623. const String token (nextToken (t));
  70624. const tchar firstChar = token[0];
  70625. int startNum = 0;
  70626. if (firstChar == T('m') || firstChar == T('l'))
  70627. {
  70628. marker = firstChar;
  70629. numValues = 2;
  70630. }
  70631. else if (firstChar == T('q'))
  70632. {
  70633. marker = firstChar;
  70634. numValues = 4;
  70635. }
  70636. else if (firstChar == T('c'))
  70637. {
  70638. marker = firstChar;
  70639. numValues = 6;
  70640. }
  70641. else if (firstChar == T('z'))
  70642. {
  70643. marker = firstChar;
  70644. numValues = 0;
  70645. }
  70646. else if (firstChar == T('a'))
  70647. {
  70648. setUsingNonZeroWinding (false);
  70649. continue;
  70650. }
  70651. else
  70652. {
  70653. ++startNum;
  70654. values [0] = token.getFloatValue();
  70655. }
  70656. for (int i = startNum; i < numValues; ++i)
  70657. values [i] = nextToken (t).getFloatValue();
  70658. switch (marker)
  70659. {
  70660. case T('m'):
  70661. startNewSubPath (values[0], values[1]);
  70662. break;
  70663. case T('l'):
  70664. lineTo (values[0], values[1]);
  70665. break;
  70666. case T('q'):
  70667. quadraticTo (values[0], values[1],
  70668. values[2], values[3]);
  70669. break;
  70670. case T('c'):
  70671. cubicTo (values[0], values[1],
  70672. values[2], values[3],
  70673. values[4], values[5]);
  70674. break;
  70675. case T('z'):
  70676. closeSubPath();
  70677. break;
  70678. default:
  70679. jassertfalse // illegal string format?
  70680. break;
  70681. }
  70682. }
  70683. }
  70684. Path::Iterator::Iterator (const Path& path_)
  70685. : path (path_),
  70686. index (0)
  70687. {
  70688. }
  70689. Path::Iterator::~Iterator()
  70690. {
  70691. }
  70692. bool Path::Iterator::next()
  70693. {
  70694. const float* const elements = path.elements;
  70695. if (index < path.numElements)
  70696. {
  70697. const float type = elements [index++];
  70698. if (type == moveMarker)
  70699. {
  70700. elementType = startNewSubPath;
  70701. x1 = elements [index++];
  70702. y1 = elements [index++];
  70703. }
  70704. else if (type == lineMarker)
  70705. {
  70706. elementType = lineTo;
  70707. x1 = elements [index++];
  70708. y1 = elements [index++];
  70709. }
  70710. else if (type == quadMarker)
  70711. {
  70712. elementType = quadraticTo;
  70713. x1 = elements [index++];
  70714. y1 = elements [index++];
  70715. x2 = elements [index++];
  70716. y2 = elements [index++];
  70717. }
  70718. else if (type == cubicMarker)
  70719. {
  70720. elementType = cubicTo;
  70721. x1 = elements [index++];
  70722. y1 = elements [index++];
  70723. x2 = elements [index++];
  70724. y2 = elements [index++];
  70725. x3 = elements [index++];
  70726. y3 = elements [index++];
  70727. }
  70728. else if (type == closeSubPathMarker)
  70729. {
  70730. elementType = closePath;
  70731. }
  70732. return true;
  70733. }
  70734. return false;
  70735. }
  70736. END_JUCE_NAMESPACE
  70737. /********* End of inlined file: juce_Path.cpp *********/
  70738. /********* Start of inlined file: juce_PathIterator.cpp *********/
  70739. BEGIN_JUCE_NAMESPACE
  70740. #if JUCE_MSVC
  70741. #pragma optimize ("t", on)
  70742. #endif
  70743. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  70744. const AffineTransform& transform_,
  70745. float tolerence_) throw()
  70746. : x2 (0),
  70747. y2 (0),
  70748. closesSubPath (false),
  70749. subPathIndex (-1),
  70750. path (path_),
  70751. transform (transform_),
  70752. points (path_.elements),
  70753. tolerence (tolerence_ * tolerence_),
  70754. subPathCloseX (0),
  70755. subPathCloseY (0),
  70756. index (0),
  70757. stackSize (32)
  70758. {
  70759. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  70760. isIdentityTransform = transform.isIdentity();
  70761. stackPos = stackBase;
  70762. }
  70763. PathFlatteningIterator::~PathFlatteningIterator() throw()
  70764. {
  70765. juce_free (stackBase);
  70766. }
  70767. bool PathFlatteningIterator::next() throw()
  70768. {
  70769. x1 = x2;
  70770. y1 = y2;
  70771. float x3 = 0;
  70772. float y3 = 0;
  70773. float x4 = 0;
  70774. float y4 = 0;
  70775. float type;
  70776. for (;;)
  70777. {
  70778. if (stackPos == stackBase)
  70779. {
  70780. if (index >= path.numElements)
  70781. {
  70782. return false;
  70783. }
  70784. else
  70785. {
  70786. type = points [index++];
  70787. if (type != Path::closeSubPathMarker)
  70788. {
  70789. x2 = points [index++];
  70790. y2 = points [index++];
  70791. if (! isIdentityTransform)
  70792. transform.transformPoint (x2, y2);
  70793. if (type == Path::quadMarker)
  70794. {
  70795. x3 = points [index++];
  70796. y3 = points [index++];
  70797. if (! isIdentityTransform)
  70798. transform.transformPoint (x3, y3);
  70799. }
  70800. else if (type == Path::cubicMarker)
  70801. {
  70802. x3 = points [index++];
  70803. y3 = points [index++];
  70804. x4 = points [index++];
  70805. y4 = points [index++];
  70806. if (! isIdentityTransform)
  70807. {
  70808. transform.transformPoint (x3, y3);
  70809. transform.transformPoint (x4, y4);
  70810. }
  70811. }
  70812. }
  70813. }
  70814. }
  70815. else
  70816. {
  70817. type = *--stackPos;
  70818. if (type != Path::closeSubPathMarker)
  70819. {
  70820. x2 = *--stackPos;
  70821. y2 = *--stackPos;
  70822. if (type == Path::quadMarker)
  70823. {
  70824. x3 = *--stackPos;
  70825. y3 = *--stackPos;
  70826. }
  70827. else if (type == Path::cubicMarker)
  70828. {
  70829. x3 = *--stackPos;
  70830. y3 = *--stackPos;
  70831. x4 = *--stackPos;
  70832. y4 = *--stackPos;
  70833. }
  70834. }
  70835. }
  70836. if (type == Path::lineMarker)
  70837. {
  70838. ++subPathIndex;
  70839. closesSubPath = (stackPos == stackBase)
  70840. && (index < path.numElements)
  70841. && (points [index] == Path::closeSubPathMarker)
  70842. && x2 == subPathCloseX
  70843. && y2 == subPathCloseY;
  70844. return true;
  70845. }
  70846. else if (type == Path::quadMarker)
  70847. {
  70848. const int offset = (int) (stackPos - stackBase);
  70849. if (offset >= stackSize - 10)
  70850. {
  70851. stackSize <<= 1;
  70852. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70853. stackPos = stackBase + offset;
  70854. }
  70855. const float dx1 = x1 - x2;
  70856. const float dy1 = y1 - y2;
  70857. const float dx2 = x2 - x3;
  70858. const float dy2 = y2 - y3;
  70859. const float m1x = (x1 + x2) * 0.5f;
  70860. const float m1y = (y1 + y2) * 0.5f;
  70861. const float m2x = (x2 + x3) * 0.5f;
  70862. const float m2y = (y2 + y3) * 0.5f;
  70863. const float m3x = (m1x + m2x) * 0.5f;
  70864. const float m3y = (m1y + m2y) * 0.5f;
  70865. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  70866. {
  70867. *stackPos++ = y3;
  70868. *stackPos++ = x3;
  70869. *stackPos++ = m2y;
  70870. *stackPos++ = m2x;
  70871. *stackPos++ = Path::quadMarker;
  70872. *stackPos++ = m3y;
  70873. *stackPos++ = m3x;
  70874. *stackPos++ = m1y;
  70875. *stackPos++ = m1x;
  70876. *stackPos++ = Path::quadMarker;
  70877. }
  70878. else
  70879. {
  70880. *stackPos++ = y3;
  70881. *stackPos++ = x3;
  70882. *stackPos++ = Path::lineMarker;
  70883. *stackPos++ = m3y;
  70884. *stackPos++ = m3x;
  70885. *stackPos++ = Path::lineMarker;
  70886. }
  70887. jassert (stackPos < stackBase + stackSize);
  70888. }
  70889. else if (type == Path::cubicMarker)
  70890. {
  70891. const int offset = (int) (stackPos - stackBase);
  70892. if (offset >= stackSize - 16)
  70893. {
  70894. stackSize <<= 1;
  70895. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70896. stackPos = stackBase + offset;
  70897. }
  70898. const float dx1 = x1 - x2;
  70899. const float dy1 = y1 - y2;
  70900. const float dx2 = x2 - x3;
  70901. const float dy2 = y2 - y3;
  70902. const float dx3 = x3 - x4;
  70903. const float dy3 = y3 - y4;
  70904. const float m1x = (x1 + x2) * 0.5f;
  70905. const float m1y = (y1 + y2) * 0.5f;
  70906. const float m2x = (x3 + x2) * 0.5f;
  70907. const float m2y = (y3 + y2) * 0.5f;
  70908. const float m3x = (x3 + x4) * 0.5f;
  70909. const float m3y = (y3 + y4) * 0.5f;
  70910. const float m4x = (m1x + m2x) * 0.5f;
  70911. const float m4y = (m1y + m2y) * 0.5f;
  70912. const float m5x = (m3x + m2x) * 0.5f;
  70913. const float m5y = (m3y + m2y) * 0.5f;
  70914. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  70915. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  70916. {
  70917. *stackPos++ = y4;
  70918. *stackPos++ = x4;
  70919. *stackPos++ = m3y;
  70920. *stackPos++ = m3x;
  70921. *stackPos++ = m5y;
  70922. *stackPos++ = m5x;
  70923. *stackPos++ = Path::cubicMarker;
  70924. *stackPos++ = (m4y + m5y) * 0.5f;
  70925. *stackPos++ = (m4x + m5x) * 0.5f;
  70926. *stackPos++ = m4y;
  70927. *stackPos++ = m4x;
  70928. *stackPos++ = m1y;
  70929. *stackPos++ = m1x;
  70930. *stackPos++ = Path::cubicMarker;
  70931. }
  70932. else
  70933. {
  70934. *stackPos++ = y4;
  70935. *stackPos++ = x4;
  70936. *stackPos++ = Path::lineMarker;
  70937. *stackPos++ = m5y;
  70938. *stackPos++ = m5x;
  70939. *stackPos++ = Path::lineMarker;
  70940. *stackPos++ = m4y;
  70941. *stackPos++ = m4x;
  70942. *stackPos++ = Path::lineMarker;
  70943. }
  70944. }
  70945. else if (type == Path::closeSubPathMarker)
  70946. {
  70947. if (x2 != subPathCloseX || y2 != subPathCloseY)
  70948. {
  70949. x1 = x2;
  70950. y1 = y2;
  70951. x2 = subPathCloseX;
  70952. y2 = subPathCloseY;
  70953. closesSubPath = true;
  70954. return true;
  70955. }
  70956. }
  70957. else
  70958. {
  70959. jassert (type == Path::moveMarker);
  70960. subPathIndex = -1;
  70961. subPathCloseX = x1 = x2;
  70962. subPathCloseY = y1 = y2;
  70963. }
  70964. }
  70965. }
  70966. END_JUCE_NAMESPACE
  70967. /********* End of inlined file: juce_PathIterator.cpp *********/
  70968. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  70969. BEGIN_JUCE_NAMESPACE
  70970. PathStrokeType::PathStrokeType (const float strokeThickness,
  70971. const JointStyle jointStyle_,
  70972. const EndCapStyle endStyle_) throw()
  70973. : thickness (strokeThickness),
  70974. jointStyle (jointStyle_),
  70975. endStyle (endStyle_)
  70976. {
  70977. }
  70978. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  70979. : thickness (other.thickness),
  70980. jointStyle (other.jointStyle),
  70981. endStyle (other.endStyle)
  70982. {
  70983. }
  70984. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  70985. {
  70986. thickness = other.thickness;
  70987. jointStyle = other.jointStyle;
  70988. endStyle = other.endStyle;
  70989. return *this;
  70990. }
  70991. PathStrokeType::~PathStrokeType() throw()
  70992. {
  70993. }
  70994. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  70995. {
  70996. return thickness == other.thickness
  70997. && jointStyle == other.jointStyle
  70998. && endStyle == other.endStyle;
  70999. }
  71000. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  71001. {
  71002. return ! operator== (other);
  71003. }
  71004. static bool lineIntersection (const float x1, const float y1,
  71005. const float x2, const float y2,
  71006. const float x3, const float y3,
  71007. const float x4, const float y4,
  71008. float& intersectionX,
  71009. float& intersectionY,
  71010. float& distanceBeyondLine1EndSquared) throw()
  71011. {
  71012. if (x2 != x3 || y2 != y3)
  71013. {
  71014. const float dx1 = x2 - x1;
  71015. const float dy1 = y2 - y1;
  71016. const float dx2 = x4 - x3;
  71017. const float dy2 = y4 - y3;
  71018. const float divisor = dx1 * dy2 - dx2 * dy1;
  71019. if (divisor == 0)
  71020. {
  71021. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  71022. {
  71023. if (dy1 == 0 && dy2 != 0)
  71024. {
  71025. const float along = (y1 - y3) / dy2;
  71026. intersectionX = x3 + along * dx2;
  71027. intersectionY = y1;
  71028. distanceBeyondLine1EndSquared = intersectionX - x2;
  71029. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71030. if ((x2 > x1) == (intersectionX < x2))
  71031. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71032. return along >= 0 && along <= 1.0f;
  71033. }
  71034. else if (dy2 == 0 && dy1 != 0)
  71035. {
  71036. const float along = (y3 - y1) / dy1;
  71037. intersectionX = x1 + along * dx1;
  71038. intersectionY = y3;
  71039. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  71040. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71041. if (along < 1.0f)
  71042. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71043. return along >= 0 && along <= 1.0f;
  71044. }
  71045. else if (dx1 == 0 && dx2 != 0)
  71046. {
  71047. const float along = (x1 - x3) / dx2;
  71048. intersectionX = x1;
  71049. intersectionY = y3 + along * dy2;
  71050. distanceBeyondLine1EndSquared = intersectionY - y2;
  71051. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71052. if ((y2 > y1) == (intersectionY < y2))
  71053. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71054. return along >= 0 && along <= 1.0f;
  71055. }
  71056. else if (dx2 == 0 && dx1 != 0)
  71057. {
  71058. const float along = (x3 - x1) / dx1;
  71059. intersectionX = x3;
  71060. intersectionY = y1 + along * dy1;
  71061. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  71062. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71063. if (along < 1.0f)
  71064. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71065. return along >= 0 && along <= 1.0f;
  71066. }
  71067. }
  71068. intersectionX = 0.5f * (x2 + x3);
  71069. intersectionY = 0.5f * (y2 + y3);
  71070. distanceBeyondLine1EndSquared = 0.0f;
  71071. return false;
  71072. }
  71073. else
  71074. {
  71075. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  71076. intersectionX = x1 + along1 * dx1;
  71077. intersectionY = y1 + along1 * dy1;
  71078. if (along1 >= 0 && along1 <= 1.0f)
  71079. {
  71080. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  71081. if (along2 >= 0 && along2 <= divisor)
  71082. {
  71083. distanceBeyondLine1EndSquared = 0.0f;
  71084. return true;
  71085. }
  71086. }
  71087. distanceBeyondLine1EndSquared = along1 - 1.0f;
  71088. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  71089. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  71090. if (along1 < 1.0f)
  71091. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  71092. return false;
  71093. }
  71094. }
  71095. intersectionX = x2;
  71096. intersectionY = y2;
  71097. distanceBeyondLine1EndSquared = 0.0f;
  71098. return true;
  71099. }
  71100. // part of stroke drawing stuff
  71101. static void addEdgeAndJoint (Path& destPath,
  71102. const PathStrokeType::JointStyle style,
  71103. const float maxMiterExtensionSquared, const float width,
  71104. const float x1, const float y1,
  71105. const float x2, const float y2,
  71106. const float x3, const float y3,
  71107. const float x4, const float y4,
  71108. const float midX, const float midY) throw()
  71109. {
  71110. if (style == PathStrokeType::beveled
  71111. || (x3 == x4 && y3 == y4)
  71112. || (x1 == x2 && y1 == y2))
  71113. {
  71114. destPath.lineTo (x2, y2);
  71115. destPath.lineTo (x3, y3);
  71116. }
  71117. else
  71118. {
  71119. float jx, jy, distanceBeyondLine1EndSquared;
  71120. // if they intersect, use this point..
  71121. if (lineIntersection (x1, y1, x2, y2,
  71122. x3, y3, x4, y4,
  71123. jx, jy, distanceBeyondLine1EndSquared))
  71124. {
  71125. destPath.lineTo (jx, jy);
  71126. }
  71127. else
  71128. {
  71129. if (style == PathStrokeType::mitered)
  71130. {
  71131. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  71132. && distanceBeyondLine1EndSquared > 0.0f)
  71133. {
  71134. destPath.lineTo (jx, jy);
  71135. }
  71136. else
  71137. {
  71138. // the end sticks out too far, so just use a blunt joint
  71139. destPath.lineTo (x2, y2);
  71140. destPath.lineTo (x3, y3);
  71141. }
  71142. }
  71143. else
  71144. {
  71145. // curved joints
  71146. float angle = atan2f (x2 - midX, y2 - midY);
  71147. float angle2 = atan2f (x3 - midX, y3 - midY);
  71148. while (angle < angle2 - 0.01f)
  71149. angle2 -= float_Pi * 2.0f;
  71150. destPath.lineTo (x2, y2);
  71151. while (angle > angle2)
  71152. {
  71153. destPath.lineTo (midX + width * sinf (angle),
  71154. midY + width * cosf (angle));
  71155. angle -= 0.1f;
  71156. }
  71157. destPath.lineTo (x3, y3);
  71158. }
  71159. }
  71160. }
  71161. }
  71162. static inline void addLineEnd (Path& destPath,
  71163. const PathStrokeType::EndCapStyle style,
  71164. const float x1, const float y1,
  71165. const float x2, const float y2,
  71166. const float width) throw()
  71167. {
  71168. if (style == PathStrokeType::butt)
  71169. {
  71170. destPath.lineTo (x2, y2);
  71171. }
  71172. else
  71173. {
  71174. float offx1, offy1, offx2, offy2;
  71175. float dx = x2 - x1;
  71176. float dy = y2 - y1;
  71177. const float len = juce_hypotf (dx, dy);
  71178. if (len == 0)
  71179. {
  71180. offx1 = offx2 = x1;
  71181. offy1 = offy2 = y1;
  71182. }
  71183. else
  71184. {
  71185. const float offset = width / len;
  71186. dx *= offset;
  71187. dy *= offset;
  71188. offx1 = x1 + dy;
  71189. offy1 = y1 - dx;
  71190. offx2 = x2 + dy;
  71191. offy2 = y2 - dx;
  71192. }
  71193. if (style == PathStrokeType::square)
  71194. {
  71195. // sqaure ends
  71196. destPath.lineTo (offx1, offy1);
  71197. destPath.lineTo (offx2, offy2);
  71198. destPath.lineTo (x2, y2);
  71199. }
  71200. else
  71201. {
  71202. // rounded ends
  71203. const float midx = (offx1 + offx2) * 0.5f;
  71204. const float midy = (offy1 + offy2) * 0.5f;
  71205. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  71206. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  71207. midx, midy);
  71208. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  71209. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  71210. x2, y2);
  71211. }
  71212. }
  71213. }
  71214. struct LineSection
  71215. {
  71216. LineSection() throw() {}
  71217. LineSection (int) throw() {}
  71218. float x1, y1, x2, y2; // original line
  71219. float lx1, ly1, lx2, ly2; // the left-hand stroke
  71220. float rx1, ry1, rx2, ry2; // the right-hand stroke
  71221. };
  71222. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  71223. const bool isClosed,
  71224. const float width, const float maxMiterExtensionSquared,
  71225. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  71226. {
  71227. jassert (subPath.size() > 0);
  71228. const LineSection& firstLine = subPath.getReference (0);
  71229. float lastX1 = firstLine.lx1;
  71230. float lastY1 = firstLine.ly1;
  71231. float lastX2 = firstLine.lx2;
  71232. float lastY2 = firstLine.ly2;
  71233. if (isClosed)
  71234. {
  71235. destPath.startNewSubPath (lastX1, lastY1);
  71236. }
  71237. else
  71238. {
  71239. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  71240. addLineEnd (destPath, endStyle,
  71241. firstLine.rx2, firstLine.ry2,
  71242. lastX1, lastY1,
  71243. width);
  71244. }
  71245. int i;
  71246. for (i = 1; i < subPath.size(); ++i)
  71247. {
  71248. const LineSection& l = subPath.getReference (i);
  71249. addEdgeAndJoint (destPath, jointStyle,
  71250. maxMiterExtensionSquared, width,
  71251. lastX1, lastY1, lastX2, lastY2,
  71252. l.lx1, l.ly1, l.lx2, l.ly2,
  71253. l.x1, l.y1);
  71254. lastX1 = l.lx1;
  71255. lastY1 = l.ly1;
  71256. lastX2 = l.lx2;
  71257. lastY2 = l.ly2;
  71258. }
  71259. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  71260. if (isClosed)
  71261. {
  71262. const LineSection& l = subPath.getReference (0);
  71263. addEdgeAndJoint (destPath, jointStyle,
  71264. maxMiterExtensionSquared, width,
  71265. lastX1, lastY1, lastX2, lastY2,
  71266. l.lx1, l.ly1, l.lx2, l.ly2,
  71267. l.x1, l.y1);
  71268. destPath.closeSubPath();
  71269. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  71270. }
  71271. else
  71272. {
  71273. destPath.lineTo (lastX2, lastY2);
  71274. addLineEnd (destPath, endStyle,
  71275. lastX2, lastY2,
  71276. lastLine.rx1, lastLine.ry1,
  71277. width);
  71278. }
  71279. lastX1 = lastLine.rx1;
  71280. lastY1 = lastLine.ry1;
  71281. lastX2 = lastLine.rx2;
  71282. lastY2 = lastLine.ry2;
  71283. for (i = subPath.size() - 1; --i >= 0;)
  71284. {
  71285. const LineSection& l = subPath.getReference (i);
  71286. addEdgeAndJoint (destPath, jointStyle,
  71287. maxMiterExtensionSquared, width,
  71288. lastX1, lastY1, lastX2, lastY2,
  71289. l.rx1, l.ry1, l.rx2, l.ry2,
  71290. l.x2, l.y2);
  71291. lastX1 = l.rx1;
  71292. lastY1 = l.ry1;
  71293. lastX2 = l.rx2;
  71294. lastY2 = l.ry2;
  71295. }
  71296. if (isClosed)
  71297. {
  71298. addEdgeAndJoint (destPath, jointStyle,
  71299. maxMiterExtensionSquared, width,
  71300. lastX1, lastY1, lastX2, lastY2,
  71301. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  71302. lastLine.x2, lastLine.y2);
  71303. }
  71304. else
  71305. {
  71306. // do the last line
  71307. destPath.lineTo (lastX2, lastY2);
  71308. }
  71309. destPath.closeSubPath();
  71310. }
  71311. void PathStrokeType::createStrokedPath (Path& destPath,
  71312. const Path& source,
  71313. const AffineTransform& transform,
  71314. const float extraAccuracy) const throw()
  71315. {
  71316. if (thickness <= 0)
  71317. {
  71318. destPath.clear();
  71319. return;
  71320. }
  71321. const Path* sourcePath = &source;
  71322. Path temp;
  71323. if (sourcePath == &destPath)
  71324. {
  71325. destPath.swapWithPath (temp);
  71326. sourcePath = &temp;
  71327. }
  71328. else
  71329. {
  71330. destPath.clear();
  71331. }
  71332. destPath.setUsingNonZeroWinding (true);
  71333. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  71334. const float width = 0.5f * thickness;
  71335. // Iterate the path, creating a list of the
  71336. // left/right-hand lines along either side of it...
  71337. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  71338. Array <LineSection> subPath;
  71339. LineSection l;
  71340. l.x1 = 0;
  71341. l.y1 = 0;
  71342. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  71343. while (it.next())
  71344. {
  71345. if (it.subPathIndex == 0)
  71346. {
  71347. if (subPath.size() > 0)
  71348. {
  71349. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71350. subPath.clearQuick();
  71351. }
  71352. l.x1 = it.x1;
  71353. l.y1 = it.y1;
  71354. }
  71355. l.x2 = it.x2;
  71356. l.y2 = it.y2;
  71357. float dx = l.x2 - l.x1;
  71358. float dy = l.y2 - l.y1;
  71359. const float hypotSquared = dx*dx + dy*dy;
  71360. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  71361. {
  71362. const float len = sqrtf (hypotSquared);
  71363. if (len == 0)
  71364. {
  71365. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  71366. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  71367. }
  71368. else
  71369. {
  71370. const float offset = width / len;
  71371. dx *= offset;
  71372. dy *= offset;
  71373. l.rx2 = l.x1 - dy;
  71374. l.ry2 = l.y1 + dx;
  71375. l.lx1 = l.x1 + dy;
  71376. l.ly1 = l.y1 - dx;
  71377. l.lx2 = l.x2 + dy;
  71378. l.ly2 = l.y2 - dx;
  71379. l.rx1 = l.x2 - dy;
  71380. l.ry1 = l.y2 + dx;
  71381. }
  71382. subPath.add (l);
  71383. if (it.closesSubPath)
  71384. {
  71385. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71386. subPath.clearQuick();
  71387. }
  71388. else
  71389. {
  71390. l.x1 = it.x2;
  71391. l.y1 = it.y2;
  71392. }
  71393. }
  71394. }
  71395. if (subPath.size() > 0)
  71396. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71397. }
  71398. void PathStrokeType::createDashedStroke (Path& destPath,
  71399. const Path& sourcePath,
  71400. const float* dashLengths,
  71401. int numDashLengths,
  71402. const AffineTransform& transform,
  71403. const float extraAccuracy) const throw()
  71404. {
  71405. if (thickness <= 0)
  71406. return;
  71407. // this should really be an even number..
  71408. jassert ((numDashLengths & 1) == 0);
  71409. Path newDestPath;
  71410. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  71411. bool first = true;
  71412. int dashNum = 0;
  71413. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  71414. float dx = 0.0f, dy = 0.0f;
  71415. for (;;)
  71416. {
  71417. const bool isSolid = ((dashNum & 1) == 0);
  71418. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  71419. jassert (dashLen > 0); // must be a positive increment!
  71420. if (dashLen <= 0)
  71421. break;
  71422. pos += dashLen;
  71423. while (pos > lineEndPos)
  71424. {
  71425. if (! it.next())
  71426. {
  71427. if (isSolid && ! first)
  71428. newDestPath.lineTo (it.x2, it.y2);
  71429. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  71430. return;
  71431. }
  71432. if (isSolid && ! first)
  71433. newDestPath.lineTo (it.x1, it.y1);
  71434. else
  71435. newDestPath.startNewSubPath (it.x1, it.y1);
  71436. dx = it.x2 - it.x1;
  71437. dy = it.y2 - it.y1;
  71438. lineLen = juce_hypotf (dx, dy);
  71439. lineEndPos += lineLen;
  71440. first = it.closesSubPath;
  71441. }
  71442. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  71443. if (isSolid)
  71444. newDestPath.lineTo (it.x1 + dx * alpha,
  71445. it.y1 + dy * alpha);
  71446. else
  71447. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  71448. it.y1 + dy * alpha);
  71449. }
  71450. }
  71451. END_JUCE_NAMESPACE
  71452. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  71453. /********* Start of inlined file: juce_Point.cpp *********/
  71454. BEGIN_JUCE_NAMESPACE
  71455. Point::Point() throw()
  71456. : x (0.0f),
  71457. y (0.0f)
  71458. {
  71459. }
  71460. Point::Point (const Point& other) throw()
  71461. : x (other.x),
  71462. y (other.y)
  71463. {
  71464. }
  71465. const Point& Point::operator= (const Point& other) throw()
  71466. {
  71467. x = other.x;
  71468. y = other.y;
  71469. return *this;
  71470. }
  71471. Point::Point (const float x_,
  71472. const float y_) throw()
  71473. : x (x_),
  71474. y (y_)
  71475. {
  71476. }
  71477. Point::~Point() throw()
  71478. {
  71479. }
  71480. void Point::setXY (const float x_,
  71481. const float y_) throw()
  71482. {
  71483. x = x_;
  71484. y = y_;
  71485. }
  71486. void Point::applyTransform (const AffineTransform& transform) throw()
  71487. {
  71488. transform.transformPoint (x, y);
  71489. }
  71490. END_JUCE_NAMESPACE
  71491. /********* End of inlined file: juce_Point.cpp *********/
  71492. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  71493. BEGIN_JUCE_NAMESPACE
  71494. PositionedRectangle::PositionedRectangle() throw()
  71495. : x (0.0),
  71496. y (0.0),
  71497. w (0.0),
  71498. h (0.0),
  71499. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71500. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71501. wMode (absoluteSize),
  71502. hMode (absoluteSize)
  71503. {
  71504. }
  71505. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  71506. : x (other.x),
  71507. y (other.y),
  71508. w (other.w),
  71509. h (other.h),
  71510. xMode (other.xMode),
  71511. yMode (other.yMode),
  71512. wMode (other.wMode),
  71513. hMode (other.hMode)
  71514. {
  71515. }
  71516. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  71517. {
  71518. if (this != &other)
  71519. {
  71520. x = other.x;
  71521. y = other.y;
  71522. w = other.w;
  71523. h = other.h;
  71524. xMode = other.xMode;
  71525. yMode = other.yMode;
  71526. wMode = other.wMode;
  71527. hMode = other.hMode;
  71528. }
  71529. return *this;
  71530. }
  71531. PositionedRectangle::~PositionedRectangle() throw()
  71532. {
  71533. }
  71534. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  71535. {
  71536. return x == other.x
  71537. && y == other.y
  71538. && w == other.w
  71539. && h == other.h
  71540. && xMode == other.xMode
  71541. && yMode == other.yMode
  71542. && wMode == other.wMode
  71543. && hMode == other.hMode;
  71544. }
  71545. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  71546. {
  71547. return ! operator== (other);
  71548. }
  71549. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  71550. {
  71551. StringArray tokens;
  71552. tokens.addTokens (stringVersion, false);
  71553. decodePosString (tokens [0], xMode, x);
  71554. decodePosString (tokens [1], yMode, y);
  71555. decodeSizeString (tokens [2], wMode, w);
  71556. decodeSizeString (tokens [3], hMode, h);
  71557. }
  71558. const String PositionedRectangle::toString() const throw()
  71559. {
  71560. String s;
  71561. s.preallocateStorage (12);
  71562. addPosDescription (s, xMode, x);
  71563. s << T(' ');
  71564. addPosDescription (s, yMode, y);
  71565. s << T(' ');
  71566. addSizeDescription (s, wMode, w);
  71567. s << T(' ');
  71568. addSizeDescription (s, hMode, h);
  71569. return s;
  71570. }
  71571. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  71572. {
  71573. jassert (! target.isEmpty());
  71574. double x_, y_, w_, h_;
  71575. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71576. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71577. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  71578. roundDoubleToInt (w_), roundDoubleToInt (h_));
  71579. }
  71580. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  71581. double& x_, double& y_,
  71582. double& w_, double& h_) const throw()
  71583. {
  71584. jassert (! target.isEmpty());
  71585. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71586. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71587. }
  71588. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  71589. {
  71590. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  71591. }
  71592. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  71593. const Rectangle& target) throw()
  71594. {
  71595. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  71596. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  71597. }
  71598. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  71599. const double newW, const double newH,
  71600. const Rectangle& target) throw()
  71601. {
  71602. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  71603. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  71604. }
  71605. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  71606. {
  71607. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  71608. updateFrom (comp.getBounds(), Rectangle());
  71609. else
  71610. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  71611. }
  71612. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  71613. {
  71614. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71615. }
  71616. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  71617. {
  71618. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  71619. | absoluteFromParentBottomRight
  71620. | absoluteFromParentCentre
  71621. | proportionOfParentSize));
  71622. }
  71623. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  71624. {
  71625. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71626. }
  71627. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  71628. {
  71629. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  71630. | absoluteFromParentBottomRight
  71631. | absoluteFromParentCentre
  71632. | proportionOfParentSize));
  71633. }
  71634. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  71635. {
  71636. return (SizeMode) wMode;
  71637. }
  71638. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  71639. {
  71640. return (SizeMode) hMode;
  71641. }
  71642. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  71643. const PositionMode xMode_,
  71644. const AnchorPoint yAnchor,
  71645. const PositionMode yMode_,
  71646. const SizeMode widthMode,
  71647. const SizeMode heightMode,
  71648. const Rectangle& target) throw()
  71649. {
  71650. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  71651. {
  71652. double tx, tw;
  71653. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  71654. xMode = (uint8) (xAnchor | xMode_);
  71655. wMode = (uint8) widthMode;
  71656. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  71657. }
  71658. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  71659. {
  71660. double ty, th;
  71661. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  71662. yMode = (uint8) (yAnchor | yMode_);
  71663. hMode = (uint8) heightMode;
  71664. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  71665. }
  71666. }
  71667. bool PositionedRectangle::isPositionAbsolute() const throw()
  71668. {
  71669. return xMode == absoluteFromParentTopLeft
  71670. && yMode == absoluteFromParentTopLeft
  71671. && wMode == absoluteSize
  71672. && hMode == absoluteSize;
  71673. }
  71674. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  71675. {
  71676. if ((mode & proportionOfParentSize) != 0)
  71677. {
  71678. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71679. }
  71680. else
  71681. {
  71682. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71683. if ((mode & absoluteFromParentBottomRight) != 0)
  71684. s << T('R');
  71685. else if ((mode & absoluteFromParentCentre) != 0)
  71686. s << T('C');
  71687. }
  71688. if ((mode & anchorAtRightOrBottom) != 0)
  71689. s << T('r');
  71690. else if ((mode & anchorAtCentre) != 0)
  71691. s << T('c');
  71692. }
  71693. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  71694. {
  71695. if (mode == proportionalSize)
  71696. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71697. else if (mode == parentSizeMinusAbsolute)
  71698. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  71699. else
  71700. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71701. }
  71702. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  71703. {
  71704. if (s.containsChar (T('r')))
  71705. mode = anchorAtRightOrBottom;
  71706. else if (s.containsChar (T('c')))
  71707. mode = anchorAtCentre;
  71708. else
  71709. mode = anchorAtLeftOrTop;
  71710. if (s.containsChar (T('%')))
  71711. {
  71712. mode |= proportionOfParentSize;
  71713. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  71714. }
  71715. else
  71716. {
  71717. if (s.containsChar (T('R')))
  71718. mode |= absoluteFromParentBottomRight;
  71719. else if (s.containsChar (T('C')))
  71720. mode |= absoluteFromParentCentre;
  71721. else
  71722. mode |= absoluteFromParentTopLeft;
  71723. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  71724. }
  71725. }
  71726. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  71727. {
  71728. if (s.containsChar (T('%')))
  71729. {
  71730. mode = proportionalSize;
  71731. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  71732. }
  71733. else if (s.containsChar (T('M')))
  71734. {
  71735. mode = parentSizeMinusAbsolute;
  71736. value = s.getDoubleValue();
  71737. }
  71738. else
  71739. {
  71740. mode = absoluteSize;
  71741. value = s.getDoubleValue();
  71742. }
  71743. }
  71744. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  71745. const double x_, const double w_,
  71746. const uint8 xMode_, const uint8 wMode_,
  71747. const int parentPos,
  71748. const int parentSize) const throw()
  71749. {
  71750. if (wMode_ == proportionalSize)
  71751. wOut = roundDoubleToInt (w_ * parentSize);
  71752. else if (wMode_ == parentSizeMinusAbsolute)
  71753. wOut = jmax (0, parentSize - roundDoubleToInt (w_));
  71754. else
  71755. wOut = roundDoubleToInt (w_);
  71756. if ((xMode_ & proportionOfParentSize) != 0)
  71757. xOut = parentPos + x_ * parentSize;
  71758. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71759. xOut = (parentPos + parentSize) - x_;
  71760. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71761. xOut = x_ + (parentPos + parentSize / 2);
  71762. else
  71763. xOut = x_ + parentPos;
  71764. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71765. xOut -= wOut;
  71766. else if ((xMode_ & anchorAtCentre) != 0)
  71767. xOut -= wOut / 2;
  71768. }
  71769. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  71770. double x_, const double w_,
  71771. const uint8 xMode_, const uint8 wMode_,
  71772. const int parentPos,
  71773. const int parentSize) const throw()
  71774. {
  71775. if (wMode_ == proportionalSize)
  71776. {
  71777. if (parentSize > 0)
  71778. wOut = w_ / parentSize;
  71779. }
  71780. else if (wMode_ == parentSizeMinusAbsolute)
  71781. wOut = parentSize - w_;
  71782. else
  71783. wOut = w_;
  71784. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71785. x_ += w_;
  71786. else if ((xMode_ & anchorAtCentre) != 0)
  71787. x_ += w_ / 2;
  71788. if ((xMode_ & proportionOfParentSize) != 0)
  71789. {
  71790. if (parentSize > 0)
  71791. xOut = (x_ - parentPos) / parentSize;
  71792. }
  71793. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71794. xOut = (parentPos + parentSize) - x_;
  71795. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71796. xOut = x_ - (parentPos + parentSize / 2);
  71797. else
  71798. xOut = x_ - parentPos;
  71799. }
  71800. END_JUCE_NAMESPACE
  71801. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  71802. /********* Start of inlined file: juce_Rectangle.cpp *********/
  71803. BEGIN_JUCE_NAMESPACE
  71804. Rectangle::Rectangle() throw()
  71805. : x (0),
  71806. y (0),
  71807. w (0),
  71808. h (0)
  71809. {
  71810. }
  71811. Rectangle::Rectangle (const int x_, const int y_,
  71812. const int w_, const int h_) throw()
  71813. : x (x_),
  71814. y (y_),
  71815. w (w_),
  71816. h (h_)
  71817. {
  71818. }
  71819. Rectangle::Rectangle (const int w_, const int h_) throw()
  71820. : x (0),
  71821. y (0),
  71822. w (w_),
  71823. h (h_)
  71824. {
  71825. }
  71826. Rectangle::Rectangle (const Rectangle& other) throw()
  71827. : x (other.x),
  71828. y (other.y),
  71829. w (other.w),
  71830. h (other.h)
  71831. {
  71832. }
  71833. Rectangle::~Rectangle() throw()
  71834. {
  71835. }
  71836. bool Rectangle::isEmpty() const throw()
  71837. {
  71838. return w <= 0 || h <= 0;
  71839. }
  71840. void Rectangle::setBounds (const int x_,
  71841. const int y_,
  71842. const int w_,
  71843. const int h_) throw()
  71844. {
  71845. x = x_;
  71846. y = y_;
  71847. w = w_;
  71848. h = h_;
  71849. }
  71850. void Rectangle::setPosition (const int x_,
  71851. const int y_) throw()
  71852. {
  71853. x = x_;
  71854. y = y_;
  71855. }
  71856. void Rectangle::setSize (const int w_,
  71857. const int h_) throw()
  71858. {
  71859. w = w_;
  71860. h = h_;
  71861. }
  71862. void Rectangle::setLeft (const int newLeft) throw()
  71863. {
  71864. w = jmax (0, x + w - newLeft);
  71865. x = newLeft;
  71866. }
  71867. void Rectangle::setTop (const int newTop) throw()
  71868. {
  71869. h = jmax (0, y + h - newTop);
  71870. y = newTop;
  71871. }
  71872. void Rectangle::setRight (const int newRight) throw()
  71873. {
  71874. x = jmin (x, newRight);
  71875. w = newRight - x;
  71876. }
  71877. void Rectangle::setBottom (const int newBottom) throw()
  71878. {
  71879. y = jmin (y, newBottom);
  71880. h = newBottom - y;
  71881. }
  71882. void Rectangle::translate (const int dx,
  71883. const int dy) throw()
  71884. {
  71885. x += dx;
  71886. y += dy;
  71887. }
  71888. const Rectangle Rectangle::translated (const int dx,
  71889. const int dy) const throw()
  71890. {
  71891. return Rectangle (x + dx, y + dy, w, h);
  71892. }
  71893. void Rectangle::expand (const int deltaX,
  71894. const int deltaY) throw()
  71895. {
  71896. const int nw = jmax (0, w + deltaX + deltaX);
  71897. const int nh = jmax (0, h + deltaY + deltaY);
  71898. setBounds (x - deltaX,
  71899. y - deltaY,
  71900. nw, nh);
  71901. }
  71902. const Rectangle Rectangle::expanded (const int deltaX,
  71903. const int deltaY) const throw()
  71904. {
  71905. const int nw = jmax (0, w + deltaX + deltaX);
  71906. const int nh = jmax (0, h + deltaY + deltaY);
  71907. return Rectangle (x - deltaX,
  71908. y - deltaY,
  71909. nw, nh);
  71910. }
  71911. void Rectangle::reduce (const int deltaX,
  71912. const int deltaY) throw()
  71913. {
  71914. expand (-deltaX, -deltaY);
  71915. }
  71916. const Rectangle Rectangle::reduced (const int deltaX,
  71917. const int deltaY) const throw()
  71918. {
  71919. return expanded (-deltaX, -deltaY);
  71920. }
  71921. bool Rectangle::operator== (const Rectangle& other) const throw()
  71922. {
  71923. return x == other.x
  71924. && y == other.y
  71925. && w == other.w
  71926. && h == other.h;
  71927. }
  71928. bool Rectangle::operator!= (const Rectangle& other) const throw()
  71929. {
  71930. return x != other.x
  71931. || y != other.y
  71932. || w != other.w
  71933. || h != other.h;
  71934. }
  71935. bool Rectangle::contains (const int px,
  71936. const int py) const throw()
  71937. {
  71938. return px >= x
  71939. && py >= y
  71940. && px < x + w
  71941. && py < y + h;
  71942. }
  71943. bool Rectangle::contains (const Rectangle& other) const throw()
  71944. {
  71945. return x <= other.x
  71946. && y <= other.y
  71947. && x + w >= other.x + other.w
  71948. && y + h >= other.y + other.h;
  71949. }
  71950. bool Rectangle::intersects (const Rectangle& other) const throw()
  71951. {
  71952. return x + w > other.x
  71953. && y + h > other.y
  71954. && x < other.x + other.w
  71955. && y < other.y + other.h
  71956. && w > 0
  71957. && h > 0;
  71958. }
  71959. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  71960. {
  71961. const int nx = jmax (x, other.x);
  71962. const int ny = jmax (y, other.y);
  71963. const int nw = jmin (x + w, other.x + other.w) - nx;
  71964. const int nh = jmin (y + h, other.y + other.h) - ny;
  71965. if (nw >= 0 && nh >= 0)
  71966. return Rectangle (nx, ny, nw, nh);
  71967. else
  71968. return Rectangle();
  71969. }
  71970. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  71971. {
  71972. const int maxX = jmax (x1, x);
  71973. w1 = jmin (x1 + w1, x + w) - maxX;
  71974. if (w1 > 0)
  71975. {
  71976. const int maxY = jmax (y1, y);
  71977. h1 = jmin (y1 + h1, y + h) - maxY;
  71978. if (h1 > 0)
  71979. {
  71980. x1 = maxX;
  71981. y1 = maxY;
  71982. return true;
  71983. }
  71984. }
  71985. return false;
  71986. }
  71987. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  71988. int x2, int y2, int w2, int h2) throw()
  71989. {
  71990. const int x = jmax (x1, x2);
  71991. w1 = jmin (x1 + w1, x2 + w2) - x;
  71992. if (w1 > 0)
  71993. {
  71994. const int y = jmax (y1, y2);
  71995. h1 = jmin (y1 + h1, y2 + h2) - y;
  71996. if (h1 > 0)
  71997. {
  71998. x1 = x;
  71999. y1 = y;
  72000. return true;
  72001. }
  72002. }
  72003. return false;
  72004. }
  72005. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  72006. {
  72007. const int newX = jmin (x, other.x);
  72008. const int newY = jmin (y, other.y);
  72009. return Rectangle (newX, newY,
  72010. jmax (x + w, other.x + other.w) - newX,
  72011. jmax (y + h, other.y + other.h) - newY);
  72012. }
  72013. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  72014. {
  72015. if (x == other.x && getRight() == other.getRight()
  72016. && (other.getBottom() >= y && other.y <= getBottom()))
  72017. {
  72018. const int newY = jmin (y, other.y);
  72019. h = jmax (getBottom(), other.getBottom()) - newY;
  72020. y = newY;
  72021. return true;
  72022. }
  72023. else if (y == other.y && getBottom() == other.getBottom()
  72024. && (other.getRight() >= x && other.x <= getRight()))
  72025. {
  72026. const int newX = jmin (x, other.x);
  72027. w = jmax (getRight(), other.getRight()) - newX;
  72028. x = newX;
  72029. return true;
  72030. }
  72031. return false;
  72032. }
  72033. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  72034. {
  72035. int inside = 0;
  72036. const int otherR = other.getRight();
  72037. if (x >= other.x && x < otherR)
  72038. inside = 1;
  72039. const int otherB = other.getBottom();
  72040. if (y >= other.y && y < otherB)
  72041. inside |= 2;
  72042. const int r = x + w;
  72043. if (r >= other.x && r < otherR)
  72044. inside |= 4;
  72045. const int b = y + h;
  72046. if (b >= other.y && b < otherB)
  72047. inside |= 8;
  72048. switch (inside)
  72049. {
  72050. case 1 + 2 + 8:
  72051. w = r - otherR;
  72052. x = otherR;
  72053. return true;
  72054. case 1 + 2 + 4:
  72055. h = b - otherB;
  72056. y = otherB;
  72057. return true;
  72058. case 2 + 4 + 8:
  72059. w = other.x - x;
  72060. return true;
  72061. case 1 + 4 + 8:
  72062. h = other.y - y;
  72063. return true;
  72064. }
  72065. return false;
  72066. }
  72067. const String Rectangle::toString() const throw()
  72068. {
  72069. String s;
  72070. s.preallocateStorage (16);
  72071. s << x << T(' ')
  72072. << y << T(' ')
  72073. << w << T(' ')
  72074. << h;
  72075. return s;
  72076. }
  72077. const Rectangle Rectangle::fromString (const String& stringVersion)
  72078. {
  72079. StringArray toks;
  72080. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  72081. return Rectangle (toks[0].trim().getIntValue(),
  72082. toks[1].trim().getIntValue(),
  72083. toks[2].trim().getIntValue(),
  72084. toks[3].trim().getIntValue());
  72085. }
  72086. END_JUCE_NAMESPACE
  72087. /********* End of inlined file: juce_Rectangle.cpp *********/
  72088. /********* Start of inlined file: juce_RectangleList.cpp *********/
  72089. BEGIN_JUCE_NAMESPACE
  72090. RectangleList::RectangleList() throw()
  72091. {
  72092. }
  72093. RectangleList::RectangleList (const Rectangle& rect) throw()
  72094. {
  72095. if (! rect.isEmpty())
  72096. rects.add (rect);
  72097. }
  72098. RectangleList::RectangleList (const RectangleList& other) throw()
  72099. : rects (other.rects)
  72100. {
  72101. }
  72102. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  72103. {
  72104. if (this != &other)
  72105. rects = other.rects;
  72106. return *this;
  72107. }
  72108. RectangleList::~RectangleList() throw()
  72109. {
  72110. }
  72111. void RectangleList::clear() throw()
  72112. {
  72113. rects.clearQuick();
  72114. }
  72115. const Rectangle RectangleList::getRectangle (const int index) const throw()
  72116. {
  72117. if (((unsigned int) index) < (unsigned int) rects.size())
  72118. return rects.getReference (index);
  72119. return Rectangle();
  72120. }
  72121. bool RectangleList::isEmpty() const throw()
  72122. {
  72123. return rects.size() == 0;
  72124. }
  72125. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  72126. : current (0),
  72127. owner (list),
  72128. index (list.rects.size())
  72129. {
  72130. }
  72131. RectangleList::Iterator::~Iterator() throw()
  72132. {
  72133. }
  72134. bool RectangleList::Iterator::next() throw()
  72135. {
  72136. if (--index >= 0)
  72137. {
  72138. current = & (owner.rects.getReference (index));
  72139. return true;
  72140. }
  72141. return false;
  72142. }
  72143. void RectangleList::add (const Rectangle& rect) throw()
  72144. {
  72145. if (! rect.isEmpty())
  72146. {
  72147. if (rects.size() == 0)
  72148. {
  72149. rects.add (rect);
  72150. }
  72151. else
  72152. {
  72153. bool anyOverlaps = false;
  72154. int i;
  72155. for (i = rects.size(); --i >= 0;)
  72156. {
  72157. Rectangle& ourRect = rects.getReference (i);
  72158. if (rect.intersects (ourRect))
  72159. {
  72160. if (rect.contains (ourRect))
  72161. rects.remove (i);
  72162. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  72163. anyOverlaps = true;
  72164. }
  72165. }
  72166. if (anyOverlaps && rects.size() > 0)
  72167. {
  72168. RectangleList r (rect);
  72169. for (i = rects.size(); --i >= 0;)
  72170. {
  72171. const Rectangle& ourRect = rects.getReference (i);
  72172. if (rect.intersects (ourRect))
  72173. {
  72174. r.subtract (ourRect);
  72175. if (r.rects.size() == 0)
  72176. return;
  72177. }
  72178. }
  72179. for (i = r.getNumRectangles(); --i >= 0;)
  72180. rects.add (r.rects.getReference (i));
  72181. }
  72182. else
  72183. {
  72184. rects.add (rect);
  72185. }
  72186. }
  72187. }
  72188. }
  72189. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  72190. {
  72191. rects.add (rect);
  72192. }
  72193. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  72194. {
  72195. if (rects.size() == 0)
  72196. {
  72197. if (w > 0 && h > 0)
  72198. rects.add (Rectangle (x, y, w, h));
  72199. }
  72200. else
  72201. {
  72202. add (Rectangle (x, y, w, h));
  72203. }
  72204. }
  72205. void RectangleList::add (const RectangleList& other) throw()
  72206. {
  72207. for (int i = 0; i < other.rects.size(); ++i)
  72208. add (other.rects.getReference (i));
  72209. }
  72210. void RectangleList::subtract (const Rectangle& rect) throw()
  72211. {
  72212. const int originalNumRects = rects.size();
  72213. if (originalNumRects > 0)
  72214. {
  72215. const int x1 = rect.x;
  72216. const int y1 = rect.y;
  72217. const int x2 = x1 + rect.w;
  72218. const int y2 = y1 + rect.h;
  72219. for (int i = getNumRectangles(); --i >= 0;)
  72220. {
  72221. Rectangle& r = rects.getReference (i);
  72222. const int rx1 = r.x;
  72223. const int ry1 = r.y;
  72224. const int rx2 = rx1 + r.w;
  72225. const int ry2 = ry1 + r.h;
  72226. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  72227. {
  72228. if (x1 > rx1 && x1 < rx2)
  72229. {
  72230. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  72231. {
  72232. r.w = x1 - rx1;
  72233. }
  72234. else
  72235. {
  72236. r.x = x1;
  72237. r.w = rx2 - x1;
  72238. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  72239. i += 2;
  72240. }
  72241. }
  72242. else if (x2 > rx1 && x2 < rx2)
  72243. {
  72244. r.x = x2;
  72245. r.w = rx2 - x2;
  72246. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  72247. {
  72248. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  72249. i += 2;
  72250. }
  72251. }
  72252. else if (y1 > ry1 && y1 < ry2)
  72253. {
  72254. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  72255. {
  72256. r.h = y1 - ry1;
  72257. }
  72258. else
  72259. {
  72260. r.y = y1;
  72261. r.h = ry2 - y1;
  72262. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  72263. i += 2;
  72264. }
  72265. }
  72266. else if (y2 > ry1 && y2 < ry2)
  72267. {
  72268. r.y = y2;
  72269. r.h = ry2 - y2;
  72270. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  72271. {
  72272. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  72273. i += 2;
  72274. }
  72275. }
  72276. else
  72277. {
  72278. rects.remove (i);
  72279. }
  72280. }
  72281. }
  72282. if (rects.size() > originalNumRects + 10)
  72283. consolidate();
  72284. }
  72285. }
  72286. void RectangleList::subtract (const RectangleList& otherList) throw()
  72287. {
  72288. for (int i = otherList.rects.size(); --i >= 0;)
  72289. subtract (otherList.rects.getReference (i));
  72290. }
  72291. bool RectangleList::clipTo (const Rectangle& rect) throw()
  72292. {
  72293. bool notEmpty = false;
  72294. if (rect.isEmpty())
  72295. {
  72296. clear();
  72297. }
  72298. else
  72299. {
  72300. for (int i = rects.size(); --i >= 0;)
  72301. {
  72302. Rectangle& r = rects.getReference (i);
  72303. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72304. rects.remove (i);
  72305. else
  72306. notEmpty = true;
  72307. }
  72308. }
  72309. return notEmpty;
  72310. }
  72311. bool RectangleList::clipTo (const RectangleList& other) throw()
  72312. {
  72313. if (rects.size() == 0)
  72314. return false;
  72315. RectangleList result;
  72316. for (int j = 0; j < rects.size(); ++j)
  72317. {
  72318. const Rectangle& rect = rects.getReference (j);
  72319. for (int i = other.rects.size(); --i >= 0;)
  72320. {
  72321. Rectangle r (other.rects.getReference (i));
  72322. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72323. result.rects.add (r);
  72324. }
  72325. }
  72326. swapWith (result);
  72327. return ! isEmpty();
  72328. }
  72329. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  72330. {
  72331. destRegion.clear();
  72332. if (! rect.isEmpty())
  72333. {
  72334. for (int i = rects.size(); --i >= 0;)
  72335. {
  72336. Rectangle r (rects.getReference (i));
  72337. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72338. destRegion.rects.add (r);
  72339. }
  72340. }
  72341. return destRegion.rects.size() > 0;
  72342. }
  72343. void RectangleList::swapWith (RectangleList& otherList) throw()
  72344. {
  72345. rects.swapWithArray (otherList.rects);
  72346. }
  72347. void RectangleList::consolidate() throw()
  72348. {
  72349. int i;
  72350. for (i = 0; i < getNumRectangles() - 1; ++i)
  72351. {
  72352. Rectangle& r = rects.getReference (i);
  72353. const int rx1 = r.x;
  72354. const int ry1 = r.y;
  72355. const int rx2 = rx1 + r.w;
  72356. const int ry2 = ry1 + r.h;
  72357. for (int j = rects.size(); --j > i;)
  72358. {
  72359. Rectangle& r2 = rects.getReference (j);
  72360. const int jrx1 = r2.x;
  72361. const int jry1 = r2.y;
  72362. const int jrx2 = jrx1 + r2.w;
  72363. const int jry2 = jry1 + r2.h;
  72364. // if the vertical edges of any blocks are touching and their horizontals don't
  72365. // line up, split them horizontally..
  72366. if (jrx1 == rx2 || jrx2 == rx1)
  72367. {
  72368. if (jry1 > ry1 && jry1 < ry2)
  72369. {
  72370. r.h = jry1 - ry1;
  72371. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  72372. i = -1;
  72373. break;
  72374. }
  72375. if (jry2 > ry1 && jry2 < ry2)
  72376. {
  72377. r.h = jry2 - ry1;
  72378. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  72379. i = -1;
  72380. break;
  72381. }
  72382. else if (ry1 > jry1 && ry1 < jry2)
  72383. {
  72384. r2.h = ry1 - jry1;
  72385. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  72386. i = -1;
  72387. break;
  72388. }
  72389. else if (ry2 > jry1 && ry2 < jry2)
  72390. {
  72391. r2.h = ry2 - jry1;
  72392. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  72393. i = -1;
  72394. break;
  72395. }
  72396. }
  72397. }
  72398. }
  72399. for (i = 0; i < rects.size() - 1; ++i)
  72400. {
  72401. Rectangle& r = rects.getReference (i);
  72402. for (int j = rects.size(); --j > i;)
  72403. {
  72404. if (r.enlargeIfAdjacent (rects.getReference (j)))
  72405. {
  72406. rects.remove (j);
  72407. i = -1;
  72408. break;
  72409. }
  72410. }
  72411. }
  72412. }
  72413. bool RectangleList::containsPoint (const int x, const int y) const throw()
  72414. {
  72415. for (int i = getNumRectangles(); --i >= 0;)
  72416. if (rects.getReference (i).contains (x, y))
  72417. return true;
  72418. return false;
  72419. }
  72420. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  72421. {
  72422. if (rects.size() > 1)
  72423. {
  72424. RectangleList r (rectangleToCheck);
  72425. for (int i = rects.size(); --i >= 0;)
  72426. {
  72427. r.subtract (rects.getReference (i));
  72428. if (r.rects.size() == 0)
  72429. return true;
  72430. }
  72431. }
  72432. else if (rects.size() > 0)
  72433. {
  72434. return rects.getReference (0).contains (rectangleToCheck);
  72435. }
  72436. return false;
  72437. }
  72438. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  72439. {
  72440. for (int i = rects.size(); --i >= 0;)
  72441. if (rects.getReference (i).intersects (rectangleToCheck))
  72442. return true;
  72443. return false;
  72444. }
  72445. bool RectangleList::intersects (const RectangleList& other) const throw()
  72446. {
  72447. for (int i = rects.size(); --i >= 0;)
  72448. if (other.intersectsRectangle (rects.getReference (i)))
  72449. return true;
  72450. return false;
  72451. }
  72452. const Rectangle RectangleList::getBounds() const throw()
  72453. {
  72454. if (rects.size() <= 1)
  72455. {
  72456. if (rects.size() == 0)
  72457. return Rectangle();
  72458. else
  72459. return rects.getReference (0);
  72460. }
  72461. else
  72462. {
  72463. const Rectangle& r = rects.getReference (0);
  72464. int minX = r.x;
  72465. int minY = r.y;
  72466. int maxX = minX + r.w;
  72467. int maxY = minY + r.h;
  72468. for (int i = rects.size(); --i > 0;)
  72469. {
  72470. const Rectangle& r2 = rects.getReference (i);
  72471. minX = jmin (minX, r2.x);
  72472. minY = jmin (minY, r2.y);
  72473. maxX = jmax (maxX, r2.getRight());
  72474. maxY = jmax (maxY, r2.getBottom());
  72475. }
  72476. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  72477. }
  72478. }
  72479. void RectangleList::offsetAll (const int dx, const int dy) throw()
  72480. {
  72481. for (int i = rects.size(); --i >= 0;)
  72482. {
  72483. Rectangle& r = rects.getReference (i);
  72484. r.x += dx;
  72485. r.y += dy;
  72486. }
  72487. }
  72488. const Path RectangleList::toPath() const throw()
  72489. {
  72490. Path p;
  72491. for (int i = rects.size(); --i >= 0;)
  72492. {
  72493. const Rectangle& r = rects.getReference (i);
  72494. p.addRectangle ((float) r.x,
  72495. (float) r.y,
  72496. (float) r.w,
  72497. (float) r.h);
  72498. }
  72499. return p;
  72500. }
  72501. END_JUCE_NAMESPACE
  72502. /********* End of inlined file: juce_RectangleList.cpp *********/
  72503. /********* Start of inlined file: juce_Image.cpp *********/
  72504. BEGIN_JUCE_NAMESPACE
  72505. static const int fullAlphaThreshold = 253;
  72506. Image::Image (const PixelFormat format_,
  72507. const int imageWidth_,
  72508. const int imageHeight_)
  72509. : format (format_),
  72510. imageWidth (imageWidth_),
  72511. imageHeight (imageHeight_),
  72512. imageData (0)
  72513. {
  72514. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72515. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72516. // actual image will be at least 1x1.
  72517. }
  72518. Image::Image (const PixelFormat format_,
  72519. const int imageWidth_,
  72520. const int imageHeight_,
  72521. const bool clearImage)
  72522. : format (format_),
  72523. imageWidth (imageWidth_),
  72524. imageHeight (imageHeight_)
  72525. {
  72526. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72527. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72528. // actual image will be at least 1x1.
  72529. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72530. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  72531. const int dataSize = lineStride * jmax (1, imageHeight_);
  72532. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  72533. : juce_malloc (dataSize));
  72534. }
  72535. Image::Image (const Image& other)
  72536. : format (other.format),
  72537. imageWidth (other.imageWidth),
  72538. imageHeight (other.imageHeight)
  72539. {
  72540. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72541. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  72542. const int dataSize = lineStride * jmax (1, imageHeight);
  72543. imageData = (uint8*) juce_malloc (dataSize);
  72544. int ls, ps;
  72545. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72546. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  72547. other.releasePixelDataReadOnly (srcData);
  72548. }
  72549. Image::~Image()
  72550. {
  72551. juce_free (imageData);
  72552. }
  72553. LowLevelGraphicsContext* Image::createLowLevelContext()
  72554. {
  72555. return new LowLevelGraphicsSoftwareRenderer (*this);
  72556. }
  72557. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  72558. {
  72559. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72560. w = w;
  72561. h = h;
  72562. ls = lineStride;
  72563. ps = pixelStride;
  72564. return imageData + x * pixelStride + y * lineStride;
  72565. }
  72566. void Image::releasePixelDataReadWrite (void*)
  72567. {
  72568. }
  72569. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  72570. {
  72571. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72572. w = w;
  72573. h = h;
  72574. ls = lineStride;
  72575. ps = pixelStride;
  72576. return imageData + x * pixelStride + y * lineStride;
  72577. }
  72578. void Image::releasePixelDataReadOnly (const void*) const
  72579. {
  72580. }
  72581. void Image::setPixelData (int x, int y, int w, int h,
  72582. const uint8* sourcePixelData, int sourceLineStride)
  72583. {
  72584. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72585. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  72586. {
  72587. int ls, ps;
  72588. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  72589. for (int i = 0; i < h; ++i)
  72590. {
  72591. memcpy (dest + ls * i,
  72592. sourcePixelData + sourceLineStride * i,
  72593. w * pixelStride);
  72594. }
  72595. releasePixelDataReadWrite (dest);
  72596. }
  72597. }
  72598. void Image::clear (int dx, int dy, int dw, int dh,
  72599. const Colour& colourToClearTo)
  72600. {
  72601. const PixelARGB col (colourToClearTo.getPixelARGB());
  72602. int ls, ps;
  72603. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  72604. uint8* dest = dstData;
  72605. while (--dh >= 0)
  72606. {
  72607. uint8* line = dest;
  72608. dest += ls;
  72609. if (isARGB())
  72610. {
  72611. for (int x = dw; --x >= 0;)
  72612. {
  72613. ((PixelARGB*) line)->set (col);
  72614. line += ps;
  72615. }
  72616. }
  72617. else if (isRGB())
  72618. {
  72619. for (int x = dw; --x >= 0;)
  72620. {
  72621. ((PixelRGB*) line)->set (col);
  72622. line += ps;
  72623. }
  72624. }
  72625. else
  72626. {
  72627. for (int x = dw; --x >= 0;)
  72628. {
  72629. *line = col.getAlpha();
  72630. line += ps;
  72631. }
  72632. }
  72633. }
  72634. releasePixelDataReadWrite (dstData);
  72635. }
  72636. Image* Image::createCopy (int newWidth, int newHeight,
  72637. const Graphics::ResamplingQuality quality) const
  72638. {
  72639. if (newWidth < 0)
  72640. newWidth = imageWidth;
  72641. if (newHeight < 0)
  72642. newHeight = imageHeight;
  72643. Image* const newImage = new Image (format, newWidth, newHeight, true);
  72644. Graphics g (*newImage);
  72645. g.setImageResamplingQuality (quality);
  72646. g.drawImage (this,
  72647. 0, 0, newWidth, newHeight,
  72648. 0, 0, imageWidth, imageHeight,
  72649. false);
  72650. return newImage;
  72651. }
  72652. const Colour Image::getPixelAt (const int x, const int y) const
  72653. {
  72654. Colour c;
  72655. if (((unsigned int) x) < (unsigned int) imageWidth
  72656. && ((unsigned int) y) < (unsigned int) imageHeight)
  72657. {
  72658. int ls, ps;
  72659. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  72660. if (isARGB())
  72661. {
  72662. PixelARGB p (*(const PixelARGB*) pixels);
  72663. p.unpremultiply();
  72664. c = Colour (p.getARGB());
  72665. }
  72666. else if (isRGB())
  72667. c = Colour (((const PixelRGB*) pixels)->getARGB());
  72668. else
  72669. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  72670. releasePixelDataReadOnly (pixels);
  72671. }
  72672. return c;
  72673. }
  72674. void Image::setPixelAt (const int x, const int y,
  72675. const Colour& colour)
  72676. {
  72677. if (((unsigned int) x) < (unsigned int) imageWidth
  72678. && ((unsigned int) y) < (unsigned int) imageHeight)
  72679. {
  72680. int ls, ps;
  72681. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72682. const PixelARGB col (colour.getPixelARGB());
  72683. if (isARGB())
  72684. ((PixelARGB*) pixels)->set (col);
  72685. else if (isRGB())
  72686. ((PixelRGB*) pixels)->set (col);
  72687. else
  72688. *pixels = col.getAlpha();
  72689. releasePixelDataReadWrite (pixels);
  72690. }
  72691. }
  72692. void Image::multiplyAlphaAt (const int x, const int y,
  72693. const float multiplier)
  72694. {
  72695. if (((unsigned int) x) < (unsigned int) imageWidth
  72696. && ((unsigned int) y) < (unsigned int) imageHeight
  72697. && hasAlphaChannel())
  72698. {
  72699. int ls, ps;
  72700. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72701. if (isARGB())
  72702. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  72703. else
  72704. *pixels = (uint8) (*pixels * multiplier);
  72705. releasePixelDataReadWrite (pixels);
  72706. }
  72707. }
  72708. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  72709. {
  72710. if (hasAlphaChannel())
  72711. {
  72712. int ls, ps;
  72713. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72714. if (isARGB())
  72715. {
  72716. for (int y = 0; y < imageHeight; ++y)
  72717. {
  72718. uint8* p = pixels + y * ls;
  72719. for (int x = 0; x < imageWidth; ++x)
  72720. {
  72721. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  72722. p += ps;
  72723. }
  72724. }
  72725. }
  72726. else
  72727. {
  72728. for (int y = 0; y < imageHeight; ++y)
  72729. {
  72730. uint8* p = pixels + y * ls;
  72731. for (int x = 0; x < imageWidth; ++x)
  72732. {
  72733. *p = (uint8) (*p * amountToMultiplyBy);
  72734. p += ps;
  72735. }
  72736. }
  72737. }
  72738. releasePixelDataReadWrite (pixels);
  72739. }
  72740. else
  72741. {
  72742. jassertfalse // can't do this without an alpha-channel!
  72743. }
  72744. }
  72745. void Image::desaturate()
  72746. {
  72747. if (isARGB() || isRGB())
  72748. {
  72749. int ls, ps;
  72750. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72751. if (isARGB())
  72752. {
  72753. for (int y = 0; y < imageHeight; ++y)
  72754. {
  72755. uint8* p = pixels + y * ls;
  72756. for (int x = 0; x < imageWidth; ++x)
  72757. {
  72758. ((PixelARGB*) p)->desaturate();
  72759. p += ps;
  72760. }
  72761. }
  72762. }
  72763. else
  72764. {
  72765. for (int y = 0; y < imageHeight; ++y)
  72766. {
  72767. uint8* p = pixels + y * ls;
  72768. for (int x = 0; x < imageWidth; ++x)
  72769. {
  72770. ((PixelRGB*) p)->desaturate();
  72771. p += ps;
  72772. }
  72773. }
  72774. }
  72775. releasePixelDataReadWrite (pixels);
  72776. }
  72777. }
  72778. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  72779. {
  72780. if (hasAlphaChannel())
  72781. {
  72782. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  72783. SparseSet <int> pixelsOnRow;
  72784. int ls, ps;
  72785. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72786. for (int y = 0; y < imageHeight; ++y)
  72787. {
  72788. pixelsOnRow.clear();
  72789. const uint8* lineData = pixels + ls * y;
  72790. if (isARGB())
  72791. {
  72792. for (int x = 0; x < imageWidth; ++x)
  72793. {
  72794. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  72795. pixelsOnRow.addRange (x, 1);
  72796. lineData += ps;
  72797. }
  72798. }
  72799. else
  72800. {
  72801. for (int x = 0; x < imageWidth; ++x)
  72802. {
  72803. if (*lineData >= threshold)
  72804. pixelsOnRow.addRange (x, 1);
  72805. lineData += ps;
  72806. }
  72807. }
  72808. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  72809. {
  72810. int x, w;
  72811. if (pixelsOnRow.getRange (i, x, w))
  72812. result.add (Rectangle (x, y, w, 1));
  72813. }
  72814. result.consolidate();
  72815. }
  72816. releasePixelDataReadOnly (pixels);
  72817. }
  72818. else
  72819. {
  72820. result.add (0, 0, imageWidth, imageHeight);
  72821. }
  72822. }
  72823. void Image::moveImageSection (int dx, int dy,
  72824. int sx, int sy,
  72825. int w, int h)
  72826. {
  72827. if (dx < 0)
  72828. {
  72829. w += dx;
  72830. sx -= dx;
  72831. dx = 0;
  72832. }
  72833. if (dy < 0)
  72834. {
  72835. h += dy;
  72836. sy -= dy;
  72837. dy = 0;
  72838. }
  72839. if (sx < 0)
  72840. {
  72841. w += sx;
  72842. dx -= sx;
  72843. sx = 0;
  72844. }
  72845. if (sy < 0)
  72846. {
  72847. h += sy;
  72848. dy -= sy;
  72849. sy = 0;
  72850. }
  72851. const int minX = jmin (dx, sx);
  72852. const int minY = jmin (dy, sy);
  72853. w = jmin (w, getWidth() - jmax (sx, dx));
  72854. h = jmin (h, getHeight() - jmax (sy, dy));
  72855. if (w > 0 && h > 0)
  72856. {
  72857. const int maxX = jmax (dx, sx) + w;
  72858. const int maxY = jmax (dy, sy) + h;
  72859. int ls, ps;
  72860. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  72861. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  72862. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  72863. const int lineSize = ps * w;
  72864. if (dy > sy)
  72865. {
  72866. while (--h >= 0)
  72867. {
  72868. const int offset = h * ls;
  72869. memmove (dst + offset, src + offset, lineSize);
  72870. }
  72871. }
  72872. else if (dst != src)
  72873. {
  72874. while (--h >= 0)
  72875. {
  72876. memmove (dst, src, lineSize);
  72877. dst += ls;
  72878. src += ls;
  72879. }
  72880. }
  72881. releasePixelDataReadWrite (pixels);
  72882. }
  72883. }
  72884. END_JUCE_NAMESPACE
  72885. /********* End of inlined file: juce_Image.cpp *********/
  72886. /********* Start of inlined file: juce_ImageCache.cpp *********/
  72887. BEGIN_JUCE_NAMESPACE
  72888. struct CachedImageInfo
  72889. {
  72890. Image* image;
  72891. int64 hashCode;
  72892. int refCount;
  72893. unsigned int releaseTime;
  72894. juce_UseDebuggingNewOperator
  72895. };
  72896. static ImageCache* instance = 0;
  72897. static int cacheTimeout = 5000;
  72898. ImageCache::ImageCache() throw()
  72899. : images (4)
  72900. {
  72901. }
  72902. ImageCache::~ImageCache()
  72903. {
  72904. const ScopedLock sl (lock);
  72905. for (int i = images.size(); --i >= 0;)
  72906. {
  72907. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  72908. delete ci->image;
  72909. delete ci;
  72910. }
  72911. images.clear();
  72912. jassert (instance == this);
  72913. instance = 0;
  72914. }
  72915. Image* ImageCache::getFromHashCode (const int64 hashCode)
  72916. {
  72917. if (instance != 0)
  72918. {
  72919. const ScopedLock sl (instance->lock);
  72920. for (int i = instance->images.size(); --i >= 0;)
  72921. {
  72922. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72923. if (ci->hashCode == hashCode)
  72924. {
  72925. atomicIncrement (ci->refCount);
  72926. return ci->image;
  72927. }
  72928. }
  72929. }
  72930. return 0;
  72931. }
  72932. void ImageCache::addImageToCache (Image* const image,
  72933. const int64 hashCode)
  72934. {
  72935. if (image != 0)
  72936. {
  72937. if (instance == 0)
  72938. instance = new ImageCache();
  72939. CachedImageInfo* const newC = new CachedImageInfo();
  72940. newC->hashCode = hashCode;
  72941. newC->image = image;
  72942. newC->refCount = 1;
  72943. newC->releaseTime = 0;
  72944. const ScopedLock sl (instance->lock);
  72945. instance->images.add (newC);
  72946. }
  72947. }
  72948. void ImageCache::release (Image* const imageToRelease)
  72949. {
  72950. if (imageToRelease != 0 && instance != 0)
  72951. {
  72952. const ScopedLock sl (instance->lock);
  72953. for (int i = instance->images.size(); --i >= 0;)
  72954. {
  72955. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72956. if (ci->image == imageToRelease)
  72957. {
  72958. if (--(ci->refCount) == 0)
  72959. ci->releaseTime = Time::getApproximateMillisecondCounter();
  72960. if (! instance->isTimerRunning())
  72961. instance->startTimer (999);
  72962. break;
  72963. }
  72964. }
  72965. }
  72966. }
  72967. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  72968. {
  72969. if (instance != 0)
  72970. {
  72971. const ScopedLock sl (instance->lock);
  72972. for (int i = instance->images.size(); --i >= 0;)
  72973. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  72974. return true;
  72975. }
  72976. return false;
  72977. }
  72978. void ImageCache::incReferenceCount (Image* const image)
  72979. {
  72980. if (instance != 0)
  72981. {
  72982. const ScopedLock sl (instance->lock);
  72983. for (int i = instance->images.size(); --i >= 0;)
  72984. {
  72985. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72986. if (ci->image == image)
  72987. {
  72988. ci->refCount++;
  72989. return;
  72990. }
  72991. }
  72992. }
  72993. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  72994. }
  72995. void ImageCache::timerCallback()
  72996. {
  72997. int numberStillNeedingReleasing = 0;
  72998. const unsigned int now = Time::getApproximateMillisecondCounter();
  72999. const ScopedLock sl (lock);
  73000. for (int i = images.size(); --i >= 0;)
  73001. {
  73002. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  73003. if (ci->refCount <= 0)
  73004. {
  73005. if (now > ci->releaseTime + cacheTimeout
  73006. || now < ci->releaseTime - 1000)
  73007. {
  73008. images.remove (i);
  73009. delete ci->image;
  73010. delete ci;
  73011. }
  73012. else
  73013. {
  73014. ++numberStillNeedingReleasing;
  73015. }
  73016. }
  73017. }
  73018. if (numberStillNeedingReleasing == 0)
  73019. stopTimer();
  73020. }
  73021. Image* ImageCache::getFromFile (const File& file)
  73022. {
  73023. const int64 hashCode = file.getFullPathName().hashCode64();
  73024. Image* image = getFromHashCode (hashCode);
  73025. if (image == 0)
  73026. {
  73027. image = ImageFileFormat::loadFrom (file);
  73028. addImageToCache (image, hashCode);
  73029. }
  73030. return image;
  73031. }
  73032. Image* ImageCache::getFromMemory (const void* imageData,
  73033. const int dataSize)
  73034. {
  73035. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  73036. Image* image = getFromHashCode (hashCode);
  73037. if (image == 0)
  73038. {
  73039. image = ImageFileFormat::loadFrom (imageData, dataSize);
  73040. addImageToCache (image, hashCode);
  73041. }
  73042. return image;
  73043. }
  73044. void ImageCache::setCacheTimeout (const int millisecs)
  73045. {
  73046. cacheTimeout = millisecs;
  73047. }
  73048. END_JUCE_NAMESPACE
  73049. /********* End of inlined file: juce_ImageCache.cpp *********/
  73050. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  73051. BEGIN_JUCE_NAMESPACE
  73052. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  73053. : size (size_)
  73054. {
  73055. values = new float* [size];
  73056. for (int i = size; --i >= 0;)
  73057. values[i] = new float [size];
  73058. clear();
  73059. }
  73060. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  73061. {
  73062. for (int i = size; --i >= 0;)
  73063. delete[] values[i];
  73064. delete[] values;
  73065. }
  73066. void ImageConvolutionKernel::setKernelValue (const int x,
  73067. const int y,
  73068. const float value) throw()
  73069. {
  73070. if (((unsigned int) x) < (unsigned int) size
  73071. && ((unsigned int) y) < (unsigned int) size)
  73072. {
  73073. values[x][y] = value;
  73074. }
  73075. else
  73076. {
  73077. jassertfalse
  73078. }
  73079. }
  73080. void ImageConvolutionKernel::clear() throw()
  73081. {
  73082. for (int y = size; --y >= 0;)
  73083. for (int x = size; --x >= 0;)
  73084. values[x][y] = 0;
  73085. }
  73086. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  73087. {
  73088. double currentTotal = 0.0;
  73089. for (int y = size; --y >= 0;)
  73090. for (int x = size; --x >= 0;)
  73091. currentTotal += values[x][y];
  73092. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  73093. }
  73094. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  73095. {
  73096. for (int y = size; --y >= 0;)
  73097. for (int x = size; --x >= 0;)
  73098. values[x][y] *= multiplier;
  73099. }
  73100. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  73101. {
  73102. const double radiusFactor = -1.0 / (radius * radius * 2);
  73103. const int centre = size >> 1;
  73104. for (int y = size; --y >= 0;)
  73105. {
  73106. for (int x = size; --x >= 0;)
  73107. {
  73108. const int cx = x - centre;
  73109. const int cy = y - centre;
  73110. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  73111. }
  73112. }
  73113. setOverallSum (1.0f);
  73114. }
  73115. void ImageConvolutionKernel::applyToImage (Image& destImage,
  73116. const Image* sourceImage,
  73117. int dx,
  73118. int dy,
  73119. int dw,
  73120. int dh) const
  73121. {
  73122. Image* imageCreated = 0;
  73123. if (sourceImage == 0)
  73124. {
  73125. sourceImage = imageCreated = destImage.createCopy();
  73126. }
  73127. else
  73128. {
  73129. jassert (sourceImage->getWidth() == destImage.getWidth()
  73130. && sourceImage->getHeight() == destImage.getHeight()
  73131. && sourceImage->getFormat() == destImage.getFormat());
  73132. if (sourceImage->getWidth() != destImage.getWidth()
  73133. || sourceImage->getHeight() != destImage.getHeight()
  73134. || sourceImage->getFormat() != destImage.getFormat())
  73135. return;
  73136. }
  73137. const int imageWidth = destImage.getWidth();
  73138. const int imageHeight = destImage.getHeight();
  73139. if (dx >= imageWidth || dy >= imageHeight)
  73140. return;
  73141. if (dx + dw > imageWidth)
  73142. dw = imageWidth - dx;
  73143. if (dy + dh > imageHeight)
  73144. dh = imageHeight - dy;
  73145. const int dx2 = dx + dw;
  73146. const int dy2 = dy + dh;
  73147. int lineStride, pixelStride;
  73148. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  73149. uint8* line = pixels;
  73150. int srcLineStride, srcPixelStride;
  73151. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  73152. if (pixelStride == 4)
  73153. {
  73154. for (int y = dy; y < dy2; ++y)
  73155. {
  73156. uint8* dest = line;
  73157. line += lineStride;
  73158. for (int x = dx; x < dx2; ++x)
  73159. {
  73160. float c1 = 0;
  73161. float c2 = 0;
  73162. float c3 = 0;
  73163. float c4 = 0;
  73164. for (int yy = 0; yy < size; ++yy)
  73165. {
  73166. const int sy = y + yy - (size >> 1);
  73167. if (sy >= imageHeight)
  73168. break;
  73169. if (sy >= 0)
  73170. {
  73171. int sx = x - (size >> 1);
  73172. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  73173. for (int xx = 0; xx < size; ++xx)
  73174. {
  73175. if (sx >= imageWidth)
  73176. break;
  73177. if (sx >= 0)
  73178. {
  73179. const float kernelMult = values[xx][yy];
  73180. c1 += kernelMult * *src++;
  73181. c2 += kernelMult * *src++;
  73182. c3 += kernelMult * *src++;
  73183. c4 += kernelMult * *src++;
  73184. }
  73185. else
  73186. {
  73187. src += 4;
  73188. }
  73189. ++sx;
  73190. }
  73191. }
  73192. }
  73193. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  73194. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  73195. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  73196. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  73197. }
  73198. }
  73199. }
  73200. else if (pixelStride == 3)
  73201. {
  73202. for (int y = dy; y < dy2; ++y)
  73203. {
  73204. uint8* dest = line;
  73205. line += lineStride;
  73206. for (int x = dx; x < dx2; ++x)
  73207. {
  73208. float c1 = 0;
  73209. float c2 = 0;
  73210. float c3 = 0;
  73211. for (int yy = 0; yy < size; ++yy)
  73212. {
  73213. const int sy = y + yy - (size >> 1);
  73214. if (sy >= imageHeight)
  73215. break;
  73216. if (sy >= 0)
  73217. {
  73218. int sx = x - (size >> 1);
  73219. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  73220. for (int xx = 0; xx < size; ++xx)
  73221. {
  73222. if (sx >= imageWidth)
  73223. break;
  73224. if (sx >= 0)
  73225. {
  73226. const float kernelMult = values[xx][yy];
  73227. c1 += kernelMult * *src++;
  73228. c2 += kernelMult * *src++;
  73229. c3 += kernelMult * *src++;
  73230. }
  73231. else
  73232. {
  73233. src += 3;
  73234. }
  73235. ++sx;
  73236. }
  73237. }
  73238. }
  73239. *dest++ = (uint8) roundFloatToInt (c1);
  73240. *dest++ = (uint8) roundFloatToInt (c2);
  73241. *dest++ = (uint8) roundFloatToInt (c3);
  73242. }
  73243. }
  73244. }
  73245. sourceImage->releasePixelDataReadOnly (srcPixels);
  73246. destImage.releasePixelDataReadWrite (pixels);
  73247. if (imageCreated != 0)
  73248. delete imageCreated;
  73249. }
  73250. END_JUCE_NAMESPACE
  73251. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  73252. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  73253. BEGIN_JUCE_NAMESPACE
  73254. /********* Start of inlined file: juce_GIFLoader.h *********/
  73255. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  73256. #define __JUCE_GIFLOADER_JUCEHEADER__
  73257. #ifndef DOXYGEN
  73258. static const int maxGifCode = 1 << 12;
  73259. /**
  73260. Used internally by ImageFileFormat - don't use this class directly in your
  73261. application.
  73262. @see ImageFileFormat
  73263. */
  73264. class GIFLoader
  73265. {
  73266. public:
  73267. GIFLoader (InputStream& in);
  73268. ~GIFLoader() throw();
  73269. Image* getImage() const throw() { return image; }
  73270. private:
  73271. Image* image;
  73272. InputStream& input;
  73273. uint8 buffer [300];
  73274. uint8 palette [256][4];
  73275. bool dataBlockIsZero, fresh, finished;
  73276. int currentBit, lastBit, lastByteIndex;
  73277. int codeSize, setCodeSize;
  73278. int maxCode, maxCodeSize;
  73279. int firstcode, oldcode;
  73280. int clearCode, end_code;
  73281. int table [2] [maxGifCode];
  73282. int stack [2 * maxGifCode];
  73283. int *sp;
  73284. bool getSizeFromHeader (int& width, int& height);
  73285. bool readPalette (const int numCols);
  73286. int readDataBlock (unsigned char* dest);
  73287. int processExtension (int type, int& transparent);
  73288. int readLZWByte (bool initialise, int input_code_size);
  73289. int getCode (int code_size, bool initialise);
  73290. bool readImage (int width, int height,
  73291. int interlace, int transparent);
  73292. GIFLoader (const GIFLoader&);
  73293. const GIFLoader& operator= (const GIFLoader&);
  73294. };
  73295. #endif // DOXYGEN
  73296. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  73297. /********* End of inlined file: juce_GIFLoader.h *********/
  73298. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  73299. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  73300. PNGImageFormat::PNGImageFormat() throw() {}
  73301. PNGImageFormat::~PNGImageFormat() throw() {}
  73302. const String PNGImageFormat::getFormatName()
  73303. {
  73304. return T("PNG");
  73305. }
  73306. bool PNGImageFormat::canUnderstand (InputStream& in)
  73307. {
  73308. const int bytesNeeded = 4;
  73309. char header [bytesNeeded];
  73310. return in.read (header, bytesNeeded) == bytesNeeded
  73311. && header[1] == 'P'
  73312. && header[2] == 'N'
  73313. && header[3] == 'G';
  73314. }
  73315. Image* PNGImageFormat::decodeImage (InputStream& in)
  73316. {
  73317. return juce_loadPNGImageFromStream (in);
  73318. }
  73319. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  73320. OutputStream& destStream)
  73321. {
  73322. return juce_writePNGImageToStream (sourceImage, destStream);
  73323. }
  73324. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  73325. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  73326. JPEGImageFormat::JPEGImageFormat() throw()
  73327. : quality (-1.0f)
  73328. {
  73329. }
  73330. JPEGImageFormat::~JPEGImageFormat() throw() {}
  73331. void JPEGImageFormat::setQuality (const float newQuality)
  73332. {
  73333. quality = newQuality;
  73334. }
  73335. const String JPEGImageFormat::getFormatName()
  73336. {
  73337. return T("JPEG");
  73338. }
  73339. bool JPEGImageFormat::canUnderstand (InputStream& in)
  73340. {
  73341. const int bytesNeeded = 10;
  73342. uint8 header [bytesNeeded];
  73343. if (in.read (header, bytesNeeded) == bytesNeeded)
  73344. {
  73345. return header[0] == 0xff
  73346. && header[1] == 0xd8
  73347. && header[2] == 0xff
  73348. && (header[3] == 0xe0 || header[3] == 0xe1);
  73349. }
  73350. return false;
  73351. }
  73352. Image* JPEGImageFormat::decodeImage (InputStream& in)
  73353. {
  73354. return juce_loadJPEGImageFromStream (in);
  73355. }
  73356. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  73357. OutputStream& destStream)
  73358. {
  73359. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  73360. }
  73361. class GIFImageFormat : public ImageFileFormat
  73362. {
  73363. public:
  73364. GIFImageFormat() throw() {}
  73365. ~GIFImageFormat() throw() {}
  73366. const String getFormatName()
  73367. {
  73368. return T("GIF");
  73369. }
  73370. bool canUnderstand (InputStream& in)
  73371. {
  73372. const int bytesNeeded = 4;
  73373. char header [bytesNeeded];
  73374. return (in.read (header, bytesNeeded) == bytesNeeded)
  73375. && header[0] == 'G'
  73376. && header[1] == 'I'
  73377. && header[2] == 'F';
  73378. }
  73379. Image* decodeImage (InputStream& in)
  73380. {
  73381. GIFLoader* const loader = new GIFLoader (in);
  73382. Image* const im = loader->getImage();
  73383. delete loader;
  73384. return im;
  73385. }
  73386. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  73387. {
  73388. return false;
  73389. }
  73390. };
  73391. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  73392. {
  73393. static PNGImageFormat png;
  73394. static JPEGImageFormat jpg;
  73395. static GIFImageFormat gif;
  73396. ImageFileFormat* formats[4];
  73397. int numFormats = 0;
  73398. formats [numFormats++] = &png;
  73399. formats [numFormats++] = &jpg;
  73400. formats [numFormats++] = &gif;
  73401. const int64 streamPos = input.getPosition();
  73402. for (int i = 0; i < numFormats; ++i)
  73403. {
  73404. const bool found = formats[i]->canUnderstand (input);
  73405. input.setPosition (streamPos);
  73406. if (found)
  73407. return formats[i];
  73408. }
  73409. return 0;
  73410. }
  73411. Image* ImageFileFormat::loadFrom (InputStream& input)
  73412. {
  73413. ImageFileFormat* const format = findImageFormatForStream (input);
  73414. if (format != 0)
  73415. return format->decodeImage (input);
  73416. return 0;
  73417. }
  73418. Image* ImageFileFormat::loadFrom (const File& file)
  73419. {
  73420. InputStream* const in = file.createInputStream();
  73421. if (in != 0)
  73422. {
  73423. BufferedInputStream b (in, 8192, true);
  73424. return loadFrom (b);
  73425. }
  73426. return 0;
  73427. }
  73428. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  73429. {
  73430. if (rawData != 0 && numBytes > 4)
  73431. {
  73432. MemoryInputStream stream (rawData, numBytes, false);
  73433. return loadFrom (stream);
  73434. }
  73435. return 0;
  73436. }
  73437. END_JUCE_NAMESPACE
  73438. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  73439. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  73440. BEGIN_JUCE_NAMESPACE
  73441. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  73442. {
  73443. return (b << 8) | a;
  73444. }
  73445. GIFLoader::GIFLoader (InputStream& in)
  73446. : image (0),
  73447. input (in),
  73448. dataBlockIsZero (false),
  73449. fresh (false),
  73450. finished (false)
  73451. {
  73452. currentBit = lastBit = lastByteIndex = 0;
  73453. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  73454. firstcode = oldcode = 0;
  73455. clearCode = end_code = 0;
  73456. int imageWidth, imageHeight;
  73457. int transparent = -1;
  73458. if (! getSizeFromHeader (imageWidth, imageHeight))
  73459. return;
  73460. if ((imageWidth <= 0) || (imageHeight <= 0))
  73461. return;
  73462. unsigned char buf [16];
  73463. if (in.read (buf, 3) != 3)
  73464. return;
  73465. int numColours = 2 << (buf[0] & 7);
  73466. if ((buf[0] & 0x80) != 0)
  73467. readPalette (numColours);
  73468. for (;;)
  73469. {
  73470. if (input.read (buf, 1) != 1)
  73471. break;
  73472. if (buf[0] == ';')
  73473. break;
  73474. if (buf[0] == '!')
  73475. {
  73476. if (input.read (buf, 1) != 1)
  73477. break;
  73478. if (processExtension (buf[0], transparent) < 0)
  73479. break;
  73480. continue;
  73481. }
  73482. if (buf[0] != ',')
  73483. continue;
  73484. if (input.read (buf, 9) != 9)
  73485. break;
  73486. imageWidth = makeWord (buf[4], buf[5]);
  73487. imageHeight = makeWord (buf[6], buf[7]);
  73488. numColours = 2 << (buf[8] & 7);
  73489. if ((buf[8] & 0x80) != 0)
  73490. if (! readPalette (numColours))
  73491. break;
  73492. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  73493. imageWidth, imageHeight, (transparent >= 0));
  73494. readImage (imageWidth, imageHeight,
  73495. (buf[8] & 0x40) != 0,
  73496. transparent);
  73497. break;
  73498. }
  73499. }
  73500. GIFLoader::~GIFLoader() throw()
  73501. {
  73502. }
  73503. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  73504. {
  73505. unsigned char b [8];
  73506. if (input.read (b, 6) == 6)
  73507. {
  73508. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  73509. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  73510. {
  73511. if (input.read (b, 4) == 4)
  73512. {
  73513. w = makeWord (b[0], b[1]);
  73514. h = makeWord (b[2], b[3]);
  73515. return true;
  73516. }
  73517. }
  73518. }
  73519. return false;
  73520. }
  73521. bool GIFLoader::readPalette (const int numCols)
  73522. {
  73523. unsigned char rgb[4];
  73524. for (int i = 0; i < numCols; ++i)
  73525. {
  73526. input.read (rgb, 3);
  73527. palette [i][0] = rgb[0];
  73528. palette [i][1] = rgb[1];
  73529. palette [i][2] = rgb[2];
  73530. palette [i][3] = 0xff;
  73531. }
  73532. return true;
  73533. }
  73534. int GIFLoader::readDataBlock (unsigned char* const dest)
  73535. {
  73536. unsigned char n;
  73537. if (input.read (&n, 1) == 1)
  73538. {
  73539. dataBlockIsZero = (n == 0);
  73540. if (dataBlockIsZero || (input.read (dest, n) == n))
  73541. return n;
  73542. }
  73543. return -1;
  73544. }
  73545. int GIFLoader::processExtension (const int type, int& transparent)
  73546. {
  73547. unsigned char b [300];
  73548. int n = 0;
  73549. if (type == 0xf9)
  73550. {
  73551. n = readDataBlock (b);
  73552. if (n < 0)
  73553. return 1;
  73554. if ((b[0] & 0x1) != 0)
  73555. transparent = b[3];
  73556. }
  73557. do
  73558. {
  73559. n = readDataBlock (b);
  73560. }
  73561. while (n > 0);
  73562. return n;
  73563. }
  73564. int GIFLoader::getCode (const int codeSize, const bool initialise)
  73565. {
  73566. if (initialise)
  73567. {
  73568. currentBit = 0;
  73569. lastBit = 0;
  73570. finished = false;
  73571. return 0;
  73572. }
  73573. if ((currentBit + codeSize) >= lastBit)
  73574. {
  73575. if (finished)
  73576. return -1;
  73577. buffer[0] = buffer [lastByteIndex - 2];
  73578. buffer[1] = buffer [lastByteIndex - 1];
  73579. const int n = readDataBlock (&buffer[2]);
  73580. if (n == 0)
  73581. finished = true;
  73582. lastByteIndex = 2 + n;
  73583. currentBit = (currentBit - lastBit) + 16;
  73584. lastBit = (2 + n) * 8 ;
  73585. }
  73586. int result = 0;
  73587. int i = currentBit;
  73588. for (int j = 0; j < codeSize; ++j)
  73589. {
  73590. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  73591. ++i;
  73592. }
  73593. currentBit += codeSize;
  73594. return result;
  73595. }
  73596. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  73597. {
  73598. int code, incode, i;
  73599. if (initialise)
  73600. {
  73601. setCodeSize = inputCodeSize;
  73602. codeSize = setCodeSize + 1;
  73603. clearCode = 1 << setCodeSize;
  73604. end_code = clearCode + 1;
  73605. maxCodeSize = 2 * clearCode;
  73606. maxCode = clearCode + 2;
  73607. getCode (0, true);
  73608. fresh = true;
  73609. for (i = 0; i < clearCode; ++i)
  73610. {
  73611. table[0][i] = 0;
  73612. table[1][i] = i;
  73613. }
  73614. for (; i < maxGifCode; ++i)
  73615. {
  73616. table[0][i] = 0;
  73617. table[1][i] = 0;
  73618. }
  73619. sp = stack;
  73620. return 0;
  73621. }
  73622. else if (fresh)
  73623. {
  73624. fresh = false;
  73625. do
  73626. {
  73627. firstcode = oldcode
  73628. = getCode (codeSize, false);
  73629. }
  73630. while (firstcode == clearCode);
  73631. return firstcode;
  73632. }
  73633. if (sp > stack)
  73634. return *--sp;
  73635. while ((code = getCode (codeSize, false)) >= 0)
  73636. {
  73637. if (code == clearCode)
  73638. {
  73639. for (i = 0; i < clearCode; ++i)
  73640. {
  73641. table[0][i] = 0;
  73642. table[1][i] = i;
  73643. }
  73644. for (; i < maxGifCode; ++i)
  73645. {
  73646. table[0][i] = 0;
  73647. table[1][i] = 0;
  73648. }
  73649. codeSize = setCodeSize + 1;
  73650. maxCodeSize = 2 * clearCode;
  73651. maxCode = clearCode + 2;
  73652. sp = stack;
  73653. firstcode = oldcode = getCode (codeSize, false);
  73654. return firstcode;
  73655. }
  73656. else if (code == end_code)
  73657. {
  73658. if (dataBlockIsZero)
  73659. return -2;
  73660. unsigned char buf [260];
  73661. int n;
  73662. while ((n = readDataBlock (buf)) > 0)
  73663. {}
  73664. if (n != 0)
  73665. return -2;
  73666. }
  73667. incode = code;
  73668. if (code >= maxCode)
  73669. {
  73670. *sp++ = firstcode;
  73671. code = oldcode;
  73672. }
  73673. while (code >= clearCode)
  73674. {
  73675. *sp++ = table[1][code];
  73676. if (code == table[0][code])
  73677. return -2;
  73678. code = table[0][code];
  73679. }
  73680. *sp++ = firstcode = table[1][code];
  73681. if ((code = maxCode) < maxGifCode)
  73682. {
  73683. table[0][code] = oldcode;
  73684. table[1][code] = firstcode;
  73685. ++maxCode;
  73686. if ((maxCode >= maxCodeSize)
  73687. && (maxCodeSize < maxGifCode))
  73688. {
  73689. maxCodeSize <<= 1;
  73690. ++codeSize;
  73691. }
  73692. }
  73693. oldcode = incode;
  73694. if (sp > stack)
  73695. return *--sp;
  73696. }
  73697. return code;
  73698. }
  73699. bool GIFLoader::readImage (const int width, const int height,
  73700. const int interlace, const int transparent)
  73701. {
  73702. unsigned char c;
  73703. if (input.read (&c, 1) != 1
  73704. || readLZWByte (true, c) < 0)
  73705. return false;
  73706. if (transparent >= 0)
  73707. {
  73708. palette [transparent][0] = 0;
  73709. palette [transparent][1] = 0;
  73710. palette [transparent][2] = 0;
  73711. palette [transparent][3] = 0;
  73712. }
  73713. int index;
  73714. int xpos = 0, ypos = 0, pass = 0;
  73715. int stride, pixelStride;
  73716. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  73717. uint8* p = pixels;
  73718. const bool hasAlpha = image->hasAlphaChannel();
  73719. while ((index = readLZWByte (false, c)) >= 0)
  73720. {
  73721. const uint8* const paletteEntry = palette [index];
  73722. if (hasAlpha)
  73723. {
  73724. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  73725. paletteEntry[0],
  73726. paletteEntry[1],
  73727. paletteEntry[2]);
  73728. ((PixelARGB*) p)->premultiply();
  73729. p += pixelStride;
  73730. }
  73731. else
  73732. {
  73733. ((PixelRGB*) p)->setARGB (0,
  73734. paletteEntry[0],
  73735. paletteEntry[1],
  73736. paletteEntry[2]);
  73737. p += pixelStride;
  73738. }
  73739. ++xpos;
  73740. if (xpos == width)
  73741. {
  73742. xpos = 0;
  73743. if (interlace)
  73744. {
  73745. switch (pass)
  73746. {
  73747. case 0:
  73748. case 1:
  73749. ypos += 8;
  73750. break;
  73751. case 2:
  73752. ypos += 4;
  73753. break;
  73754. case 3:
  73755. ypos += 2;
  73756. break;
  73757. }
  73758. while (ypos >= height)
  73759. {
  73760. ++pass;
  73761. switch (pass)
  73762. {
  73763. case 1:
  73764. ypos = 4;
  73765. break;
  73766. case 2:
  73767. ypos = 2;
  73768. break;
  73769. case 3:
  73770. ypos = 1;
  73771. break;
  73772. default:
  73773. return true;
  73774. }
  73775. }
  73776. }
  73777. else
  73778. {
  73779. ++ypos;
  73780. }
  73781. p = pixels + xpos * pixelStride + ypos * stride;
  73782. }
  73783. if (ypos >= height)
  73784. break;
  73785. }
  73786. image->releasePixelDataReadWrite (pixels);
  73787. return true;
  73788. }
  73789. END_JUCE_NAMESPACE
  73790. /********* End of inlined file: juce_GIFLoader.cpp *********/
  73791. #endif
  73792. //==============================================================================
  73793. // some files include lots of library code, so leave them to the end to avoid cluttering
  73794. // up the build for the clean files.
  73795. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  73796. namespace zlibNamespace
  73797. {
  73798. #if JUCE_INCLUDE_ZLIB_CODE
  73799. #undef OS_CODE
  73800. #undef fdopen
  73801. /********* Start of inlined file: zlib.h *********/
  73802. #ifndef ZLIB_H
  73803. #define ZLIB_H
  73804. /********* Start of inlined file: zconf.h *********/
  73805. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73806. #ifndef ZCONF_H
  73807. #define ZCONF_H
  73808. // *** Just a few hacks here to make it compile nicely with Juce..
  73809. #define Z_PREFIX 1
  73810. #undef __MACTYPES__
  73811. #ifdef _MSC_VER
  73812. #pragma warning (disable : 4131 4127 4244 4267)
  73813. #endif
  73814. /*
  73815. * If you *really* need a unique prefix for all types and library functions,
  73816. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  73817. */
  73818. #ifdef Z_PREFIX
  73819. # define deflateInit_ z_deflateInit_
  73820. # define deflate z_deflate
  73821. # define deflateEnd z_deflateEnd
  73822. # define inflateInit_ z_inflateInit_
  73823. # define inflate z_inflate
  73824. # define inflateEnd z_inflateEnd
  73825. # define deflateInit2_ z_deflateInit2_
  73826. # define deflateSetDictionary z_deflateSetDictionary
  73827. # define deflateCopy z_deflateCopy
  73828. # define deflateReset z_deflateReset
  73829. # define deflateParams z_deflateParams
  73830. # define deflateBound z_deflateBound
  73831. # define deflatePrime z_deflatePrime
  73832. # define inflateInit2_ z_inflateInit2_
  73833. # define inflateSetDictionary z_inflateSetDictionary
  73834. # define inflateSync z_inflateSync
  73835. # define inflateSyncPoint z_inflateSyncPoint
  73836. # define inflateCopy z_inflateCopy
  73837. # define inflateReset z_inflateReset
  73838. # define inflateBack z_inflateBack
  73839. # define inflateBackEnd z_inflateBackEnd
  73840. # define compress z_compress
  73841. # define compress2 z_compress2
  73842. # define compressBound z_compressBound
  73843. # define uncompress z_uncompress
  73844. # define adler32 z_adler32
  73845. # define crc32 z_crc32
  73846. # define get_crc_table z_get_crc_table
  73847. # define zError z_zError
  73848. # define alloc_func z_alloc_func
  73849. # define free_func z_free_func
  73850. # define in_func z_in_func
  73851. # define out_func z_out_func
  73852. # define Byte z_Byte
  73853. # define uInt z_uInt
  73854. # define uLong z_uLong
  73855. # define Bytef z_Bytef
  73856. # define charf z_charf
  73857. # define intf z_intf
  73858. # define uIntf z_uIntf
  73859. # define uLongf z_uLongf
  73860. # define voidpf z_voidpf
  73861. # define voidp z_voidp
  73862. #endif
  73863. #if defined(__MSDOS__) && !defined(MSDOS)
  73864. # define MSDOS
  73865. #endif
  73866. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  73867. # define OS2
  73868. #endif
  73869. #if defined(_WINDOWS) && !defined(WINDOWS)
  73870. # define WINDOWS
  73871. #endif
  73872. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  73873. # ifndef WIN32
  73874. # define WIN32
  73875. # endif
  73876. #endif
  73877. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  73878. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  73879. # ifndef SYS16BIT
  73880. # define SYS16BIT
  73881. # endif
  73882. # endif
  73883. #endif
  73884. /*
  73885. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  73886. * than 64k bytes at a time (needed on systems with 16-bit int).
  73887. */
  73888. #ifdef SYS16BIT
  73889. # define MAXSEG_64K
  73890. #endif
  73891. #ifdef MSDOS
  73892. # define UNALIGNED_OK
  73893. #endif
  73894. #ifdef __STDC_VERSION__
  73895. # ifndef STDC
  73896. # define STDC
  73897. # endif
  73898. # if __STDC_VERSION__ >= 199901L
  73899. # ifndef STDC99
  73900. # define STDC99
  73901. # endif
  73902. # endif
  73903. #endif
  73904. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  73905. # define STDC
  73906. #endif
  73907. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  73908. # define STDC
  73909. #endif
  73910. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  73911. # define STDC
  73912. #endif
  73913. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  73914. # define STDC
  73915. #endif
  73916. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  73917. # define STDC
  73918. #endif
  73919. #ifndef STDC
  73920. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  73921. # define const /* note: need a more gentle solution here */
  73922. # endif
  73923. #endif
  73924. /* Some Mac compilers merge all .h files incorrectly: */
  73925. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  73926. # define NO_DUMMY_DECL
  73927. #endif
  73928. /* Maximum value for memLevel in deflateInit2 */
  73929. #ifndef MAX_MEM_LEVEL
  73930. # ifdef MAXSEG_64K
  73931. # define MAX_MEM_LEVEL 8
  73932. # else
  73933. # define MAX_MEM_LEVEL 9
  73934. # endif
  73935. #endif
  73936. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  73937. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  73938. * created by gzip. (Files created by minigzip can still be extracted by
  73939. * gzip.)
  73940. */
  73941. #ifndef MAX_WBITS
  73942. # define MAX_WBITS 15 /* 32K LZ77 window */
  73943. #endif
  73944. /* The memory requirements for deflate are (in bytes):
  73945. (1 << (windowBits+2)) + (1 << (memLevel+9))
  73946. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  73947. plus a few kilobytes for small objects. For example, if you want to reduce
  73948. the default memory requirements from 256K to 128K, compile with
  73949. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  73950. Of course this will generally degrade compression (there's no free lunch).
  73951. The memory requirements for inflate are (in bytes) 1 << windowBits
  73952. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  73953. for small objects.
  73954. */
  73955. /* Type declarations */
  73956. #ifndef OF /* function prototypes */
  73957. # ifdef STDC
  73958. # define OF(args) args
  73959. # else
  73960. # define OF(args) ()
  73961. # endif
  73962. #endif
  73963. /* The following definitions for FAR are needed only for MSDOS mixed
  73964. * model programming (small or medium model with some far allocations).
  73965. * This was tested only with MSC; for other MSDOS compilers you may have
  73966. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  73967. * just define FAR to be empty.
  73968. */
  73969. #ifdef SYS16BIT
  73970. # if defined(M_I86SM) || defined(M_I86MM)
  73971. /* MSC small or medium model */
  73972. # define SMALL_MEDIUM
  73973. # ifdef _MSC_VER
  73974. # define FAR _far
  73975. # else
  73976. # define FAR far
  73977. # endif
  73978. # endif
  73979. # if (defined(__SMALL__) || defined(__MEDIUM__))
  73980. /* Turbo C small or medium model */
  73981. # define SMALL_MEDIUM
  73982. # ifdef __BORLANDC__
  73983. # define FAR _far
  73984. # else
  73985. # define FAR far
  73986. # endif
  73987. # endif
  73988. #endif
  73989. #if defined(WINDOWS) || defined(WIN32)
  73990. /* If building or using zlib as a DLL, define ZLIB_DLL.
  73991. * This is not mandatory, but it offers a little performance increase.
  73992. */
  73993. # ifdef ZLIB_DLL
  73994. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  73995. # ifdef ZLIB_INTERNAL
  73996. # define ZEXTERN extern __declspec(dllexport)
  73997. # else
  73998. # define ZEXTERN extern __declspec(dllimport)
  73999. # endif
  74000. # endif
  74001. # endif /* ZLIB_DLL */
  74002. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  74003. * define ZLIB_WINAPI.
  74004. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  74005. */
  74006. # ifdef ZLIB_WINAPI
  74007. # ifdef FAR
  74008. # undef FAR
  74009. # endif
  74010. # include <windows.h>
  74011. /* No need for _export, use ZLIB.DEF instead. */
  74012. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  74013. # define ZEXPORT WINAPI
  74014. # ifdef WIN32
  74015. # define ZEXPORTVA WINAPIV
  74016. # else
  74017. # define ZEXPORTVA FAR CDECL
  74018. # endif
  74019. # endif
  74020. #endif
  74021. #if defined (__BEOS__)
  74022. # ifdef ZLIB_DLL
  74023. # ifdef ZLIB_INTERNAL
  74024. # define ZEXPORT __declspec(dllexport)
  74025. # define ZEXPORTVA __declspec(dllexport)
  74026. # else
  74027. # define ZEXPORT __declspec(dllimport)
  74028. # define ZEXPORTVA __declspec(dllimport)
  74029. # endif
  74030. # endif
  74031. #endif
  74032. #ifndef ZEXTERN
  74033. # define ZEXTERN extern
  74034. #endif
  74035. #ifndef ZEXPORT
  74036. # define ZEXPORT
  74037. #endif
  74038. #ifndef ZEXPORTVA
  74039. # define ZEXPORTVA
  74040. #endif
  74041. #ifndef FAR
  74042. # define FAR
  74043. #endif
  74044. #if !defined(__MACTYPES__)
  74045. typedef unsigned char Byte; /* 8 bits */
  74046. #endif
  74047. typedef unsigned int uInt; /* 16 bits or more */
  74048. typedef unsigned long uLong; /* 32 bits or more */
  74049. #ifdef SMALL_MEDIUM
  74050. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  74051. # define Bytef Byte FAR
  74052. #else
  74053. typedef Byte FAR Bytef;
  74054. #endif
  74055. typedef char FAR charf;
  74056. typedef int FAR intf;
  74057. typedef uInt FAR uIntf;
  74058. typedef uLong FAR uLongf;
  74059. #ifdef STDC
  74060. typedef void const *voidpc;
  74061. typedef void FAR *voidpf;
  74062. typedef void *voidp;
  74063. #else
  74064. typedef Byte const *voidpc;
  74065. typedef Byte FAR *voidpf;
  74066. typedef Byte *voidp;
  74067. #endif
  74068. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  74069. # include <sys/types.h> /* for off_t */
  74070. # include <unistd.h> /* for SEEK_* and off_t */
  74071. # ifdef VMS
  74072. # include <unixio.h> /* for off_t */
  74073. # endif
  74074. # define z_off_t off_t
  74075. #endif
  74076. #ifndef SEEK_SET
  74077. # define SEEK_SET 0 /* Seek from beginning of file. */
  74078. # define SEEK_CUR 1 /* Seek from current position. */
  74079. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  74080. #endif
  74081. #ifndef z_off_t
  74082. # define z_off_t long
  74083. #endif
  74084. #if defined(__OS400__)
  74085. # define NO_vsnprintf
  74086. #endif
  74087. #if defined(__MVS__)
  74088. # define NO_vsnprintf
  74089. # ifdef FAR
  74090. # undef FAR
  74091. # endif
  74092. #endif
  74093. /* MVS linker does not support external names larger than 8 bytes */
  74094. #if defined(__MVS__)
  74095. # pragma map(deflateInit_,"DEIN")
  74096. # pragma map(deflateInit2_,"DEIN2")
  74097. # pragma map(deflateEnd,"DEEND")
  74098. # pragma map(deflateBound,"DEBND")
  74099. # pragma map(inflateInit_,"ININ")
  74100. # pragma map(inflateInit2_,"ININ2")
  74101. # pragma map(inflateEnd,"INEND")
  74102. # pragma map(inflateSync,"INSY")
  74103. # pragma map(inflateSetDictionary,"INSEDI")
  74104. # pragma map(compressBound,"CMBND")
  74105. # pragma map(inflate_table,"INTABL")
  74106. # pragma map(inflate_fast,"INFA")
  74107. # pragma map(inflate_copyright,"INCOPY")
  74108. #endif
  74109. #endif /* ZCONF_H */
  74110. /********* End of inlined file: zconf.h *********/
  74111. #ifdef __cplusplus
  74112. extern "C" {
  74113. #endif
  74114. #define ZLIB_VERSION "1.2.3"
  74115. #define ZLIB_VERNUM 0x1230
  74116. /*
  74117. The 'zlib' compression library provides in-memory compression and
  74118. decompression functions, including integrity checks of the uncompressed
  74119. data. This version of the library supports only one compression method
  74120. (deflation) but other algorithms will be added later and will have the same
  74121. stream interface.
  74122. Compression can be done in a single step if the buffers are large
  74123. enough (for example if an input file is mmap'ed), or can be done by
  74124. repeated calls of the compression function. In the latter case, the
  74125. application must provide more input and/or consume the output
  74126. (providing more output space) before each call.
  74127. The compressed data format used by default by the in-memory functions is
  74128. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  74129. around a deflate stream, which is itself documented in RFC 1951.
  74130. The library also supports reading and writing files in gzip (.gz) format
  74131. with an interface similar to that of stdio using the functions that start
  74132. with "gz". The gzip format is different from the zlib format. gzip is a
  74133. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  74134. This library can optionally read and write gzip streams in memory as well.
  74135. The zlib format was designed to be compact and fast for use in memory
  74136. and on communications channels. The gzip format was designed for single-
  74137. file compression on file systems, has a larger header than zlib to maintain
  74138. directory information, and uses a different, slower check method than zlib.
  74139. The library does not install any signal handler. The decoder checks
  74140. the consistency of the compressed data, so the library should never
  74141. crash even in case of corrupted input.
  74142. */
  74143. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  74144. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  74145. struct internal_state;
  74146. typedef struct z_stream_s {
  74147. Bytef *next_in; /* next input byte */
  74148. uInt avail_in; /* number of bytes available at next_in */
  74149. uLong total_in; /* total nb of input bytes read so far */
  74150. Bytef *next_out; /* next output byte should be put there */
  74151. uInt avail_out; /* remaining free space at next_out */
  74152. uLong total_out; /* total nb of bytes output so far */
  74153. char *msg; /* last error message, NULL if no error */
  74154. struct internal_state FAR *state; /* not visible by applications */
  74155. alloc_func zalloc; /* used to allocate the internal state */
  74156. free_func zfree; /* used to free the internal state */
  74157. voidpf opaque; /* private data object passed to zalloc and zfree */
  74158. int data_type; /* best guess about the data type: binary or text */
  74159. uLong adler; /* adler32 value of the uncompressed data */
  74160. uLong reserved; /* reserved for future use */
  74161. } z_stream;
  74162. typedef z_stream FAR *z_streamp;
  74163. /*
  74164. gzip header information passed to and from zlib routines. See RFC 1952
  74165. for more details on the meanings of these fields.
  74166. */
  74167. typedef struct gz_header_s {
  74168. int text; /* true if compressed data believed to be text */
  74169. uLong time; /* modification time */
  74170. int xflags; /* extra flags (not used when writing a gzip file) */
  74171. int os; /* operating system */
  74172. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  74173. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  74174. uInt extra_max; /* space at extra (only when reading header) */
  74175. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  74176. uInt name_max; /* space at name (only when reading header) */
  74177. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  74178. uInt comm_max; /* space at comment (only when reading header) */
  74179. int hcrc; /* true if there was or will be a header crc */
  74180. int done; /* true when done reading gzip header (not used
  74181. when writing a gzip file) */
  74182. } gz_header;
  74183. typedef gz_header FAR *gz_headerp;
  74184. /*
  74185. The application must update next_in and avail_in when avail_in has
  74186. dropped to zero. It must update next_out and avail_out when avail_out
  74187. has dropped to zero. The application must initialize zalloc, zfree and
  74188. opaque before calling the init function. All other fields are set by the
  74189. compression library and must not be updated by the application.
  74190. The opaque value provided by the application will be passed as the first
  74191. parameter for calls of zalloc and zfree. This can be useful for custom
  74192. memory management. The compression library attaches no meaning to the
  74193. opaque value.
  74194. zalloc must return Z_NULL if there is not enough memory for the object.
  74195. If zlib is used in a multi-threaded application, zalloc and zfree must be
  74196. thread safe.
  74197. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  74198. exactly 65536 bytes, but will not be required to allocate more than this
  74199. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  74200. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  74201. have their offset normalized to zero. The default allocation function
  74202. provided by this library ensures this (see zutil.c). To reduce memory
  74203. requirements and avoid any allocation of 64K objects, at the expense of
  74204. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  74205. The fields total_in and total_out can be used for statistics or
  74206. progress reports. After compression, total_in holds the total size of
  74207. the uncompressed data and may be saved for use in the decompressor
  74208. (particularly if the decompressor wants to decompress everything in
  74209. a single step).
  74210. */
  74211. /* constants */
  74212. #define Z_NO_FLUSH 0
  74213. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  74214. #define Z_SYNC_FLUSH 2
  74215. #define Z_FULL_FLUSH 3
  74216. #define Z_FINISH 4
  74217. #define Z_BLOCK 5
  74218. /* Allowed flush values; see deflate() and inflate() below for details */
  74219. #define Z_OK 0
  74220. #define Z_STREAM_END 1
  74221. #define Z_NEED_DICT 2
  74222. #define Z_ERRNO (-1)
  74223. #define Z_STREAM_ERROR (-2)
  74224. #define Z_DATA_ERROR (-3)
  74225. #define Z_MEM_ERROR (-4)
  74226. #define Z_BUF_ERROR (-5)
  74227. #define Z_VERSION_ERROR (-6)
  74228. /* Return codes for the compression/decompression functions. Negative
  74229. * values are errors, positive values are used for special but normal events.
  74230. */
  74231. #define Z_NO_COMPRESSION 0
  74232. #define Z_BEST_SPEED 1
  74233. #define Z_BEST_COMPRESSION 9
  74234. #define Z_DEFAULT_COMPRESSION (-1)
  74235. /* compression levels */
  74236. #define Z_FILTERED 1
  74237. #define Z_HUFFMAN_ONLY 2
  74238. #define Z_RLE 3
  74239. #define Z_FIXED 4
  74240. #define Z_DEFAULT_STRATEGY 0
  74241. /* compression strategy; see deflateInit2() below for details */
  74242. #define Z_BINARY 0
  74243. #define Z_TEXT 1
  74244. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  74245. #define Z_UNKNOWN 2
  74246. /* Possible values of the data_type field (though see inflate()) */
  74247. #define Z_DEFLATED 8
  74248. /* The deflate compression method (the only one supported in this version) */
  74249. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  74250. #define zlib_version zlibVersion()
  74251. /* for compatibility with versions < 1.0.2 */
  74252. /* basic functions */
  74253. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  74254. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  74255. If the first character differs, the library code actually used is
  74256. not compatible with the zlib.h header file used by the application.
  74257. This check is automatically made by deflateInit and inflateInit.
  74258. */
  74259. /*
  74260. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  74261. Initializes the internal stream state for compression. The fields
  74262. zalloc, zfree and opaque must be initialized before by the caller.
  74263. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  74264. use default allocation functions.
  74265. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  74266. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  74267. all (the input data is simply copied a block at a time).
  74268. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  74269. compression (currently equivalent to level 6).
  74270. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  74271. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  74272. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  74273. with the version assumed by the caller (ZLIB_VERSION).
  74274. msg is set to null if there is no error message. deflateInit does not
  74275. perform any compression: this will be done by deflate().
  74276. */
  74277. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  74278. /*
  74279. deflate compresses as much data as possible, and stops when the input
  74280. buffer becomes empty or the output buffer becomes full. It may introduce some
  74281. output latency (reading input without producing any output) except when
  74282. forced to flush.
  74283. The detailed semantics are as follows. deflate performs one or both of the
  74284. following actions:
  74285. - Compress more input starting at next_in and update next_in and avail_in
  74286. accordingly. If not all input can be processed (because there is not
  74287. enough room in the output buffer), next_in and avail_in are updated and
  74288. processing will resume at this point for the next call of deflate().
  74289. - Provide more output starting at next_out and update next_out and avail_out
  74290. accordingly. This action is forced if the parameter flush is non zero.
  74291. Forcing flush frequently degrades the compression ratio, so this parameter
  74292. should be set only when necessary (in interactive applications).
  74293. Some output may be provided even if flush is not set.
  74294. Before the call of deflate(), the application should ensure that at least
  74295. one of the actions is possible, by providing more input and/or consuming
  74296. more output, and updating avail_in or avail_out accordingly; avail_out
  74297. should never be zero before the call. The application can consume the
  74298. compressed output when it wants, for example when the output buffer is full
  74299. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  74300. and with zero avail_out, it must be called again after making room in the
  74301. output buffer because there might be more output pending.
  74302. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  74303. decide how much data to accumualte before producing output, in order to
  74304. maximize compression.
  74305. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  74306. flushed to the output buffer and the output is aligned on a byte boundary, so
  74307. that the decompressor can get all input data available so far. (In particular
  74308. avail_in is zero after the call if enough output space has been provided
  74309. before the call.) Flushing may degrade compression for some compression
  74310. algorithms and so it should be used only when necessary.
  74311. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  74312. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  74313. restart from this point if previous compressed data has been damaged or if
  74314. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  74315. compression.
  74316. If deflate returns with avail_out == 0, this function must be called again
  74317. with the same value of the flush parameter and more output space (updated
  74318. avail_out), until the flush is complete (deflate returns with non-zero
  74319. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  74320. avail_out is greater than six to avoid repeated flush markers due to
  74321. avail_out == 0 on return.
  74322. If the parameter flush is set to Z_FINISH, pending input is processed,
  74323. pending output is flushed and deflate returns with Z_STREAM_END if there
  74324. was enough output space; if deflate returns with Z_OK, this function must be
  74325. called again with Z_FINISH and more output space (updated avail_out) but no
  74326. more input data, until it returns with Z_STREAM_END or an error. After
  74327. deflate has returned Z_STREAM_END, the only possible operations on the
  74328. stream are deflateReset or deflateEnd.
  74329. Z_FINISH can be used immediately after deflateInit if all the compression
  74330. is to be done in a single step. In this case, avail_out must be at least
  74331. the value returned by deflateBound (see below). If deflate does not return
  74332. Z_STREAM_END, then it must be called again as described above.
  74333. deflate() sets strm->adler to the adler32 checksum of all input read
  74334. so far (that is, total_in bytes).
  74335. deflate() may update strm->data_type if it can make a good guess about
  74336. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  74337. binary. This field is only for information purposes and does not affect
  74338. the compression algorithm in any manner.
  74339. deflate() returns Z_OK if some progress has been made (more input
  74340. processed or more output produced), Z_STREAM_END if all input has been
  74341. consumed and all output has been produced (only when flush is set to
  74342. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  74343. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  74344. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  74345. fatal, and deflate() can be called again with more input and more output
  74346. space to continue compressing.
  74347. */
  74348. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  74349. /*
  74350. All dynamically allocated data structures for this stream are freed.
  74351. This function discards any unprocessed input and does not flush any
  74352. pending output.
  74353. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  74354. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  74355. prematurely (some input or output was discarded). In the error case,
  74356. msg may be set but then points to a static string (which must not be
  74357. deallocated).
  74358. */
  74359. /*
  74360. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  74361. Initializes the internal stream state for decompression. The fields
  74362. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  74363. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  74364. value depends on the compression method), inflateInit determines the
  74365. compression method from the zlib header and allocates all data structures
  74366. accordingly; otherwise the allocation will be deferred to the first call of
  74367. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  74368. use default allocation functions.
  74369. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74370. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  74371. version assumed by the caller. msg is set to null if there is no error
  74372. message. inflateInit does not perform any decompression apart from reading
  74373. the zlib header if present: this will be done by inflate(). (So next_in and
  74374. avail_in may be modified, but next_out and avail_out are unchanged.)
  74375. */
  74376. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  74377. /*
  74378. inflate decompresses as much data as possible, and stops when the input
  74379. buffer becomes empty or the output buffer becomes full. It may introduce
  74380. some output latency (reading input without producing any output) except when
  74381. forced to flush.
  74382. The detailed semantics are as follows. inflate performs one or both of the
  74383. following actions:
  74384. - Decompress more input starting at next_in and update next_in and avail_in
  74385. accordingly. If not all input can be processed (because there is not
  74386. enough room in the output buffer), next_in is updated and processing
  74387. will resume at this point for the next call of inflate().
  74388. - Provide more output starting at next_out and update next_out and avail_out
  74389. accordingly. inflate() provides as much output as possible, until there
  74390. is no more input data or no more space in the output buffer (see below
  74391. about the flush parameter).
  74392. Before the call of inflate(), the application should ensure that at least
  74393. one of the actions is possible, by providing more input and/or consuming
  74394. more output, and updating the next_* and avail_* values accordingly.
  74395. The application can consume the uncompressed output when it wants, for
  74396. example when the output buffer is full (avail_out == 0), or after each
  74397. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  74398. must be called again after making room in the output buffer because there
  74399. might be more output pending.
  74400. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  74401. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  74402. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  74403. if and when it gets to the next deflate block boundary. When decoding the
  74404. zlib or gzip format, this will cause inflate() to return immediately after
  74405. the header and before the first block. When doing a raw inflate, inflate()
  74406. will go ahead and process the first block, and will return when it gets to
  74407. the end of that block, or when it runs out of data.
  74408. The Z_BLOCK option assists in appending to or combining deflate streams.
  74409. Also to assist in this, on return inflate() will set strm->data_type to the
  74410. number of unused bits in the last byte taken from strm->next_in, plus 64
  74411. if inflate() is currently decoding the last block in the deflate stream,
  74412. plus 128 if inflate() returned immediately after decoding an end-of-block
  74413. code or decoding the complete header up to just before the first byte of the
  74414. deflate stream. The end-of-block will not be indicated until all of the
  74415. uncompressed data from that block has been written to strm->next_out. The
  74416. number of unused bits may in general be greater than seven, except when
  74417. bit 7 of data_type is set, in which case the number of unused bits will be
  74418. less than eight.
  74419. inflate() should normally be called until it returns Z_STREAM_END or an
  74420. error. However if all decompression is to be performed in a single step
  74421. (a single call of inflate), the parameter flush should be set to
  74422. Z_FINISH. In this case all pending input is processed and all pending
  74423. output is flushed; avail_out must be large enough to hold all the
  74424. uncompressed data. (The size of the uncompressed data may have been saved
  74425. by the compressor for this purpose.) The next operation on this stream must
  74426. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  74427. is never required, but can be used to inform inflate that a faster approach
  74428. may be used for the single inflate() call.
  74429. In this implementation, inflate() always flushes as much output as
  74430. possible to the output buffer, and always uses the faster approach on the
  74431. first call. So the only effect of the flush parameter in this implementation
  74432. is on the return value of inflate(), as noted below, or when it returns early
  74433. because Z_BLOCK is used.
  74434. If a preset dictionary is needed after this call (see inflateSetDictionary
  74435. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  74436. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  74437. strm->adler to the adler32 checksum of all output produced so far (that is,
  74438. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  74439. below. At the end of the stream, inflate() checks that its computed adler32
  74440. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  74441. only if the checksum is correct.
  74442. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  74443. deflate data. The header type is detected automatically. Any information
  74444. contained in the gzip header is not retained, so applications that need that
  74445. information should instead use raw inflate, see inflateInit2() below, or
  74446. inflateBack() and perform their own processing of the gzip header and
  74447. trailer.
  74448. inflate() returns Z_OK if some progress has been made (more input processed
  74449. or more output produced), Z_STREAM_END if the end of the compressed data has
  74450. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  74451. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  74452. corrupted (input stream not conforming to the zlib format or incorrect check
  74453. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  74454. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  74455. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  74456. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  74457. inflate() can be called again with more input and more output space to
  74458. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  74459. call inflateSync() to look for a good compression block if a partial recovery
  74460. of the data is desired.
  74461. */
  74462. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  74463. /*
  74464. All dynamically allocated data structures for this stream are freed.
  74465. This function discards any unprocessed input and does not flush any
  74466. pending output.
  74467. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  74468. was inconsistent. In the error case, msg may be set but then points to a
  74469. static string (which must not be deallocated).
  74470. */
  74471. /* Advanced functions */
  74472. /*
  74473. The following functions are needed only in some special applications.
  74474. */
  74475. /*
  74476. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  74477. int level,
  74478. int method,
  74479. int windowBits,
  74480. int memLevel,
  74481. int strategy));
  74482. This is another version of deflateInit with more compression options. The
  74483. fields next_in, zalloc, zfree and opaque must be initialized before by
  74484. the caller.
  74485. The method parameter is the compression method. It must be Z_DEFLATED in
  74486. this version of the library.
  74487. The windowBits parameter is the base two logarithm of the window size
  74488. (the size of the history buffer). It should be in the range 8..15 for this
  74489. version of the library. Larger values of this parameter result in better
  74490. compression at the expense of memory usage. The default value is 15 if
  74491. deflateInit is used instead.
  74492. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  74493. determines the window size. deflate() will then generate raw deflate data
  74494. with no zlib header or trailer, and will not compute an adler32 check value.
  74495. windowBits can also be greater than 15 for optional gzip encoding. Add
  74496. 16 to windowBits to write a simple gzip header and trailer around the
  74497. compressed data instead of a zlib wrapper. The gzip header will have no
  74498. file name, no extra data, no comment, no modification time (set to zero),
  74499. no header crc, and the operating system will be set to 255 (unknown). If a
  74500. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  74501. The memLevel parameter specifies how much memory should be allocated
  74502. for the internal compression state. memLevel=1 uses minimum memory but
  74503. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  74504. for optimal speed. The default value is 8. See zconf.h for total memory
  74505. usage as a function of windowBits and memLevel.
  74506. The strategy parameter is used to tune the compression algorithm. Use the
  74507. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  74508. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  74509. string match), or Z_RLE to limit match distances to one (run-length
  74510. encoding). Filtered data consists mostly of small values with a somewhat
  74511. random distribution. In this case, the compression algorithm is tuned to
  74512. compress them better. The effect of Z_FILTERED is to force more Huffman
  74513. coding and less string matching; it is somewhat intermediate between
  74514. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  74515. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  74516. parameter only affects the compression ratio but not the correctness of the
  74517. compressed output even if it is not set appropriately. Z_FIXED prevents the
  74518. use of dynamic Huffman codes, allowing for a simpler decoder for special
  74519. applications.
  74520. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74521. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  74522. method). msg is set to null if there is no error message. deflateInit2 does
  74523. not perform any compression: this will be done by deflate().
  74524. */
  74525. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  74526. const Bytef *dictionary,
  74527. uInt dictLength));
  74528. /*
  74529. Initializes the compression dictionary from the given byte sequence
  74530. without producing any compressed output. This function must be called
  74531. immediately after deflateInit, deflateInit2 or deflateReset, before any
  74532. call of deflate. The compressor and decompressor must use exactly the same
  74533. dictionary (see inflateSetDictionary).
  74534. The dictionary should consist of strings (byte sequences) that are likely
  74535. to be encountered later in the data to be compressed, with the most commonly
  74536. used strings preferably put towards the end of the dictionary. Using a
  74537. dictionary is most useful when the data to be compressed is short and can be
  74538. predicted with good accuracy; the data can then be compressed better than
  74539. with the default empty dictionary.
  74540. Depending on the size of the compression data structures selected by
  74541. deflateInit or deflateInit2, a part of the dictionary may in effect be
  74542. discarded, for example if the dictionary is larger than the window size in
  74543. deflate or deflate2. Thus the strings most likely to be useful should be
  74544. put at the end of the dictionary, not at the front. In addition, the
  74545. current implementation of deflate will use at most the window size minus
  74546. 262 bytes of the provided dictionary.
  74547. Upon return of this function, strm->adler is set to the adler32 value
  74548. of the dictionary; the decompressor may later use this value to determine
  74549. which dictionary has been used by the compressor. (The adler32 value
  74550. applies to the whole dictionary even if only a subset of the dictionary is
  74551. actually used by the compressor.) If a raw deflate was requested, then the
  74552. adler32 value is not computed and strm->adler is not set.
  74553. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  74554. parameter is invalid (such as NULL dictionary) or the stream state is
  74555. inconsistent (for example if deflate has already been called for this stream
  74556. or if the compression method is bsort). deflateSetDictionary does not
  74557. perform any compression: this will be done by deflate().
  74558. */
  74559. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  74560. z_streamp source));
  74561. /*
  74562. Sets the destination stream as a complete copy of the source stream.
  74563. This function can be useful when several compression strategies will be
  74564. tried, for example when there are several ways of pre-processing the input
  74565. data with a filter. The streams that will be discarded should then be freed
  74566. by calling deflateEnd. Note that deflateCopy duplicates the internal
  74567. compression state which can be quite large, so this strategy is slow and
  74568. can consume lots of memory.
  74569. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74570. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74571. (such as zalloc being NULL). msg is left unchanged in both source and
  74572. destination.
  74573. */
  74574. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  74575. /*
  74576. This function is equivalent to deflateEnd followed by deflateInit,
  74577. but does not free and reallocate all the internal compression state.
  74578. The stream will keep the same compression level and any other attributes
  74579. that may have been set by deflateInit2.
  74580. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74581. stream state was inconsistent (such as zalloc or state being NULL).
  74582. */
  74583. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  74584. int level,
  74585. int strategy));
  74586. /*
  74587. Dynamically update the compression level and compression strategy. The
  74588. interpretation of level and strategy is as in deflateInit2. This can be
  74589. used to switch between compression and straight copy of the input data, or
  74590. to switch to a different kind of input data requiring a different
  74591. strategy. If the compression level is changed, the input available so far
  74592. is compressed with the old level (and may be flushed); the new level will
  74593. take effect only at the next call of deflate().
  74594. Before the call of deflateParams, the stream state must be set as for
  74595. a call of deflate(), since the currently available input may have to
  74596. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  74597. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  74598. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  74599. if strm->avail_out was zero.
  74600. */
  74601. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  74602. int good_length,
  74603. int max_lazy,
  74604. int nice_length,
  74605. int max_chain));
  74606. /*
  74607. Fine tune deflate's internal compression parameters. This should only be
  74608. used by someone who understands the algorithm used by zlib's deflate for
  74609. searching for the best matching string, and even then only by the most
  74610. fanatic optimizer trying to squeeze out the last compressed bit for their
  74611. specific input data. Read the deflate.c source code for the meaning of the
  74612. max_lazy, good_length, nice_length, and max_chain parameters.
  74613. deflateTune() can be called after deflateInit() or deflateInit2(), and
  74614. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  74615. */
  74616. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  74617. uLong sourceLen));
  74618. /*
  74619. deflateBound() returns an upper bound on the compressed size after
  74620. deflation of sourceLen bytes. It must be called after deflateInit()
  74621. or deflateInit2(). This would be used to allocate an output buffer
  74622. for deflation in a single pass, and so would be called before deflate().
  74623. */
  74624. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  74625. int bits,
  74626. int value));
  74627. /*
  74628. deflatePrime() inserts bits in the deflate output stream. The intent
  74629. is that this function is used to start off the deflate output with the
  74630. bits leftover from a previous deflate stream when appending to it. As such,
  74631. this function can only be used for raw deflate, and must be used before the
  74632. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  74633. less than or equal to 16, and that many of the least significant bits of
  74634. value will be inserted in the output.
  74635. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74636. stream state was inconsistent.
  74637. */
  74638. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  74639. gz_headerp head));
  74640. /*
  74641. deflateSetHeader() provides gzip header information for when a gzip
  74642. stream is requested by deflateInit2(). deflateSetHeader() may be called
  74643. after deflateInit2() or deflateReset() and before the first call of
  74644. deflate(). The text, time, os, extra field, name, and comment information
  74645. in the provided gz_header structure are written to the gzip header (xflag is
  74646. ignored -- the extra flags are set according to the compression level). The
  74647. caller must assure that, if not Z_NULL, name and comment are terminated with
  74648. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  74649. available there. If hcrc is true, a gzip header crc is included. Note that
  74650. the current versions of the command-line version of gzip (up through version
  74651. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  74652. gzip file" and give up.
  74653. If deflateSetHeader is not used, the default gzip header has text false,
  74654. the time set to zero, and os set to 255, with no extra, name, or comment
  74655. fields. The gzip header is returned to the default state by deflateReset().
  74656. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74657. stream state was inconsistent.
  74658. */
  74659. /*
  74660. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  74661. int windowBits));
  74662. This is another version of inflateInit with an extra parameter. The
  74663. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  74664. before by the caller.
  74665. The windowBits parameter is the base two logarithm of the maximum window
  74666. size (the size of the history buffer). It should be in the range 8..15 for
  74667. this version of the library. The default value is 15 if inflateInit is used
  74668. instead. windowBits must be greater than or equal to the windowBits value
  74669. provided to deflateInit2() while compressing, or it must be equal to 15 if
  74670. deflateInit2() was not used. If a compressed stream with a larger window
  74671. size is given as input, inflate() will return with the error code
  74672. Z_DATA_ERROR instead of trying to allocate a larger window.
  74673. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  74674. determines the window size. inflate() will then process raw deflate data,
  74675. not looking for a zlib or gzip header, not generating a check value, and not
  74676. looking for any check values for comparison at the end of the stream. This
  74677. is for use with other formats that use the deflate compressed data format
  74678. such as zip. Those formats provide their own check values. If a custom
  74679. format is developed using the raw deflate format for compressed data, it is
  74680. recommended that a check value such as an adler32 or a crc32 be applied to
  74681. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  74682. most applications, the zlib format should be used as is. Note that comments
  74683. above on the use in deflateInit2() applies to the magnitude of windowBits.
  74684. windowBits can also be greater than 15 for optional gzip decoding. Add
  74685. 32 to windowBits to enable zlib and gzip decoding with automatic header
  74686. detection, or add 16 to decode only the gzip format (the zlib format will
  74687. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  74688. a crc32 instead of an adler32.
  74689. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74690. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  74691. is set to null if there is no error message. inflateInit2 does not perform
  74692. any decompression apart from reading the zlib header if present: this will
  74693. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  74694. and avail_out are unchanged.)
  74695. */
  74696. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  74697. const Bytef *dictionary,
  74698. uInt dictLength));
  74699. /*
  74700. Initializes the decompression dictionary from the given uncompressed byte
  74701. sequence. This function must be called immediately after a call of inflate,
  74702. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  74703. can be determined from the adler32 value returned by that call of inflate.
  74704. The compressor and decompressor must use exactly the same dictionary (see
  74705. deflateSetDictionary). For raw inflate, this function can be called
  74706. immediately after inflateInit2() or inflateReset() and before any call of
  74707. inflate() to set the dictionary. The application must insure that the
  74708. dictionary that was used for compression is provided.
  74709. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  74710. parameter is invalid (such as NULL dictionary) or the stream state is
  74711. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  74712. expected one (incorrect adler32 value). inflateSetDictionary does not
  74713. perform any decompression: this will be done by subsequent calls of
  74714. inflate().
  74715. */
  74716. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  74717. /*
  74718. Skips invalid compressed data until a full flush point (see above the
  74719. description of deflate with Z_FULL_FLUSH) can be found, or until all
  74720. available input is skipped. No output is provided.
  74721. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  74722. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  74723. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  74724. case, the application may save the current current value of total_in which
  74725. indicates where valid compressed data was found. In the error case, the
  74726. application may repeatedly call inflateSync, providing more input each time,
  74727. until success or end of the input data.
  74728. */
  74729. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  74730. z_streamp source));
  74731. /*
  74732. Sets the destination stream as a complete copy of the source stream.
  74733. This function can be useful when randomly accessing a large stream. The
  74734. first pass through the stream can periodically record the inflate state,
  74735. allowing restarting inflate at those points when randomly accessing the
  74736. stream.
  74737. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74738. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74739. (such as zalloc being NULL). msg is left unchanged in both source and
  74740. destination.
  74741. */
  74742. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  74743. /*
  74744. This function is equivalent to inflateEnd followed by inflateInit,
  74745. but does not free and reallocate all the internal decompression state.
  74746. The stream will keep attributes that may have been set by inflateInit2.
  74747. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74748. stream state was inconsistent (such as zalloc or state being NULL).
  74749. */
  74750. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  74751. int bits,
  74752. int value));
  74753. /*
  74754. This function inserts bits in the inflate input stream. The intent is
  74755. that this function is used to start inflating at a bit position in the
  74756. middle of a byte. The provided bits will be used before any bytes are used
  74757. from next_in. This function should only be used with raw inflate, and
  74758. should be used before the first inflate() call after inflateInit2() or
  74759. inflateReset(). bits must be less than or equal to 16, and that many of the
  74760. least significant bits of value will be inserted in the input.
  74761. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74762. stream state was inconsistent.
  74763. */
  74764. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  74765. gz_headerp head));
  74766. /*
  74767. inflateGetHeader() requests that gzip header information be stored in the
  74768. provided gz_header structure. inflateGetHeader() may be called after
  74769. inflateInit2() or inflateReset(), and before the first call of inflate().
  74770. As inflate() processes the gzip stream, head->done is zero until the header
  74771. is completed, at which time head->done is set to one. If a zlib stream is
  74772. being decoded, then head->done is set to -1 to indicate that there will be
  74773. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  74774. force inflate() to return immediately after header processing is complete
  74775. and before any actual data is decompressed.
  74776. The text, time, xflags, and os fields are filled in with the gzip header
  74777. contents. hcrc is set to true if there is a header CRC. (The header CRC
  74778. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  74779. contains the maximum number of bytes to write to extra. Once done is true,
  74780. extra_len contains the actual extra field length, and extra contains the
  74781. extra field, or that field truncated if extra_max is less than extra_len.
  74782. If name is not Z_NULL, then up to name_max characters are written there,
  74783. terminated with a zero unless the length is greater than name_max. If
  74784. comment is not Z_NULL, then up to comm_max characters are written there,
  74785. terminated with a zero unless the length is greater than comm_max. When
  74786. any of extra, name, or comment are not Z_NULL and the respective field is
  74787. not present in the header, then that field is set to Z_NULL to signal its
  74788. absence. This allows the use of deflateSetHeader() with the returned
  74789. structure to duplicate the header. However if those fields are set to
  74790. allocated memory, then the application will need to save those pointers
  74791. elsewhere so that they can be eventually freed.
  74792. If inflateGetHeader is not used, then the header information is simply
  74793. discarded. The header is always checked for validity, including the header
  74794. CRC if present. inflateReset() will reset the process to discard the header
  74795. information. The application would need to call inflateGetHeader() again to
  74796. retrieve the header from the next gzip stream.
  74797. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74798. stream state was inconsistent.
  74799. */
  74800. /*
  74801. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  74802. unsigned char FAR *window));
  74803. Initialize the internal stream state for decompression using inflateBack()
  74804. calls. The fields zalloc, zfree and opaque in strm must be initialized
  74805. before the call. If zalloc and zfree are Z_NULL, then the default library-
  74806. derived memory allocation routines are used. windowBits is the base two
  74807. logarithm of the window size, in the range 8..15. window is a caller
  74808. supplied buffer of that size. Except for special applications where it is
  74809. assured that deflate was used with small window sizes, windowBits must be 15
  74810. and a 32K byte window must be supplied to be able to decompress general
  74811. deflate streams.
  74812. See inflateBack() for the usage of these routines.
  74813. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  74814. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  74815. be allocated, or Z_VERSION_ERROR if the version of the library does not
  74816. match the version of the header file.
  74817. */
  74818. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  74819. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  74820. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  74821. in_func in, void FAR *in_desc,
  74822. out_func out, void FAR *out_desc));
  74823. /*
  74824. inflateBack() does a raw inflate with a single call using a call-back
  74825. interface for input and output. This is more efficient than inflate() for
  74826. file i/o applications in that it avoids copying between the output and the
  74827. sliding window by simply making the window itself the output buffer. This
  74828. function trusts the application to not change the output buffer passed by
  74829. the output function, at least until inflateBack() returns.
  74830. inflateBackInit() must be called first to allocate the internal state
  74831. and to initialize the state with the user-provided window buffer.
  74832. inflateBack() may then be used multiple times to inflate a complete, raw
  74833. deflate stream with each call. inflateBackEnd() is then called to free
  74834. the allocated state.
  74835. A raw deflate stream is one with no zlib or gzip header or trailer.
  74836. This routine would normally be used in a utility that reads zip or gzip
  74837. files and writes out uncompressed files. The utility would decode the
  74838. header and process the trailer on its own, hence this routine expects
  74839. only the raw deflate stream to decompress. This is different from the
  74840. normal behavior of inflate(), which expects either a zlib or gzip header and
  74841. trailer around the deflate stream.
  74842. inflateBack() uses two subroutines supplied by the caller that are then
  74843. called by inflateBack() for input and output. inflateBack() calls those
  74844. routines until it reads a complete deflate stream and writes out all of the
  74845. uncompressed data, or until it encounters an error. The function's
  74846. parameters and return types are defined above in the in_func and out_func
  74847. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  74848. number of bytes of provided input, and a pointer to that input in buf. If
  74849. there is no input available, in() must return zero--buf is ignored in that
  74850. case--and inflateBack() will return a buffer error. inflateBack() will call
  74851. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  74852. should return zero on success, or non-zero on failure. If out() returns
  74853. non-zero, inflateBack() will return with an error. Neither in() nor out()
  74854. are permitted to change the contents of the window provided to
  74855. inflateBackInit(), which is also the buffer that out() uses to write from.
  74856. The length written by out() will be at most the window size. Any non-zero
  74857. amount of input may be provided by in().
  74858. For convenience, inflateBack() can be provided input on the first call by
  74859. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  74860. in() will be called. Therefore strm->next_in must be initialized before
  74861. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  74862. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  74863. must also be initialized, and then if strm->avail_in is not zero, input will
  74864. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  74865. The in_desc and out_desc parameters of inflateBack() is passed as the
  74866. first parameter of in() and out() respectively when they are called. These
  74867. descriptors can be optionally used to pass any information that the caller-
  74868. supplied in() and out() functions need to do their job.
  74869. On return, inflateBack() will set strm->next_in and strm->avail_in to
  74870. pass back any unused input that was provided by the last in() call. The
  74871. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  74872. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  74873. error in the deflate stream (in which case strm->msg is set to indicate the
  74874. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  74875. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  74876. distinguished using strm->next_in which will be Z_NULL only if in() returned
  74877. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  74878. out() returning non-zero. (in() will always be called before out(), so
  74879. strm->next_in is assured to be defined if out() returns non-zero.) Note
  74880. that inflateBack() cannot return Z_OK.
  74881. */
  74882. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  74883. /*
  74884. All memory allocated by inflateBackInit() is freed.
  74885. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  74886. state was inconsistent.
  74887. */
  74888. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  74889. /* Return flags indicating compile-time options.
  74890. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  74891. 1.0: size of uInt
  74892. 3.2: size of uLong
  74893. 5.4: size of voidpf (pointer)
  74894. 7.6: size of z_off_t
  74895. Compiler, assembler, and debug options:
  74896. 8: DEBUG
  74897. 9: ASMV or ASMINF -- use ASM code
  74898. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  74899. 11: 0 (reserved)
  74900. One-time table building (smaller code, but not thread-safe if true):
  74901. 12: BUILDFIXED -- build static block decoding tables when needed
  74902. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  74903. 14,15: 0 (reserved)
  74904. Library content (indicates missing functionality):
  74905. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  74906. deflate code when not needed)
  74907. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  74908. and decode gzip streams (to avoid linking crc code)
  74909. 18-19: 0 (reserved)
  74910. Operation variations (changes in library functionality):
  74911. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  74912. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  74913. 22,23: 0 (reserved)
  74914. The sprintf variant used by gzprintf (zero is best):
  74915. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  74916. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  74917. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  74918. Remainder:
  74919. 27-31: 0 (reserved)
  74920. */
  74921. /* utility functions */
  74922. /*
  74923. The following utility functions are implemented on top of the
  74924. basic stream-oriented functions. To simplify the interface, some
  74925. default options are assumed (compression level and memory usage,
  74926. standard memory allocation functions). The source code of these
  74927. utility functions can easily be modified if you need special options.
  74928. */
  74929. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  74930. const Bytef *source, uLong sourceLen));
  74931. /*
  74932. Compresses the source buffer into the destination buffer. sourceLen is
  74933. the byte length of the source buffer. Upon entry, destLen is the total
  74934. size of the destination buffer, which must be at least the value returned
  74935. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74936. compressed buffer.
  74937. This function can be used to compress a whole file at once if the
  74938. input file is mmap'ed.
  74939. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  74940. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74941. buffer.
  74942. */
  74943. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  74944. const Bytef *source, uLong sourceLen,
  74945. int level));
  74946. /*
  74947. Compresses the source buffer into the destination buffer. The level
  74948. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74949. length of the source buffer. Upon entry, destLen is the total size of the
  74950. destination buffer, which must be at least the value returned by
  74951. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74952. compressed buffer.
  74953. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74954. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74955. Z_STREAM_ERROR if the level parameter is invalid.
  74956. */
  74957. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  74958. /*
  74959. compressBound() returns an upper bound on the compressed size after
  74960. compress() or compress2() on sourceLen bytes. It would be used before
  74961. a compress() or compress2() call to allocate the destination buffer.
  74962. */
  74963. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  74964. const Bytef *source, uLong sourceLen));
  74965. /*
  74966. Decompresses the source buffer into the destination buffer. sourceLen is
  74967. the byte length of the source buffer. Upon entry, destLen is the total
  74968. size of the destination buffer, which must be large enough to hold the
  74969. entire uncompressed data. (The size of the uncompressed data must have
  74970. been saved previously by the compressor and transmitted to the decompressor
  74971. by some mechanism outside the scope of this compression library.)
  74972. Upon exit, destLen is the actual size of the compressed buffer.
  74973. This function can be used to decompress a whole file at once if the
  74974. input file is mmap'ed.
  74975. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  74976. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74977. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  74978. */
  74979. typedef voidp gzFile;
  74980. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  74981. /*
  74982. Opens a gzip (.gz) file for reading or writing. The mode parameter
  74983. is as in fopen ("rb" or "wb") but can also include a compression level
  74984. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  74985. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  74986. as in "wb1R". (See the description of deflateInit2 for more information
  74987. about the strategy parameter.)
  74988. gzopen can be used to read a file which is not in gzip format; in this
  74989. case gzread will directly read from the file without decompression.
  74990. gzopen returns NULL if the file could not be opened or if there was
  74991. insufficient memory to allocate the (de)compression state; errno
  74992. can be checked to distinguish the two cases (if errno is zero, the
  74993. zlib error is Z_MEM_ERROR). */
  74994. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  74995. /*
  74996. gzdopen() associates a gzFile with the file descriptor fd. File
  74997. descriptors are obtained from calls like open, dup, creat, pipe or
  74998. fileno (in the file has been previously opened with fopen).
  74999. The mode parameter is as in gzopen.
  75000. The next call of gzclose on the returned gzFile will also close the
  75001. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  75002. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  75003. gzdopen returns NULL if there was insufficient memory to allocate
  75004. the (de)compression state.
  75005. */
  75006. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  75007. /*
  75008. Dynamically update the compression level or strategy. See the description
  75009. of deflateInit2 for the meaning of these parameters.
  75010. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  75011. opened for writing.
  75012. */
  75013. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  75014. /*
  75015. Reads the given number of uncompressed bytes from the compressed file.
  75016. If the input file was not in gzip format, gzread copies the given number
  75017. of bytes into the buffer.
  75018. gzread returns the number of uncompressed bytes actually read (0 for
  75019. end of file, -1 for error). */
  75020. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  75021. voidpc buf, unsigned len));
  75022. /*
  75023. Writes the given number of uncompressed bytes into the compressed file.
  75024. gzwrite returns the number of uncompressed bytes actually written
  75025. (0 in case of error).
  75026. */
  75027. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  75028. /*
  75029. Converts, formats, and writes the args to the compressed file under
  75030. control of the format string, as in fprintf. gzprintf returns the number of
  75031. uncompressed bytes actually written (0 in case of error). The number of
  75032. uncompressed bytes written is limited to 4095. The caller should assure that
  75033. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  75034. return an error (0) with nothing written. In this case, there may also be a
  75035. buffer overflow with unpredictable consequences, which is possible only if
  75036. zlib was compiled with the insecure functions sprintf() or vsprintf()
  75037. because the secure snprintf() or vsnprintf() functions were not available.
  75038. */
  75039. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  75040. /*
  75041. Writes the given null-terminated string to the compressed file, excluding
  75042. the terminating null character.
  75043. gzputs returns the number of characters written, or -1 in case of error.
  75044. */
  75045. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  75046. /*
  75047. Reads bytes from the compressed file until len-1 characters are read, or
  75048. a newline character is read and transferred to buf, or an end-of-file
  75049. condition is encountered. The string is then terminated with a null
  75050. character.
  75051. gzgets returns buf, or Z_NULL in case of error.
  75052. */
  75053. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  75054. /*
  75055. Writes c, converted to an unsigned char, into the compressed file.
  75056. gzputc returns the value that was written, or -1 in case of error.
  75057. */
  75058. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  75059. /*
  75060. Reads one byte from the compressed file. gzgetc returns this byte
  75061. or -1 in case of end of file or error.
  75062. */
  75063. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  75064. /*
  75065. Push one character back onto the stream to be read again later.
  75066. Only one character of push-back is allowed. gzungetc() returns the
  75067. character pushed, or -1 on failure. gzungetc() will fail if a
  75068. character has been pushed but not read yet, or if c is -1. The pushed
  75069. character will be discarded if the stream is repositioned with gzseek()
  75070. or gzrewind().
  75071. */
  75072. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  75073. /*
  75074. Flushes all pending output into the compressed file. The parameter
  75075. flush is as in the deflate() function. The return value is the zlib
  75076. error number (see function gzerror below). gzflush returns Z_OK if
  75077. the flush parameter is Z_FINISH and all output could be flushed.
  75078. gzflush should be called only when strictly necessary because it can
  75079. degrade compression.
  75080. */
  75081. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  75082. z_off_t offset, int whence));
  75083. /*
  75084. Sets the starting position for the next gzread or gzwrite on the
  75085. given compressed file. The offset represents a number of bytes in the
  75086. uncompressed data stream. The whence parameter is defined as in lseek(2);
  75087. the value SEEK_END is not supported.
  75088. If the file is opened for reading, this function is emulated but can be
  75089. extremely slow. If the file is opened for writing, only forward seeks are
  75090. supported; gzseek then compresses a sequence of zeroes up to the new
  75091. starting position.
  75092. gzseek returns the resulting offset location as measured in bytes from
  75093. the beginning of the uncompressed stream, or -1 in case of error, in
  75094. particular if the file is opened for writing and the new starting position
  75095. would be before the current position.
  75096. */
  75097. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  75098. /*
  75099. Rewinds the given file. This function is supported only for reading.
  75100. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  75101. */
  75102. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  75103. /*
  75104. Returns the starting position for the next gzread or gzwrite on the
  75105. given compressed file. This position represents a number of bytes in the
  75106. uncompressed data stream.
  75107. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  75108. */
  75109. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  75110. /*
  75111. Returns 1 when EOF has previously been detected reading the given
  75112. input stream, otherwise zero.
  75113. */
  75114. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  75115. /*
  75116. Returns 1 if file is being read directly without decompression, otherwise
  75117. zero.
  75118. */
  75119. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  75120. /*
  75121. Flushes all pending output if necessary, closes the compressed file
  75122. and deallocates all the (de)compression state. The return value is the zlib
  75123. error number (see function gzerror below).
  75124. */
  75125. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  75126. /*
  75127. Returns the error message for the last error which occurred on the
  75128. given compressed file. errnum is set to zlib error number. If an
  75129. error occurred in the file system and not in the compression library,
  75130. errnum is set to Z_ERRNO and the application may consult errno
  75131. to get the exact error code.
  75132. */
  75133. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  75134. /*
  75135. Clears the error and end-of-file flags for file. This is analogous to the
  75136. clearerr() function in stdio. This is useful for continuing to read a gzip
  75137. file that is being written concurrently.
  75138. */
  75139. /* checksum functions */
  75140. /*
  75141. These functions are not related to compression but are exported
  75142. anyway because they might be useful in applications using the
  75143. compression library.
  75144. */
  75145. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  75146. /*
  75147. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  75148. return the updated checksum. If buf is NULL, this function returns
  75149. the required initial value for the checksum.
  75150. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  75151. much faster. Usage example:
  75152. uLong adler = adler32(0L, Z_NULL, 0);
  75153. while (read_buffer(buffer, length) != EOF) {
  75154. adler = adler32(adler, buffer, length);
  75155. }
  75156. if (adler != original_adler) error();
  75157. */
  75158. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  75159. z_off_t len2));
  75160. /*
  75161. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  75162. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  75163. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  75164. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  75165. */
  75166. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  75167. /*
  75168. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  75169. updated CRC-32. If buf is NULL, this function returns the required initial
  75170. value for the for the crc. Pre- and post-conditioning (one's complement) is
  75171. performed within this function so it shouldn't be done by the application.
  75172. Usage example:
  75173. uLong crc = crc32(0L, Z_NULL, 0);
  75174. while (read_buffer(buffer, length) != EOF) {
  75175. crc = crc32(crc, buffer, length);
  75176. }
  75177. if (crc != original_crc) error();
  75178. */
  75179. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  75180. /*
  75181. Combine two CRC-32 check values into one. For two sequences of bytes,
  75182. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  75183. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  75184. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  75185. len2.
  75186. */
  75187. /* various hacks, don't look :) */
  75188. /* deflateInit and inflateInit are macros to allow checking the zlib version
  75189. * and the compiler's view of z_stream:
  75190. */
  75191. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  75192. const char *version, int stream_size));
  75193. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  75194. const char *version, int stream_size));
  75195. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  75196. int windowBits, int memLevel,
  75197. int strategy, const char *version,
  75198. int stream_size));
  75199. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  75200. const char *version, int stream_size));
  75201. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  75202. unsigned char FAR *window,
  75203. const char *version,
  75204. int stream_size));
  75205. #define deflateInit(strm, level) \
  75206. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  75207. #define inflateInit(strm) \
  75208. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  75209. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  75210. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  75211. (strategy), ZLIB_VERSION, sizeof(z_stream))
  75212. #define inflateInit2(strm, windowBits) \
  75213. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  75214. #define inflateBackInit(strm, windowBits, window) \
  75215. inflateBackInit_((strm), (windowBits), (window), \
  75216. ZLIB_VERSION, sizeof(z_stream))
  75217. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  75218. struct internal_state {int dummy;}; /* hack for buggy compilers */
  75219. #endif
  75220. ZEXTERN const char * ZEXPORT zError OF((int));
  75221. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  75222. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  75223. #ifdef __cplusplus
  75224. }
  75225. #endif
  75226. #endif /* ZLIB_H */
  75227. /********* End of inlined file: zlib.h *********/
  75228. #undef OS_CODE
  75229. #else
  75230. #include <zlib.h>
  75231. #endif
  75232. }
  75233. BEGIN_JUCE_NAMESPACE
  75234. using namespace zlibNamespace;
  75235. // internal helper object that holds the zlib structures so they don't have to be
  75236. // included publicly.
  75237. class GZIPCompressorHelper
  75238. {
  75239. private:
  75240. z_stream* stream;
  75241. uint8* data;
  75242. int dataSize, compLevel, strategy;
  75243. bool setParams;
  75244. public:
  75245. bool finished, shouldFinish;
  75246. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  75247. : data (0),
  75248. dataSize (0),
  75249. compLevel (compressionLevel),
  75250. strategy (0),
  75251. setParams (true),
  75252. finished (false),
  75253. shouldFinish (false)
  75254. {
  75255. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  75256. if (deflateInit2 (stream,
  75257. compLevel,
  75258. Z_DEFLATED,
  75259. nowrap ? -MAX_WBITS : MAX_WBITS,
  75260. 8,
  75261. strategy) != Z_OK)
  75262. {
  75263. juce_free (stream);
  75264. stream = 0;
  75265. }
  75266. }
  75267. ~GZIPCompressorHelper()
  75268. {
  75269. if (stream != 0)
  75270. {
  75271. deflateEnd (stream);
  75272. juce_free (stream);
  75273. }
  75274. }
  75275. bool needsInput() const throw()
  75276. {
  75277. return dataSize <= 0;
  75278. }
  75279. void setInput (uint8* const newData, const int size) throw()
  75280. {
  75281. data = newData;
  75282. dataSize = size;
  75283. }
  75284. int doNextBlock (uint8* const dest, const int destSize) throw()
  75285. {
  75286. if (stream != 0)
  75287. {
  75288. stream->next_in = data;
  75289. stream->next_out = dest;
  75290. stream->avail_in = dataSize;
  75291. stream->avail_out = destSize;
  75292. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  75293. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  75294. setParams = false;
  75295. switch (result)
  75296. {
  75297. case Z_STREAM_END:
  75298. finished = true;
  75299. case Z_OK:
  75300. data += dataSize - stream->avail_in;
  75301. dataSize = stream->avail_in;
  75302. return destSize - stream->avail_out;
  75303. default:
  75304. break;
  75305. }
  75306. }
  75307. return 0;
  75308. }
  75309. };
  75310. const int gzipCompBufferSize = 32768;
  75311. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  75312. int compressionLevel,
  75313. const bool deleteDestStream_,
  75314. const bool noWrap)
  75315. : destStream (destStream_),
  75316. deleteDestStream (deleteDestStream_)
  75317. {
  75318. if (compressionLevel < 1 || compressionLevel > 9)
  75319. compressionLevel = -1;
  75320. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  75321. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  75322. }
  75323. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  75324. {
  75325. flush();
  75326. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75327. delete h;
  75328. juce_free (buffer);
  75329. if (deleteDestStream)
  75330. delete destStream;
  75331. }
  75332. void GZIPCompressorOutputStream::flush()
  75333. {
  75334. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75335. if (! h->finished)
  75336. {
  75337. h->shouldFinish = true;
  75338. while (! h->finished)
  75339. doNextBlock();
  75340. }
  75341. destStream->flush();
  75342. }
  75343. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  75344. {
  75345. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75346. if (! h->finished)
  75347. {
  75348. h->setInput ((uint8*) destBuffer, howMany);
  75349. while (! h->needsInput())
  75350. {
  75351. if (! doNextBlock())
  75352. return false;
  75353. }
  75354. }
  75355. return true;
  75356. }
  75357. bool GZIPCompressorOutputStream::doNextBlock()
  75358. {
  75359. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75360. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  75361. if (len > 0)
  75362. return destStream->write (buffer, len);
  75363. else
  75364. return true;
  75365. }
  75366. int64 GZIPCompressorOutputStream::getPosition()
  75367. {
  75368. return destStream->getPosition();
  75369. }
  75370. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  75371. {
  75372. jassertfalse // can't do it!
  75373. return false;
  75374. }
  75375. END_JUCE_NAMESPACE
  75376. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  75377. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  75378. #if JUCE_MSVC
  75379. #pragma warning (push)
  75380. #pragma warning (disable: 4309 4305)
  75381. #endif
  75382. namespace zlibNamespace
  75383. {
  75384. #if JUCE_INCLUDE_ZLIB_CODE
  75385. extern "C"
  75386. {
  75387. #undef OS_CODE
  75388. #undef fdopen
  75389. #define ZLIB_INTERNAL
  75390. #define NO_DUMMY_DECL
  75391. /********* Start of inlined file: adler32.c *********/
  75392. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75393. #define ZLIB_INTERNAL
  75394. #define BASE 65521UL /* largest prime smaller than 65536 */
  75395. #define NMAX 5552
  75396. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  75397. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  75398. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  75399. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  75400. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  75401. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  75402. /* use NO_DIVIDE if your processor does not do division in hardware */
  75403. #ifdef NO_DIVIDE
  75404. # define MOD(a) \
  75405. do { \
  75406. if (a >= (BASE << 16)) a -= (BASE << 16); \
  75407. if (a >= (BASE << 15)) a -= (BASE << 15); \
  75408. if (a >= (BASE << 14)) a -= (BASE << 14); \
  75409. if (a >= (BASE << 13)) a -= (BASE << 13); \
  75410. if (a >= (BASE << 12)) a -= (BASE << 12); \
  75411. if (a >= (BASE << 11)) a -= (BASE << 11); \
  75412. if (a >= (BASE << 10)) a -= (BASE << 10); \
  75413. if (a >= (BASE << 9)) a -= (BASE << 9); \
  75414. if (a >= (BASE << 8)) a -= (BASE << 8); \
  75415. if (a >= (BASE << 7)) a -= (BASE << 7); \
  75416. if (a >= (BASE << 6)) a -= (BASE << 6); \
  75417. if (a >= (BASE << 5)) a -= (BASE << 5); \
  75418. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75419. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75420. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75421. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75422. if (a >= BASE) a -= BASE; \
  75423. } while (0)
  75424. # define MOD4(a) \
  75425. do { \
  75426. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75427. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75428. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75429. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75430. if (a >= BASE) a -= BASE; \
  75431. } while (0)
  75432. #else
  75433. # define MOD(a) a %= BASE
  75434. # define MOD4(a) a %= BASE
  75435. #endif
  75436. /* ========================================================================= */
  75437. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  75438. {
  75439. unsigned long sum2;
  75440. unsigned n;
  75441. /* split Adler-32 into component sums */
  75442. sum2 = (adler >> 16) & 0xffff;
  75443. adler &= 0xffff;
  75444. /* in case user likes doing a byte at a time, keep it fast */
  75445. if (len == 1) {
  75446. adler += buf[0];
  75447. if (adler >= BASE)
  75448. adler -= BASE;
  75449. sum2 += adler;
  75450. if (sum2 >= BASE)
  75451. sum2 -= BASE;
  75452. return adler | (sum2 << 16);
  75453. }
  75454. /* initial Adler-32 value (deferred check for len == 1 speed) */
  75455. if (buf == Z_NULL)
  75456. return 1L;
  75457. /* in case short lengths are provided, keep it somewhat fast */
  75458. if (len < 16) {
  75459. while (len--) {
  75460. adler += *buf++;
  75461. sum2 += adler;
  75462. }
  75463. if (adler >= BASE)
  75464. adler -= BASE;
  75465. MOD4(sum2); /* only added so many BASE's */
  75466. return adler | (sum2 << 16);
  75467. }
  75468. /* do length NMAX blocks -- requires just one modulo operation */
  75469. while (len >= NMAX) {
  75470. len -= NMAX;
  75471. n = NMAX / 16; /* NMAX is divisible by 16 */
  75472. do {
  75473. DO16(buf); /* 16 sums unrolled */
  75474. buf += 16;
  75475. } while (--n);
  75476. MOD(adler);
  75477. MOD(sum2);
  75478. }
  75479. /* do remaining bytes (less than NMAX, still just one modulo) */
  75480. if (len) { /* avoid modulos if none remaining */
  75481. while (len >= 16) {
  75482. len -= 16;
  75483. DO16(buf);
  75484. buf += 16;
  75485. }
  75486. while (len--) {
  75487. adler += *buf++;
  75488. sum2 += adler;
  75489. }
  75490. MOD(adler);
  75491. MOD(sum2);
  75492. }
  75493. /* return recombined sums */
  75494. return adler | (sum2 << 16);
  75495. }
  75496. /* ========================================================================= */
  75497. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  75498. {
  75499. unsigned long sum1;
  75500. unsigned long sum2;
  75501. unsigned rem;
  75502. /* the derivation of this formula is left as an exercise for the reader */
  75503. rem = (unsigned)(len2 % BASE);
  75504. sum1 = adler1 & 0xffff;
  75505. sum2 = rem * sum1;
  75506. MOD(sum2);
  75507. sum1 += (adler2 & 0xffff) + BASE - 1;
  75508. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  75509. if (sum1 > BASE) sum1 -= BASE;
  75510. if (sum1 > BASE) sum1 -= BASE;
  75511. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  75512. if (sum2 > BASE) sum2 -= BASE;
  75513. return sum1 | (sum2 << 16);
  75514. }
  75515. /********* End of inlined file: adler32.c *********/
  75516. /********* Start of inlined file: compress.c *********/
  75517. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75518. #define ZLIB_INTERNAL
  75519. /* ===========================================================================
  75520. Compresses the source buffer into the destination buffer. The level
  75521. parameter has the same meaning as in deflateInit. sourceLen is the byte
  75522. length of the source buffer. Upon entry, destLen is the total size of the
  75523. destination buffer, which must be at least 0.1% larger than sourceLen plus
  75524. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  75525. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75526. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  75527. Z_STREAM_ERROR if the level parameter is invalid.
  75528. */
  75529. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  75530. uLong sourceLen, int level)
  75531. {
  75532. z_stream stream;
  75533. int err;
  75534. stream.next_in = (Bytef*)source;
  75535. stream.avail_in = (uInt)sourceLen;
  75536. #ifdef MAXSEG_64K
  75537. /* Check for source > 64K on 16-bit machine: */
  75538. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  75539. #endif
  75540. stream.next_out = dest;
  75541. stream.avail_out = (uInt)*destLen;
  75542. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  75543. stream.zalloc = (alloc_func)0;
  75544. stream.zfree = (free_func)0;
  75545. stream.opaque = (voidpf)0;
  75546. err = deflateInit(&stream, level);
  75547. if (err != Z_OK) return err;
  75548. err = deflate(&stream, Z_FINISH);
  75549. if (err != Z_STREAM_END) {
  75550. deflateEnd(&stream);
  75551. return err == Z_OK ? Z_BUF_ERROR : err;
  75552. }
  75553. *destLen = stream.total_out;
  75554. err = deflateEnd(&stream);
  75555. return err;
  75556. }
  75557. /* ===========================================================================
  75558. */
  75559. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  75560. {
  75561. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  75562. }
  75563. /* ===========================================================================
  75564. If the default memLevel or windowBits for deflateInit() is changed, then
  75565. this function needs to be updated.
  75566. */
  75567. uLong ZEXPORT compressBound (uLong sourceLen)
  75568. {
  75569. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  75570. }
  75571. /********* End of inlined file: compress.c *********/
  75572. #undef DO1
  75573. #undef DO8
  75574. /********* Start of inlined file: crc32.c *********/
  75575. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75576. /*
  75577. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  75578. protection on the static variables used to control the first-use generation
  75579. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  75580. first call get_crc_table() to initialize the tables before allowing more than
  75581. one thread to use crc32().
  75582. */
  75583. #ifdef MAKECRCH
  75584. # include <stdio.h>
  75585. # ifndef DYNAMIC_CRC_TABLE
  75586. # define DYNAMIC_CRC_TABLE
  75587. # endif /* !DYNAMIC_CRC_TABLE */
  75588. #endif /* MAKECRCH */
  75589. /********* Start of inlined file: zutil.h *********/
  75590. /* WARNING: this file should *not* be used by applications. It is
  75591. part of the implementation of the compression library and is
  75592. subject to change. Applications should only use zlib.h.
  75593. */
  75594. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75595. #ifndef ZUTIL_H
  75596. #define ZUTIL_H
  75597. #define ZLIB_INTERNAL
  75598. #ifdef STDC
  75599. # ifndef _WIN32_WCE
  75600. # include <stddef.h>
  75601. # endif
  75602. # include <string.h>
  75603. # include <stdlib.h>
  75604. #endif
  75605. #ifdef NO_ERRNO_H
  75606. # ifdef _WIN32_WCE
  75607. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  75608. * errno. We define it as a global variable to simplify porting.
  75609. * Its value is always 0 and should not be used. We rename it to
  75610. * avoid conflict with other libraries that use the same workaround.
  75611. */
  75612. # define errno z_errno
  75613. # endif
  75614. extern int errno;
  75615. #else
  75616. # ifndef _WIN32_WCE
  75617. # include <errno.h>
  75618. # endif
  75619. #endif
  75620. #ifndef local
  75621. # define local static
  75622. #endif
  75623. /* compile with -Dlocal if your debugger can't find static symbols */
  75624. typedef unsigned char uch;
  75625. typedef uch FAR uchf;
  75626. typedef unsigned short ush;
  75627. typedef ush FAR ushf;
  75628. typedef unsigned long ulg;
  75629. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  75630. /* (size given to avoid silly warnings with Visual C++) */
  75631. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  75632. #define ERR_RETURN(strm,err) \
  75633. return (strm->msg = (char*)ERR_MSG(err), (err))
  75634. /* To be used only when the state is known to be valid */
  75635. /* common constants */
  75636. #ifndef DEF_WBITS
  75637. # define DEF_WBITS MAX_WBITS
  75638. #endif
  75639. /* default windowBits for decompression. MAX_WBITS is for compression only */
  75640. #if MAX_MEM_LEVEL >= 8
  75641. # define DEF_MEM_LEVEL 8
  75642. #else
  75643. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  75644. #endif
  75645. /* default memLevel */
  75646. #define STORED_BLOCK 0
  75647. #define STATIC_TREES 1
  75648. #define DYN_TREES 2
  75649. /* The three kinds of block type */
  75650. #define MIN_MATCH 3
  75651. #define MAX_MATCH 258
  75652. /* The minimum and maximum match lengths */
  75653. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  75654. /* target dependencies */
  75655. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  75656. # define OS_CODE 0x00
  75657. # if defined(__TURBOC__) || defined(__BORLANDC__)
  75658. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  75659. /* Allow compilation with ANSI keywords only enabled */
  75660. void _Cdecl farfree( void *block );
  75661. void *_Cdecl farmalloc( unsigned long nbytes );
  75662. # else
  75663. # include <alloc.h>
  75664. # endif
  75665. # else /* MSC or DJGPP */
  75666. # include <malloc.h>
  75667. # endif
  75668. #endif
  75669. #ifdef AMIGA
  75670. # define OS_CODE 0x01
  75671. #endif
  75672. #if defined(VAXC) || defined(VMS)
  75673. # define OS_CODE 0x02
  75674. # define F_OPEN(name, mode) \
  75675. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  75676. #endif
  75677. #if defined(ATARI) || defined(atarist)
  75678. # define OS_CODE 0x05
  75679. #endif
  75680. #ifdef OS2
  75681. # define OS_CODE 0x06
  75682. # ifdef M_I86
  75683. #include <malloc.h>
  75684. # endif
  75685. #endif
  75686. #if defined(MACOS) || TARGET_OS_MAC
  75687. # define OS_CODE 0x07
  75688. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  75689. # include <unix.h> /* for fdopen */
  75690. # else
  75691. # ifndef fdopen
  75692. # define fdopen(fd,mode) NULL /* No fdopen() */
  75693. # endif
  75694. # endif
  75695. #endif
  75696. #ifdef TOPS20
  75697. # define OS_CODE 0x0a
  75698. #endif
  75699. #ifdef WIN32
  75700. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  75701. # define OS_CODE 0x0b
  75702. # endif
  75703. #endif
  75704. #ifdef __50SERIES /* Prime/PRIMOS */
  75705. # define OS_CODE 0x0f
  75706. #endif
  75707. #if defined(_BEOS_) || defined(RISCOS)
  75708. # define fdopen(fd,mode) NULL /* No fdopen() */
  75709. #endif
  75710. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  75711. # if defined(_WIN32_WCE)
  75712. # define fdopen(fd,mode) NULL /* No fdopen() */
  75713. # ifndef _PTRDIFF_T_DEFINED
  75714. typedef int ptrdiff_t;
  75715. # define _PTRDIFF_T_DEFINED
  75716. # endif
  75717. # else
  75718. # define fdopen(fd,type) _fdopen(fd,type)
  75719. # endif
  75720. #endif
  75721. /* common defaults */
  75722. #ifndef OS_CODE
  75723. # define OS_CODE 0x03 /* assume Unix */
  75724. #endif
  75725. #ifndef F_OPEN
  75726. # define F_OPEN(name, mode) fopen((name), (mode))
  75727. #endif
  75728. /* functions */
  75729. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  75730. # ifndef HAVE_VSNPRINTF
  75731. # define HAVE_VSNPRINTF
  75732. # endif
  75733. #endif
  75734. #if defined(__CYGWIN__)
  75735. # ifndef HAVE_VSNPRINTF
  75736. # define HAVE_VSNPRINTF
  75737. # endif
  75738. #endif
  75739. #ifndef HAVE_VSNPRINTF
  75740. # ifdef MSDOS
  75741. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  75742. but for now we just assume it doesn't. */
  75743. # define NO_vsnprintf
  75744. # endif
  75745. # ifdef __TURBOC__
  75746. # define NO_vsnprintf
  75747. # endif
  75748. # ifdef WIN32
  75749. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  75750. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  75751. # define vsnprintf _vsnprintf
  75752. # endif
  75753. # endif
  75754. # ifdef __SASC
  75755. # define NO_vsnprintf
  75756. # endif
  75757. #endif
  75758. #ifdef VMS
  75759. # define NO_vsnprintf
  75760. #endif
  75761. #if defined(pyr)
  75762. # define NO_MEMCPY
  75763. #endif
  75764. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  75765. /* Use our own functions for small and medium model with MSC <= 5.0.
  75766. * You may have to use the same strategy for Borland C (untested).
  75767. * The __SC__ check is for Symantec.
  75768. */
  75769. # define NO_MEMCPY
  75770. #endif
  75771. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  75772. # define HAVE_MEMCPY
  75773. #endif
  75774. #ifdef HAVE_MEMCPY
  75775. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  75776. # define zmemcpy _fmemcpy
  75777. # define zmemcmp _fmemcmp
  75778. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  75779. # else
  75780. # define zmemcpy memcpy
  75781. # define zmemcmp memcmp
  75782. # define zmemzero(dest, len) memset(dest, 0, len)
  75783. # endif
  75784. #else
  75785. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  75786. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  75787. extern void zmemzero OF((Bytef* dest, uInt len));
  75788. #endif
  75789. /* Diagnostic functions */
  75790. #ifdef DEBUG
  75791. # include <stdio.h>
  75792. extern int z_verbose;
  75793. extern void z_error OF((const char *m));
  75794. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  75795. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  75796. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  75797. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  75798. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  75799. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  75800. #else
  75801. # define Assert(cond,msg)
  75802. # define Trace(x)
  75803. # define Tracev(x)
  75804. # define Tracevv(x)
  75805. # define Tracec(c,x)
  75806. # define Tracecv(c,x)
  75807. #endif
  75808. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  75809. void zcfree OF((voidpf opaque, voidpf ptr));
  75810. #define ZALLOC(strm, items, size) \
  75811. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  75812. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  75813. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  75814. #endif /* ZUTIL_H */
  75815. /********* End of inlined file: zutil.h *********/
  75816. /* for STDC and FAR definitions */
  75817. #define local static
  75818. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  75819. #ifndef NOBYFOUR
  75820. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  75821. # include <limits.h>
  75822. # define BYFOUR
  75823. # if (UINT_MAX == 0xffffffffUL)
  75824. typedef unsigned int u4;
  75825. # else
  75826. # if (ULONG_MAX == 0xffffffffUL)
  75827. typedef unsigned long u4;
  75828. # else
  75829. # if (USHRT_MAX == 0xffffffffUL)
  75830. typedef unsigned short u4;
  75831. # else
  75832. # undef BYFOUR /* can't find a four-byte integer type! */
  75833. # endif
  75834. # endif
  75835. # endif
  75836. # endif /* STDC */
  75837. #endif /* !NOBYFOUR */
  75838. /* Definitions for doing the crc four data bytes at a time. */
  75839. #ifdef BYFOUR
  75840. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  75841. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  75842. local unsigned long crc32_little OF((unsigned long,
  75843. const unsigned char FAR *, unsigned));
  75844. local unsigned long crc32_big OF((unsigned long,
  75845. const unsigned char FAR *, unsigned));
  75846. # define TBLS 8
  75847. #else
  75848. # define TBLS 1
  75849. #endif /* BYFOUR */
  75850. /* Local functions for crc concatenation */
  75851. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  75852. unsigned long vec));
  75853. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  75854. #ifdef DYNAMIC_CRC_TABLE
  75855. local volatile int crc_table_empty = 1;
  75856. local unsigned long FAR crc_table[TBLS][256];
  75857. local void make_crc_table OF((void));
  75858. #ifdef MAKECRCH
  75859. local void write_table OF((FILE *, const unsigned long FAR *));
  75860. #endif /* MAKECRCH */
  75861. /*
  75862. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  75863. 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.
  75864. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  75865. with the lowest powers in the most significant bit. Then adding polynomials
  75866. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  75867. one. If we call the above polynomial p, and represent a byte as the
  75868. polynomial q, also with the lowest power in the most significant bit (so the
  75869. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  75870. where a mod b means the remainder after dividing a by b.
  75871. This calculation is done using the shift-register method of multiplying and
  75872. taking the remainder. The register is initialized to zero, and for each
  75873. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  75874. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  75875. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  75876. out is a one). We start with the highest power (least significant bit) of
  75877. q and repeat for all eight bits of q.
  75878. The first table is simply the CRC of all possible eight bit values. This is
  75879. all the information needed to generate CRCs on data a byte at a time for all
  75880. combinations of CRC register values and incoming bytes. The remaining tables
  75881. allow for word-at-a-time CRC calculation for both big-endian and little-
  75882. endian machines, where a word is four bytes.
  75883. */
  75884. local void make_crc_table()
  75885. {
  75886. unsigned long c;
  75887. int n, k;
  75888. unsigned long poly; /* polynomial exclusive-or pattern */
  75889. /* terms of polynomial defining this crc (except x^32): */
  75890. static volatile int first = 1; /* flag to limit concurrent making */
  75891. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  75892. /* See if another task is already doing this (not thread-safe, but better
  75893. than nothing -- significantly reduces duration of vulnerability in
  75894. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  75895. if (first) {
  75896. first = 0;
  75897. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  75898. poly = 0UL;
  75899. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  75900. poly |= 1UL << (31 - p[n]);
  75901. /* generate a crc for every 8-bit value */
  75902. for (n = 0; n < 256; n++) {
  75903. c = (unsigned long)n;
  75904. for (k = 0; k < 8; k++)
  75905. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  75906. crc_table[0][n] = c;
  75907. }
  75908. #ifdef BYFOUR
  75909. /* generate crc for each value followed by one, two, and three zeros,
  75910. and then the byte reversal of those as well as the first table */
  75911. for (n = 0; n < 256; n++) {
  75912. c = crc_table[0][n];
  75913. crc_table[4][n] = REV(c);
  75914. for (k = 1; k < 4; k++) {
  75915. c = crc_table[0][c & 0xff] ^ (c >> 8);
  75916. crc_table[k][n] = c;
  75917. crc_table[k + 4][n] = REV(c);
  75918. }
  75919. }
  75920. #endif /* BYFOUR */
  75921. crc_table_empty = 0;
  75922. }
  75923. else { /* not first */
  75924. /* wait for the other guy to finish (not efficient, but rare) */
  75925. while (crc_table_empty)
  75926. ;
  75927. }
  75928. #ifdef MAKECRCH
  75929. /* write out CRC tables to crc32.h */
  75930. {
  75931. FILE *out;
  75932. out = fopen("crc32.h", "w");
  75933. if (out == NULL) return;
  75934. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  75935. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  75936. fprintf(out, "local const unsigned long FAR ");
  75937. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  75938. write_table(out, crc_table[0]);
  75939. # ifdef BYFOUR
  75940. fprintf(out, "#ifdef BYFOUR\n");
  75941. for (k = 1; k < 8; k++) {
  75942. fprintf(out, " },\n {\n");
  75943. write_table(out, crc_table[k]);
  75944. }
  75945. fprintf(out, "#endif\n");
  75946. # endif /* BYFOUR */
  75947. fprintf(out, " }\n};\n");
  75948. fclose(out);
  75949. }
  75950. #endif /* MAKECRCH */
  75951. }
  75952. #ifdef MAKECRCH
  75953. local void write_table(out, table)
  75954. FILE *out;
  75955. const unsigned long FAR *table;
  75956. {
  75957. int n;
  75958. for (n = 0; n < 256; n++)
  75959. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  75960. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  75961. }
  75962. #endif /* MAKECRCH */
  75963. #else /* !DYNAMIC_CRC_TABLE */
  75964. /* ========================================================================
  75965. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  75966. */
  75967. /********* Start of inlined file: crc32.h *********/
  75968. local const unsigned long FAR crc_table[TBLS][256] =
  75969. {
  75970. {
  75971. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  75972. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  75973. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  75974. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  75975. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  75976. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  75977. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  75978. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  75979. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  75980. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  75981. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  75982. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  75983. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  75984. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  75985. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  75986. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  75987. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  75988. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  75989. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  75990. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  75991. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  75992. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  75993. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  75994. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  75995. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  75996. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  75997. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  75998. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  75999. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  76000. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  76001. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  76002. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  76003. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  76004. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  76005. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  76006. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  76007. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  76008. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  76009. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  76010. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  76011. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  76012. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  76013. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  76014. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  76015. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  76016. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  76017. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  76018. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  76019. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  76020. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  76021. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  76022. 0x2d02ef8dUL
  76023. #ifdef BYFOUR
  76024. },
  76025. {
  76026. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  76027. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  76028. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  76029. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  76030. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  76031. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  76032. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  76033. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  76034. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  76035. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  76036. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  76037. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  76038. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  76039. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  76040. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  76041. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  76042. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  76043. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  76044. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  76045. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  76046. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  76047. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  76048. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  76049. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  76050. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  76051. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  76052. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  76053. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  76054. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  76055. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  76056. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  76057. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  76058. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  76059. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  76060. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  76061. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  76062. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  76063. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  76064. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  76065. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  76066. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  76067. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  76068. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  76069. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  76070. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  76071. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  76072. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  76073. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  76074. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  76075. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  76076. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  76077. 0x9324fd72UL
  76078. },
  76079. {
  76080. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  76081. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  76082. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  76083. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  76084. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  76085. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  76086. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  76087. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  76088. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  76089. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  76090. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  76091. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  76092. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  76093. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  76094. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  76095. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  76096. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  76097. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  76098. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  76099. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  76100. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  76101. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  76102. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  76103. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  76104. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  76105. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  76106. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  76107. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  76108. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  76109. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  76110. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  76111. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  76112. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  76113. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  76114. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  76115. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  76116. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  76117. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  76118. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  76119. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  76120. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  76121. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  76122. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  76123. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  76124. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  76125. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  76126. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  76127. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  76128. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  76129. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  76130. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  76131. 0xbe9834edUL
  76132. },
  76133. {
  76134. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  76135. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  76136. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  76137. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  76138. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  76139. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  76140. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  76141. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  76142. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  76143. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  76144. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  76145. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  76146. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  76147. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  76148. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  76149. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  76150. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  76151. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  76152. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  76153. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  76154. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  76155. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  76156. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  76157. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  76158. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  76159. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  76160. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  76161. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  76162. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  76163. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  76164. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  76165. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  76166. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  76167. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  76168. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  76169. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  76170. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  76171. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  76172. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  76173. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  76174. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  76175. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  76176. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  76177. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  76178. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  76179. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  76180. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  76181. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  76182. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  76183. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  76184. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  76185. 0xde0506f1UL
  76186. },
  76187. {
  76188. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  76189. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  76190. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  76191. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  76192. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  76193. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  76194. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  76195. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  76196. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  76197. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  76198. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  76199. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  76200. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  76201. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  76202. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  76203. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  76204. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  76205. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  76206. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  76207. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  76208. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  76209. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  76210. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  76211. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  76212. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  76213. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  76214. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  76215. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  76216. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  76217. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  76218. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  76219. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  76220. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  76221. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  76222. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  76223. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  76224. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  76225. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  76226. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  76227. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  76228. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  76229. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  76230. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  76231. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  76232. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  76233. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  76234. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  76235. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  76236. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  76237. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  76238. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  76239. 0x8def022dUL
  76240. },
  76241. {
  76242. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  76243. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  76244. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  76245. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  76246. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  76247. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  76248. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  76249. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  76250. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  76251. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  76252. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  76253. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  76254. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  76255. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  76256. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  76257. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  76258. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  76259. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  76260. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  76261. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  76262. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  76263. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  76264. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  76265. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  76266. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  76267. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  76268. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  76269. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  76270. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  76271. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  76272. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  76273. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  76274. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  76275. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  76276. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  76277. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  76278. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  76279. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  76280. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  76281. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  76282. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  76283. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  76284. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  76285. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  76286. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  76287. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  76288. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  76289. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  76290. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  76291. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  76292. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  76293. 0x72fd2493UL
  76294. },
  76295. {
  76296. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  76297. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  76298. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  76299. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  76300. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  76301. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  76302. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  76303. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  76304. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  76305. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  76306. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  76307. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  76308. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  76309. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  76310. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  76311. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  76312. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  76313. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  76314. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  76315. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  76316. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  76317. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  76318. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  76319. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  76320. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  76321. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  76322. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  76323. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  76324. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  76325. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  76326. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  76327. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  76328. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  76329. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  76330. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  76331. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  76332. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  76333. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  76334. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  76335. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  76336. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  76337. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  76338. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  76339. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  76340. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  76341. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  76342. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  76343. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  76344. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  76345. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  76346. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  76347. 0xed3498beUL
  76348. },
  76349. {
  76350. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  76351. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  76352. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  76353. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  76354. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  76355. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  76356. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  76357. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  76358. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  76359. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  76360. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  76361. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  76362. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  76363. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  76364. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  76365. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  76366. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  76367. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  76368. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  76369. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  76370. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  76371. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  76372. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  76373. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  76374. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  76375. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  76376. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  76377. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  76378. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  76379. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  76380. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  76381. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  76382. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  76383. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  76384. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  76385. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  76386. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  76387. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  76388. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  76389. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  76390. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  76391. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  76392. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  76393. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  76394. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  76395. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  76396. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  76397. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  76398. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  76399. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  76400. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  76401. 0xf10605deUL
  76402. #endif
  76403. }
  76404. };
  76405. /********* End of inlined file: crc32.h *********/
  76406. #endif /* DYNAMIC_CRC_TABLE */
  76407. /* =========================================================================
  76408. * This function can be used by asm versions of crc32()
  76409. */
  76410. const unsigned long FAR * ZEXPORT get_crc_table()
  76411. {
  76412. #ifdef DYNAMIC_CRC_TABLE
  76413. if (crc_table_empty)
  76414. make_crc_table();
  76415. #endif /* DYNAMIC_CRC_TABLE */
  76416. return (const unsigned long FAR *)crc_table;
  76417. }
  76418. /* ========================================================================= */
  76419. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  76420. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  76421. /* ========================================================================= */
  76422. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76423. {
  76424. if (buf == Z_NULL) return 0UL;
  76425. #ifdef DYNAMIC_CRC_TABLE
  76426. if (crc_table_empty)
  76427. make_crc_table();
  76428. #endif /* DYNAMIC_CRC_TABLE */
  76429. #ifdef BYFOUR
  76430. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  76431. u4 endian;
  76432. endian = 1;
  76433. if (*((unsigned char *)(&endian)))
  76434. return crc32_little(crc, buf, len);
  76435. else
  76436. return crc32_big(crc, buf, len);
  76437. }
  76438. #endif /* BYFOUR */
  76439. crc = crc ^ 0xffffffffUL;
  76440. while (len >= 8) {
  76441. DO8;
  76442. len -= 8;
  76443. }
  76444. if (len) do {
  76445. DO1;
  76446. } while (--len);
  76447. return crc ^ 0xffffffffUL;
  76448. }
  76449. #ifdef BYFOUR
  76450. /* ========================================================================= */
  76451. #define DOLIT4 c ^= *buf4++; \
  76452. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  76453. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  76454. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  76455. /* ========================================================================= */
  76456. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76457. {
  76458. register u4 c;
  76459. register const u4 FAR *buf4;
  76460. c = (u4)crc;
  76461. c = ~c;
  76462. while (len && ((ptrdiff_t)buf & 3)) {
  76463. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76464. len--;
  76465. }
  76466. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76467. while (len >= 32) {
  76468. DOLIT32;
  76469. len -= 32;
  76470. }
  76471. while (len >= 4) {
  76472. DOLIT4;
  76473. len -= 4;
  76474. }
  76475. buf = (const unsigned char FAR *)buf4;
  76476. if (len) do {
  76477. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76478. } while (--len);
  76479. c = ~c;
  76480. return (unsigned long)c;
  76481. }
  76482. /* ========================================================================= */
  76483. #define DOBIG4 c ^= *++buf4; \
  76484. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  76485. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  76486. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  76487. /* ========================================================================= */
  76488. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76489. {
  76490. register u4 c;
  76491. register const u4 FAR *buf4;
  76492. c = REV((u4)crc);
  76493. c = ~c;
  76494. while (len && ((ptrdiff_t)buf & 3)) {
  76495. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76496. len--;
  76497. }
  76498. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76499. buf4--;
  76500. while (len >= 32) {
  76501. DOBIG32;
  76502. len -= 32;
  76503. }
  76504. while (len >= 4) {
  76505. DOBIG4;
  76506. len -= 4;
  76507. }
  76508. buf4++;
  76509. buf = (const unsigned char FAR *)buf4;
  76510. if (len) do {
  76511. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76512. } while (--len);
  76513. c = ~c;
  76514. return (unsigned long)(REV(c));
  76515. }
  76516. #endif /* BYFOUR */
  76517. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  76518. /* ========================================================================= */
  76519. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  76520. {
  76521. unsigned long sum;
  76522. sum = 0;
  76523. while (vec) {
  76524. if (vec & 1)
  76525. sum ^= *mat;
  76526. vec >>= 1;
  76527. mat++;
  76528. }
  76529. return sum;
  76530. }
  76531. /* ========================================================================= */
  76532. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  76533. {
  76534. int n;
  76535. for (n = 0; n < GF2_DIM; n++)
  76536. square[n] = gf2_matrix_times(mat, mat[n]);
  76537. }
  76538. /* ========================================================================= */
  76539. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  76540. {
  76541. int n;
  76542. unsigned long row;
  76543. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  76544. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  76545. /* degenerate case */
  76546. if (len2 == 0)
  76547. return crc1;
  76548. /* put operator for one zero bit in odd */
  76549. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  76550. row = 1;
  76551. for (n = 1; n < GF2_DIM; n++) {
  76552. odd[n] = row;
  76553. row <<= 1;
  76554. }
  76555. /* put operator for two zero bits in even */
  76556. gf2_matrix_square(even, odd);
  76557. /* put operator for four zero bits in odd */
  76558. gf2_matrix_square(odd, even);
  76559. /* apply len2 zeros to crc1 (first square will put the operator for one
  76560. zero byte, eight zero bits, in even) */
  76561. do {
  76562. /* apply zeros operator for this bit of len2 */
  76563. gf2_matrix_square(even, odd);
  76564. if (len2 & 1)
  76565. crc1 = gf2_matrix_times(even, crc1);
  76566. len2 >>= 1;
  76567. /* if no more bits set, then done */
  76568. if (len2 == 0)
  76569. break;
  76570. /* another iteration of the loop with odd and even swapped */
  76571. gf2_matrix_square(odd, even);
  76572. if (len2 & 1)
  76573. crc1 = gf2_matrix_times(odd, crc1);
  76574. len2 >>= 1;
  76575. /* if no more bits set, then done */
  76576. } while (len2 != 0);
  76577. /* return combined crc */
  76578. crc1 ^= crc2;
  76579. return crc1;
  76580. }
  76581. /********* End of inlined file: crc32.c *********/
  76582. /********* Start of inlined file: deflate.c *********/
  76583. /*
  76584. * ALGORITHM
  76585. *
  76586. * The "deflation" process depends on being able to identify portions
  76587. * of the input text which are identical to earlier input (within a
  76588. * sliding window trailing behind the input currently being processed).
  76589. *
  76590. * The most straightforward technique turns out to be the fastest for
  76591. * most input files: try all possible matches and select the longest.
  76592. * The key feature of this algorithm is that insertions into the string
  76593. * dictionary are very simple and thus fast, and deletions are avoided
  76594. * completely. Insertions are performed at each input character, whereas
  76595. * string matches are performed only when the previous match ends. So it
  76596. * is preferable to spend more time in matches to allow very fast string
  76597. * insertions and avoid deletions. The matching algorithm for small
  76598. * strings is inspired from that of Rabin & Karp. A brute force approach
  76599. * is used to find longer strings when a small match has been found.
  76600. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  76601. * (by Leonid Broukhis).
  76602. * A previous version of this file used a more sophisticated algorithm
  76603. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  76604. * time, but has a larger average cost, uses more memory and is patented.
  76605. * However the F&G algorithm may be faster for some highly redundant
  76606. * files if the parameter max_chain_length (described below) is too large.
  76607. *
  76608. * ACKNOWLEDGEMENTS
  76609. *
  76610. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  76611. * I found it in 'freeze' written by Leonid Broukhis.
  76612. * Thanks to many people for bug reports and testing.
  76613. *
  76614. * REFERENCES
  76615. *
  76616. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  76617. * Available in http://www.ietf.org/rfc/rfc1951.txt
  76618. *
  76619. * A description of the Rabin and Karp algorithm is given in the book
  76620. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  76621. *
  76622. * Fiala,E.R., and Greene,D.H.
  76623. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  76624. *
  76625. */
  76626. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76627. /********* Start of inlined file: deflate.h *********/
  76628. /* WARNING: this file should *not* be used by applications. It is
  76629. part of the implementation of the compression library and is
  76630. subject to change. Applications should only use zlib.h.
  76631. */
  76632. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76633. #ifndef DEFLATE_H
  76634. #define DEFLATE_H
  76635. /* define NO_GZIP when compiling if you want to disable gzip header and
  76636. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  76637. the crc code when it is not needed. For shared libraries, gzip encoding
  76638. should be left enabled. */
  76639. #ifndef NO_GZIP
  76640. # define GZIP
  76641. #endif
  76642. #define NO_DUMMY_DECL
  76643. /* ===========================================================================
  76644. * Internal compression state.
  76645. */
  76646. #define LENGTH_CODES 29
  76647. /* number of length codes, not counting the special END_BLOCK code */
  76648. #define LITERALS 256
  76649. /* number of literal bytes 0..255 */
  76650. #define L_CODES (LITERALS+1+LENGTH_CODES)
  76651. /* number of Literal or Length codes, including the END_BLOCK code */
  76652. #define D_CODES 30
  76653. /* number of distance codes */
  76654. #define BL_CODES 19
  76655. /* number of codes used to transfer the bit lengths */
  76656. #define HEAP_SIZE (2*L_CODES+1)
  76657. /* maximum heap size */
  76658. #define MAX_BITS 15
  76659. /* All codes must not exceed MAX_BITS bits */
  76660. #define INIT_STATE 42
  76661. #define EXTRA_STATE 69
  76662. #define NAME_STATE 73
  76663. #define COMMENT_STATE 91
  76664. #define HCRC_STATE 103
  76665. #define BUSY_STATE 113
  76666. #define FINISH_STATE 666
  76667. /* Stream status */
  76668. /* Data structure describing a single value and its code string. */
  76669. typedef struct ct_data_s {
  76670. union {
  76671. ush freq; /* frequency count */
  76672. ush code; /* bit string */
  76673. } fc;
  76674. union {
  76675. ush dad; /* father node in Huffman tree */
  76676. ush len; /* length of bit string */
  76677. } dl;
  76678. } FAR ct_data;
  76679. #define Freq fc.freq
  76680. #define Code fc.code
  76681. #define Dad dl.dad
  76682. #define Len dl.len
  76683. typedef struct static_tree_desc_s static_tree_desc;
  76684. typedef struct tree_desc_s {
  76685. ct_data *dyn_tree; /* the dynamic tree */
  76686. int max_code; /* largest code with non zero frequency */
  76687. static_tree_desc *stat_desc; /* the corresponding static tree */
  76688. } FAR tree_desc;
  76689. typedef ush Pos;
  76690. typedef Pos FAR Posf;
  76691. typedef unsigned IPos;
  76692. /* A Pos is an index in the character window. We use short instead of int to
  76693. * save space in the various tables. IPos is used only for parameter passing.
  76694. */
  76695. typedef struct internal_state {
  76696. z_streamp strm; /* pointer back to this zlib stream */
  76697. int status; /* as the name implies */
  76698. Bytef *pending_buf; /* output still pending */
  76699. ulg pending_buf_size; /* size of pending_buf */
  76700. Bytef *pending_out; /* next pending byte to output to the stream */
  76701. uInt pending; /* nb of bytes in the pending buffer */
  76702. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76703. gz_headerp gzhead; /* gzip header information to write */
  76704. uInt gzindex; /* where in extra, name, or comment */
  76705. Byte method; /* STORED (for zip only) or DEFLATED */
  76706. int last_flush; /* value of flush param for previous deflate call */
  76707. /* used by deflate.c: */
  76708. uInt w_size; /* LZ77 window size (32K by default) */
  76709. uInt w_bits; /* log2(w_size) (8..16) */
  76710. uInt w_mask; /* w_size - 1 */
  76711. Bytef *window;
  76712. /* Sliding window. Input bytes are read into the second half of the window,
  76713. * and move to the first half later to keep a dictionary of at least wSize
  76714. * bytes. With this organization, matches are limited to a distance of
  76715. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  76716. * performed with a length multiple of the block size. Also, it limits
  76717. * the window size to 64K, which is quite useful on MSDOS.
  76718. * To do: use the user input buffer as sliding window.
  76719. */
  76720. ulg window_size;
  76721. /* Actual size of window: 2*wSize, except when the user input buffer
  76722. * is directly used as sliding window.
  76723. */
  76724. Posf *prev;
  76725. /* Link to older string with same hash index. To limit the size of this
  76726. * array to 64K, this link is maintained only for the last 32K strings.
  76727. * An index in this array is thus a window index modulo 32K.
  76728. */
  76729. Posf *head; /* Heads of the hash chains or NIL. */
  76730. uInt ins_h; /* hash index of string to be inserted */
  76731. uInt hash_size; /* number of elements in hash table */
  76732. uInt hash_bits; /* log2(hash_size) */
  76733. uInt hash_mask; /* hash_size-1 */
  76734. uInt hash_shift;
  76735. /* Number of bits by which ins_h must be shifted at each input
  76736. * step. It must be such that after MIN_MATCH steps, the oldest
  76737. * byte no longer takes part in the hash key, that is:
  76738. * hash_shift * MIN_MATCH >= hash_bits
  76739. */
  76740. long block_start;
  76741. /* Window position at the beginning of the current output block. Gets
  76742. * negative when the window is moved backwards.
  76743. */
  76744. uInt match_length; /* length of best match */
  76745. IPos prev_match; /* previous match */
  76746. int match_available; /* set if previous match exists */
  76747. uInt strstart; /* start of string to insert */
  76748. uInt match_start; /* start of matching string */
  76749. uInt lookahead; /* number of valid bytes ahead in window */
  76750. uInt prev_length;
  76751. /* Length of the best match at previous step. Matches not greater than this
  76752. * are discarded. This is used in the lazy match evaluation.
  76753. */
  76754. uInt max_chain_length;
  76755. /* To speed up deflation, hash chains are never searched beyond this
  76756. * length. A higher limit improves compression ratio but degrades the
  76757. * speed.
  76758. */
  76759. uInt max_lazy_match;
  76760. /* Attempt to find a better match only when the current match is strictly
  76761. * smaller than this value. This mechanism is used only for compression
  76762. * levels >= 4.
  76763. */
  76764. # define max_insert_length max_lazy_match
  76765. /* Insert new strings in the hash table only if the match length is not
  76766. * greater than this length. This saves time but degrades compression.
  76767. * max_insert_length is used only for compression levels <= 3.
  76768. */
  76769. int level; /* compression level (1..9) */
  76770. int strategy; /* favor or force Huffman coding*/
  76771. uInt good_match;
  76772. /* Use a faster search when the previous match is longer than this */
  76773. int nice_match; /* Stop searching when current match exceeds this */
  76774. /* used by trees.c: */
  76775. /* Didn't use ct_data typedef below to supress compiler warning */
  76776. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  76777. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  76778. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  76779. struct tree_desc_s l_desc; /* desc. for literal tree */
  76780. struct tree_desc_s d_desc; /* desc. for distance tree */
  76781. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  76782. ush bl_count[MAX_BITS+1];
  76783. /* number of codes at each bit length for an optimal tree */
  76784. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  76785. int heap_len; /* number of elements in the heap */
  76786. int heap_max; /* element of largest frequency */
  76787. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  76788. * The same heap array is used to build all trees.
  76789. */
  76790. uch depth[2*L_CODES+1];
  76791. /* Depth of each subtree used as tie breaker for trees of equal frequency
  76792. */
  76793. uchf *l_buf; /* buffer for literals or lengths */
  76794. uInt lit_bufsize;
  76795. /* Size of match buffer for literals/lengths. There are 4 reasons for
  76796. * limiting lit_bufsize to 64K:
  76797. * - frequencies can be kept in 16 bit counters
  76798. * - if compression is not successful for the first block, all input
  76799. * data is still in the window so we can still emit a stored block even
  76800. * when input comes from standard input. (This can also be done for
  76801. * all blocks if lit_bufsize is not greater than 32K.)
  76802. * - if compression is not successful for a file smaller than 64K, we can
  76803. * even emit a stored file instead of a stored block (saving 5 bytes).
  76804. * This is applicable only for zip (not gzip or zlib).
  76805. * - creating new Huffman trees less frequently may not provide fast
  76806. * adaptation to changes in the input data statistics. (Take for
  76807. * example a binary file with poorly compressible code followed by
  76808. * a highly compressible string table.) Smaller buffer sizes give
  76809. * fast adaptation but have of course the overhead of transmitting
  76810. * trees more frequently.
  76811. * - I can't count above 4
  76812. */
  76813. uInt last_lit; /* running index in l_buf */
  76814. ushf *d_buf;
  76815. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  76816. * the same number of elements. To use different lengths, an extra flag
  76817. * array would be necessary.
  76818. */
  76819. ulg opt_len; /* bit length of current block with optimal trees */
  76820. ulg static_len; /* bit length of current block with static trees */
  76821. uInt matches; /* number of string matches in current block */
  76822. int last_eob_len; /* bit length of EOB code for last block */
  76823. #ifdef DEBUG
  76824. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  76825. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  76826. #endif
  76827. ush bi_buf;
  76828. /* Output buffer. bits are inserted starting at the bottom (least
  76829. * significant bits).
  76830. */
  76831. int bi_valid;
  76832. /* Number of valid bits in bi_buf. All bits above the last valid bit
  76833. * are always zero.
  76834. */
  76835. } FAR deflate_state;
  76836. /* Output a byte on the stream.
  76837. * IN assertion: there is enough room in pending_buf.
  76838. */
  76839. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  76840. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76841. /* Minimum amount of lookahead, except at the end of the input file.
  76842. * See deflate.c for comments about the MIN_MATCH+1.
  76843. */
  76844. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  76845. /* In order to simplify the code, particularly on 16 bit machines, match
  76846. * distances are limited to MAX_DIST instead of WSIZE.
  76847. */
  76848. /* in trees.c */
  76849. void _tr_init OF((deflate_state *s));
  76850. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  76851. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76852. int eof));
  76853. void _tr_align OF((deflate_state *s));
  76854. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76855. int eof));
  76856. #define d_code(dist) \
  76857. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  76858. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  76859. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  76860. * used.
  76861. */
  76862. #ifndef DEBUG
  76863. /* Inline versions of _tr_tally for speed: */
  76864. #if defined(GEN_TREES_H) || !defined(STDC)
  76865. extern uch _length_code[];
  76866. extern uch _dist_code[];
  76867. #else
  76868. extern const uch _length_code[];
  76869. extern const uch _dist_code[];
  76870. #endif
  76871. # define _tr_tally_lit(s, c, flush) \
  76872. { uch cc = (c); \
  76873. s->d_buf[s->last_lit] = 0; \
  76874. s->l_buf[s->last_lit++] = cc; \
  76875. s->dyn_ltree[cc].Freq++; \
  76876. flush = (s->last_lit == s->lit_bufsize-1); \
  76877. }
  76878. # define _tr_tally_dist(s, distance, length, flush) \
  76879. { uch len = (length); \
  76880. ush dist = (distance); \
  76881. s->d_buf[s->last_lit] = dist; \
  76882. s->l_buf[s->last_lit++] = len; \
  76883. dist--; \
  76884. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  76885. s->dyn_dtree[d_code(dist)].Freq++; \
  76886. flush = (s->last_lit == s->lit_bufsize-1); \
  76887. }
  76888. #else
  76889. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  76890. # define _tr_tally_dist(s, distance, length, flush) \
  76891. flush = _tr_tally(s, distance, length)
  76892. #endif
  76893. #endif /* DEFLATE_H */
  76894. /********* End of inlined file: deflate.h *********/
  76895. const char deflate_copyright[] =
  76896. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  76897. /*
  76898. If you use the zlib library in a product, an acknowledgment is welcome
  76899. in the documentation of your product. If for some reason you cannot
  76900. include such an acknowledgment, I would appreciate that you keep this
  76901. copyright string in the executable of your product.
  76902. */
  76903. /* ===========================================================================
  76904. * Function prototypes.
  76905. */
  76906. typedef enum {
  76907. need_more, /* block not completed, need more input or more output */
  76908. block_done, /* block flush performed */
  76909. finish_started, /* finish started, need only more output at next deflate */
  76910. finish_done /* finish done, accept no more input or output */
  76911. } block_state;
  76912. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  76913. /* Compression function. Returns the block state after the call. */
  76914. local void fill_window OF((deflate_state *s));
  76915. local block_state deflate_stored OF((deflate_state *s, int flush));
  76916. local block_state deflate_fast OF((deflate_state *s, int flush));
  76917. #ifndef FASTEST
  76918. local block_state deflate_slow OF((deflate_state *s, int flush));
  76919. #endif
  76920. local void lm_init OF((deflate_state *s));
  76921. local void putShortMSB OF((deflate_state *s, uInt b));
  76922. local void flush_pending OF((z_streamp strm));
  76923. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  76924. #ifndef FASTEST
  76925. #ifdef ASMV
  76926. void match_init OF((void)); /* asm code initialization */
  76927. uInt longest_match OF((deflate_state *s, IPos cur_match));
  76928. #else
  76929. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  76930. #endif
  76931. #endif
  76932. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  76933. #ifdef DEBUG
  76934. local void check_match OF((deflate_state *s, IPos start, IPos match,
  76935. int length));
  76936. #endif
  76937. /* ===========================================================================
  76938. * Local data
  76939. */
  76940. #define NIL 0
  76941. /* Tail of hash chains */
  76942. #ifndef TOO_FAR
  76943. # define TOO_FAR 4096
  76944. #endif
  76945. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  76946. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76947. /* Minimum amount of lookahead, except at the end of the input file.
  76948. * See deflate.c for comments about the MIN_MATCH+1.
  76949. */
  76950. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  76951. * the desired pack level (0..9). The values given below have been tuned to
  76952. * exclude worst case performance for pathological files. Better values may be
  76953. * found for specific files.
  76954. */
  76955. typedef struct config_s {
  76956. ush good_length; /* reduce lazy search above this match length */
  76957. ush max_lazy; /* do not perform lazy search above this match length */
  76958. ush nice_length; /* quit search above this match length */
  76959. ush max_chain;
  76960. compress_func func;
  76961. } config;
  76962. #ifdef FASTEST
  76963. local const config configuration_table[2] = {
  76964. /* good lazy nice chain */
  76965. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76966. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  76967. #else
  76968. local const config configuration_table[10] = {
  76969. /* good lazy nice chain */
  76970. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76971. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  76972. /* 2 */ {4, 5, 16, 8, deflate_fast},
  76973. /* 3 */ {4, 6, 32, 32, deflate_fast},
  76974. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  76975. /* 5 */ {8, 16, 32, 32, deflate_slow},
  76976. /* 6 */ {8, 16, 128, 128, deflate_slow},
  76977. /* 7 */ {8, 32, 128, 256, deflate_slow},
  76978. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  76979. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  76980. #endif
  76981. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  76982. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  76983. * meaning.
  76984. */
  76985. #define EQUAL 0
  76986. /* result of memcmp for equal strings */
  76987. #ifndef NO_DUMMY_DECL
  76988. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  76989. #endif
  76990. /* ===========================================================================
  76991. * Update a hash value with the given input byte
  76992. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  76993. * input characters, so that a running hash key can be computed from the
  76994. * previous key instead of complete recalculation each time.
  76995. */
  76996. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  76997. /* ===========================================================================
  76998. * Insert string str in the dictionary and set match_head to the previous head
  76999. * of the hash chain (the most recent string with same hash key). Return
  77000. * the previous length of the hash chain.
  77001. * If this file is compiled with -DFASTEST, the compression level is forced
  77002. * to 1, and no hash chains are maintained.
  77003. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  77004. * input characters and the first MIN_MATCH bytes of str are valid
  77005. * (except for the last MIN_MATCH-1 bytes of the input file).
  77006. */
  77007. #ifdef FASTEST
  77008. #define INSERT_STRING(s, str, match_head) \
  77009. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  77010. match_head = s->head[s->ins_h], \
  77011. s->head[s->ins_h] = (Pos)(str))
  77012. #else
  77013. #define INSERT_STRING(s, str, match_head) \
  77014. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  77015. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  77016. s->head[s->ins_h] = (Pos)(str))
  77017. #endif
  77018. /* ===========================================================================
  77019. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  77020. * prev[] will be initialized on the fly.
  77021. */
  77022. #define CLEAR_HASH(s) \
  77023. s->head[s->hash_size-1] = NIL; \
  77024. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  77025. /* ========================================================================= */
  77026. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  77027. {
  77028. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  77029. Z_DEFAULT_STRATEGY, version, stream_size);
  77030. /* To do: ignore strm->next_in if we use it as window */
  77031. }
  77032. /* ========================================================================= */
  77033. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  77034. {
  77035. deflate_state *s;
  77036. int wrap = 1;
  77037. static const char my_version[] = ZLIB_VERSION;
  77038. ushf *overlay;
  77039. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  77040. * output size for (length,distance) codes is <= 24 bits.
  77041. */
  77042. if (version == Z_NULL || version[0] != my_version[0] ||
  77043. stream_size != sizeof(z_stream)) {
  77044. return Z_VERSION_ERROR;
  77045. }
  77046. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77047. strm->msg = Z_NULL;
  77048. if (strm->zalloc == (alloc_func)0) {
  77049. strm->zalloc = zcalloc;
  77050. strm->opaque = (voidpf)0;
  77051. }
  77052. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77053. #ifdef FASTEST
  77054. if (level != 0) level = 1;
  77055. #else
  77056. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77057. #endif
  77058. if (windowBits < 0) { /* suppress zlib wrapper */
  77059. wrap = 0;
  77060. windowBits = -windowBits;
  77061. }
  77062. #ifdef GZIP
  77063. else if (windowBits > 15) {
  77064. wrap = 2; /* write gzip wrapper instead */
  77065. windowBits -= 16;
  77066. }
  77067. #endif
  77068. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  77069. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  77070. strategy < 0 || strategy > Z_FIXED) {
  77071. return Z_STREAM_ERROR;
  77072. }
  77073. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  77074. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  77075. if (s == Z_NULL) return Z_MEM_ERROR;
  77076. strm->state = (struct internal_state FAR *)s;
  77077. s->strm = strm;
  77078. s->wrap = wrap;
  77079. s->gzhead = Z_NULL;
  77080. s->w_bits = windowBits;
  77081. s->w_size = 1 << s->w_bits;
  77082. s->w_mask = s->w_size - 1;
  77083. s->hash_bits = memLevel + 7;
  77084. s->hash_size = 1 << s->hash_bits;
  77085. s->hash_mask = s->hash_size - 1;
  77086. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  77087. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  77088. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  77089. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  77090. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  77091. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  77092. s->pending_buf = (uchf *) overlay;
  77093. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  77094. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  77095. s->pending_buf == Z_NULL) {
  77096. s->status = FINISH_STATE;
  77097. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  77098. deflateEnd (strm);
  77099. return Z_MEM_ERROR;
  77100. }
  77101. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  77102. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  77103. s->level = level;
  77104. s->strategy = strategy;
  77105. s->method = (Byte)method;
  77106. return deflateReset(strm);
  77107. }
  77108. /* ========================================================================= */
  77109. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  77110. {
  77111. deflate_state *s;
  77112. uInt length = dictLength;
  77113. uInt n;
  77114. IPos hash_head = 0;
  77115. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  77116. strm->state->wrap == 2 ||
  77117. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  77118. return Z_STREAM_ERROR;
  77119. s = strm->state;
  77120. if (s->wrap)
  77121. strm->adler = adler32(strm->adler, dictionary, dictLength);
  77122. if (length < MIN_MATCH) return Z_OK;
  77123. if (length > MAX_DIST(s)) {
  77124. length = MAX_DIST(s);
  77125. dictionary += dictLength - length; /* use the tail of the dictionary */
  77126. }
  77127. zmemcpy(s->window, dictionary, length);
  77128. s->strstart = length;
  77129. s->block_start = (long)length;
  77130. /* Insert all strings in the hash table (except for the last two bytes).
  77131. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  77132. * call of fill_window.
  77133. */
  77134. s->ins_h = s->window[0];
  77135. UPDATE_HASH(s, s->ins_h, s->window[1]);
  77136. for (n = 0; n <= length - MIN_MATCH; n++) {
  77137. INSERT_STRING(s, n, hash_head);
  77138. }
  77139. if (hash_head) hash_head = 0; /* to make compiler happy */
  77140. return Z_OK;
  77141. }
  77142. /* ========================================================================= */
  77143. int ZEXPORT deflateReset (z_streamp strm)
  77144. {
  77145. deflate_state *s;
  77146. if (strm == Z_NULL || strm->state == Z_NULL ||
  77147. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  77148. return Z_STREAM_ERROR;
  77149. }
  77150. strm->total_in = strm->total_out = 0;
  77151. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  77152. strm->data_type = Z_UNKNOWN;
  77153. s = (deflate_state *)strm->state;
  77154. s->pending = 0;
  77155. s->pending_out = s->pending_buf;
  77156. if (s->wrap < 0) {
  77157. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  77158. }
  77159. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  77160. strm->adler =
  77161. #ifdef GZIP
  77162. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  77163. #endif
  77164. adler32(0L, Z_NULL, 0);
  77165. s->last_flush = Z_NO_FLUSH;
  77166. _tr_init(s);
  77167. lm_init(s);
  77168. return Z_OK;
  77169. }
  77170. /* ========================================================================= */
  77171. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  77172. {
  77173. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77174. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  77175. strm->state->gzhead = head;
  77176. return Z_OK;
  77177. }
  77178. /* ========================================================================= */
  77179. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  77180. {
  77181. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77182. strm->state->bi_valid = bits;
  77183. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  77184. return Z_OK;
  77185. }
  77186. /* ========================================================================= */
  77187. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  77188. {
  77189. deflate_state *s;
  77190. compress_func func;
  77191. int err = Z_OK;
  77192. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77193. s = strm->state;
  77194. #ifdef FASTEST
  77195. if (level != 0) level = 1;
  77196. #else
  77197. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77198. #endif
  77199. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  77200. return Z_STREAM_ERROR;
  77201. }
  77202. func = configuration_table[s->level].func;
  77203. if (func != configuration_table[level].func && strm->total_in != 0) {
  77204. /* Flush the last buffer: */
  77205. err = deflate(strm, Z_PARTIAL_FLUSH);
  77206. }
  77207. if (s->level != level) {
  77208. s->level = level;
  77209. s->max_lazy_match = configuration_table[level].max_lazy;
  77210. s->good_match = configuration_table[level].good_length;
  77211. s->nice_match = configuration_table[level].nice_length;
  77212. s->max_chain_length = configuration_table[level].max_chain;
  77213. }
  77214. s->strategy = strategy;
  77215. return err;
  77216. }
  77217. /* ========================================================================= */
  77218. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  77219. {
  77220. deflate_state *s;
  77221. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77222. s = strm->state;
  77223. s->good_match = good_length;
  77224. s->max_lazy_match = max_lazy;
  77225. s->nice_match = nice_length;
  77226. s->max_chain_length = max_chain;
  77227. return Z_OK;
  77228. }
  77229. /* =========================================================================
  77230. * For the default windowBits of 15 and memLevel of 8, this function returns
  77231. * a close to exact, as well as small, upper bound on the compressed size.
  77232. * They are coded as constants here for a reason--if the #define's are
  77233. * changed, then this function needs to be changed as well. The return
  77234. * value for 15 and 8 only works for those exact settings.
  77235. *
  77236. * For any setting other than those defaults for windowBits and memLevel,
  77237. * the value returned is a conservative worst case for the maximum expansion
  77238. * resulting from using fixed blocks instead of stored blocks, which deflate
  77239. * can emit on compressed data for some combinations of the parameters.
  77240. *
  77241. * This function could be more sophisticated to provide closer upper bounds
  77242. * for every combination of windowBits and memLevel, as well as wrap.
  77243. * But even the conservative upper bound of about 14% expansion does not
  77244. * seem onerous for output buffer allocation.
  77245. */
  77246. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  77247. {
  77248. deflate_state *s;
  77249. uLong destLen;
  77250. /* conservative upper bound */
  77251. destLen = sourceLen +
  77252. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  77253. /* if can't get parameters, return conservative bound */
  77254. if (strm == Z_NULL || strm->state == Z_NULL)
  77255. return destLen;
  77256. /* if not default parameters, return conservative bound */
  77257. s = strm->state;
  77258. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  77259. return destLen;
  77260. /* default settings: return tight bound for that case */
  77261. return compressBound(sourceLen);
  77262. }
  77263. /* =========================================================================
  77264. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  77265. * IN assertion: the stream state is correct and there is enough room in
  77266. * pending_buf.
  77267. */
  77268. local void putShortMSB (deflate_state *s, uInt b)
  77269. {
  77270. put_byte(s, (Byte)(b >> 8));
  77271. put_byte(s, (Byte)(b & 0xff));
  77272. }
  77273. /* =========================================================================
  77274. * Flush as much pending output as possible. All deflate() output goes
  77275. * through this function so some applications may wish to modify it
  77276. * to avoid allocating a large strm->next_out buffer and copying into it.
  77277. * (See also read_buf()).
  77278. */
  77279. local void flush_pending (z_streamp strm)
  77280. {
  77281. unsigned len = strm->state->pending;
  77282. if (len > strm->avail_out) len = strm->avail_out;
  77283. if (len == 0) return;
  77284. zmemcpy(strm->next_out, strm->state->pending_out, len);
  77285. strm->next_out += len;
  77286. strm->state->pending_out += len;
  77287. strm->total_out += len;
  77288. strm->avail_out -= len;
  77289. strm->state->pending -= len;
  77290. if (strm->state->pending == 0) {
  77291. strm->state->pending_out = strm->state->pending_buf;
  77292. }
  77293. }
  77294. /* ========================================================================= */
  77295. int ZEXPORT deflate (z_streamp strm, int flush)
  77296. {
  77297. int old_flush; /* value of flush param for previous deflate call */
  77298. deflate_state *s;
  77299. if (strm == Z_NULL || strm->state == Z_NULL ||
  77300. flush > Z_FINISH || flush < 0) {
  77301. return Z_STREAM_ERROR;
  77302. }
  77303. s = strm->state;
  77304. if (strm->next_out == Z_NULL ||
  77305. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  77306. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  77307. ERR_RETURN(strm, Z_STREAM_ERROR);
  77308. }
  77309. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  77310. s->strm = strm; /* just in case */
  77311. old_flush = s->last_flush;
  77312. s->last_flush = flush;
  77313. /* Write the header */
  77314. if (s->status == INIT_STATE) {
  77315. #ifdef GZIP
  77316. if (s->wrap == 2) {
  77317. strm->adler = crc32(0L, Z_NULL, 0);
  77318. put_byte(s, 31);
  77319. put_byte(s, 139);
  77320. put_byte(s, 8);
  77321. if (s->gzhead == NULL) {
  77322. put_byte(s, 0);
  77323. put_byte(s, 0);
  77324. put_byte(s, 0);
  77325. put_byte(s, 0);
  77326. put_byte(s, 0);
  77327. put_byte(s, s->level == 9 ? 2 :
  77328. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77329. 4 : 0));
  77330. put_byte(s, OS_CODE);
  77331. s->status = BUSY_STATE;
  77332. }
  77333. else {
  77334. put_byte(s, (s->gzhead->text ? 1 : 0) +
  77335. (s->gzhead->hcrc ? 2 : 0) +
  77336. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  77337. (s->gzhead->name == Z_NULL ? 0 : 8) +
  77338. (s->gzhead->comment == Z_NULL ? 0 : 16)
  77339. );
  77340. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  77341. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  77342. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  77343. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  77344. put_byte(s, s->level == 9 ? 2 :
  77345. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77346. 4 : 0));
  77347. put_byte(s, s->gzhead->os & 0xff);
  77348. if (s->gzhead->extra != NULL) {
  77349. put_byte(s, s->gzhead->extra_len & 0xff);
  77350. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  77351. }
  77352. if (s->gzhead->hcrc)
  77353. strm->adler = crc32(strm->adler, s->pending_buf,
  77354. s->pending);
  77355. s->gzindex = 0;
  77356. s->status = EXTRA_STATE;
  77357. }
  77358. }
  77359. else
  77360. #endif
  77361. {
  77362. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  77363. uInt level_flags;
  77364. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  77365. level_flags = 0;
  77366. else if (s->level < 6)
  77367. level_flags = 1;
  77368. else if (s->level == 6)
  77369. level_flags = 2;
  77370. else
  77371. level_flags = 3;
  77372. header |= (level_flags << 6);
  77373. if (s->strstart != 0) header |= PRESET_DICT;
  77374. header += 31 - (header % 31);
  77375. s->status = BUSY_STATE;
  77376. putShortMSB(s, header);
  77377. /* Save the adler32 of the preset dictionary: */
  77378. if (s->strstart != 0) {
  77379. putShortMSB(s, (uInt)(strm->adler >> 16));
  77380. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77381. }
  77382. strm->adler = adler32(0L, Z_NULL, 0);
  77383. }
  77384. }
  77385. #ifdef GZIP
  77386. if (s->status == EXTRA_STATE) {
  77387. if (s->gzhead->extra != NULL) {
  77388. uInt beg = s->pending; /* start of bytes to update crc */
  77389. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  77390. if (s->pending == s->pending_buf_size) {
  77391. if (s->gzhead->hcrc && s->pending > beg)
  77392. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77393. s->pending - beg);
  77394. flush_pending(strm);
  77395. beg = s->pending;
  77396. if (s->pending == s->pending_buf_size)
  77397. break;
  77398. }
  77399. put_byte(s, s->gzhead->extra[s->gzindex]);
  77400. s->gzindex++;
  77401. }
  77402. if (s->gzhead->hcrc && s->pending > beg)
  77403. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77404. s->pending - beg);
  77405. if (s->gzindex == s->gzhead->extra_len) {
  77406. s->gzindex = 0;
  77407. s->status = NAME_STATE;
  77408. }
  77409. }
  77410. else
  77411. s->status = NAME_STATE;
  77412. }
  77413. if (s->status == NAME_STATE) {
  77414. if (s->gzhead->name != NULL) {
  77415. uInt beg = s->pending; /* start of bytes to update crc */
  77416. int val;
  77417. do {
  77418. if (s->pending == s->pending_buf_size) {
  77419. if (s->gzhead->hcrc && s->pending > beg)
  77420. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77421. s->pending - beg);
  77422. flush_pending(strm);
  77423. beg = s->pending;
  77424. if (s->pending == s->pending_buf_size) {
  77425. val = 1;
  77426. break;
  77427. }
  77428. }
  77429. val = s->gzhead->name[s->gzindex++];
  77430. put_byte(s, val);
  77431. } while (val != 0);
  77432. if (s->gzhead->hcrc && s->pending > beg)
  77433. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77434. s->pending - beg);
  77435. if (val == 0) {
  77436. s->gzindex = 0;
  77437. s->status = COMMENT_STATE;
  77438. }
  77439. }
  77440. else
  77441. s->status = COMMENT_STATE;
  77442. }
  77443. if (s->status == COMMENT_STATE) {
  77444. if (s->gzhead->comment != NULL) {
  77445. uInt beg = s->pending; /* start of bytes to update crc */
  77446. int val;
  77447. do {
  77448. if (s->pending == s->pending_buf_size) {
  77449. if (s->gzhead->hcrc && s->pending > beg)
  77450. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77451. s->pending - beg);
  77452. flush_pending(strm);
  77453. beg = s->pending;
  77454. if (s->pending == s->pending_buf_size) {
  77455. val = 1;
  77456. break;
  77457. }
  77458. }
  77459. val = s->gzhead->comment[s->gzindex++];
  77460. put_byte(s, val);
  77461. } while (val != 0);
  77462. if (s->gzhead->hcrc && s->pending > beg)
  77463. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77464. s->pending - beg);
  77465. if (val == 0)
  77466. s->status = HCRC_STATE;
  77467. }
  77468. else
  77469. s->status = HCRC_STATE;
  77470. }
  77471. if (s->status == HCRC_STATE) {
  77472. if (s->gzhead->hcrc) {
  77473. if (s->pending + 2 > s->pending_buf_size)
  77474. flush_pending(strm);
  77475. if (s->pending + 2 <= s->pending_buf_size) {
  77476. put_byte(s, (Byte)(strm->adler & 0xff));
  77477. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77478. strm->adler = crc32(0L, Z_NULL, 0);
  77479. s->status = BUSY_STATE;
  77480. }
  77481. }
  77482. else
  77483. s->status = BUSY_STATE;
  77484. }
  77485. #endif
  77486. /* Flush as much pending output as possible */
  77487. if (s->pending != 0) {
  77488. flush_pending(strm);
  77489. if (strm->avail_out == 0) {
  77490. /* Since avail_out is 0, deflate will be called again with
  77491. * more output space, but possibly with both pending and
  77492. * avail_in equal to zero. There won't be anything to do,
  77493. * but this is not an error situation so make sure we
  77494. * return OK instead of BUF_ERROR at next call of deflate:
  77495. */
  77496. s->last_flush = -1;
  77497. return Z_OK;
  77498. }
  77499. /* Make sure there is something to do and avoid duplicate consecutive
  77500. * flushes. For repeated and useless calls with Z_FINISH, we keep
  77501. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  77502. */
  77503. } else if (strm->avail_in == 0 && flush <= old_flush &&
  77504. flush != Z_FINISH) {
  77505. ERR_RETURN(strm, Z_BUF_ERROR);
  77506. }
  77507. /* User must not provide more input after the first FINISH: */
  77508. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  77509. ERR_RETURN(strm, Z_BUF_ERROR);
  77510. }
  77511. /* Start a new block or continue the current one.
  77512. */
  77513. if (strm->avail_in != 0 || s->lookahead != 0 ||
  77514. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  77515. block_state bstate;
  77516. bstate = (*(configuration_table[s->level].func))(s, flush);
  77517. if (bstate == finish_started || bstate == finish_done) {
  77518. s->status = FINISH_STATE;
  77519. }
  77520. if (bstate == need_more || bstate == finish_started) {
  77521. if (strm->avail_out == 0) {
  77522. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  77523. }
  77524. return Z_OK;
  77525. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  77526. * of deflate should use the same flush parameter to make sure
  77527. * that the flush is complete. So we don't have to output an
  77528. * empty block here, this will be done at next call. This also
  77529. * ensures that for a very small output buffer, we emit at most
  77530. * one empty block.
  77531. */
  77532. }
  77533. if (bstate == block_done) {
  77534. if (flush == Z_PARTIAL_FLUSH) {
  77535. _tr_align(s);
  77536. } else { /* FULL_FLUSH or SYNC_FLUSH */
  77537. _tr_stored_block(s, (char*)0, 0L, 0);
  77538. /* For a full flush, this empty block will be recognized
  77539. * as a special marker by inflate_sync().
  77540. */
  77541. if (flush == Z_FULL_FLUSH) {
  77542. CLEAR_HASH(s); /* forget history */
  77543. }
  77544. }
  77545. flush_pending(strm);
  77546. if (strm->avail_out == 0) {
  77547. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  77548. return Z_OK;
  77549. }
  77550. }
  77551. }
  77552. Assert(strm->avail_out > 0, "bug2");
  77553. if (flush != Z_FINISH) return Z_OK;
  77554. if (s->wrap <= 0) return Z_STREAM_END;
  77555. /* Write the trailer */
  77556. #ifdef GZIP
  77557. if (s->wrap == 2) {
  77558. put_byte(s, (Byte)(strm->adler & 0xff));
  77559. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77560. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  77561. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  77562. put_byte(s, (Byte)(strm->total_in & 0xff));
  77563. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  77564. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  77565. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  77566. }
  77567. else
  77568. #endif
  77569. {
  77570. putShortMSB(s, (uInt)(strm->adler >> 16));
  77571. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77572. }
  77573. flush_pending(strm);
  77574. /* If avail_out is zero, the application will call deflate again
  77575. * to flush the rest.
  77576. */
  77577. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  77578. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  77579. }
  77580. /* ========================================================================= */
  77581. int ZEXPORT deflateEnd (z_streamp strm)
  77582. {
  77583. int status;
  77584. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77585. status = strm->state->status;
  77586. if (status != INIT_STATE &&
  77587. status != EXTRA_STATE &&
  77588. status != NAME_STATE &&
  77589. status != COMMENT_STATE &&
  77590. status != HCRC_STATE &&
  77591. status != BUSY_STATE &&
  77592. status != FINISH_STATE) {
  77593. return Z_STREAM_ERROR;
  77594. }
  77595. /* Deallocate in reverse order of allocations: */
  77596. TRY_FREE(strm, strm->state->pending_buf);
  77597. TRY_FREE(strm, strm->state->head);
  77598. TRY_FREE(strm, strm->state->prev);
  77599. TRY_FREE(strm, strm->state->window);
  77600. ZFREE(strm, strm->state);
  77601. strm->state = Z_NULL;
  77602. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  77603. }
  77604. /* =========================================================================
  77605. * Copy the source state to the destination state.
  77606. * To simplify the source, this is not supported for 16-bit MSDOS (which
  77607. * doesn't have enough memory anyway to duplicate compression states).
  77608. */
  77609. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  77610. {
  77611. #ifdef MAXSEG_64K
  77612. return Z_STREAM_ERROR;
  77613. #else
  77614. deflate_state *ds;
  77615. deflate_state *ss;
  77616. ushf *overlay;
  77617. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  77618. return Z_STREAM_ERROR;
  77619. }
  77620. ss = source->state;
  77621. zmemcpy(dest, source, sizeof(z_stream));
  77622. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  77623. if (ds == Z_NULL) return Z_MEM_ERROR;
  77624. dest->state = (struct internal_state FAR *) ds;
  77625. zmemcpy(ds, ss, sizeof(deflate_state));
  77626. ds->strm = dest;
  77627. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  77628. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  77629. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  77630. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  77631. ds->pending_buf = (uchf *) overlay;
  77632. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  77633. ds->pending_buf == Z_NULL) {
  77634. deflateEnd (dest);
  77635. return Z_MEM_ERROR;
  77636. }
  77637. /* following zmemcpy do not work for 16-bit MSDOS */
  77638. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  77639. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  77640. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  77641. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  77642. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  77643. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  77644. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  77645. ds->l_desc.dyn_tree = ds->dyn_ltree;
  77646. ds->d_desc.dyn_tree = ds->dyn_dtree;
  77647. ds->bl_desc.dyn_tree = ds->bl_tree;
  77648. return Z_OK;
  77649. #endif /* MAXSEG_64K */
  77650. }
  77651. /* ===========================================================================
  77652. * Read a new buffer from the current input stream, update the adler32
  77653. * and total number of bytes read. All deflate() input goes through
  77654. * this function so some applications may wish to modify it to avoid
  77655. * allocating a large strm->next_in buffer and copying from it.
  77656. * (See also flush_pending()).
  77657. */
  77658. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  77659. {
  77660. unsigned len = strm->avail_in;
  77661. if (len > size) len = size;
  77662. if (len == 0) return 0;
  77663. strm->avail_in -= len;
  77664. if (strm->state->wrap == 1) {
  77665. strm->adler = adler32(strm->adler, strm->next_in, len);
  77666. }
  77667. #ifdef GZIP
  77668. else if (strm->state->wrap == 2) {
  77669. strm->adler = crc32(strm->adler, strm->next_in, len);
  77670. }
  77671. #endif
  77672. zmemcpy(buf, strm->next_in, len);
  77673. strm->next_in += len;
  77674. strm->total_in += len;
  77675. return (int)len;
  77676. }
  77677. /* ===========================================================================
  77678. * Initialize the "longest match" routines for a new zlib stream
  77679. */
  77680. local void lm_init (deflate_state *s)
  77681. {
  77682. s->window_size = (ulg)2L*s->w_size;
  77683. CLEAR_HASH(s);
  77684. /* Set the default configuration parameters:
  77685. */
  77686. s->max_lazy_match = configuration_table[s->level].max_lazy;
  77687. s->good_match = configuration_table[s->level].good_length;
  77688. s->nice_match = configuration_table[s->level].nice_length;
  77689. s->max_chain_length = configuration_table[s->level].max_chain;
  77690. s->strstart = 0;
  77691. s->block_start = 0L;
  77692. s->lookahead = 0;
  77693. s->match_length = s->prev_length = MIN_MATCH-1;
  77694. s->match_available = 0;
  77695. s->ins_h = 0;
  77696. #ifndef FASTEST
  77697. #ifdef ASMV
  77698. match_init(); /* initialize the asm code */
  77699. #endif
  77700. #endif
  77701. }
  77702. #ifndef FASTEST
  77703. /* ===========================================================================
  77704. * Set match_start to the longest match starting at the given string and
  77705. * return its length. Matches shorter or equal to prev_length are discarded,
  77706. * in which case the result is equal to prev_length and match_start is
  77707. * garbage.
  77708. * IN assertions: cur_match is the head of the hash chain for the current
  77709. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  77710. * OUT assertion: the match length is not greater than s->lookahead.
  77711. */
  77712. #ifndef ASMV
  77713. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  77714. * match.S. The code will be functionally equivalent.
  77715. */
  77716. local uInt longest_match(deflate_state *s, IPos cur_match)
  77717. {
  77718. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  77719. register Bytef *scan = s->window + s->strstart; /* current string */
  77720. register Bytef *match; /* matched string */
  77721. register int len; /* length of current match */
  77722. int best_len = s->prev_length; /* best match length so far */
  77723. int nice_match = s->nice_match; /* stop if match long enough */
  77724. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  77725. s->strstart - (IPos)MAX_DIST(s) : NIL;
  77726. /* Stop when cur_match becomes <= limit. To simplify the code,
  77727. * we prevent matches with the string of window index 0.
  77728. */
  77729. Posf *prev = s->prev;
  77730. uInt wmask = s->w_mask;
  77731. #ifdef UNALIGNED_OK
  77732. /* Compare two bytes at a time. Note: this is not always beneficial.
  77733. * Try with and without -DUNALIGNED_OK to check.
  77734. */
  77735. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  77736. register ush scan_start = *(ushf*)scan;
  77737. register ush scan_end = *(ushf*)(scan+best_len-1);
  77738. #else
  77739. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77740. register Byte scan_end1 = scan[best_len-1];
  77741. register Byte scan_end = scan[best_len];
  77742. #endif
  77743. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77744. * It is easy to get rid of this optimization if necessary.
  77745. */
  77746. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77747. /* Do not waste too much time if we already have a good match: */
  77748. if (s->prev_length >= s->good_match) {
  77749. chain_length >>= 2;
  77750. }
  77751. /* Do not look for matches beyond the end of the input. This is necessary
  77752. * to make deflate deterministic.
  77753. */
  77754. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  77755. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77756. do {
  77757. Assert(cur_match < s->strstart, "no future");
  77758. match = s->window + cur_match;
  77759. /* Skip to next match if the match length cannot increase
  77760. * or if the match length is less than 2. Note that the checks below
  77761. * for insufficient lookahead only occur occasionally for performance
  77762. * reasons. Therefore uninitialized memory will be accessed, and
  77763. * conditional jumps will be made that depend on those values.
  77764. * However the length of the match is limited to the lookahead, so
  77765. * the output of deflate is not affected by the uninitialized values.
  77766. */
  77767. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  77768. /* This code assumes sizeof(unsigned short) == 2. Do not use
  77769. * UNALIGNED_OK if your compiler uses a different size.
  77770. */
  77771. if (*(ushf*)(match+best_len-1) != scan_end ||
  77772. *(ushf*)match != scan_start) continue;
  77773. /* It is not necessary to compare scan[2] and match[2] since they are
  77774. * always equal when the other bytes match, given that the hash keys
  77775. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  77776. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  77777. * lookahead only every 4th comparison; the 128th check will be made
  77778. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  77779. * necessary to put more guard bytes at the end of the window, or
  77780. * to check more often for insufficient lookahead.
  77781. */
  77782. Assert(scan[2] == match[2], "scan[2]?");
  77783. scan++, match++;
  77784. do {
  77785. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77786. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77787. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77788. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77789. scan < strend);
  77790. /* The funny "do {}" generates better code on most compilers */
  77791. /* Here, scan <= window+strstart+257 */
  77792. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77793. if (*scan == *match) scan++;
  77794. len = (MAX_MATCH - 1) - (int)(strend-scan);
  77795. scan = strend - (MAX_MATCH-1);
  77796. #else /* UNALIGNED_OK */
  77797. if (match[best_len] != scan_end ||
  77798. match[best_len-1] != scan_end1 ||
  77799. *match != *scan ||
  77800. *++match != scan[1]) continue;
  77801. /* The check at best_len-1 can be removed because it will be made
  77802. * again later. (This heuristic is not always a win.)
  77803. * It is not necessary to compare scan[2] and match[2] since they
  77804. * are always equal when the other bytes match, given that
  77805. * the hash keys are equal and that HASH_BITS >= 8.
  77806. */
  77807. scan += 2, match++;
  77808. Assert(*scan == *match, "match[2]?");
  77809. /* We check for insufficient lookahead only every 8th comparison;
  77810. * the 256th check will be made at strstart+258.
  77811. */
  77812. do {
  77813. } while (*++scan == *++match && *++scan == *++match &&
  77814. *++scan == *++match && *++scan == *++match &&
  77815. *++scan == *++match && *++scan == *++match &&
  77816. *++scan == *++match && *++scan == *++match &&
  77817. scan < strend);
  77818. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77819. len = MAX_MATCH - (int)(strend - scan);
  77820. scan = strend - MAX_MATCH;
  77821. #endif /* UNALIGNED_OK */
  77822. if (len > best_len) {
  77823. s->match_start = cur_match;
  77824. best_len = len;
  77825. if (len >= nice_match) break;
  77826. #ifdef UNALIGNED_OK
  77827. scan_end = *(ushf*)(scan+best_len-1);
  77828. #else
  77829. scan_end1 = scan[best_len-1];
  77830. scan_end = scan[best_len];
  77831. #endif
  77832. }
  77833. } while ((cur_match = prev[cur_match & wmask]) > limit
  77834. && --chain_length != 0);
  77835. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  77836. return s->lookahead;
  77837. }
  77838. #endif /* ASMV */
  77839. #endif /* FASTEST */
  77840. /* ---------------------------------------------------------------------------
  77841. * Optimized version for level == 1 or strategy == Z_RLE only
  77842. */
  77843. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  77844. {
  77845. register Bytef *scan = s->window + s->strstart; /* current string */
  77846. register Bytef *match; /* matched string */
  77847. register int len; /* length of current match */
  77848. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77849. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77850. * It is easy to get rid of this optimization if necessary.
  77851. */
  77852. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77853. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77854. Assert(cur_match < s->strstart, "no future");
  77855. match = s->window + cur_match;
  77856. /* Return failure if the match length is less than 2:
  77857. */
  77858. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  77859. /* The check at best_len-1 can be removed because it will be made
  77860. * again later. (This heuristic is not always a win.)
  77861. * It is not necessary to compare scan[2] and match[2] since they
  77862. * are always equal when the other bytes match, given that
  77863. * the hash keys are equal and that HASH_BITS >= 8.
  77864. */
  77865. scan += 2, match += 2;
  77866. Assert(*scan == *match, "match[2]?");
  77867. /* We check for insufficient lookahead only every 8th comparison;
  77868. * the 256th check will be made at strstart+258.
  77869. */
  77870. do {
  77871. } while (*++scan == *++match && *++scan == *++match &&
  77872. *++scan == *++match && *++scan == *++match &&
  77873. *++scan == *++match && *++scan == *++match &&
  77874. *++scan == *++match && *++scan == *++match &&
  77875. scan < strend);
  77876. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77877. len = MAX_MATCH - (int)(strend - scan);
  77878. if (len < MIN_MATCH) return MIN_MATCH - 1;
  77879. s->match_start = cur_match;
  77880. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  77881. }
  77882. #ifdef DEBUG
  77883. /* ===========================================================================
  77884. * Check that the match at match_start is indeed a match.
  77885. */
  77886. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  77887. {
  77888. /* check that the match is indeed a match */
  77889. if (zmemcmp(s->window + match,
  77890. s->window + start, length) != EQUAL) {
  77891. fprintf(stderr, " start %u, match %u, length %d\n",
  77892. start, match, length);
  77893. do {
  77894. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  77895. } while (--length != 0);
  77896. z_error("invalid match");
  77897. }
  77898. if (z_verbose > 1) {
  77899. fprintf(stderr,"\\[%d,%d]", start-match, length);
  77900. do { putc(s->window[start++], stderr); } while (--length != 0);
  77901. }
  77902. }
  77903. #else
  77904. # define check_match(s, start, match, length)
  77905. #endif /* DEBUG */
  77906. /* ===========================================================================
  77907. * Fill the window when the lookahead becomes insufficient.
  77908. * Updates strstart and lookahead.
  77909. *
  77910. * IN assertion: lookahead < MIN_LOOKAHEAD
  77911. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  77912. * At least one byte has been read, or avail_in == 0; reads are
  77913. * performed for at least two bytes (required for the zip translate_eol
  77914. * option -- not supported here).
  77915. */
  77916. local void fill_window (deflate_state *s)
  77917. {
  77918. register unsigned n, m;
  77919. register Posf *p;
  77920. unsigned more; /* Amount of free space at the end of the window. */
  77921. uInt wsize = s->w_size;
  77922. do {
  77923. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  77924. /* Deal with !@#$% 64K limit: */
  77925. if (sizeof(int) <= 2) {
  77926. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  77927. more = wsize;
  77928. } else if (more == (unsigned)(-1)) {
  77929. /* Very unlikely, but possible on 16 bit machine if
  77930. * strstart == 0 && lookahead == 1 (input done a byte at time)
  77931. */
  77932. more--;
  77933. }
  77934. }
  77935. /* If the window is almost full and there is insufficient lookahead,
  77936. * move the upper half to the lower one to make room in the upper half.
  77937. */
  77938. if (s->strstart >= wsize+MAX_DIST(s)) {
  77939. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  77940. s->match_start -= wsize;
  77941. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  77942. s->block_start -= (long) wsize;
  77943. /* Slide the hash table (could be avoided with 32 bit values
  77944. at the expense of memory usage). We slide even when level == 0
  77945. to keep the hash table consistent if we switch back to level > 0
  77946. later. (Using level 0 permanently is not an optimal usage of
  77947. zlib, so we don't care about this pathological case.)
  77948. */
  77949. /* %%% avoid this when Z_RLE */
  77950. n = s->hash_size;
  77951. p = &s->head[n];
  77952. do {
  77953. m = *--p;
  77954. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77955. } while (--n);
  77956. n = wsize;
  77957. #ifndef FASTEST
  77958. p = &s->prev[n];
  77959. do {
  77960. m = *--p;
  77961. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77962. /* If n is not on any hash chain, prev[n] is garbage but
  77963. * its value will never be used.
  77964. */
  77965. } while (--n);
  77966. #endif
  77967. more += wsize;
  77968. }
  77969. if (s->strm->avail_in == 0) return;
  77970. /* If there was no sliding:
  77971. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  77972. * more == window_size - lookahead - strstart
  77973. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  77974. * => more >= window_size - 2*WSIZE + 2
  77975. * In the BIG_MEM or MMAP case (not yet supported),
  77976. * window_size == input_size + MIN_LOOKAHEAD &&
  77977. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  77978. * Otherwise, window_size == 2*WSIZE so more >= 2.
  77979. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  77980. */
  77981. Assert(more >= 2, "more < 2");
  77982. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  77983. s->lookahead += n;
  77984. /* Initialize the hash value now that we have some input: */
  77985. if (s->lookahead >= MIN_MATCH) {
  77986. s->ins_h = s->window[s->strstart];
  77987. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77988. #if MIN_MATCH != 3
  77989. Call UPDATE_HASH() MIN_MATCH-3 more times
  77990. #endif
  77991. }
  77992. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  77993. * but this is not important since only literal bytes will be emitted.
  77994. */
  77995. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  77996. }
  77997. /* ===========================================================================
  77998. * Flush the current block, with given end-of-file flag.
  77999. * IN assertion: strstart is set to the end of the current match.
  78000. */
  78001. #define FLUSH_BLOCK_ONLY(s, eof) { \
  78002. _tr_flush_block(s, (s->block_start >= 0L ? \
  78003. (charf *)&s->window[(unsigned)s->block_start] : \
  78004. (charf *)Z_NULL), \
  78005. (ulg)((long)s->strstart - s->block_start), \
  78006. (eof)); \
  78007. s->block_start = s->strstart; \
  78008. flush_pending(s->strm); \
  78009. Tracev((stderr,"[FLUSH]")); \
  78010. }
  78011. /* Same but force premature exit if necessary. */
  78012. #define FLUSH_BLOCK(s, eof) { \
  78013. FLUSH_BLOCK_ONLY(s, eof); \
  78014. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  78015. }
  78016. /* ===========================================================================
  78017. * Copy without compression as much as possible from the input stream, return
  78018. * the current block state.
  78019. * This function does not insert new strings in the dictionary since
  78020. * uncompressible data is probably not useful. This function is used
  78021. * only for the level=0 compression option.
  78022. * NOTE: this function should be optimized to avoid extra copying from
  78023. * window to pending_buf.
  78024. */
  78025. local block_state deflate_stored(deflate_state *s, int flush)
  78026. {
  78027. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  78028. * to pending_buf_size, and each stored block has a 5 byte header:
  78029. */
  78030. ulg max_block_size = 0xffff;
  78031. ulg max_start;
  78032. if (max_block_size > s->pending_buf_size - 5) {
  78033. max_block_size = s->pending_buf_size - 5;
  78034. }
  78035. /* Copy as much as possible from input to output: */
  78036. for (;;) {
  78037. /* Fill the window as much as possible: */
  78038. if (s->lookahead <= 1) {
  78039. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  78040. s->block_start >= (long)s->w_size, "slide too late");
  78041. fill_window(s);
  78042. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  78043. if (s->lookahead == 0) break; /* flush the current block */
  78044. }
  78045. Assert(s->block_start >= 0L, "block gone");
  78046. s->strstart += s->lookahead;
  78047. s->lookahead = 0;
  78048. /* Emit a stored block if pending_buf will be full: */
  78049. max_start = s->block_start + max_block_size;
  78050. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  78051. /* strstart == 0 is possible when wraparound on 16-bit machine */
  78052. s->lookahead = (uInt)(s->strstart - max_start);
  78053. s->strstart = (uInt)max_start;
  78054. FLUSH_BLOCK(s, 0);
  78055. }
  78056. /* Flush if we may have to slide, otherwise block_start may become
  78057. * negative and the data will be gone:
  78058. */
  78059. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  78060. FLUSH_BLOCK(s, 0);
  78061. }
  78062. }
  78063. FLUSH_BLOCK(s, flush == Z_FINISH);
  78064. return flush == Z_FINISH ? finish_done : block_done;
  78065. }
  78066. /* ===========================================================================
  78067. * Compress as much as possible from the input stream, return the current
  78068. * block state.
  78069. * This function does not perform lazy evaluation of matches and inserts
  78070. * new strings in the dictionary only for unmatched strings or for short
  78071. * matches. It is used only for the fast compression options.
  78072. */
  78073. local block_state deflate_fast(deflate_state *s, int flush)
  78074. {
  78075. IPos hash_head = NIL; /* head of the hash chain */
  78076. int bflush; /* set if current block must be flushed */
  78077. for (;;) {
  78078. /* Make sure that we always have enough lookahead, except
  78079. * at the end of the input file. We need MAX_MATCH bytes
  78080. * for the next match, plus MIN_MATCH bytes to insert the
  78081. * string following the next match.
  78082. */
  78083. if (s->lookahead < MIN_LOOKAHEAD) {
  78084. fill_window(s);
  78085. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78086. return need_more;
  78087. }
  78088. if (s->lookahead == 0) break; /* flush the current block */
  78089. }
  78090. /* Insert the string window[strstart .. strstart+2] in the
  78091. * dictionary, and set hash_head to the head of the hash chain:
  78092. */
  78093. if (s->lookahead >= MIN_MATCH) {
  78094. INSERT_STRING(s, s->strstart, hash_head);
  78095. }
  78096. /* Find the longest match, discarding those <= prev_length.
  78097. * At this point we have always match_length < MIN_MATCH
  78098. */
  78099. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  78100. /* To simplify the code, we prevent matches with the string
  78101. * of window index 0 (in particular we have to avoid a match
  78102. * of the string with itself at the start of the input file).
  78103. */
  78104. #ifdef FASTEST
  78105. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  78106. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  78107. s->match_length = longest_match_fast (s, hash_head);
  78108. }
  78109. #else
  78110. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78111. s->match_length = longest_match (s, hash_head);
  78112. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78113. s->match_length = longest_match_fast (s, hash_head);
  78114. }
  78115. #endif
  78116. /* longest_match() or longest_match_fast() sets match_start */
  78117. }
  78118. if (s->match_length >= MIN_MATCH) {
  78119. check_match(s, s->strstart, s->match_start, s->match_length);
  78120. _tr_tally_dist(s, s->strstart - s->match_start,
  78121. s->match_length - MIN_MATCH, bflush);
  78122. s->lookahead -= s->match_length;
  78123. /* Insert new strings in the hash table only if the match length
  78124. * is not too large. This saves time but degrades compression.
  78125. */
  78126. #ifndef FASTEST
  78127. if (s->match_length <= s->max_insert_length &&
  78128. s->lookahead >= MIN_MATCH) {
  78129. s->match_length--; /* string at strstart already in table */
  78130. do {
  78131. s->strstart++;
  78132. INSERT_STRING(s, s->strstart, hash_head);
  78133. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  78134. * always MIN_MATCH bytes ahead.
  78135. */
  78136. } while (--s->match_length != 0);
  78137. s->strstart++;
  78138. } else
  78139. #endif
  78140. {
  78141. s->strstart += s->match_length;
  78142. s->match_length = 0;
  78143. s->ins_h = s->window[s->strstart];
  78144. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  78145. #if MIN_MATCH != 3
  78146. Call UPDATE_HASH() MIN_MATCH-3 more times
  78147. #endif
  78148. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  78149. * matter since it will be recomputed at next deflate call.
  78150. */
  78151. }
  78152. } else {
  78153. /* No match, output a literal byte */
  78154. Tracevv((stderr,"%c", s->window[s->strstart]));
  78155. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78156. s->lookahead--;
  78157. s->strstart++;
  78158. }
  78159. if (bflush) FLUSH_BLOCK(s, 0);
  78160. }
  78161. FLUSH_BLOCK(s, flush == Z_FINISH);
  78162. return flush == Z_FINISH ? finish_done : block_done;
  78163. }
  78164. #ifndef FASTEST
  78165. /* ===========================================================================
  78166. * Same as above, but achieves better compression. We use a lazy
  78167. * evaluation for matches: a match is finally adopted only if there is
  78168. * no better match at the next window position.
  78169. */
  78170. local block_state deflate_slow(deflate_state *s, int flush)
  78171. {
  78172. IPos hash_head = NIL; /* head of hash chain */
  78173. int bflush; /* set if current block must be flushed */
  78174. /* Process the input block. */
  78175. for (;;) {
  78176. /* Make sure that we always have enough lookahead, except
  78177. * at the end of the input file. We need MAX_MATCH bytes
  78178. * for the next match, plus MIN_MATCH bytes to insert the
  78179. * string following the next match.
  78180. */
  78181. if (s->lookahead < MIN_LOOKAHEAD) {
  78182. fill_window(s);
  78183. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78184. return need_more;
  78185. }
  78186. if (s->lookahead == 0) break; /* flush the current block */
  78187. }
  78188. /* Insert the string window[strstart .. strstart+2] in the
  78189. * dictionary, and set hash_head to the head of the hash chain:
  78190. */
  78191. if (s->lookahead >= MIN_MATCH) {
  78192. INSERT_STRING(s, s->strstart, hash_head);
  78193. }
  78194. /* Find the longest match, discarding those <= prev_length.
  78195. */
  78196. s->prev_length = s->match_length, s->prev_match = s->match_start;
  78197. s->match_length = MIN_MATCH-1;
  78198. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  78199. s->strstart - hash_head <= MAX_DIST(s)) {
  78200. /* To simplify the code, we prevent matches with the string
  78201. * of window index 0 (in particular we have to avoid a match
  78202. * of the string with itself at the start of the input file).
  78203. */
  78204. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78205. s->match_length = longest_match (s, hash_head);
  78206. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78207. s->match_length = longest_match_fast (s, hash_head);
  78208. }
  78209. /* longest_match() or longest_match_fast() sets match_start */
  78210. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  78211. #if TOO_FAR <= 32767
  78212. || (s->match_length == MIN_MATCH &&
  78213. s->strstart - s->match_start > TOO_FAR)
  78214. #endif
  78215. )) {
  78216. /* If prev_match is also MIN_MATCH, match_start is garbage
  78217. * but we will ignore the current match anyway.
  78218. */
  78219. s->match_length = MIN_MATCH-1;
  78220. }
  78221. }
  78222. /* If there was a match at the previous step and the current
  78223. * match is not better, output the previous match:
  78224. */
  78225. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  78226. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  78227. /* Do not insert strings in hash table beyond this. */
  78228. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  78229. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  78230. s->prev_length - MIN_MATCH, bflush);
  78231. /* Insert in hash table all strings up to the end of the match.
  78232. * strstart-1 and strstart are already inserted. If there is not
  78233. * enough lookahead, the last two strings are not inserted in
  78234. * the hash table.
  78235. */
  78236. s->lookahead -= s->prev_length-1;
  78237. s->prev_length -= 2;
  78238. do {
  78239. if (++s->strstart <= max_insert) {
  78240. INSERT_STRING(s, s->strstart, hash_head);
  78241. }
  78242. } while (--s->prev_length != 0);
  78243. s->match_available = 0;
  78244. s->match_length = MIN_MATCH-1;
  78245. s->strstart++;
  78246. if (bflush) FLUSH_BLOCK(s, 0);
  78247. } else if (s->match_available) {
  78248. /* If there was no match at the previous position, output a
  78249. * single literal. If there was a match but the current match
  78250. * is longer, truncate the previous match to a single literal.
  78251. */
  78252. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78253. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78254. if (bflush) {
  78255. FLUSH_BLOCK_ONLY(s, 0);
  78256. }
  78257. s->strstart++;
  78258. s->lookahead--;
  78259. if (s->strm->avail_out == 0) return need_more;
  78260. } else {
  78261. /* There is no previous match to compare with, wait for
  78262. * the next step to decide.
  78263. */
  78264. s->match_available = 1;
  78265. s->strstart++;
  78266. s->lookahead--;
  78267. }
  78268. }
  78269. Assert (flush != Z_NO_FLUSH, "no flush?");
  78270. if (s->match_available) {
  78271. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78272. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78273. s->match_available = 0;
  78274. }
  78275. FLUSH_BLOCK(s, flush == Z_FINISH);
  78276. return flush == Z_FINISH ? finish_done : block_done;
  78277. }
  78278. #endif /* FASTEST */
  78279. #if 0
  78280. /* ===========================================================================
  78281. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  78282. * one. Do not maintain a hash table. (It will be regenerated if this run of
  78283. * deflate switches away from Z_RLE.)
  78284. */
  78285. local block_state deflate_rle(s, flush)
  78286. deflate_state *s;
  78287. int flush;
  78288. {
  78289. int bflush; /* set if current block must be flushed */
  78290. uInt run; /* length of run */
  78291. uInt max; /* maximum length of run */
  78292. uInt prev; /* byte at distance one to match */
  78293. Bytef *scan; /* scan for end of run */
  78294. for (;;) {
  78295. /* Make sure that we always have enough lookahead, except
  78296. * at the end of the input file. We need MAX_MATCH bytes
  78297. * for the longest encodable run.
  78298. */
  78299. if (s->lookahead < MAX_MATCH) {
  78300. fill_window(s);
  78301. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  78302. return need_more;
  78303. }
  78304. if (s->lookahead == 0) break; /* flush the current block */
  78305. }
  78306. /* See how many times the previous byte repeats */
  78307. run = 0;
  78308. if (s->strstart > 0) { /* if there is a previous byte, that is */
  78309. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  78310. scan = s->window + s->strstart - 1;
  78311. prev = *scan++;
  78312. do {
  78313. if (*scan++ != prev)
  78314. break;
  78315. } while (++run < max);
  78316. }
  78317. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  78318. if (run >= MIN_MATCH) {
  78319. check_match(s, s->strstart, s->strstart - 1, run);
  78320. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  78321. s->lookahead -= run;
  78322. s->strstart += run;
  78323. } else {
  78324. /* No match, output a literal byte */
  78325. Tracevv((stderr,"%c", s->window[s->strstart]));
  78326. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78327. s->lookahead--;
  78328. s->strstart++;
  78329. }
  78330. if (bflush) FLUSH_BLOCK(s, 0);
  78331. }
  78332. FLUSH_BLOCK(s, flush == Z_FINISH);
  78333. return flush == Z_FINISH ? finish_done : block_done;
  78334. }
  78335. #endif
  78336. /********* End of inlined file: deflate.c *********/
  78337. /********* Start of inlined file: inffast.c *********/
  78338. /********* Start of inlined file: inftrees.h *********/
  78339. /* WARNING: this file should *not* be used by applications. It is
  78340. part of the implementation of the compression library and is
  78341. subject to change. Applications should only use zlib.h.
  78342. */
  78343. #ifndef _INFTREES_H_
  78344. #define _INFTREES_H_
  78345. /* Structure for decoding tables. Each entry provides either the
  78346. information needed to do the operation requested by the code that
  78347. indexed that table entry, or it provides a pointer to another
  78348. table that indexes more bits of the code. op indicates whether
  78349. the entry is a pointer to another table, a literal, a length or
  78350. distance, an end-of-block, or an invalid code. For a table
  78351. pointer, the low four bits of op is the number of index bits of
  78352. that table. For a length or distance, the low four bits of op
  78353. is the number of extra bits to get after the code. bits is
  78354. the number of bits in this code or part of the code to drop off
  78355. of the bit buffer. val is the actual byte to output in the case
  78356. of a literal, the base length or distance, or the offset from
  78357. the current table to the next table. Each entry is four bytes. */
  78358. typedef struct {
  78359. unsigned char op; /* operation, extra bits, table bits */
  78360. unsigned char bits; /* bits in this part of the code */
  78361. unsigned short val; /* offset in table or code value */
  78362. } code;
  78363. /* op values as set by inflate_table():
  78364. 00000000 - literal
  78365. 0000tttt - table link, tttt != 0 is the number of table index bits
  78366. 0001eeee - length or distance, eeee is the number of extra bits
  78367. 01100000 - end of block
  78368. 01000000 - invalid code
  78369. */
  78370. /* Maximum size of dynamic tree. The maximum found in a long but non-
  78371. exhaustive search was 1444 code structures (852 for length/literals
  78372. and 592 for distances, the latter actually the result of an
  78373. exhaustive search). The true maximum is not known, but the value
  78374. below is more than safe. */
  78375. #define ENOUGH 2048
  78376. #define MAXD 592
  78377. /* Type of code to build for inftable() */
  78378. typedef enum {
  78379. CODES,
  78380. LENS,
  78381. DISTS
  78382. } codetype;
  78383. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  78384. unsigned codes, code FAR * FAR *table,
  78385. unsigned FAR *bits, unsigned short FAR *work));
  78386. #endif
  78387. /********* End of inlined file: inftrees.h *********/
  78388. /********* Start of inlined file: inflate.h *********/
  78389. /* WARNING: this file should *not* be used by applications. It is
  78390. part of the implementation of the compression library and is
  78391. subject to change. Applications should only use zlib.h.
  78392. */
  78393. #ifndef _INFLATE_H_
  78394. #define _INFLATE_H_
  78395. /* define NO_GZIP when compiling if you want to disable gzip header and
  78396. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  78397. the crc code when it is not needed. For shared libraries, gzip decoding
  78398. should be left enabled. */
  78399. #ifndef NO_GZIP
  78400. # define GUNZIP
  78401. #endif
  78402. /* Possible inflate modes between inflate() calls */
  78403. typedef enum {
  78404. HEAD, /* i: waiting for magic header */
  78405. FLAGS, /* i: waiting for method and flags (gzip) */
  78406. TIME, /* i: waiting for modification time (gzip) */
  78407. OS, /* i: waiting for extra flags and operating system (gzip) */
  78408. EXLEN, /* i: waiting for extra length (gzip) */
  78409. EXTRA, /* i: waiting for extra bytes (gzip) */
  78410. NAME, /* i: waiting for end of file name (gzip) */
  78411. COMMENT, /* i: waiting for end of comment (gzip) */
  78412. HCRC, /* i: waiting for header crc (gzip) */
  78413. DICTID, /* i: waiting for dictionary check value */
  78414. DICT, /* waiting for inflateSetDictionary() call */
  78415. TYPE, /* i: waiting for type bits, including last-flag bit */
  78416. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  78417. STORED, /* i: waiting for stored size (length and complement) */
  78418. COPY, /* i/o: waiting for input or output to copy stored block */
  78419. TABLE, /* i: waiting for dynamic block table lengths */
  78420. LENLENS, /* i: waiting for code length code lengths */
  78421. CODELENS, /* i: waiting for length/lit and distance code lengths */
  78422. LEN, /* i: waiting for length/lit code */
  78423. LENEXT, /* i: waiting for length extra bits */
  78424. DIST, /* i: waiting for distance code */
  78425. DISTEXT, /* i: waiting for distance extra bits */
  78426. MATCH, /* o: waiting for output space to copy string */
  78427. LIT, /* o: waiting for output space to write literal */
  78428. CHECK, /* i: waiting for 32-bit check value */
  78429. LENGTH, /* i: waiting for 32-bit length (gzip) */
  78430. DONE, /* finished check, done -- remain here until reset */
  78431. BAD, /* got a data error -- remain here until reset */
  78432. MEM, /* got an inflate() memory error -- remain here until reset */
  78433. SYNC /* looking for synchronization bytes to restart inflate() */
  78434. } inflate_mode;
  78435. /*
  78436. State transitions between above modes -
  78437. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  78438. Process header:
  78439. HEAD -> (gzip) or (zlib)
  78440. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  78441. NAME -> COMMENT -> HCRC -> TYPE
  78442. (zlib) -> DICTID or TYPE
  78443. DICTID -> DICT -> TYPE
  78444. Read deflate blocks:
  78445. TYPE -> STORED or TABLE or LEN or CHECK
  78446. STORED -> COPY -> TYPE
  78447. TABLE -> LENLENS -> CODELENS -> LEN
  78448. Read deflate codes:
  78449. LEN -> LENEXT or LIT or TYPE
  78450. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  78451. LIT -> LEN
  78452. Process trailer:
  78453. CHECK -> LENGTH -> DONE
  78454. */
  78455. /* state maintained between inflate() calls. Approximately 7K bytes. */
  78456. struct inflate_state {
  78457. inflate_mode mode; /* current inflate mode */
  78458. int last; /* true if processing last block */
  78459. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  78460. int havedict; /* true if dictionary provided */
  78461. int flags; /* gzip header method and flags (0 if zlib) */
  78462. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  78463. unsigned long check; /* protected copy of check value */
  78464. unsigned long total; /* protected copy of output count */
  78465. gz_headerp head; /* where to save gzip header information */
  78466. /* sliding window */
  78467. unsigned wbits; /* log base 2 of requested window size */
  78468. unsigned wsize; /* window size or zero if not using window */
  78469. unsigned whave; /* valid bytes in the window */
  78470. unsigned write; /* window write index */
  78471. unsigned char FAR *window; /* allocated sliding window, if needed */
  78472. /* bit accumulator */
  78473. unsigned long hold; /* input bit accumulator */
  78474. unsigned bits; /* number of bits in "in" */
  78475. /* for string and stored block copying */
  78476. unsigned length; /* literal or length of data to copy */
  78477. unsigned offset; /* distance back to copy string from */
  78478. /* for table and code decoding */
  78479. unsigned extra; /* extra bits needed */
  78480. /* fixed and dynamic code tables */
  78481. code const FAR *lencode; /* starting table for length/literal codes */
  78482. code const FAR *distcode; /* starting table for distance codes */
  78483. unsigned lenbits; /* index bits for lencode */
  78484. unsigned distbits; /* index bits for distcode */
  78485. /* dynamic table building */
  78486. unsigned ncode; /* number of code length code lengths */
  78487. unsigned nlen; /* number of length code lengths */
  78488. unsigned ndist; /* number of distance code lengths */
  78489. unsigned have; /* number of code lengths in lens[] */
  78490. code FAR *next; /* next available space in codes[] */
  78491. unsigned short lens[320]; /* temporary storage for code lengths */
  78492. unsigned short work[288]; /* work area for code table building */
  78493. code codes[ENOUGH]; /* space for code tables */
  78494. };
  78495. #endif
  78496. /********* End of inlined file: inflate.h *********/
  78497. /********* Start of inlined file: inffast.h *********/
  78498. /* WARNING: this file should *not* be used by applications. It is
  78499. part of the implementation of the compression library and is
  78500. subject to change. Applications should only use zlib.h.
  78501. */
  78502. void inflate_fast OF((z_streamp strm, unsigned start));
  78503. /********* End of inlined file: inffast.h *********/
  78504. #ifndef ASMINF
  78505. /* Allow machine dependent optimization for post-increment or pre-increment.
  78506. Based on testing to date,
  78507. Pre-increment preferred for:
  78508. - PowerPC G3 (Adler)
  78509. - MIPS R5000 (Randers-Pehrson)
  78510. Post-increment preferred for:
  78511. - none
  78512. No measurable difference:
  78513. - Pentium III (Anderson)
  78514. - M68060 (Nikl)
  78515. */
  78516. #ifdef POSTINC
  78517. # define OFF 0
  78518. # define PUP(a) *(a)++
  78519. #else
  78520. # define OFF 1
  78521. # define PUP(a) *++(a)
  78522. #endif
  78523. /*
  78524. Decode literal, length, and distance codes and write out the resulting
  78525. literal and match bytes until either not enough input or output is
  78526. available, an end-of-block is encountered, or a data error is encountered.
  78527. When large enough input and output buffers are supplied to inflate(), for
  78528. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  78529. inflate execution time is spent in this routine.
  78530. Entry assumptions:
  78531. state->mode == LEN
  78532. strm->avail_in >= 6
  78533. strm->avail_out >= 258
  78534. start >= strm->avail_out
  78535. state->bits < 8
  78536. On return, state->mode is one of:
  78537. LEN -- ran out of enough output space or enough available input
  78538. TYPE -- reached end of block code, inflate() to interpret next block
  78539. BAD -- error in block data
  78540. Notes:
  78541. - The maximum input bits used by a length/distance pair is 15 bits for the
  78542. length code, 5 bits for the length extra, 15 bits for the distance code,
  78543. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  78544. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  78545. checking for available input while decoding.
  78546. - The maximum bytes that a single length/distance pair can output is 258
  78547. bytes, which is the maximum length that can be coded. inflate_fast()
  78548. requires strm->avail_out >= 258 for each loop to avoid checking for
  78549. output space.
  78550. */
  78551. void inflate_fast (z_streamp strm, unsigned start)
  78552. {
  78553. struct inflate_state FAR *state;
  78554. unsigned char FAR *in; /* local strm->next_in */
  78555. unsigned char FAR *last; /* while in < last, enough input available */
  78556. unsigned char FAR *out; /* local strm->next_out */
  78557. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  78558. unsigned char FAR *end; /* while out < end, enough space available */
  78559. #ifdef INFLATE_STRICT
  78560. unsigned dmax; /* maximum distance from zlib header */
  78561. #endif
  78562. unsigned wsize; /* window size or zero if not using window */
  78563. unsigned whave; /* valid bytes in the window */
  78564. unsigned write; /* window write index */
  78565. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  78566. unsigned long hold; /* local strm->hold */
  78567. unsigned bits; /* local strm->bits */
  78568. code const FAR *lcode; /* local strm->lencode */
  78569. code const FAR *dcode; /* local strm->distcode */
  78570. unsigned lmask; /* mask for first level of length codes */
  78571. unsigned dmask; /* mask for first level of distance codes */
  78572. code thisx; /* retrieved table entry */
  78573. unsigned op; /* code bits, operation, extra bits, or */
  78574. /* window position, window bytes to copy */
  78575. unsigned len; /* match length, unused bytes */
  78576. unsigned dist; /* match distance */
  78577. unsigned char FAR *from; /* where to copy match from */
  78578. /* copy state to local variables */
  78579. state = (struct inflate_state FAR *)strm->state;
  78580. in = strm->next_in - OFF;
  78581. last = in + (strm->avail_in - 5);
  78582. out = strm->next_out - OFF;
  78583. beg = out - (start - strm->avail_out);
  78584. end = out + (strm->avail_out - 257);
  78585. #ifdef INFLATE_STRICT
  78586. dmax = state->dmax;
  78587. #endif
  78588. wsize = state->wsize;
  78589. whave = state->whave;
  78590. write = state->write;
  78591. window = state->window;
  78592. hold = state->hold;
  78593. bits = state->bits;
  78594. lcode = state->lencode;
  78595. dcode = state->distcode;
  78596. lmask = (1U << state->lenbits) - 1;
  78597. dmask = (1U << state->distbits) - 1;
  78598. /* decode literals and length/distances until end-of-block or not enough
  78599. input data or output space */
  78600. do {
  78601. if (bits < 15) {
  78602. hold += (unsigned long)(PUP(in)) << bits;
  78603. bits += 8;
  78604. hold += (unsigned long)(PUP(in)) << bits;
  78605. bits += 8;
  78606. }
  78607. thisx = lcode[hold & lmask];
  78608. dolen:
  78609. op = (unsigned)(thisx.bits);
  78610. hold >>= op;
  78611. bits -= op;
  78612. op = (unsigned)(thisx.op);
  78613. if (op == 0) { /* literal */
  78614. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78615. "inflate: literal '%c'\n" :
  78616. "inflate: literal 0x%02x\n", thisx.val));
  78617. PUP(out) = (unsigned char)(thisx.val);
  78618. }
  78619. else if (op & 16) { /* length base */
  78620. len = (unsigned)(thisx.val);
  78621. op &= 15; /* number of extra bits */
  78622. if (op) {
  78623. if (bits < op) {
  78624. hold += (unsigned long)(PUP(in)) << bits;
  78625. bits += 8;
  78626. }
  78627. len += (unsigned)hold & ((1U << op) - 1);
  78628. hold >>= op;
  78629. bits -= op;
  78630. }
  78631. Tracevv((stderr, "inflate: length %u\n", len));
  78632. if (bits < 15) {
  78633. hold += (unsigned long)(PUP(in)) << bits;
  78634. bits += 8;
  78635. hold += (unsigned long)(PUP(in)) << bits;
  78636. bits += 8;
  78637. }
  78638. thisx = dcode[hold & dmask];
  78639. dodist:
  78640. op = (unsigned)(thisx.bits);
  78641. hold >>= op;
  78642. bits -= op;
  78643. op = (unsigned)(thisx.op);
  78644. if (op & 16) { /* distance base */
  78645. dist = (unsigned)(thisx.val);
  78646. op &= 15; /* number of extra bits */
  78647. if (bits < op) {
  78648. hold += (unsigned long)(PUP(in)) << bits;
  78649. bits += 8;
  78650. if (bits < op) {
  78651. hold += (unsigned long)(PUP(in)) << bits;
  78652. bits += 8;
  78653. }
  78654. }
  78655. dist += (unsigned)hold & ((1U << op) - 1);
  78656. #ifdef INFLATE_STRICT
  78657. if (dist > dmax) {
  78658. strm->msg = (char *)"invalid distance too far back";
  78659. state->mode = BAD;
  78660. break;
  78661. }
  78662. #endif
  78663. hold >>= op;
  78664. bits -= op;
  78665. Tracevv((stderr, "inflate: distance %u\n", dist));
  78666. op = (unsigned)(out - beg); /* max distance in output */
  78667. if (dist > op) { /* see if copy from window */
  78668. op = dist - op; /* distance back in window */
  78669. if (op > whave) {
  78670. strm->msg = (char *)"invalid distance too far back";
  78671. state->mode = BAD;
  78672. break;
  78673. }
  78674. from = window - OFF;
  78675. if (write == 0) { /* very common case */
  78676. from += wsize - op;
  78677. if (op < len) { /* some from window */
  78678. len -= op;
  78679. do {
  78680. PUP(out) = PUP(from);
  78681. } while (--op);
  78682. from = out - dist; /* rest from output */
  78683. }
  78684. }
  78685. else if (write < op) { /* wrap around window */
  78686. from += wsize + write - op;
  78687. op -= write;
  78688. if (op < len) { /* some from end of window */
  78689. len -= op;
  78690. do {
  78691. PUP(out) = PUP(from);
  78692. } while (--op);
  78693. from = window - OFF;
  78694. if (write < len) { /* some from start of window */
  78695. op = write;
  78696. len -= op;
  78697. do {
  78698. PUP(out) = PUP(from);
  78699. } while (--op);
  78700. from = out - dist; /* rest from output */
  78701. }
  78702. }
  78703. }
  78704. else { /* contiguous in window */
  78705. from += write - op;
  78706. if (op < len) { /* some from window */
  78707. len -= op;
  78708. do {
  78709. PUP(out) = PUP(from);
  78710. } while (--op);
  78711. from = out - dist; /* rest from output */
  78712. }
  78713. }
  78714. while (len > 2) {
  78715. PUP(out) = PUP(from);
  78716. PUP(out) = PUP(from);
  78717. PUP(out) = PUP(from);
  78718. len -= 3;
  78719. }
  78720. if (len) {
  78721. PUP(out) = PUP(from);
  78722. if (len > 1)
  78723. PUP(out) = PUP(from);
  78724. }
  78725. }
  78726. else {
  78727. from = out - dist; /* copy direct from output */
  78728. do { /* minimum length is three */
  78729. PUP(out) = PUP(from);
  78730. PUP(out) = PUP(from);
  78731. PUP(out) = PUP(from);
  78732. len -= 3;
  78733. } while (len > 2);
  78734. if (len) {
  78735. PUP(out) = PUP(from);
  78736. if (len > 1)
  78737. PUP(out) = PUP(from);
  78738. }
  78739. }
  78740. }
  78741. else if ((op & 64) == 0) { /* 2nd level distance code */
  78742. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  78743. goto dodist;
  78744. }
  78745. else {
  78746. strm->msg = (char *)"invalid distance code";
  78747. state->mode = BAD;
  78748. break;
  78749. }
  78750. }
  78751. else if ((op & 64) == 0) { /* 2nd level length code */
  78752. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  78753. goto dolen;
  78754. }
  78755. else if (op & 32) { /* end-of-block */
  78756. Tracevv((stderr, "inflate: end of block\n"));
  78757. state->mode = TYPE;
  78758. break;
  78759. }
  78760. else {
  78761. strm->msg = (char *)"invalid literal/length code";
  78762. state->mode = BAD;
  78763. break;
  78764. }
  78765. } while (in < last && out < end);
  78766. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  78767. len = bits >> 3;
  78768. in -= len;
  78769. bits -= len << 3;
  78770. hold &= (1U << bits) - 1;
  78771. /* update state and return */
  78772. strm->next_in = in + OFF;
  78773. strm->next_out = out + OFF;
  78774. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  78775. strm->avail_out = (unsigned)(out < end ?
  78776. 257 + (end - out) : 257 - (out - end));
  78777. state->hold = hold;
  78778. state->bits = bits;
  78779. return;
  78780. }
  78781. /*
  78782. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  78783. - Using bit fields for code structure
  78784. - Different op definition to avoid & for extra bits (do & for table bits)
  78785. - Three separate decoding do-loops for direct, window, and write == 0
  78786. - Special case for distance > 1 copies to do overlapped load and store copy
  78787. - Explicit branch predictions (based on measured branch probabilities)
  78788. - Deferring match copy and interspersed it with decoding subsequent codes
  78789. - Swapping literal/length else
  78790. - Swapping window/direct else
  78791. - Larger unrolled copy loops (three is about right)
  78792. - Moving len -= 3 statement into middle of loop
  78793. */
  78794. #endif /* !ASMINF */
  78795. /********* End of inlined file: inffast.c *********/
  78796. #undef PULLBYTE
  78797. #undef LOAD
  78798. #undef RESTORE
  78799. #undef INITBITS
  78800. #undef NEEDBITS
  78801. #undef DROPBITS
  78802. #undef BYTEBITS
  78803. /********* Start of inlined file: inflate.c *********/
  78804. /*
  78805. * Change history:
  78806. *
  78807. * 1.2.beta0 24 Nov 2002
  78808. * - First version -- complete rewrite of inflate to simplify code, avoid
  78809. * creation of window when not needed, minimize use of window when it is
  78810. * needed, make inffast.c even faster, implement gzip decoding, and to
  78811. * improve code readability and style over the previous zlib inflate code
  78812. *
  78813. * 1.2.beta1 25 Nov 2002
  78814. * - Use pointers for available input and output checking in inffast.c
  78815. * - Remove input and output counters in inffast.c
  78816. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  78817. * - Remove unnecessary second byte pull from length extra in inffast.c
  78818. * - Unroll direct copy to three copies per loop in inffast.c
  78819. *
  78820. * 1.2.beta2 4 Dec 2002
  78821. * - Change external routine names to reduce potential conflicts
  78822. * - Correct filename to inffixed.h for fixed tables in inflate.c
  78823. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  78824. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  78825. * to avoid negation problem on Alphas (64 bit) in inflate.c
  78826. *
  78827. * 1.2.beta3 22 Dec 2002
  78828. * - Add comments on state->bits assertion in inffast.c
  78829. * - Add comments on op field in inftrees.h
  78830. * - Fix bug in reuse of allocated window after inflateReset()
  78831. * - Remove bit fields--back to byte structure for speed
  78832. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  78833. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  78834. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  78835. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  78836. * - Use local copies of stream next and avail values, as well as local bit
  78837. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  78838. *
  78839. * 1.2.beta4 1 Jan 2003
  78840. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  78841. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  78842. * - Add comments in inffast.c to introduce the inflate_fast() routine
  78843. * - Rearrange window copies in inflate_fast() for speed and simplification
  78844. * - Unroll last copy for window match in inflate_fast()
  78845. * - Use local copies of window variables in inflate_fast() for speed
  78846. * - Pull out common write == 0 case for speed in inflate_fast()
  78847. * - Make op and len in inflate_fast() unsigned for consistency
  78848. * - Add FAR to lcode and dcode declarations in inflate_fast()
  78849. * - Simplified bad distance check in inflate_fast()
  78850. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  78851. * source file infback.c to provide a call-back interface to inflate for
  78852. * programs like gzip and unzip -- uses window as output buffer to avoid
  78853. * window copying
  78854. *
  78855. * 1.2.beta5 1 Jan 2003
  78856. * - Improved inflateBack() interface to allow the caller to provide initial
  78857. * input in strm.
  78858. * - Fixed stored blocks bug in inflateBack()
  78859. *
  78860. * 1.2.beta6 4 Jan 2003
  78861. * - Added comments in inffast.c on effectiveness of POSTINC
  78862. * - Typecasting all around to reduce compiler warnings
  78863. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  78864. * make compilers happy
  78865. * - Changed type of window in inflateBackInit() to unsigned char *
  78866. *
  78867. * 1.2.beta7 27 Jan 2003
  78868. * - Changed many types to unsigned or unsigned short to avoid warnings
  78869. * - Added inflateCopy() function
  78870. *
  78871. * 1.2.0 9 Mar 2003
  78872. * - Changed inflateBack() interface to provide separate opaque descriptors
  78873. * for the in() and out() functions
  78874. * - Changed inflateBack() argument and in_func typedef to swap the length
  78875. * and buffer address return values for the input function
  78876. * - Check next_in and next_out for Z_NULL on entry to inflate()
  78877. *
  78878. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  78879. */
  78880. /********* Start of inlined file: inffast.h *********/
  78881. /* WARNING: this file should *not* be used by applications. It is
  78882. part of the implementation of the compression library and is
  78883. subject to change. Applications should only use zlib.h.
  78884. */
  78885. void inflate_fast OF((z_streamp strm, unsigned start));
  78886. /********* End of inlined file: inffast.h *********/
  78887. #ifdef MAKEFIXED
  78888. # ifndef BUILDFIXED
  78889. # define BUILDFIXED
  78890. # endif
  78891. #endif
  78892. /* function prototypes */
  78893. local void fixedtables OF((struct inflate_state FAR *state));
  78894. local int updatewindow OF((z_streamp strm, unsigned out));
  78895. #ifdef BUILDFIXED
  78896. void makefixed OF((void));
  78897. #endif
  78898. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  78899. unsigned len));
  78900. int ZEXPORT inflateReset (z_streamp strm)
  78901. {
  78902. struct inflate_state FAR *state;
  78903. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78904. state = (struct inflate_state FAR *)strm->state;
  78905. strm->total_in = strm->total_out = state->total = 0;
  78906. strm->msg = Z_NULL;
  78907. strm->adler = 1; /* to support ill-conceived Java test suite */
  78908. state->mode = HEAD;
  78909. state->last = 0;
  78910. state->havedict = 0;
  78911. state->dmax = 32768U;
  78912. state->head = Z_NULL;
  78913. state->wsize = 0;
  78914. state->whave = 0;
  78915. state->write = 0;
  78916. state->hold = 0;
  78917. state->bits = 0;
  78918. state->lencode = state->distcode = state->next = state->codes;
  78919. Tracev((stderr, "inflate: reset\n"));
  78920. return Z_OK;
  78921. }
  78922. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  78923. {
  78924. struct inflate_state FAR *state;
  78925. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78926. state = (struct inflate_state FAR *)strm->state;
  78927. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  78928. value &= (1L << bits) - 1;
  78929. state->hold += value << state->bits;
  78930. state->bits += bits;
  78931. return Z_OK;
  78932. }
  78933. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  78934. {
  78935. struct inflate_state FAR *state;
  78936. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  78937. stream_size != (int)(sizeof(z_stream)))
  78938. return Z_VERSION_ERROR;
  78939. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78940. strm->msg = Z_NULL; /* in case we return an error */
  78941. if (strm->zalloc == (alloc_func)0) {
  78942. strm->zalloc = zcalloc;
  78943. strm->opaque = (voidpf)0;
  78944. }
  78945. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78946. state = (struct inflate_state FAR *)
  78947. ZALLOC(strm, 1, sizeof(struct inflate_state));
  78948. if (state == Z_NULL) return Z_MEM_ERROR;
  78949. Tracev((stderr, "inflate: allocated\n"));
  78950. strm->state = (struct internal_state FAR *)state;
  78951. if (windowBits < 0) {
  78952. state->wrap = 0;
  78953. windowBits = -windowBits;
  78954. }
  78955. else {
  78956. state->wrap = (windowBits >> 4) + 1;
  78957. #ifdef GUNZIP
  78958. if (windowBits < 48) windowBits &= 15;
  78959. #endif
  78960. }
  78961. if (windowBits < 8 || windowBits > 15) {
  78962. ZFREE(strm, state);
  78963. strm->state = Z_NULL;
  78964. return Z_STREAM_ERROR;
  78965. }
  78966. state->wbits = (unsigned)windowBits;
  78967. state->window = Z_NULL;
  78968. return inflateReset(strm);
  78969. }
  78970. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  78971. {
  78972. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  78973. }
  78974. /*
  78975. Return state with length and distance decoding tables and index sizes set to
  78976. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  78977. If BUILDFIXED is defined, then instead this routine builds the tables the
  78978. first time it's called, and returns those tables the first time and
  78979. thereafter. This reduces the size of the code by about 2K bytes, in
  78980. exchange for a little execution time. However, BUILDFIXED should not be
  78981. used for threaded applications, since the rewriting of the tables and virgin
  78982. may not be thread-safe.
  78983. */
  78984. local void fixedtables (struct inflate_state FAR *state)
  78985. {
  78986. #ifdef BUILDFIXED
  78987. static int virgin = 1;
  78988. static code *lenfix, *distfix;
  78989. static code fixed[544];
  78990. /* build fixed huffman tables if first call (may not be thread safe) */
  78991. if (virgin) {
  78992. unsigned sym, bits;
  78993. static code *next;
  78994. /* literal/length table */
  78995. sym = 0;
  78996. while (sym < 144) state->lens[sym++] = 8;
  78997. while (sym < 256) state->lens[sym++] = 9;
  78998. while (sym < 280) state->lens[sym++] = 7;
  78999. while (sym < 288) state->lens[sym++] = 8;
  79000. next = fixed;
  79001. lenfix = next;
  79002. bits = 9;
  79003. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  79004. /* distance table */
  79005. sym = 0;
  79006. while (sym < 32) state->lens[sym++] = 5;
  79007. distfix = next;
  79008. bits = 5;
  79009. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  79010. /* do this just once */
  79011. virgin = 0;
  79012. }
  79013. #else /* !BUILDFIXED */
  79014. /********* Start of inlined file: inffixed.h *********/
  79015. /* inffixed.h -- table for decoding fixed codes
  79016. * Generated automatically by makefixed().
  79017. */
  79018. /* WARNING: this file should *not* be used by applications. It
  79019. is part of the implementation of the compression library and
  79020. is subject to change. Applications should only use zlib.h.
  79021. */
  79022. static const code lenfix[512] = {
  79023. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  79024. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  79025. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  79026. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  79027. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  79028. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  79029. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  79030. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  79031. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  79032. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  79033. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  79034. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  79035. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  79036. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  79037. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  79038. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  79039. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  79040. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  79041. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  79042. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  79043. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  79044. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  79045. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  79046. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  79047. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  79048. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  79049. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  79050. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  79051. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  79052. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  79053. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  79054. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  79055. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  79056. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  79057. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  79058. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  79059. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  79060. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  79061. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  79062. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  79063. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  79064. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  79065. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  79066. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  79067. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  79068. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  79069. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  79070. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  79071. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  79072. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  79073. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  79074. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  79075. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  79076. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  79077. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  79078. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  79079. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  79080. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  79081. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  79082. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  79083. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  79084. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  79085. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  79086. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  79087. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  79088. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  79089. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  79090. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  79091. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  79092. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  79093. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  79094. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  79095. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  79096. {0,9,255}
  79097. };
  79098. static const code distfix[32] = {
  79099. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  79100. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  79101. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  79102. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  79103. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  79104. {22,5,193},{64,5,0}
  79105. };
  79106. /********* End of inlined file: inffixed.h *********/
  79107. #endif /* BUILDFIXED */
  79108. state->lencode = lenfix;
  79109. state->lenbits = 9;
  79110. state->distcode = distfix;
  79111. state->distbits = 5;
  79112. }
  79113. #ifdef MAKEFIXED
  79114. #include <stdio.h>
  79115. /*
  79116. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  79117. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  79118. those tables to stdout, which would be piped to inffixed.h. A small program
  79119. can simply call makefixed to do this:
  79120. void makefixed(void);
  79121. int main(void)
  79122. {
  79123. makefixed();
  79124. return 0;
  79125. }
  79126. Then that can be linked with zlib built with MAKEFIXED defined and run:
  79127. a.out > inffixed.h
  79128. */
  79129. void makefixed()
  79130. {
  79131. unsigned low, size;
  79132. struct inflate_state state;
  79133. fixedtables(&state);
  79134. puts(" /* inffixed.h -- table for decoding fixed codes");
  79135. puts(" * Generated automatically by makefixed().");
  79136. puts(" */");
  79137. puts("");
  79138. puts(" /* WARNING: this file should *not* be used by applications.");
  79139. puts(" It is part of the implementation of this library and is");
  79140. puts(" subject to change. Applications should only use zlib.h.");
  79141. puts(" */");
  79142. puts("");
  79143. size = 1U << 9;
  79144. printf(" static const code lenfix[%u] = {", size);
  79145. low = 0;
  79146. for (;;) {
  79147. if ((low % 7) == 0) printf("\n ");
  79148. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  79149. state.lencode[low].val);
  79150. if (++low == size) break;
  79151. putchar(',');
  79152. }
  79153. puts("\n };");
  79154. size = 1U << 5;
  79155. printf("\n static const code distfix[%u] = {", size);
  79156. low = 0;
  79157. for (;;) {
  79158. if ((low % 6) == 0) printf("\n ");
  79159. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  79160. state.distcode[low].val);
  79161. if (++low == size) break;
  79162. putchar(',');
  79163. }
  79164. puts("\n };");
  79165. }
  79166. #endif /* MAKEFIXED */
  79167. /*
  79168. Update the window with the last wsize (normally 32K) bytes written before
  79169. returning. If window does not exist yet, create it. This is only called
  79170. when a window is already in use, or when output has been written during this
  79171. inflate call, but the end of the deflate stream has not been reached yet.
  79172. It is also called to create a window for dictionary data when a dictionary
  79173. is loaded.
  79174. Providing output buffers larger than 32K to inflate() should provide a speed
  79175. advantage, since only the last 32K of output is copied to the sliding window
  79176. upon return from inflate(), and since all distances after the first 32K of
  79177. output will fall in the output data, making match copies simpler and faster.
  79178. The advantage may be dependent on the size of the processor's data caches.
  79179. */
  79180. local int updatewindow (z_streamp strm, unsigned out)
  79181. {
  79182. struct inflate_state FAR *state;
  79183. unsigned copy, dist;
  79184. state = (struct inflate_state FAR *)strm->state;
  79185. /* if it hasn't been done already, allocate space for the window */
  79186. if (state->window == Z_NULL) {
  79187. state->window = (unsigned char FAR *)
  79188. ZALLOC(strm, 1U << state->wbits,
  79189. sizeof(unsigned char));
  79190. if (state->window == Z_NULL) return 1;
  79191. }
  79192. /* if window not in use yet, initialize */
  79193. if (state->wsize == 0) {
  79194. state->wsize = 1U << state->wbits;
  79195. state->write = 0;
  79196. state->whave = 0;
  79197. }
  79198. /* copy state->wsize or less output bytes into the circular window */
  79199. copy = out - strm->avail_out;
  79200. if (copy >= state->wsize) {
  79201. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  79202. state->write = 0;
  79203. state->whave = state->wsize;
  79204. }
  79205. else {
  79206. dist = state->wsize - state->write;
  79207. if (dist > copy) dist = copy;
  79208. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  79209. copy -= dist;
  79210. if (copy) {
  79211. zmemcpy(state->window, strm->next_out - copy, copy);
  79212. state->write = copy;
  79213. state->whave = state->wsize;
  79214. }
  79215. else {
  79216. state->write += dist;
  79217. if (state->write == state->wsize) state->write = 0;
  79218. if (state->whave < state->wsize) state->whave += dist;
  79219. }
  79220. }
  79221. return 0;
  79222. }
  79223. /* Macros for inflate(): */
  79224. /* check function to use adler32() for zlib or crc32() for gzip */
  79225. #ifdef GUNZIP
  79226. # define UPDATE(check, buf, len) \
  79227. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  79228. #else
  79229. # define UPDATE(check, buf, len) adler32(check, buf, len)
  79230. #endif
  79231. /* check macros for header crc */
  79232. #ifdef GUNZIP
  79233. # define CRC2(check, word) \
  79234. do { \
  79235. hbuf[0] = (unsigned char)(word); \
  79236. hbuf[1] = (unsigned char)((word) >> 8); \
  79237. check = crc32(check, hbuf, 2); \
  79238. } while (0)
  79239. # define CRC4(check, word) \
  79240. do { \
  79241. hbuf[0] = (unsigned char)(word); \
  79242. hbuf[1] = (unsigned char)((word) >> 8); \
  79243. hbuf[2] = (unsigned char)((word) >> 16); \
  79244. hbuf[3] = (unsigned char)((word) >> 24); \
  79245. check = crc32(check, hbuf, 4); \
  79246. } while (0)
  79247. #endif
  79248. /* Load registers with state in inflate() for speed */
  79249. #define LOAD() \
  79250. do { \
  79251. put = strm->next_out; \
  79252. left = strm->avail_out; \
  79253. next = strm->next_in; \
  79254. have = strm->avail_in; \
  79255. hold = state->hold; \
  79256. bits = state->bits; \
  79257. } while (0)
  79258. /* Restore state from registers in inflate() */
  79259. #define RESTORE() \
  79260. do { \
  79261. strm->next_out = put; \
  79262. strm->avail_out = left; \
  79263. strm->next_in = next; \
  79264. strm->avail_in = have; \
  79265. state->hold = hold; \
  79266. state->bits = bits; \
  79267. } while (0)
  79268. /* Clear the input bit accumulator */
  79269. #define INITBITS() \
  79270. do { \
  79271. hold = 0; \
  79272. bits = 0; \
  79273. } while (0)
  79274. /* Get a byte of input into the bit accumulator, or return from inflate()
  79275. if there is no input available. */
  79276. #define PULLBYTE() \
  79277. do { \
  79278. if (have == 0) goto inf_leave; \
  79279. have--; \
  79280. hold += (unsigned long)(*next++) << bits; \
  79281. bits += 8; \
  79282. } while (0)
  79283. /* Assure that there are at least n bits in the bit accumulator. If there is
  79284. not enough available input to do that, then return from inflate(). */
  79285. #define NEEDBITS(n) \
  79286. do { \
  79287. while (bits < (unsigned)(n)) \
  79288. PULLBYTE(); \
  79289. } while (0)
  79290. /* Return the low n bits of the bit accumulator (n < 16) */
  79291. #define BITS(n) \
  79292. ((unsigned)hold & ((1U << (n)) - 1))
  79293. /* Remove n bits from the bit accumulator */
  79294. #define DROPBITS(n) \
  79295. do { \
  79296. hold >>= (n); \
  79297. bits -= (unsigned)(n); \
  79298. } while (0)
  79299. /* Remove zero to seven bits as needed to go to a byte boundary */
  79300. #define BYTEBITS() \
  79301. do { \
  79302. hold >>= bits & 7; \
  79303. bits -= bits & 7; \
  79304. } while (0)
  79305. /* Reverse the bytes in a 32-bit value */
  79306. #define REVERSE(q) \
  79307. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  79308. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  79309. /*
  79310. inflate() uses a state machine to process as much input data and generate as
  79311. much output data as possible before returning. The state machine is
  79312. structured roughly as follows:
  79313. for (;;) switch (state) {
  79314. ...
  79315. case STATEn:
  79316. if (not enough input data or output space to make progress)
  79317. return;
  79318. ... make progress ...
  79319. state = STATEm;
  79320. break;
  79321. ...
  79322. }
  79323. so when inflate() is called again, the same case is attempted again, and
  79324. if the appropriate resources are provided, the machine proceeds to the
  79325. next state. The NEEDBITS() macro is usually the way the state evaluates
  79326. whether it can proceed or should return. NEEDBITS() does the return if
  79327. the requested bits are not available. The typical use of the BITS macros
  79328. is:
  79329. NEEDBITS(n);
  79330. ... do something with BITS(n) ...
  79331. DROPBITS(n);
  79332. where NEEDBITS(n) either returns from inflate() if there isn't enough
  79333. input left to load n bits into the accumulator, or it continues. BITS(n)
  79334. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  79335. the low n bits off the accumulator. INITBITS() clears the accumulator
  79336. and sets the number of available bits to zero. BYTEBITS() discards just
  79337. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  79338. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  79339. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  79340. if there is no input available. The decoding of variable length codes uses
  79341. PULLBYTE() directly in order to pull just enough bytes to decode the next
  79342. code, and no more.
  79343. Some states loop until they get enough input, making sure that enough
  79344. state information is maintained to continue the loop where it left off
  79345. if NEEDBITS() returns in the loop. For example, want, need, and keep
  79346. would all have to actually be part of the saved state in case NEEDBITS()
  79347. returns:
  79348. case STATEw:
  79349. while (want < need) {
  79350. NEEDBITS(n);
  79351. keep[want++] = BITS(n);
  79352. DROPBITS(n);
  79353. }
  79354. state = STATEx;
  79355. case STATEx:
  79356. As shown above, if the next state is also the next case, then the break
  79357. is omitted.
  79358. A state may also return if there is not enough output space available to
  79359. complete that state. Those states are copying stored data, writing a
  79360. literal byte, and copying a matching string.
  79361. When returning, a "goto inf_leave" is used to update the total counters,
  79362. update the check value, and determine whether any progress has been made
  79363. during that inflate() call in order to return the proper return code.
  79364. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  79365. When there is a window, goto inf_leave will update the window with the last
  79366. output written. If a goto inf_leave occurs in the middle of decompression
  79367. and there is no window currently, goto inf_leave will create one and copy
  79368. output to the window for the next call of inflate().
  79369. In this implementation, the flush parameter of inflate() only affects the
  79370. return code (per zlib.h). inflate() always writes as much as possible to
  79371. strm->next_out, given the space available and the provided input--the effect
  79372. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  79373. the allocation of and copying into a sliding window until necessary, which
  79374. provides the effect documented in zlib.h for Z_FINISH when the entire input
  79375. stream available. So the only thing the flush parameter actually does is:
  79376. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  79377. will return Z_BUF_ERROR if it has not reached the end of the stream.
  79378. */
  79379. int ZEXPORT inflate (z_streamp strm, int flush)
  79380. {
  79381. struct inflate_state FAR *state;
  79382. unsigned char FAR *next; /* next input */
  79383. unsigned char FAR *put; /* next output */
  79384. unsigned have, left; /* available input and output */
  79385. unsigned long hold; /* bit buffer */
  79386. unsigned bits; /* bits in bit buffer */
  79387. unsigned in, out; /* save starting available input and output */
  79388. unsigned copy; /* number of stored or match bytes to copy */
  79389. unsigned char FAR *from; /* where to copy match bytes from */
  79390. code thisx; /* current decoding table entry */
  79391. code last; /* parent table entry */
  79392. unsigned len; /* length to copy for repeats, bits to drop */
  79393. int ret; /* return code */
  79394. #ifdef GUNZIP
  79395. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  79396. #endif
  79397. static const unsigned short order[19] = /* permutation of code lengths */
  79398. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  79399. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  79400. (strm->next_in == Z_NULL && strm->avail_in != 0))
  79401. return Z_STREAM_ERROR;
  79402. state = (struct inflate_state FAR *)strm->state;
  79403. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  79404. LOAD();
  79405. in = have;
  79406. out = left;
  79407. ret = Z_OK;
  79408. for (;;)
  79409. switch (state->mode) {
  79410. case HEAD:
  79411. if (state->wrap == 0) {
  79412. state->mode = TYPEDO;
  79413. break;
  79414. }
  79415. NEEDBITS(16);
  79416. #ifdef GUNZIP
  79417. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  79418. state->check = crc32(0L, Z_NULL, 0);
  79419. CRC2(state->check, hold);
  79420. INITBITS();
  79421. state->mode = FLAGS;
  79422. break;
  79423. }
  79424. state->flags = 0; /* expect zlib header */
  79425. if (state->head != Z_NULL)
  79426. state->head->done = -1;
  79427. if (!(state->wrap & 1) || /* check if zlib header allowed */
  79428. #else
  79429. if (
  79430. #endif
  79431. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  79432. strm->msg = (char *)"incorrect header check";
  79433. state->mode = BAD;
  79434. break;
  79435. }
  79436. if (BITS(4) != Z_DEFLATED) {
  79437. strm->msg = (char *)"unknown compression method";
  79438. state->mode = BAD;
  79439. break;
  79440. }
  79441. DROPBITS(4);
  79442. len = BITS(4) + 8;
  79443. if (len > state->wbits) {
  79444. strm->msg = (char *)"invalid window size";
  79445. state->mode = BAD;
  79446. break;
  79447. }
  79448. state->dmax = 1U << len;
  79449. Tracev((stderr, "inflate: zlib header ok\n"));
  79450. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79451. state->mode = hold & 0x200 ? DICTID : TYPE;
  79452. INITBITS();
  79453. break;
  79454. #ifdef GUNZIP
  79455. case FLAGS:
  79456. NEEDBITS(16);
  79457. state->flags = (int)(hold);
  79458. if ((state->flags & 0xff) != Z_DEFLATED) {
  79459. strm->msg = (char *)"unknown compression method";
  79460. state->mode = BAD;
  79461. break;
  79462. }
  79463. if (state->flags & 0xe000) {
  79464. strm->msg = (char *)"unknown header flags set";
  79465. state->mode = BAD;
  79466. break;
  79467. }
  79468. if (state->head != Z_NULL)
  79469. state->head->text = (int)((hold >> 8) & 1);
  79470. if (state->flags & 0x0200) CRC2(state->check, hold);
  79471. INITBITS();
  79472. state->mode = TIME;
  79473. case TIME:
  79474. NEEDBITS(32);
  79475. if (state->head != Z_NULL)
  79476. state->head->time = hold;
  79477. if (state->flags & 0x0200) CRC4(state->check, hold);
  79478. INITBITS();
  79479. state->mode = OS;
  79480. case OS:
  79481. NEEDBITS(16);
  79482. if (state->head != Z_NULL) {
  79483. state->head->xflags = (int)(hold & 0xff);
  79484. state->head->os = (int)(hold >> 8);
  79485. }
  79486. if (state->flags & 0x0200) CRC2(state->check, hold);
  79487. INITBITS();
  79488. state->mode = EXLEN;
  79489. case EXLEN:
  79490. if (state->flags & 0x0400) {
  79491. NEEDBITS(16);
  79492. state->length = (unsigned)(hold);
  79493. if (state->head != Z_NULL)
  79494. state->head->extra_len = (unsigned)hold;
  79495. if (state->flags & 0x0200) CRC2(state->check, hold);
  79496. INITBITS();
  79497. }
  79498. else if (state->head != Z_NULL)
  79499. state->head->extra = Z_NULL;
  79500. state->mode = EXTRA;
  79501. case EXTRA:
  79502. if (state->flags & 0x0400) {
  79503. copy = state->length;
  79504. if (copy > have) copy = have;
  79505. if (copy) {
  79506. if (state->head != Z_NULL &&
  79507. state->head->extra != Z_NULL) {
  79508. len = state->head->extra_len - state->length;
  79509. zmemcpy(state->head->extra + len, next,
  79510. len + copy > state->head->extra_max ?
  79511. state->head->extra_max - len : copy);
  79512. }
  79513. if (state->flags & 0x0200)
  79514. state->check = crc32(state->check, next, copy);
  79515. have -= copy;
  79516. next += copy;
  79517. state->length -= copy;
  79518. }
  79519. if (state->length) goto inf_leave;
  79520. }
  79521. state->length = 0;
  79522. state->mode = NAME;
  79523. case NAME:
  79524. if (state->flags & 0x0800) {
  79525. if (have == 0) goto inf_leave;
  79526. copy = 0;
  79527. do {
  79528. len = (unsigned)(next[copy++]);
  79529. if (state->head != Z_NULL &&
  79530. state->head->name != Z_NULL &&
  79531. state->length < state->head->name_max)
  79532. state->head->name[state->length++] = len;
  79533. } while (len && copy < have);
  79534. if (state->flags & 0x0200)
  79535. state->check = crc32(state->check, next, copy);
  79536. have -= copy;
  79537. next += copy;
  79538. if (len) goto inf_leave;
  79539. }
  79540. else if (state->head != Z_NULL)
  79541. state->head->name = Z_NULL;
  79542. state->length = 0;
  79543. state->mode = COMMENT;
  79544. case COMMENT:
  79545. if (state->flags & 0x1000) {
  79546. if (have == 0) goto inf_leave;
  79547. copy = 0;
  79548. do {
  79549. len = (unsigned)(next[copy++]);
  79550. if (state->head != Z_NULL &&
  79551. state->head->comment != Z_NULL &&
  79552. state->length < state->head->comm_max)
  79553. state->head->comment[state->length++] = len;
  79554. } while (len && copy < have);
  79555. if (state->flags & 0x0200)
  79556. state->check = crc32(state->check, next, copy);
  79557. have -= copy;
  79558. next += copy;
  79559. if (len) goto inf_leave;
  79560. }
  79561. else if (state->head != Z_NULL)
  79562. state->head->comment = Z_NULL;
  79563. state->mode = HCRC;
  79564. case HCRC:
  79565. if (state->flags & 0x0200) {
  79566. NEEDBITS(16);
  79567. if (hold != (state->check & 0xffff)) {
  79568. strm->msg = (char *)"header crc mismatch";
  79569. state->mode = BAD;
  79570. break;
  79571. }
  79572. INITBITS();
  79573. }
  79574. if (state->head != Z_NULL) {
  79575. state->head->hcrc = (int)((state->flags >> 9) & 1);
  79576. state->head->done = 1;
  79577. }
  79578. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  79579. state->mode = TYPE;
  79580. break;
  79581. #endif
  79582. case DICTID:
  79583. NEEDBITS(32);
  79584. strm->adler = state->check = REVERSE(hold);
  79585. INITBITS();
  79586. state->mode = DICT;
  79587. case DICT:
  79588. if (state->havedict == 0) {
  79589. RESTORE();
  79590. return Z_NEED_DICT;
  79591. }
  79592. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79593. state->mode = TYPE;
  79594. case TYPE:
  79595. if (flush == Z_BLOCK) goto inf_leave;
  79596. case TYPEDO:
  79597. if (state->last) {
  79598. BYTEBITS();
  79599. state->mode = CHECK;
  79600. break;
  79601. }
  79602. NEEDBITS(3);
  79603. state->last = BITS(1);
  79604. DROPBITS(1);
  79605. switch (BITS(2)) {
  79606. case 0: /* stored block */
  79607. Tracev((stderr, "inflate: stored block%s\n",
  79608. state->last ? " (last)" : ""));
  79609. state->mode = STORED;
  79610. break;
  79611. case 1: /* fixed block */
  79612. fixedtables(state);
  79613. Tracev((stderr, "inflate: fixed codes block%s\n",
  79614. state->last ? " (last)" : ""));
  79615. state->mode = LEN; /* decode codes */
  79616. break;
  79617. case 2: /* dynamic block */
  79618. Tracev((stderr, "inflate: dynamic codes block%s\n",
  79619. state->last ? " (last)" : ""));
  79620. state->mode = TABLE;
  79621. break;
  79622. case 3:
  79623. strm->msg = (char *)"invalid block type";
  79624. state->mode = BAD;
  79625. }
  79626. DROPBITS(2);
  79627. break;
  79628. case STORED:
  79629. BYTEBITS(); /* go to byte boundary */
  79630. NEEDBITS(32);
  79631. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  79632. strm->msg = (char *)"invalid stored block lengths";
  79633. state->mode = BAD;
  79634. break;
  79635. }
  79636. state->length = (unsigned)hold & 0xffff;
  79637. Tracev((stderr, "inflate: stored length %u\n",
  79638. state->length));
  79639. INITBITS();
  79640. state->mode = COPY;
  79641. case COPY:
  79642. copy = state->length;
  79643. if (copy) {
  79644. if (copy > have) copy = have;
  79645. if (copy > left) copy = left;
  79646. if (copy == 0) goto inf_leave;
  79647. zmemcpy(put, next, copy);
  79648. have -= copy;
  79649. next += copy;
  79650. left -= copy;
  79651. put += copy;
  79652. state->length -= copy;
  79653. break;
  79654. }
  79655. Tracev((stderr, "inflate: stored end\n"));
  79656. state->mode = TYPE;
  79657. break;
  79658. case TABLE:
  79659. NEEDBITS(14);
  79660. state->nlen = BITS(5) + 257;
  79661. DROPBITS(5);
  79662. state->ndist = BITS(5) + 1;
  79663. DROPBITS(5);
  79664. state->ncode = BITS(4) + 4;
  79665. DROPBITS(4);
  79666. #ifndef PKZIP_BUG_WORKAROUND
  79667. if (state->nlen > 286 || state->ndist > 30) {
  79668. strm->msg = (char *)"too many length or distance symbols";
  79669. state->mode = BAD;
  79670. break;
  79671. }
  79672. #endif
  79673. Tracev((stderr, "inflate: table sizes ok\n"));
  79674. state->have = 0;
  79675. state->mode = LENLENS;
  79676. case LENLENS:
  79677. while (state->have < state->ncode) {
  79678. NEEDBITS(3);
  79679. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  79680. DROPBITS(3);
  79681. }
  79682. while (state->have < 19)
  79683. state->lens[order[state->have++]] = 0;
  79684. state->next = state->codes;
  79685. state->lencode = (code const FAR *)(state->next);
  79686. state->lenbits = 7;
  79687. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  79688. &(state->lenbits), state->work);
  79689. if (ret) {
  79690. strm->msg = (char *)"invalid code lengths set";
  79691. state->mode = BAD;
  79692. break;
  79693. }
  79694. Tracev((stderr, "inflate: code lengths ok\n"));
  79695. state->have = 0;
  79696. state->mode = CODELENS;
  79697. case CODELENS:
  79698. while (state->have < state->nlen + state->ndist) {
  79699. for (;;) {
  79700. thisx = state->lencode[BITS(state->lenbits)];
  79701. if ((unsigned)(thisx.bits) <= bits) break;
  79702. PULLBYTE();
  79703. }
  79704. if (thisx.val < 16) {
  79705. NEEDBITS(thisx.bits);
  79706. DROPBITS(thisx.bits);
  79707. state->lens[state->have++] = thisx.val;
  79708. }
  79709. else {
  79710. if (thisx.val == 16) {
  79711. NEEDBITS(thisx.bits + 2);
  79712. DROPBITS(thisx.bits);
  79713. if (state->have == 0) {
  79714. strm->msg = (char *)"invalid bit length repeat";
  79715. state->mode = BAD;
  79716. break;
  79717. }
  79718. len = state->lens[state->have - 1];
  79719. copy = 3 + BITS(2);
  79720. DROPBITS(2);
  79721. }
  79722. else if (thisx.val == 17) {
  79723. NEEDBITS(thisx.bits + 3);
  79724. DROPBITS(thisx.bits);
  79725. len = 0;
  79726. copy = 3 + BITS(3);
  79727. DROPBITS(3);
  79728. }
  79729. else {
  79730. NEEDBITS(thisx.bits + 7);
  79731. DROPBITS(thisx.bits);
  79732. len = 0;
  79733. copy = 11 + BITS(7);
  79734. DROPBITS(7);
  79735. }
  79736. if (state->have + copy > state->nlen + state->ndist) {
  79737. strm->msg = (char *)"invalid bit length repeat";
  79738. state->mode = BAD;
  79739. break;
  79740. }
  79741. while (copy--)
  79742. state->lens[state->have++] = (unsigned short)len;
  79743. }
  79744. }
  79745. /* handle error breaks in while */
  79746. if (state->mode == BAD) break;
  79747. /* build code tables */
  79748. state->next = state->codes;
  79749. state->lencode = (code const FAR *)(state->next);
  79750. state->lenbits = 9;
  79751. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  79752. &(state->lenbits), state->work);
  79753. if (ret) {
  79754. strm->msg = (char *)"invalid literal/lengths set";
  79755. state->mode = BAD;
  79756. break;
  79757. }
  79758. state->distcode = (code const FAR *)(state->next);
  79759. state->distbits = 6;
  79760. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  79761. &(state->next), &(state->distbits), state->work);
  79762. if (ret) {
  79763. strm->msg = (char *)"invalid distances set";
  79764. state->mode = BAD;
  79765. break;
  79766. }
  79767. Tracev((stderr, "inflate: codes ok\n"));
  79768. state->mode = LEN;
  79769. case LEN:
  79770. if (have >= 6 && left >= 258) {
  79771. RESTORE();
  79772. inflate_fast(strm, out);
  79773. LOAD();
  79774. break;
  79775. }
  79776. for (;;) {
  79777. thisx = state->lencode[BITS(state->lenbits)];
  79778. if ((unsigned)(thisx.bits) <= bits) break;
  79779. PULLBYTE();
  79780. }
  79781. if (thisx.op && (thisx.op & 0xf0) == 0) {
  79782. last = thisx;
  79783. for (;;) {
  79784. thisx = state->lencode[last.val +
  79785. (BITS(last.bits + last.op) >> last.bits)];
  79786. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79787. PULLBYTE();
  79788. }
  79789. DROPBITS(last.bits);
  79790. }
  79791. DROPBITS(thisx.bits);
  79792. state->length = (unsigned)thisx.val;
  79793. if ((int)(thisx.op) == 0) {
  79794. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79795. "inflate: literal '%c'\n" :
  79796. "inflate: literal 0x%02x\n", thisx.val));
  79797. state->mode = LIT;
  79798. break;
  79799. }
  79800. if (thisx.op & 32) {
  79801. Tracevv((stderr, "inflate: end of block\n"));
  79802. state->mode = TYPE;
  79803. break;
  79804. }
  79805. if (thisx.op & 64) {
  79806. strm->msg = (char *)"invalid literal/length code";
  79807. state->mode = BAD;
  79808. break;
  79809. }
  79810. state->extra = (unsigned)(thisx.op) & 15;
  79811. state->mode = LENEXT;
  79812. case LENEXT:
  79813. if (state->extra) {
  79814. NEEDBITS(state->extra);
  79815. state->length += BITS(state->extra);
  79816. DROPBITS(state->extra);
  79817. }
  79818. Tracevv((stderr, "inflate: length %u\n", state->length));
  79819. state->mode = DIST;
  79820. case DIST:
  79821. for (;;) {
  79822. thisx = state->distcode[BITS(state->distbits)];
  79823. if ((unsigned)(thisx.bits) <= bits) break;
  79824. PULLBYTE();
  79825. }
  79826. if ((thisx.op & 0xf0) == 0) {
  79827. last = thisx;
  79828. for (;;) {
  79829. thisx = state->distcode[last.val +
  79830. (BITS(last.bits + last.op) >> last.bits)];
  79831. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79832. PULLBYTE();
  79833. }
  79834. DROPBITS(last.bits);
  79835. }
  79836. DROPBITS(thisx.bits);
  79837. if (thisx.op & 64) {
  79838. strm->msg = (char *)"invalid distance code";
  79839. state->mode = BAD;
  79840. break;
  79841. }
  79842. state->offset = (unsigned)thisx.val;
  79843. state->extra = (unsigned)(thisx.op) & 15;
  79844. state->mode = DISTEXT;
  79845. case DISTEXT:
  79846. if (state->extra) {
  79847. NEEDBITS(state->extra);
  79848. state->offset += BITS(state->extra);
  79849. DROPBITS(state->extra);
  79850. }
  79851. #ifdef INFLATE_STRICT
  79852. if (state->offset > state->dmax) {
  79853. strm->msg = (char *)"invalid distance too far back";
  79854. state->mode = BAD;
  79855. break;
  79856. }
  79857. #endif
  79858. if (state->offset > state->whave + out - left) {
  79859. strm->msg = (char *)"invalid distance too far back";
  79860. state->mode = BAD;
  79861. break;
  79862. }
  79863. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  79864. state->mode = MATCH;
  79865. case MATCH:
  79866. if (left == 0) goto inf_leave;
  79867. copy = out - left;
  79868. if (state->offset > copy) { /* copy from window */
  79869. copy = state->offset - copy;
  79870. if (copy > state->write) {
  79871. copy -= state->write;
  79872. from = state->window + (state->wsize - copy);
  79873. }
  79874. else
  79875. from = state->window + (state->write - copy);
  79876. if (copy > state->length) copy = state->length;
  79877. }
  79878. else { /* copy from output */
  79879. from = put - state->offset;
  79880. copy = state->length;
  79881. }
  79882. if (copy > left) copy = left;
  79883. left -= copy;
  79884. state->length -= copy;
  79885. do {
  79886. *put++ = *from++;
  79887. } while (--copy);
  79888. if (state->length == 0) state->mode = LEN;
  79889. break;
  79890. case LIT:
  79891. if (left == 0) goto inf_leave;
  79892. *put++ = (unsigned char)(state->length);
  79893. left--;
  79894. state->mode = LEN;
  79895. break;
  79896. case CHECK:
  79897. if (state->wrap) {
  79898. NEEDBITS(32);
  79899. out -= left;
  79900. strm->total_out += out;
  79901. state->total += out;
  79902. if (out)
  79903. strm->adler = state->check =
  79904. UPDATE(state->check, put - out, out);
  79905. out = left;
  79906. if ((
  79907. #ifdef GUNZIP
  79908. state->flags ? hold :
  79909. #endif
  79910. REVERSE(hold)) != state->check) {
  79911. strm->msg = (char *)"incorrect data check";
  79912. state->mode = BAD;
  79913. break;
  79914. }
  79915. INITBITS();
  79916. Tracev((stderr, "inflate: check matches trailer\n"));
  79917. }
  79918. #ifdef GUNZIP
  79919. state->mode = LENGTH;
  79920. case LENGTH:
  79921. if (state->wrap && state->flags) {
  79922. NEEDBITS(32);
  79923. if (hold != (state->total & 0xffffffffUL)) {
  79924. strm->msg = (char *)"incorrect length check";
  79925. state->mode = BAD;
  79926. break;
  79927. }
  79928. INITBITS();
  79929. Tracev((stderr, "inflate: length matches trailer\n"));
  79930. }
  79931. #endif
  79932. state->mode = DONE;
  79933. case DONE:
  79934. ret = Z_STREAM_END;
  79935. goto inf_leave;
  79936. case BAD:
  79937. ret = Z_DATA_ERROR;
  79938. goto inf_leave;
  79939. case MEM:
  79940. return Z_MEM_ERROR;
  79941. case SYNC:
  79942. default:
  79943. return Z_STREAM_ERROR;
  79944. }
  79945. /*
  79946. Return from inflate(), updating the total counts and the check value.
  79947. If there was no progress during the inflate() call, return a buffer
  79948. error. Call updatewindow() to create and/or update the window state.
  79949. Note: a memory error from inflate() is non-recoverable.
  79950. */
  79951. inf_leave:
  79952. RESTORE();
  79953. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  79954. if (updatewindow(strm, out)) {
  79955. state->mode = MEM;
  79956. return Z_MEM_ERROR;
  79957. }
  79958. in -= strm->avail_in;
  79959. out -= strm->avail_out;
  79960. strm->total_in += in;
  79961. strm->total_out += out;
  79962. state->total += out;
  79963. if (state->wrap && out)
  79964. strm->adler = state->check =
  79965. UPDATE(state->check, strm->next_out - out, out);
  79966. strm->data_type = state->bits + (state->last ? 64 : 0) +
  79967. (state->mode == TYPE ? 128 : 0);
  79968. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  79969. ret = Z_BUF_ERROR;
  79970. return ret;
  79971. }
  79972. int ZEXPORT inflateEnd (z_streamp strm)
  79973. {
  79974. struct inflate_state FAR *state;
  79975. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  79976. return Z_STREAM_ERROR;
  79977. state = (struct inflate_state FAR *)strm->state;
  79978. if (state->window != Z_NULL) ZFREE(strm, state->window);
  79979. ZFREE(strm, strm->state);
  79980. strm->state = Z_NULL;
  79981. Tracev((stderr, "inflate: end\n"));
  79982. return Z_OK;
  79983. }
  79984. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  79985. {
  79986. struct inflate_state FAR *state;
  79987. unsigned long id_;
  79988. /* check state */
  79989. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79990. state = (struct inflate_state FAR *)strm->state;
  79991. if (state->wrap != 0 && state->mode != DICT)
  79992. return Z_STREAM_ERROR;
  79993. /* check for correct dictionary id */
  79994. if (state->mode == DICT) {
  79995. id_ = adler32(0L, Z_NULL, 0);
  79996. id_ = adler32(id_, dictionary, dictLength);
  79997. if (id_ != state->check)
  79998. return Z_DATA_ERROR;
  79999. }
  80000. /* copy dictionary to window */
  80001. if (updatewindow(strm, strm->avail_out)) {
  80002. state->mode = MEM;
  80003. return Z_MEM_ERROR;
  80004. }
  80005. if (dictLength > state->wsize) {
  80006. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  80007. state->wsize);
  80008. state->whave = state->wsize;
  80009. }
  80010. else {
  80011. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  80012. dictLength);
  80013. state->whave = dictLength;
  80014. }
  80015. state->havedict = 1;
  80016. Tracev((stderr, "inflate: dictionary set\n"));
  80017. return Z_OK;
  80018. }
  80019. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  80020. {
  80021. struct inflate_state FAR *state;
  80022. /* check state */
  80023. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80024. state = (struct inflate_state FAR *)strm->state;
  80025. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  80026. /* save header structure */
  80027. state->head = head;
  80028. head->done = 0;
  80029. return Z_OK;
  80030. }
  80031. /*
  80032. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  80033. or when out of input. When called, *have is the number of pattern bytes
  80034. found in order so far, in 0..3. On return *have is updated to the new
  80035. state. If on return *have equals four, then the pattern was found and the
  80036. return value is how many bytes were read including the last byte of the
  80037. pattern. If *have is less than four, then the pattern has not been found
  80038. yet and the return value is len. In the latter case, syncsearch() can be
  80039. called again with more data and the *have state. *have is initialized to
  80040. zero for the first call.
  80041. */
  80042. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  80043. {
  80044. unsigned got;
  80045. unsigned next;
  80046. got = *have;
  80047. next = 0;
  80048. while (next < len && got < 4) {
  80049. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  80050. got++;
  80051. else if (buf[next])
  80052. got = 0;
  80053. else
  80054. got = 4 - got;
  80055. next++;
  80056. }
  80057. *have = got;
  80058. return next;
  80059. }
  80060. int ZEXPORT inflateSync (z_streamp strm)
  80061. {
  80062. unsigned len; /* number of bytes to look at or looked at */
  80063. unsigned long in, out; /* temporary to save total_in and total_out */
  80064. unsigned char buf[4]; /* to restore bit buffer to byte string */
  80065. struct inflate_state FAR *state;
  80066. /* check parameters */
  80067. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80068. state = (struct inflate_state FAR *)strm->state;
  80069. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  80070. /* if first time, start search in bit buffer */
  80071. if (state->mode != SYNC) {
  80072. state->mode = SYNC;
  80073. state->hold <<= state->bits & 7;
  80074. state->bits -= state->bits & 7;
  80075. len = 0;
  80076. while (state->bits >= 8) {
  80077. buf[len++] = (unsigned char)(state->hold);
  80078. state->hold >>= 8;
  80079. state->bits -= 8;
  80080. }
  80081. state->have = 0;
  80082. syncsearch(&(state->have), buf, len);
  80083. }
  80084. /* search available input */
  80085. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  80086. strm->avail_in -= len;
  80087. strm->next_in += len;
  80088. strm->total_in += len;
  80089. /* return no joy or set up to restart inflate() on a new block */
  80090. if (state->have != 4) return Z_DATA_ERROR;
  80091. in = strm->total_in; out = strm->total_out;
  80092. inflateReset(strm);
  80093. strm->total_in = in; strm->total_out = out;
  80094. state->mode = TYPE;
  80095. return Z_OK;
  80096. }
  80097. /*
  80098. Returns true if inflate is currently at the end of a block generated by
  80099. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  80100. implementation to provide an additional safety check. PPP uses
  80101. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  80102. block. When decompressing, PPP checks that at the end of input packet,
  80103. inflate is waiting for these length bytes.
  80104. */
  80105. int ZEXPORT inflateSyncPoint (z_streamp strm)
  80106. {
  80107. struct inflate_state FAR *state;
  80108. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80109. state = (struct inflate_state FAR *)strm->state;
  80110. return state->mode == STORED && state->bits == 0;
  80111. }
  80112. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  80113. {
  80114. struct inflate_state FAR *state;
  80115. struct inflate_state FAR *copy;
  80116. unsigned char FAR *window;
  80117. unsigned wsize;
  80118. /* check input */
  80119. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  80120. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  80121. return Z_STREAM_ERROR;
  80122. state = (struct inflate_state FAR *)source->state;
  80123. /* allocate space */
  80124. copy = (struct inflate_state FAR *)
  80125. ZALLOC(source, 1, sizeof(struct inflate_state));
  80126. if (copy == Z_NULL) return Z_MEM_ERROR;
  80127. window = Z_NULL;
  80128. if (state->window != Z_NULL) {
  80129. window = (unsigned char FAR *)
  80130. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  80131. if (window == Z_NULL) {
  80132. ZFREE(source, copy);
  80133. return Z_MEM_ERROR;
  80134. }
  80135. }
  80136. /* copy state */
  80137. zmemcpy(dest, source, sizeof(z_stream));
  80138. zmemcpy(copy, state, sizeof(struct inflate_state));
  80139. if (state->lencode >= state->codes &&
  80140. state->lencode <= state->codes + ENOUGH - 1) {
  80141. copy->lencode = copy->codes + (state->lencode - state->codes);
  80142. copy->distcode = copy->codes + (state->distcode - state->codes);
  80143. }
  80144. copy->next = copy->codes + (state->next - state->codes);
  80145. if (window != Z_NULL) {
  80146. wsize = 1U << state->wbits;
  80147. zmemcpy(window, state->window, wsize);
  80148. }
  80149. copy->window = window;
  80150. dest->state = (struct internal_state FAR *)copy;
  80151. return Z_OK;
  80152. }
  80153. /********* End of inlined file: inflate.c *********/
  80154. /********* Start of inlined file: inftrees.c *********/
  80155. #define MAXBITS 15
  80156. const char inflate_copyright[] =
  80157. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  80158. /*
  80159. If you use the zlib library in a product, an acknowledgment is welcome
  80160. in the documentation of your product. If for some reason you cannot
  80161. include such an acknowledgment, I would appreciate that you keep this
  80162. copyright string in the executable of your product.
  80163. */
  80164. /*
  80165. Build a set of tables to decode the provided canonical Huffman code.
  80166. The code lengths are lens[0..codes-1]. The result starts at *table,
  80167. whose indices are 0..2^bits-1. work is a writable array of at least
  80168. lens shorts, which is used as a work area. type is the type of code
  80169. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  80170. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  80171. on return points to the next available entry's address. bits is the
  80172. requested root table index bits, and on return it is the actual root
  80173. table index bits. It will differ if the request is greater than the
  80174. longest code or if it is less than the shortest code.
  80175. */
  80176. int inflate_table (codetype type,
  80177. unsigned short FAR *lens,
  80178. unsigned codes,
  80179. code FAR * FAR *table,
  80180. unsigned FAR *bits,
  80181. unsigned short FAR *work)
  80182. {
  80183. unsigned len; /* a code's length in bits */
  80184. unsigned sym; /* index of code symbols */
  80185. unsigned min, max; /* minimum and maximum code lengths */
  80186. unsigned root; /* number of index bits for root table */
  80187. unsigned curr; /* number of index bits for current table */
  80188. unsigned drop; /* code bits to drop for sub-table */
  80189. int left; /* number of prefix codes available */
  80190. unsigned used; /* code entries in table used */
  80191. unsigned huff; /* Huffman code */
  80192. unsigned incr; /* for incrementing code, index */
  80193. unsigned fill; /* index for replicating entries */
  80194. unsigned low; /* low bits for current root entry */
  80195. unsigned mask; /* mask for low root bits */
  80196. code thisx; /* table entry for duplication */
  80197. code FAR *next; /* next available space in table */
  80198. const unsigned short FAR *base; /* base value table to use */
  80199. const unsigned short FAR *extra; /* extra bits table to use */
  80200. int end; /* use base and extra for symbol > end */
  80201. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  80202. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  80203. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  80204. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  80205. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  80206. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  80207. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  80208. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  80209. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  80210. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  80211. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  80212. 8193, 12289, 16385, 24577, 0, 0};
  80213. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  80214. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  80215. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  80216. 28, 28, 29, 29, 64, 64};
  80217. /*
  80218. Process a set of code lengths to create a canonical Huffman code. The
  80219. code lengths are lens[0..codes-1]. Each length corresponds to the
  80220. symbols 0..codes-1. The Huffman code is generated by first sorting the
  80221. symbols by length from short to long, and retaining the symbol order
  80222. for codes with equal lengths. Then the code starts with all zero bits
  80223. for the first code of the shortest length, and the codes are integer
  80224. increments for the same length, and zeros are appended as the length
  80225. increases. For the deflate format, these bits are stored backwards
  80226. from their more natural integer increment ordering, and so when the
  80227. decoding tables are built in the large loop below, the integer codes
  80228. are incremented backwards.
  80229. This routine assumes, but does not check, that all of the entries in
  80230. lens[] are in the range 0..MAXBITS. The caller must assure this.
  80231. 1..MAXBITS is interpreted as that code length. zero means that that
  80232. symbol does not occur in this code.
  80233. The codes are sorted by computing a count of codes for each length,
  80234. creating from that a table of starting indices for each length in the
  80235. sorted table, and then entering the symbols in order in the sorted
  80236. table. The sorted table is work[], with that space being provided by
  80237. the caller.
  80238. The length counts are used for other purposes as well, i.e. finding
  80239. the minimum and maximum length codes, determining if there are any
  80240. codes at all, checking for a valid set of lengths, and looking ahead
  80241. at length counts to determine sub-table sizes when building the
  80242. decoding tables.
  80243. */
  80244. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  80245. for (len = 0; len <= MAXBITS; len++)
  80246. count[len] = 0;
  80247. for (sym = 0; sym < codes; sym++)
  80248. count[lens[sym]]++;
  80249. /* bound code lengths, force root to be within code lengths */
  80250. root = *bits;
  80251. for (max = MAXBITS; max >= 1; max--)
  80252. if (count[max] != 0) break;
  80253. if (root > max) root = max;
  80254. if (max == 0) { /* no symbols to code at all */
  80255. thisx.op = (unsigned char)64; /* invalid code marker */
  80256. thisx.bits = (unsigned char)1;
  80257. thisx.val = (unsigned short)0;
  80258. *(*table)++ = thisx; /* make a table to force an error */
  80259. *(*table)++ = thisx;
  80260. *bits = 1;
  80261. return 0; /* no symbols, but wait for decoding to report error */
  80262. }
  80263. for (min = 1; min <= MAXBITS; min++)
  80264. if (count[min] != 0) break;
  80265. if (root < min) root = min;
  80266. /* check for an over-subscribed or incomplete set of lengths */
  80267. left = 1;
  80268. for (len = 1; len <= MAXBITS; len++) {
  80269. left <<= 1;
  80270. left -= count[len];
  80271. if (left < 0) return -1; /* over-subscribed */
  80272. }
  80273. if (left > 0 && (type == CODES || max != 1))
  80274. return -1; /* incomplete set */
  80275. /* generate offsets into symbol table for each length for sorting */
  80276. offs[1] = 0;
  80277. for (len = 1; len < MAXBITS; len++)
  80278. offs[len + 1] = offs[len] + count[len];
  80279. /* sort symbols by length, by symbol order within each length */
  80280. for (sym = 0; sym < codes; sym++)
  80281. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  80282. /*
  80283. Create and fill in decoding tables. In this loop, the table being
  80284. filled is at next and has curr index bits. The code being used is huff
  80285. with length len. That code is converted to an index by dropping drop
  80286. bits off of the bottom. For codes where len is less than drop + curr,
  80287. those top drop + curr - len bits are incremented through all values to
  80288. fill the table with replicated entries.
  80289. root is the number of index bits for the root table. When len exceeds
  80290. root, sub-tables are created pointed to by the root entry with an index
  80291. of the low root bits of huff. This is saved in low to check for when a
  80292. new sub-table should be started. drop is zero when the root table is
  80293. being filled, and drop is root when sub-tables are being filled.
  80294. When a new sub-table is needed, it is necessary to look ahead in the
  80295. code lengths to determine what size sub-table is needed. The length
  80296. counts are used for this, and so count[] is decremented as codes are
  80297. entered in the tables.
  80298. used keeps track of how many table entries have been allocated from the
  80299. provided *table space. It is checked when a LENS table is being made
  80300. against the space in *table, ENOUGH, minus the maximum space needed by
  80301. the worst case distance code, MAXD. This should never happen, but the
  80302. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  80303. This assumes that when type == LENS, bits == 9.
  80304. sym increments through all symbols, and the loop terminates when
  80305. all codes of length max, i.e. all codes, have been processed. This
  80306. routine permits incomplete codes, so another loop after this one fills
  80307. in the rest of the decoding tables with invalid code markers.
  80308. */
  80309. /* set up for code type */
  80310. switch (type) {
  80311. case CODES:
  80312. base = extra = work; /* dummy value--not used */
  80313. end = 19;
  80314. break;
  80315. case LENS:
  80316. base = lbase;
  80317. base -= 257;
  80318. extra = lext;
  80319. extra -= 257;
  80320. end = 256;
  80321. break;
  80322. default: /* DISTS */
  80323. base = dbase;
  80324. extra = dext;
  80325. end = -1;
  80326. }
  80327. /* initialize state for loop */
  80328. huff = 0; /* starting code */
  80329. sym = 0; /* starting code symbol */
  80330. len = min; /* starting code length */
  80331. next = *table; /* current table to fill in */
  80332. curr = root; /* current table index bits */
  80333. drop = 0; /* current bits to drop from code for index */
  80334. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  80335. used = 1U << root; /* use root table entries */
  80336. mask = used - 1; /* mask for comparing low */
  80337. /* check available table space */
  80338. if (type == LENS && used >= ENOUGH - MAXD)
  80339. return 1;
  80340. /* process all codes and make table entries */
  80341. for (;;) {
  80342. /* create table entry */
  80343. thisx.bits = (unsigned char)(len - drop);
  80344. if ((int)(work[sym]) < end) {
  80345. thisx.op = (unsigned char)0;
  80346. thisx.val = work[sym];
  80347. }
  80348. else if ((int)(work[sym]) > end) {
  80349. thisx.op = (unsigned char)(extra[work[sym]]);
  80350. thisx.val = base[work[sym]];
  80351. }
  80352. else {
  80353. thisx.op = (unsigned char)(32 + 64); /* end of block */
  80354. thisx.val = 0;
  80355. }
  80356. /* replicate for those indices with low len bits equal to huff */
  80357. incr = 1U << (len - drop);
  80358. fill = 1U << curr;
  80359. min = fill; /* save offset to next table */
  80360. do {
  80361. fill -= incr;
  80362. next[(huff >> drop) + fill] = thisx;
  80363. } while (fill != 0);
  80364. /* backwards increment the len-bit code huff */
  80365. incr = 1U << (len - 1);
  80366. while (huff & incr)
  80367. incr >>= 1;
  80368. if (incr != 0) {
  80369. huff &= incr - 1;
  80370. huff += incr;
  80371. }
  80372. else
  80373. huff = 0;
  80374. /* go to next symbol, update count, len */
  80375. sym++;
  80376. if (--(count[len]) == 0) {
  80377. if (len == max) break;
  80378. len = lens[work[sym]];
  80379. }
  80380. /* create new sub-table if needed */
  80381. if (len > root && (huff & mask) != low) {
  80382. /* if first time, transition to sub-tables */
  80383. if (drop == 0)
  80384. drop = root;
  80385. /* increment past last table */
  80386. next += min; /* here min is 1 << curr */
  80387. /* determine length of next table */
  80388. curr = len - drop;
  80389. left = (int)(1 << curr);
  80390. while (curr + drop < max) {
  80391. left -= count[curr + drop];
  80392. if (left <= 0) break;
  80393. curr++;
  80394. left <<= 1;
  80395. }
  80396. /* check for enough space */
  80397. used += 1U << curr;
  80398. if (type == LENS && used >= ENOUGH - MAXD)
  80399. return 1;
  80400. /* point entry in root table to sub-table */
  80401. low = huff & mask;
  80402. (*table)[low].op = (unsigned char)curr;
  80403. (*table)[low].bits = (unsigned char)root;
  80404. (*table)[low].val = (unsigned short)(next - *table);
  80405. }
  80406. }
  80407. /*
  80408. Fill in rest of table for incomplete codes. This loop is similar to the
  80409. loop above in incrementing huff for table indices. It is assumed that
  80410. len is equal to curr + drop, so there is no loop needed to increment
  80411. through high index bits. When the current sub-table is filled, the loop
  80412. drops back to the root table to fill in any remaining entries there.
  80413. */
  80414. thisx.op = (unsigned char)64; /* invalid code marker */
  80415. thisx.bits = (unsigned char)(len - drop);
  80416. thisx.val = (unsigned short)0;
  80417. while (huff != 0) {
  80418. /* when done with sub-table, drop back to root table */
  80419. if (drop != 0 && (huff & mask) != low) {
  80420. drop = 0;
  80421. len = root;
  80422. next = *table;
  80423. thisx.bits = (unsigned char)len;
  80424. }
  80425. /* put invalid code marker in table */
  80426. next[huff >> drop] = thisx;
  80427. /* backwards increment the len-bit code huff */
  80428. incr = 1U << (len - 1);
  80429. while (huff & incr)
  80430. incr >>= 1;
  80431. if (incr != 0) {
  80432. huff &= incr - 1;
  80433. huff += incr;
  80434. }
  80435. else
  80436. huff = 0;
  80437. }
  80438. /* set return parameters */
  80439. *table += used;
  80440. *bits = root;
  80441. return 0;
  80442. }
  80443. /********* End of inlined file: inftrees.c *********/
  80444. /********* Start of inlined file: trees.c *********/
  80445. /*
  80446. * ALGORITHM
  80447. *
  80448. * The "deflation" process uses several Huffman trees. The more
  80449. * common source values are represented by shorter bit sequences.
  80450. *
  80451. * Each code tree is stored in a compressed form which is itself
  80452. * a Huffman encoding of the lengths of all the code strings (in
  80453. * ascending order by source values). The actual code strings are
  80454. * reconstructed from the lengths in the inflate process, as described
  80455. * in the deflate specification.
  80456. *
  80457. * REFERENCES
  80458. *
  80459. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  80460. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  80461. *
  80462. * Storer, James A.
  80463. * Data Compression: Methods and Theory, pp. 49-50.
  80464. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  80465. *
  80466. * Sedgewick, R.
  80467. * Algorithms, p290.
  80468. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  80469. */
  80470. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80471. /* #define GEN_TREES_H */
  80472. #ifdef DEBUG
  80473. # include <ctype.h>
  80474. #endif
  80475. /* ===========================================================================
  80476. * Constants
  80477. */
  80478. #define MAX_BL_BITS 7
  80479. /* Bit length codes must not exceed MAX_BL_BITS bits */
  80480. #define END_BLOCK 256
  80481. /* end of block literal code */
  80482. #define REP_3_6 16
  80483. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  80484. #define REPZ_3_10 17
  80485. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  80486. #define REPZ_11_138 18
  80487. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  80488. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  80489. = {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};
  80490. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  80491. = {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};
  80492. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  80493. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  80494. local const uch bl_order[BL_CODES]
  80495. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  80496. /* The lengths of the bit length codes are sent in order of decreasing
  80497. * probability, to avoid transmitting the lengths for unused bit length codes.
  80498. */
  80499. #define Buf_size (8 * 2*sizeof(char))
  80500. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  80501. * more than 16 bits on some systems.)
  80502. */
  80503. /* ===========================================================================
  80504. * Local data. These are initialized only once.
  80505. */
  80506. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  80507. #if defined(GEN_TREES_H) || !defined(STDC)
  80508. /* non ANSI compilers may not accept trees.h */
  80509. local ct_data static_ltree[L_CODES+2];
  80510. /* The static literal tree. Since the bit lengths are imposed, there is no
  80511. * need for the L_CODES extra codes used during heap construction. However
  80512. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  80513. * below).
  80514. */
  80515. local ct_data static_dtree[D_CODES];
  80516. /* The static distance tree. (Actually a trivial tree since all codes use
  80517. * 5 bits.)
  80518. */
  80519. uch _dist_code[DIST_CODE_LEN];
  80520. /* Distance codes. The first 256 values correspond to the distances
  80521. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  80522. * the 15 bit distances.
  80523. */
  80524. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  80525. /* length code for each normalized match length (0 == MIN_MATCH) */
  80526. local int base_length[LENGTH_CODES];
  80527. /* First normalized length for each code (0 = MIN_MATCH) */
  80528. local int base_dist[D_CODES];
  80529. /* First normalized distance for each code (0 = distance of 1) */
  80530. #else
  80531. /********* Start of inlined file: trees.h *********/
  80532. local const ct_data static_ltree[L_CODES+2] = {
  80533. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  80534. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  80535. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  80536. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  80537. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  80538. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  80539. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  80540. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  80541. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  80542. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  80543. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  80544. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  80545. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  80546. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  80547. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  80548. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  80549. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  80550. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  80551. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  80552. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  80553. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  80554. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  80555. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  80556. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  80557. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  80558. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  80559. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  80560. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  80561. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  80562. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  80563. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  80564. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  80565. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  80566. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  80567. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  80568. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  80569. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  80570. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  80571. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  80572. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  80573. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  80574. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  80575. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  80576. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  80577. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  80578. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  80579. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  80580. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  80581. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  80582. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  80583. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  80584. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  80585. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  80586. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  80587. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  80588. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  80589. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  80590. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  80591. };
  80592. local const ct_data static_dtree[D_CODES] = {
  80593. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  80594. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  80595. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  80596. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  80597. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  80598. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  80599. };
  80600. const uch _dist_code[DIST_CODE_LEN] = {
  80601. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  80602. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  80603. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  80604. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  80605. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  80606. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  80607. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80608. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80609. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80610. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  80611. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80612. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80613. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  80614. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  80615. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80616. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80617. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80618. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  80619. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80620. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80621. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80622. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80623. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80624. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80625. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80626. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  80627. };
  80628. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  80629. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  80630. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  80631. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  80632. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  80633. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  80634. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  80635. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80636. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80637. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80638. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  80639. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80640. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80641. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  80642. };
  80643. local const int base_length[LENGTH_CODES] = {
  80644. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  80645. 64, 80, 96, 112, 128, 160, 192, 224, 0
  80646. };
  80647. local const int base_dist[D_CODES] = {
  80648. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  80649. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  80650. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  80651. };
  80652. /********* End of inlined file: trees.h *********/
  80653. #endif /* GEN_TREES_H */
  80654. struct static_tree_desc_s {
  80655. const ct_data *static_tree; /* static tree or NULL */
  80656. const intf *extra_bits; /* extra bits for each code or NULL */
  80657. int extra_base; /* base index for extra_bits */
  80658. int elems; /* max number of elements in the tree */
  80659. int max_length; /* max bit length for the codes */
  80660. };
  80661. local static_tree_desc static_l_desc =
  80662. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  80663. local static_tree_desc static_d_desc =
  80664. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  80665. local static_tree_desc static_bl_desc =
  80666. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  80667. /* ===========================================================================
  80668. * Local (static) routines in this file.
  80669. */
  80670. local void tr_static_init OF((void));
  80671. local void init_block OF((deflate_state *s));
  80672. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  80673. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  80674. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  80675. local void build_tree OF((deflate_state *s, tree_desc *desc));
  80676. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80677. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80678. local int build_bl_tree OF((deflate_state *s));
  80679. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  80680. int blcodes));
  80681. local void compress_block OF((deflate_state *s, ct_data *ltree,
  80682. ct_data *dtree));
  80683. local void set_data_type OF((deflate_state *s));
  80684. local unsigned bi_reverse OF((unsigned value, int length));
  80685. local void bi_windup OF((deflate_state *s));
  80686. local void bi_flush OF((deflate_state *s));
  80687. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  80688. int header));
  80689. #ifdef GEN_TREES_H
  80690. local void gen_trees_header OF((void));
  80691. #endif
  80692. #ifndef DEBUG
  80693. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  80694. /* Send a code of the given tree. c and tree must not have side effects */
  80695. #else /* DEBUG */
  80696. # define send_code(s, c, tree) \
  80697. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  80698. send_bits(s, tree[c].Code, tree[c].Len); }
  80699. #endif
  80700. /* ===========================================================================
  80701. * Output a short LSB first on the stream.
  80702. * IN assertion: there is enough room in pendingBuf.
  80703. */
  80704. #define put_short(s, w) { \
  80705. put_byte(s, (uch)((w) & 0xff)); \
  80706. put_byte(s, (uch)((ush)(w) >> 8)); \
  80707. }
  80708. /* ===========================================================================
  80709. * Send a value on a given number of bits.
  80710. * IN assertion: length <= 16 and value fits in length bits.
  80711. */
  80712. #ifdef DEBUG
  80713. local void send_bits OF((deflate_state *s, int value, int length));
  80714. local void send_bits (deflate_state *s, int value, int length)
  80715. {
  80716. Tracevv((stderr," l %2d v %4x ", length, value));
  80717. Assert(length > 0 && length <= 15, "invalid length");
  80718. s->bits_sent += (ulg)length;
  80719. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  80720. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  80721. * unused bits in value.
  80722. */
  80723. if (s->bi_valid > (int)Buf_size - length) {
  80724. s->bi_buf |= (value << s->bi_valid);
  80725. put_short(s, s->bi_buf);
  80726. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  80727. s->bi_valid += length - Buf_size;
  80728. } else {
  80729. s->bi_buf |= value << s->bi_valid;
  80730. s->bi_valid += length;
  80731. }
  80732. }
  80733. #else /* !DEBUG */
  80734. #define send_bits(s, value, length) \
  80735. { int len = length;\
  80736. if (s->bi_valid > (int)Buf_size - len) {\
  80737. int val = value;\
  80738. s->bi_buf |= (val << s->bi_valid);\
  80739. put_short(s, s->bi_buf);\
  80740. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  80741. s->bi_valid += len - Buf_size;\
  80742. } else {\
  80743. s->bi_buf |= (value) << s->bi_valid;\
  80744. s->bi_valid += len;\
  80745. }\
  80746. }
  80747. #endif /* DEBUG */
  80748. /* the arguments must not have side effects */
  80749. /* ===========================================================================
  80750. * Initialize the various 'constant' tables.
  80751. */
  80752. local void tr_static_init()
  80753. {
  80754. #if defined(GEN_TREES_H) || !defined(STDC)
  80755. static int static_init_done = 0;
  80756. int n; /* iterates over tree elements */
  80757. int bits; /* bit counter */
  80758. int length; /* length value */
  80759. int code; /* code value */
  80760. int dist; /* distance index */
  80761. ush bl_count[MAX_BITS+1];
  80762. /* number of codes at each bit length for an optimal tree */
  80763. if (static_init_done) return;
  80764. /* For some embedded targets, global variables are not initialized: */
  80765. static_l_desc.static_tree = static_ltree;
  80766. static_l_desc.extra_bits = extra_lbits;
  80767. static_d_desc.static_tree = static_dtree;
  80768. static_d_desc.extra_bits = extra_dbits;
  80769. static_bl_desc.extra_bits = extra_blbits;
  80770. /* Initialize the mapping length (0..255) -> length code (0..28) */
  80771. length = 0;
  80772. for (code = 0; code < LENGTH_CODES-1; code++) {
  80773. base_length[code] = length;
  80774. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  80775. _length_code[length++] = (uch)code;
  80776. }
  80777. }
  80778. Assert (length == 256, "tr_static_init: length != 256");
  80779. /* Note that the length 255 (match length 258) can be represented
  80780. * in two different ways: code 284 + 5 bits or code 285, so we
  80781. * overwrite length_code[255] to use the best encoding:
  80782. */
  80783. _length_code[length-1] = (uch)code;
  80784. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  80785. dist = 0;
  80786. for (code = 0 ; code < 16; code++) {
  80787. base_dist[code] = dist;
  80788. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  80789. _dist_code[dist++] = (uch)code;
  80790. }
  80791. }
  80792. Assert (dist == 256, "tr_static_init: dist != 256");
  80793. dist >>= 7; /* from now on, all distances are divided by 128 */
  80794. for ( ; code < D_CODES; code++) {
  80795. base_dist[code] = dist << 7;
  80796. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  80797. _dist_code[256 + dist++] = (uch)code;
  80798. }
  80799. }
  80800. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  80801. /* Construct the codes of the static literal tree */
  80802. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  80803. n = 0;
  80804. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  80805. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  80806. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  80807. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  80808. /* Codes 286 and 287 do not exist, but we must include them in the
  80809. * tree construction to get a canonical Huffman tree (longest code
  80810. * all ones)
  80811. */
  80812. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  80813. /* The static distance tree is trivial: */
  80814. for (n = 0; n < D_CODES; n++) {
  80815. static_dtree[n].Len = 5;
  80816. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  80817. }
  80818. static_init_done = 1;
  80819. # ifdef GEN_TREES_H
  80820. gen_trees_header();
  80821. # endif
  80822. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  80823. }
  80824. /* ===========================================================================
  80825. * Genererate the file trees.h describing the static trees.
  80826. */
  80827. #ifdef GEN_TREES_H
  80828. # ifndef DEBUG
  80829. # include <stdio.h>
  80830. # endif
  80831. # define SEPARATOR(i, last, width) \
  80832. ((i) == (last)? "\n};\n\n" : \
  80833. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  80834. void gen_trees_header()
  80835. {
  80836. FILE *header = fopen("trees.h", "w");
  80837. int i;
  80838. Assert (header != NULL, "Can't open trees.h");
  80839. fprintf(header,
  80840. "/* header created automatically with -DGEN_TREES_H */\n\n");
  80841. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  80842. for (i = 0; i < L_CODES+2; i++) {
  80843. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  80844. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  80845. }
  80846. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  80847. for (i = 0; i < D_CODES; i++) {
  80848. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  80849. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  80850. }
  80851. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  80852. for (i = 0; i < DIST_CODE_LEN; i++) {
  80853. fprintf(header, "%2u%s", _dist_code[i],
  80854. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  80855. }
  80856. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  80857. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  80858. fprintf(header, "%2u%s", _length_code[i],
  80859. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  80860. }
  80861. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  80862. for (i = 0; i < LENGTH_CODES; i++) {
  80863. fprintf(header, "%1u%s", base_length[i],
  80864. SEPARATOR(i, LENGTH_CODES-1, 20));
  80865. }
  80866. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  80867. for (i = 0; i < D_CODES; i++) {
  80868. fprintf(header, "%5u%s", base_dist[i],
  80869. SEPARATOR(i, D_CODES-1, 10));
  80870. }
  80871. fclose(header);
  80872. }
  80873. #endif /* GEN_TREES_H */
  80874. /* ===========================================================================
  80875. * Initialize the tree data structures for a new zlib stream.
  80876. */
  80877. void _tr_init(deflate_state *s)
  80878. {
  80879. tr_static_init();
  80880. s->l_desc.dyn_tree = s->dyn_ltree;
  80881. s->l_desc.stat_desc = &static_l_desc;
  80882. s->d_desc.dyn_tree = s->dyn_dtree;
  80883. s->d_desc.stat_desc = &static_d_desc;
  80884. s->bl_desc.dyn_tree = s->bl_tree;
  80885. s->bl_desc.stat_desc = &static_bl_desc;
  80886. s->bi_buf = 0;
  80887. s->bi_valid = 0;
  80888. s->last_eob_len = 8; /* enough lookahead for inflate */
  80889. #ifdef DEBUG
  80890. s->compressed_len = 0L;
  80891. s->bits_sent = 0L;
  80892. #endif
  80893. /* Initialize the first block of the first file: */
  80894. init_block(s);
  80895. }
  80896. /* ===========================================================================
  80897. * Initialize a new block.
  80898. */
  80899. local void init_block (deflate_state *s)
  80900. {
  80901. int n; /* iterates over tree elements */
  80902. /* Initialize the trees. */
  80903. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  80904. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  80905. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  80906. s->dyn_ltree[END_BLOCK].Freq = 1;
  80907. s->opt_len = s->static_len = 0L;
  80908. s->last_lit = s->matches = 0;
  80909. }
  80910. #define SMALLEST 1
  80911. /* Index within the heap array of least frequent node in the Huffman tree */
  80912. /* ===========================================================================
  80913. * Remove the smallest element from the heap and recreate the heap with
  80914. * one less element. Updates heap and heap_len.
  80915. */
  80916. #define pqremove(s, tree, top) \
  80917. {\
  80918. top = s->heap[SMALLEST]; \
  80919. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  80920. pqdownheap(s, tree, SMALLEST); \
  80921. }
  80922. /* ===========================================================================
  80923. * Compares to subtrees, using the tree depth as tie breaker when
  80924. * the subtrees have equal frequency. This minimizes the worst case length.
  80925. */
  80926. #define smaller(tree, n, m, depth) \
  80927. (tree[n].Freq < tree[m].Freq || \
  80928. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  80929. /* ===========================================================================
  80930. * Restore the heap property by moving down the tree starting at node k,
  80931. * exchanging a node with the smallest of its two sons if necessary, stopping
  80932. * when the heap property is re-established (each father smaller than its
  80933. * two sons).
  80934. */
  80935. local void pqdownheap (deflate_state *s,
  80936. ct_data *tree, /* the tree to restore */
  80937. int k) /* node to move down */
  80938. {
  80939. int v = s->heap[k];
  80940. int j = k << 1; /* left son of k */
  80941. while (j <= s->heap_len) {
  80942. /* Set j to the smallest of the two sons: */
  80943. if (j < s->heap_len &&
  80944. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  80945. j++;
  80946. }
  80947. /* Exit if v is smaller than both sons */
  80948. if (smaller(tree, v, s->heap[j], s->depth)) break;
  80949. /* Exchange v with the smallest son */
  80950. s->heap[k] = s->heap[j]; k = j;
  80951. /* And continue down the tree, setting j to the left son of k */
  80952. j <<= 1;
  80953. }
  80954. s->heap[k] = v;
  80955. }
  80956. /* ===========================================================================
  80957. * Compute the optimal bit lengths for a tree and update the total bit length
  80958. * for the current block.
  80959. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  80960. * above are the tree nodes sorted by increasing frequency.
  80961. * OUT assertions: the field len is set to the optimal bit length, the
  80962. * array bl_count contains the frequencies for each bit length.
  80963. * The length opt_len is updated; static_len is also updated if stree is
  80964. * not null.
  80965. */
  80966. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  80967. {
  80968. ct_data *tree = desc->dyn_tree;
  80969. int max_code = desc->max_code;
  80970. const ct_data *stree = desc->stat_desc->static_tree;
  80971. const intf *extra = desc->stat_desc->extra_bits;
  80972. int base = desc->stat_desc->extra_base;
  80973. int max_length = desc->stat_desc->max_length;
  80974. int h; /* heap index */
  80975. int n, m; /* iterate over the tree elements */
  80976. int bits; /* bit length */
  80977. int xbits; /* extra bits */
  80978. ush f; /* frequency */
  80979. int overflow = 0; /* number of elements with bit length too large */
  80980. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  80981. /* In a first pass, compute the optimal bit lengths (which may
  80982. * overflow in the case of the bit length tree).
  80983. */
  80984. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  80985. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  80986. n = s->heap[h];
  80987. bits = tree[tree[n].Dad].Len + 1;
  80988. if (bits > max_length) bits = max_length, overflow++;
  80989. tree[n].Len = (ush)bits;
  80990. /* We overwrite tree[n].Dad which is no longer needed */
  80991. if (n > max_code) continue; /* not a leaf node */
  80992. s->bl_count[bits]++;
  80993. xbits = 0;
  80994. if (n >= base) xbits = extra[n-base];
  80995. f = tree[n].Freq;
  80996. s->opt_len += (ulg)f * (bits + xbits);
  80997. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  80998. }
  80999. if (overflow == 0) return;
  81000. Trace((stderr,"\nbit length overflow\n"));
  81001. /* This happens for example on obj2 and pic of the Calgary corpus */
  81002. /* Find the first bit length which could increase: */
  81003. do {
  81004. bits = max_length-1;
  81005. while (s->bl_count[bits] == 0) bits--;
  81006. s->bl_count[bits]--; /* move one leaf down the tree */
  81007. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  81008. s->bl_count[max_length]--;
  81009. /* The brother of the overflow item also moves one step up,
  81010. * but this does not affect bl_count[max_length]
  81011. */
  81012. overflow -= 2;
  81013. } while (overflow > 0);
  81014. /* Now recompute all bit lengths, scanning in increasing frequency.
  81015. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  81016. * lengths instead of fixing only the wrong ones. This idea is taken
  81017. * from 'ar' written by Haruhiko Okumura.)
  81018. */
  81019. for (bits = max_length; bits != 0; bits--) {
  81020. n = s->bl_count[bits];
  81021. while (n != 0) {
  81022. m = s->heap[--h];
  81023. if (m > max_code) continue;
  81024. if ((unsigned) tree[m].Len != (unsigned) bits) {
  81025. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  81026. s->opt_len += ((long)bits - (long)tree[m].Len)
  81027. *(long)tree[m].Freq;
  81028. tree[m].Len = (ush)bits;
  81029. }
  81030. n--;
  81031. }
  81032. }
  81033. }
  81034. /* ===========================================================================
  81035. * Generate the codes for a given tree and bit counts (which need not be
  81036. * optimal).
  81037. * IN assertion: the array bl_count contains the bit length statistics for
  81038. * the given tree and the field len is set for all tree elements.
  81039. * OUT assertion: the field code is set for all tree elements of non
  81040. * zero code length.
  81041. */
  81042. local void gen_codes (ct_data *tree, /* the tree to decorate */
  81043. int max_code, /* largest code with non zero frequency */
  81044. ushf *bl_count) /* number of codes at each bit length */
  81045. {
  81046. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  81047. ush code = 0; /* running code value */
  81048. int bits; /* bit index */
  81049. int n; /* code index */
  81050. /* The distribution counts are first used to generate the code values
  81051. * without bit reversal.
  81052. */
  81053. for (bits = 1; bits <= MAX_BITS; bits++) {
  81054. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  81055. }
  81056. /* Check that the bit counts in bl_count are consistent. The last code
  81057. * must be all ones.
  81058. */
  81059. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  81060. "inconsistent bit counts");
  81061. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  81062. for (n = 0; n <= max_code; n++) {
  81063. int len = tree[n].Len;
  81064. if (len == 0) continue;
  81065. /* Now reverse the bits */
  81066. tree[n].Code = bi_reverse(next_code[len]++, len);
  81067. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  81068. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  81069. }
  81070. }
  81071. /* ===========================================================================
  81072. * Construct one Huffman tree and assigns the code bit strings and lengths.
  81073. * Update the total bit length for the current block.
  81074. * IN assertion: the field freq is set for all tree elements.
  81075. * OUT assertions: the fields len and code are set to the optimal bit length
  81076. * and corresponding code. The length opt_len is updated; static_len is
  81077. * also updated if stree is not null. The field max_code is set.
  81078. */
  81079. local void build_tree (deflate_state *s,
  81080. tree_desc *desc) /* the tree descriptor */
  81081. {
  81082. ct_data *tree = desc->dyn_tree;
  81083. const ct_data *stree = desc->stat_desc->static_tree;
  81084. int elems = desc->stat_desc->elems;
  81085. int n, m; /* iterate over heap elements */
  81086. int max_code = -1; /* largest code with non zero frequency */
  81087. int node; /* new node being created */
  81088. /* Construct the initial heap, with least frequent element in
  81089. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  81090. * heap[0] is not used.
  81091. */
  81092. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  81093. for (n = 0; n < elems; n++) {
  81094. if (tree[n].Freq != 0) {
  81095. s->heap[++(s->heap_len)] = max_code = n;
  81096. s->depth[n] = 0;
  81097. } else {
  81098. tree[n].Len = 0;
  81099. }
  81100. }
  81101. /* The pkzip format requires that at least one distance code exists,
  81102. * and that at least one bit should be sent even if there is only one
  81103. * possible code. So to avoid special checks later on we force at least
  81104. * two codes of non zero frequency.
  81105. */
  81106. while (s->heap_len < 2) {
  81107. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  81108. tree[node].Freq = 1;
  81109. s->depth[node] = 0;
  81110. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  81111. /* node is 0 or 1 so it does not have extra bits */
  81112. }
  81113. desc->max_code = max_code;
  81114. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  81115. * establish sub-heaps of increasing lengths:
  81116. */
  81117. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  81118. /* Construct the Huffman tree by repeatedly combining the least two
  81119. * frequent nodes.
  81120. */
  81121. node = elems; /* next internal node of the tree */
  81122. do {
  81123. pqremove(s, tree, n); /* n = node of least frequency */
  81124. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  81125. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  81126. s->heap[--(s->heap_max)] = m;
  81127. /* Create a new node father of n and m */
  81128. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  81129. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  81130. s->depth[n] : s->depth[m]) + 1);
  81131. tree[n].Dad = tree[m].Dad = (ush)node;
  81132. #ifdef DUMP_BL_TREE
  81133. if (tree == s->bl_tree) {
  81134. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  81135. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  81136. }
  81137. #endif
  81138. /* and insert the new node in the heap */
  81139. s->heap[SMALLEST] = node++;
  81140. pqdownheap(s, tree, SMALLEST);
  81141. } while (s->heap_len >= 2);
  81142. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  81143. /* At this point, the fields freq and dad are set. We can now
  81144. * generate the bit lengths.
  81145. */
  81146. gen_bitlen(s, (tree_desc *)desc);
  81147. /* The field len is now set, we can generate the bit codes */
  81148. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  81149. }
  81150. /* ===========================================================================
  81151. * Scan a literal or distance tree to determine the frequencies of the codes
  81152. * in the bit length tree.
  81153. */
  81154. local void scan_tree (deflate_state *s,
  81155. ct_data *tree, /* the tree to be scanned */
  81156. int max_code) /* and its largest code of non zero frequency */
  81157. {
  81158. int n; /* iterates over all tree elements */
  81159. int prevlen = -1; /* last emitted length */
  81160. int curlen; /* length of current code */
  81161. int nextlen = tree[0].Len; /* length of next code */
  81162. int count = 0; /* repeat count of the current code */
  81163. int max_count = 7; /* max repeat count */
  81164. int min_count = 4; /* min repeat count */
  81165. if (nextlen == 0) max_count = 138, min_count = 3;
  81166. tree[max_code+1].Len = (ush)0xffff; /* guard */
  81167. for (n = 0; n <= max_code; n++) {
  81168. curlen = nextlen; nextlen = tree[n+1].Len;
  81169. if (++count < max_count && curlen == nextlen) {
  81170. continue;
  81171. } else if (count < min_count) {
  81172. s->bl_tree[curlen].Freq += count;
  81173. } else if (curlen != 0) {
  81174. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  81175. s->bl_tree[REP_3_6].Freq++;
  81176. } else if (count <= 10) {
  81177. s->bl_tree[REPZ_3_10].Freq++;
  81178. } else {
  81179. s->bl_tree[REPZ_11_138].Freq++;
  81180. }
  81181. count = 0; prevlen = curlen;
  81182. if (nextlen == 0) {
  81183. max_count = 138, min_count = 3;
  81184. } else if (curlen == nextlen) {
  81185. max_count = 6, min_count = 3;
  81186. } else {
  81187. max_count = 7, min_count = 4;
  81188. }
  81189. }
  81190. }
  81191. /* ===========================================================================
  81192. * Send a literal or distance tree in compressed form, using the codes in
  81193. * bl_tree.
  81194. */
  81195. local void send_tree (deflate_state *s,
  81196. ct_data *tree, /* the tree to be scanned */
  81197. int max_code) /* and its largest code of non zero frequency */
  81198. {
  81199. int n; /* iterates over all tree elements */
  81200. int prevlen = -1; /* last emitted length */
  81201. int curlen; /* length of current code */
  81202. int nextlen = tree[0].Len; /* length of next code */
  81203. int count = 0; /* repeat count of the current code */
  81204. int max_count = 7; /* max repeat count */
  81205. int min_count = 4; /* min repeat count */
  81206. /* tree[max_code+1].Len = -1; */ /* guard already set */
  81207. if (nextlen == 0) max_count = 138, min_count = 3;
  81208. for (n = 0; n <= max_code; n++) {
  81209. curlen = nextlen; nextlen = tree[n+1].Len;
  81210. if (++count < max_count && curlen == nextlen) {
  81211. continue;
  81212. } else if (count < min_count) {
  81213. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  81214. } else if (curlen != 0) {
  81215. if (curlen != prevlen) {
  81216. send_code(s, curlen, s->bl_tree); count--;
  81217. }
  81218. Assert(count >= 3 && count <= 6, " 3_6?");
  81219. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  81220. } else if (count <= 10) {
  81221. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  81222. } else {
  81223. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  81224. }
  81225. count = 0; prevlen = curlen;
  81226. if (nextlen == 0) {
  81227. max_count = 138, min_count = 3;
  81228. } else if (curlen == nextlen) {
  81229. max_count = 6, min_count = 3;
  81230. } else {
  81231. max_count = 7, min_count = 4;
  81232. }
  81233. }
  81234. }
  81235. /* ===========================================================================
  81236. * Construct the Huffman tree for the bit lengths and return the index in
  81237. * bl_order of the last bit length code to send.
  81238. */
  81239. local int build_bl_tree (deflate_state *s)
  81240. {
  81241. int max_blindex; /* index of last bit length code of non zero freq */
  81242. /* Determine the bit length frequencies for literal and distance trees */
  81243. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  81244. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  81245. /* Build the bit length tree: */
  81246. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  81247. /* opt_len now includes the length of the tree representations, except
  81248. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  81249. */
  81250. /* Determine the number of bit length codes to send. The pkzip format
  81251. * requires that at least 4 bit length codes be sent. (appnote.txt says
  81252. * 3 but the actual value used is 4.)
  81253. */
  81254. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  81255. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  81256. }
  81257. /* Update opt_len to include the bit length tree and counts */
  81258. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  81259. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  81260. s->opt_len, s->static_len));
  81261. return max_blindex;
  81262. }
  81263. /* ===========================================================================
  81264. * Send the header for a block using dynamic Huffman trees: the counts, the
  81265. * lengths of the bit length codes, the literal tree and the distance tree.
  81266. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  81267. */
  81268. local void send_all_trees (deflate_state *s,
  81269. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  81270. {
  81271. int rank; /* index in bl_order */
  81272. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  81273. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  81274. "too many codes");
  81275. Tracev((stderr, "\nbl counts: "));
  81276. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  81277. send_bits(s, dcodes-1, 5);
  81278. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  81279. for (rank = 0; rank < blcodes; rank++) {
  81280. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  81281. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  81282. }
  81283. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  81284. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  81285. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  81286. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  81287. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  81288. }
  81289. /* ===========================================================================
  81290. * Send a stored block
  81291. */
  81292. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  81293. {
  81294. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  81295. #ifdef DEBUG
  81296. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  81297. s->compressed_len += (stored_len + 4) << 3;
  81298. #endif
  81299. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  81300. }
  81301. /* ===========================================================================
  81302. * Send one empty static block to give enough lookahead for inflate.
  81303. * This takes 10 bits, of which 7 may remain in the bit buffer.
  81304. * The current inflate code requires 9 bits of lookahead. If the
  81305. * last two codes for the previous block (real code plus EOB) were coded
  81306. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  81307. * the last real code. In this case we send two empty static blocks instead
  81308. * of one. (There are no problems if the previous block is stored or fixed.)
  81309. * To simplify the code, we assume the worst case of last real code encoded
  81310. * on one bit only.
  81311. */
  81312. void _tr_align (deflate_state *s)
  81313. {
  81314. send_bits(s, STATIC_TREES<<1, 3);
  81315. send_code(s, END_BLOCK, static_ltree);
  81316. #ifdef DEBUG
  81317. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  81318. #endif
  81319. bi_flush(s);
  81320. /* Of the 10 bits for the empty block, we have already sent
  81321. * (10 - bi_valid) bits. The lookahead for the last real code (before
  81322. * the EOB of the previous block) was thus at least one plus the length
  81323. * of the EOB plus what we have just sent of the empty static block.
  81324. */
  81325. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  81326. send_bits(s, STATIC_TREES<<1, 3);
  81327. send_code(s, END_BLOCK, static_ltree);
  81328. #ifdef DEBUG
  81329. s->compressed_len += 10L;
  81330. #endif
  81331. bi_flush(s);
  81332. }
  81333. s->last_eob_len = 7;
  81334. }
  81335. /* ===========================================================================
  81336. * Determine the best encoding for the current block: dynamic trees, static
  81337. * trees or store, and output the encoded block to the zip file.
  81338. */
  81339. void _tr_flush_block (deflate_state *s,
  81340. charf *buf, /* input block, or NULL if too old */
  81341. ulg stored_len, /* length of input block */
  81342. int eof) /* true if this is the last block for a file */
  81343. {
  81344. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  81345. int max_blindex = 0; /* index of last bit length code of non zero freq */
  81346. /* Build the Huffman trees unless a stored block is forced */
  81347. if (s->level > 0) {
  81348. /* Check if the file is binary or text */
  81349. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  81350. set_data_type(s);
  81351. /* Construct the literal and distance trees */
  81352. build_tree(s, (tree_desc *)(&(s->l_desc)));
  81353. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  81354. s->static_len));
  81355. build_tree(s, (tree_desc *)(&(s->d_desc)));
  81356. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  81357. s->static_len));
  81358. /* At this point, opt_len and static_len are the total bit lengths of
  81359. * the compressed block data, excluding the tree representations.
  81360. */
  81361. /* Build the bit length tree for the above two trees, and get the index
  81362. * in bl_order of the last bit length code to send.
  81363. */
  81364. max_blindex = build_bl_tree(s);
  81365. /* Determine the best encoding. Compute the block lengths in bytes. */
  81366. opt_lenb = (s->opt_len+3+7)>>3;
  81367. static_lenb = (s->static_len+3+7)>>3;
  81368. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  81369. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  81370. s->last_lit));
  81371. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  81372. } else {
  81373. Assert(buf != (char*)0, "lost buf");
  81374. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  81375. }
  81376. #ifdef FORCE_STORED
  81377. if (buf != (char*)0) { /* force stored block */
  81378. #else
  81379. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  81380. /* 4: two words for the lengths */
  81381. #endif
  81382. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  81383. * Otherwise we can't have processed more than WSIZE input bytes since
  81384. * the last block flush, because compression would have been
  81385. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  81386. * transform a block into a stored block.
  81387. */
  81388. _tr_stored_block(s, buf, stored_len, eof);
  81389. #ifdef FORCE_STATIC
  81390. } else if (static_lenb >= 0) { /* force static trees */
  81391. #else
  81392. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  81393. #endif
  81394. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  81395. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  81396. #ifdef DEBUG
  81397. s->compressed_len += 3 + s->static_len;
  81398. #endif
  81399. } else {
  81400. send_bits(s, (DYN_TREES<<1)+eof, 3);
  81401. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  81402. max_blindex+1);
  81403. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  81404. #ifdef DEBUG
  81405. s->compressed_len += 3 + s->opt_len;
  81406. #endif
  81407. }
  81408. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  81409. /* The above check is made mod 2^32, for files larger than 512 MB
  81410. * and uLong implemented on 32 bits.
  81411. */
  81412. init_block(s);
  81413. if (eof) {
  81414. bi_windup(s);
  81415. #ifdef DEBUG
  81416. s->compressed_len += 7; /* align on byte boundary */
  81417. #endif
  81418. }
  81419. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  81420. s->compressed_len-7*eof));
  81421. }
  81422. /* ===========================================================================
  81423. * Save the match info and tally the frequency counts. Return true if
  81424. * the current block must be flushed.
  81425. */
  81426. int _tr_tally (deflate_state *s,
  81427. unsigned dist, /* distance of matched string */
  81428. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  81429. {
  81430. s->d_buf[s->last_lit] = (ush)dist;
  81431. s->l_buf[s->last_lit++] = (uch)lc;
  81432. if (dist == 0) {
  81433. /* lc is the unmatched char */
  81434. s->dyn_ltree[lc].Freq++;
  81435. } else {
  81436. s->matches++;
  81437. /* Here, lc is the match length - MIN_MATCH */
  81438. dist--; /* dist = match distance - 1 */
  81439. Assert((ush)dist < (ush)MAX_DIST(s) &&
  81440. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  81441. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  81442. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  81443. s->dyn_dtree[d_code(dist)].Freq++;
  81444. }
  81445. #ifdef TRUNCATE_BLOCK
  81446. /* Try to guess if it is profitable to stop the current block here */
  81447. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  81448. /* Compute an upper bound for the compressed length */
  81449. ulg out_length = (ulg)s->last_lit*8L;
  81450. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  81451. int dcode;
  81452. for (dcode = 0; dcode < D_CODES; dcode++) {
  81453. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  81454. (5L+extra_dbits[dcode]);
  81455. }
  81456. out_length >>= 3;
  81457. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  81458. s->last_lit, in_length, out_length,
  81459. 100L - out_length*100L/in_length));
  81460. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  81461. }
  81462. #endif
  81463. return (s->last_lit == s->lit_bufsize-1);
  81464. /* We avoid equality with lit_bufsize because of wraparound at 64K
  81465. * on 16 bit machines and because stored blocks are restricted to
  81466. * 64K-1 bytes.
  81467. */
  81468. }
  81469. /* ===========================================================================
  81470. * Send the block data compressed using the given Huffman trees
  81471. */
  81472. local void compress_block (deflate_state *s,
  81473. ct_data *ltree, /* literal tree */
  81474. ct_data *dtree) /* distance tree */
  81475. {
  81476. unsigned dist; /* distance of matched string */
  81477. int lc; /* match length or unmatched char (if dist == 0) */
  81478. unsigned lx = 0; /* running index in l_buf */
  81479. unsigned code; /* the code to send */
  81480. int extra; /* number of extra bits to send */
  81481. if (s->last_lit != 0) do {
  81482. dist = s->d_buf[lx];
  81483. lc = s->l_buf[lx++];
  81484. if (dist == 0) {
  81485. send_code(s, lc, ltree); /* send a literal byte */
  81486. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  81487. } else {
  81488. /* Here, lc is the match length - MIN_MATCH */
  81489. code = _length_code[lc];
  81490. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  81491. extra = extra_lbits[code];
  81492. if (extra != 0) {
  81493. lc -= base_length[code];
  81494. send_bits(s, lc, extra); /* send the extra length bits */
  81495. }
  81496. dist--; /* dist is now the match distance - 1 */
  81497. code = d_code(dist);
  81498. Assert (code < D_CODES, "bad d_code");
  81499. send_code(s, code, dtree); /* send the distance code */
  81500. extra = extra_dbits[code];
  81501. if (extra != 0) {
  81502. dist -= base_dist[code];
  81503. send_bits(s, dist, extra); /* send the extra distance bits */
  81504. }
  81505. } /* literal or match pair ? */
  81506. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  81507. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  81508. "pendingBuf overflow");
  81509. } while (lx < s->last_lit);
  81510. send_code(s, END_BLOCK, ltree);
  81511. s->last_eob_len = ltree[END_BLOCK].Len;
  81512. }
  81513. /* ===========================================================================
  81514. * Set the data type to BINARY or TEXT, using a crude approximation:
  81515. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  81516. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  81517. * IN assertion: the fields Freq of dyn_ltree are set.
  81518. */
  81519. local void set_data_type (deflate_state *s)
  81520. {
  81521. int n;
  81522. for (n = 0; n < 9; n++)
  81523. if (s->dyn_ltree[n].Freq != 0)
  81524. break;
  81525. if (n == 9)
  81526. for (n = 14; n < 32; n++)
  81527. if (s->dyn_ltree[n].Freq != 0)
  81528. break;
  81529. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  81530. }
  81531. /* ===========================================================================
  81532. * Reverse the first len bits of a code, using straightforward code (a faster
  81533. * method would use a table)
  81534. * IN assertion: 1 <= len <= 15
  81535. */
  81536. local unsigned bi_reverse (unsigned code, int len)
  81537. {
  81538. register unsigned res = 0;
  81539. do {
  81540. res |= code & 1;
  81541. code >>= 1, res <<= 1;
  81542. } while (--len > 0);
  81543. return res >> 1;
  81544. }
  81545. /* ===========================================================================
  81546. * Flush the bit buffer, keeping at most 7 bits in it.
  81547. */
  81548. local void bi_flush (deflate_state *s)
  81549. {
  81550. if (s->bi_valid == 16) {
  81551. put_short(s, s->bi_buf);
  81552. s->bi_buf = 0;
  81553. s->bi_valid = 0;
  81554. } else if (s->bi_valid >= 8) {
  81555. put_byte(s, (Byte)s->bi_buf);
  81556. s->bi_buf >>= 8;
  81557. s->bi_valid -= 8;
  81558. }
  81559. }
  81560. /* ===========================================================================
  81561. * Flush the bit buffer and align the output on a byte boundary
  81562. */
  81563. local void bi_windup (deflate_state *s)
  81564. {
  81565. if (s->bi_valid > 8) {
  81566. put_short(s, s->bi_buf);
  81567. } else if (s->bi_valid > 0) {
  81568. put_byte(s, (Byte)s->bi_buf);
  81569. }
  81570. s->bi_buf = 0;
  81571. s->bi_valid = 0;
  81572. #ifdef DEBUG
  81573. s->bits_sent = (s->bits_sent+7) & ~7;
  81574. #endif
  81575. }
  81576. /* ===========================================================================
  81577. * Copy a stored block, storing first the length and its
  81578. * one's complement if requested.
  81579. */
  81580. local void copy_block(deflate_state *s,
  81581. charf *buf, /* the input data */
  81582. unsigned len, /* its length */
  81583. int header) /* true if block header must be written */
  81584. {
  81585. bi_windup(s); /* align on byte boundary */
  81586. s->last_eob_len = 8; /* enough lookahead for inflate */
  81587. if (header) {
  81588. put_short(s, (ush)len);
  81589. put_short(s, (ush)~len);
  81590. #ifdef DEBUG
  81591. s->bits_sent += 2*16;
  81592. #endif
  81593. }
  81594. #ifdef DEBUG
  81595. s->bits_sent += (ulg)len<<3;
  81596. #endif
  81597. while (len--) {
  81598. put_byte(s, *buf++);
  81599. }
  81600. }
  81601. /********* End of inlined file: trees.c *********/
  81602. /********* Start of inlined file: zutil.c *********/
  81603. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81604. #ifndef NO_DUMMY_DECL
  81605. struct internal_state {int dummy;}; /* for buggy compilers */
  81606. #endif
  81607. const char * const z_errmsg[10] = {
  81608. "need dictionary", /* Z_NEED_DICT 2 */
  81609. "stream end", /* Z_STREAM_END 1 */
  81610. "", /* Z_OK 0 */
  81611. "file error", /* Z_ERRNO (-1) */
  81612. "stream error", /* Z_STREAM_ERROR (-2) */
  81613. "data error", /* Z_DATA_ERROR (-3) */
  81614. "insufficient memory", /* Z_MEM_ERROR (-4) */
  81615. "buffer error", /* Z_BUF_ERROR (-5) */
  81616. "incompatible version",/* Z_VERSION_ERROR (-6) */
  81617. ""};
  81618. /*const char * ZEXPORT zlibVersion()
  81619. {
  81620. return ZLIB_VERSION;
  81621. }
  81622. uLong ZEXPORT zlibCompileFlags()
  81623. {
  81624. uLong flags;
  81625. flags = 0;
  81626. switch (sizeof(uInt)) {
  81627. case 2: break;
  81628. case 4: flags += 1; break;
  81629. case 8: flags += 2; break;
  81630. default: flags += 3;
  81631. }
  81632. switch (sizeof(uLong)) {
  81633. case 2: break;
  81634. case 4: flags += 1 << 2; break;
  81635. case 8: flags += 2 << 2; break;
  81636. default: flags += 3 << 2;
  81637. }
  81638. switch (sizeof(voidpf)) {
  81639. case 2: break;
  81640. case 4: flags += 1 << 4; break;
  81641. case 8: flags += 2 << 4; break;
  81642. default: flags += 3 << 4;
  81643. }
  81644. switch (sizeof(z_off_t)) {
  81645. case 2: break;
  81646. case 4: flags += 1 << 6; break;
  81647. case 8: flags += 2 << 6; break;
  81648. default: flags += 3 << 6;
  81649. }
  81650. #ifdef DEBUG
  81651. flags += 1 << 8;
  81652. #endif
  81653. #if defined(ASMV) || defined(ASMINF)
  81654. flags += 1 << 9;
  81655. #endif
  81656. #ifdef ZLIB_WINAPI
  81657. flags += 1 << 10;
  81658. #endif
  81659. #ifdef BUILDFIXED
  81660. flags += 1 << 12;
  81661. #endif
  81662. #ifdef DYNAMIC_CRC_TABLE
  81663. flags += 1 << 13;
  81664. #endif
  81665. #ifdef NO_GZCOMPRESS
  81666. flags += 1L << 16;
  81667. #endif
  81668. #ifdef NO_GZIP
  81669. flags += 1L << 17;
  81670. #endif
  81671. #ifdef PKZIP_BUG_WORKAROUND
  81672. flags += 1L << 20;
  81673. #endif
  81674. #ifdef FASTEST
  81675. flags += 1L << 21;
  81676. #endif
  81677. #ifdef STDC
  81678. # ifdef NO_vsnprintf
  81679. flags += 1L << 25;
  81680. # ifdef HAS_vsprintf_void
  81681. flags += 1L << 26;
  81682. # endif
  81683. # else
  81684. # ifdef HAS_vsnprintf_void
  81685. flags += 1L << 26;
  81686. # endif
  81687. # endif
  81688. #else
  81689. flags += 1L << 24;
  81690. # ifdef NO_snprintf
  81691. flags += 1L << 25;
  81692. # ifdef HAS_sprintf_void
  81693. flags += 1L << 26;
  81694. # endif
  81695. # else
  81696. # ifdef HAS_snprintf_void
  81697. flags += 1L << 26;
  81698. # endif
  81699. # endif
  81700. #endif
  81701. return flags;
  81702. }*/
  81703. #ifdef DEBUG
  81704. # ifndef verbose
  81705. # define verbose 0
  81706. # endif
  81707. int z_verbose = verbose;
  81708. void z_error (const char *m)
  81709. {
  81710. fprintf(stderr, "%s\n", m);
  81711. exit(1);
  81712. }
  81713. #endif
  81714. /* exported to allow conversion of error code to string for compress() and
  81715. * uncompress()
  81716. */
  81717. const char * ZEXPORT zError(int err)
  81718. {
  81719. return ERR_MSG(err);
  81720. }
  81721. #if defined(_WIN32_WCE)
  81722. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  81723. * errno. We define it as a global variable to simplify porting.
  81724. * Its value is always 0 and should not be used.
  81725. */
  81726. int errno = 0;
  81727. #endif
  81728. #ifndef HAVE_MEMCPY
  81729. void zmemcpy(dest, source, len)
  81730. Bytef* dest;
  81731. const Bytef* source;
  81732. uInt len;
  81733. {
  81734. if (len == 0) return;
  81735. do {
  81736. *dest++ = *source++; /* ??? to be unrolled */
  81737. } while (--len != 0);
  81738. }
  81739. int zmemcmp(s1, s2, len)
  81740. const Bytef* s1;
  81741. const Bytef* s2;
  81742. uInt len;
  81743. {
  81744. uInt j;
  81745. for (j = 0; j < len; j++) {
  81746. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  81747. }
  81748. return 0;
  81749. }
  81750. void zmemzero(dest, len)
  81751. Bytef* dest;
  81752. uInt len;
  81753. {
  81754. if (len == 0) return;
  81755. do {
  81756. *dest++ = 0; /* ??? to be unrolled */
  81757. } while (--len != 0);
  81758. }
  81759. #endif
  81760. #ifdef SYS16BIT
  81761. #ifdef __TURBOC__
  81762. /* Turbo C in 16-bit mode */
  81763. # define MY_ZCALLOC
  81764. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  81765. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  81766. * must fix the pointer. Warning: the pointer must be put back to its
  81767. * original form in order to free it, use zcfree().
  81768. */
  81769. #define MAX_PTR 10
  81770. /* 10*64K = 640K */
  81771. local int next_ptr = 0;
  81772. typedef struct ptr_table_s {
  81773. voidpf org_ptr;
  81774. voidpf new_ptr;
  81775. } ptr_table;
  81776. local ptr_table table[MAX_PTR];
  81777. /* This table is used to remember the original form of pointers
  81778. * to large buffers (64K). Such pointers are normalized with a zero offset.
  81779. * Since MSDOS is not a preemptive multitasking OS, this table is not
  81780. * protected from concurrent access. This hack doesn't work anyway on
  81781. * a protected system like OS/2. Use Microsoft C instead.
  81782. */
  81783. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81784. {
  81785. voidpf buf = opaque; /* just to make some compilers happy */
  81786. ulg bsize = (ulg)items*size;
  81787. /* If we allocate less than 65520 bytes, we assume that farmalloc
  81788. * will return a usable pointer which doesn't have to be normalized.
  81789. */
  81790. if (bsize < 65520L) {
  81791. buf = farmalloc(bsize);
  81792. if (*(ush*)&buf != 0) return buf;
  81793. } else {
  81794. buf = farmalloc(bsize + 16L);
  81795. }
  81796. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  81797. table[next_ptr].org_ptr = buf;
  81798. /* Normalize the pointer to seg:0 */
  81799. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  81800. *(ush*)&buf = 0;
  81801. table[next_ptr++].new_ptr = buf;
  81802. return buf;
  81803. }
  81804. void zcfree (voidpf opaque, voidpf ptr)
  81805. {
  81806. int n;
  81807. if (*(ush*)&ptr != 0) { /* object < 64K */
  81808. farfree(ptr);
  81809. return;
  81810. }
  81811. /* Find the original pointer */
  81812. for (n = 0; n < next_ptr; n++) {
  81813. if (ptr != table[n].new_ptr) continue;
  81814. farfree(table[n].org_ptr);
  81815. while (++n < next_ptr) {
  81816. table[n-1] = table[n];
  81817. }
  81818. next_ptr--;
  81819. return;
  81820. }
  81821. ptr = opaque; /* just to make some compilers happy */
  81822. Assert(0, "zcfree: ptr not found");
  81823. }
  81824. #endif /* __TURBOC__ */
  81825. #ifdef M_I86
  81826. /* Microsoft C in 16-bit mode */
  81827. # define MY_ZCALLOC
  81828. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  81829. # define _halloc halloc
  81830. # define _hfree hfree
  81831. #endif
  81832. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81833. {
  81834. if (opaque) opaque = 0; /* to make compiler happy */
  81835. return _halloc((long)items, size);
  81836. }
  81837. void zcfree (voidpf opaque, voidpf ptr)
  81838. {
  81839. if (opaque) opaque = 0; /* to make compiler happy */
  81840. _hfree(ptr);
  81841. }
  81842. #endif /* M_I86 */
  81843. #endif /* SYS16BIT */
  81844. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  81845. #ifndef STDC
  81846. extern voidp malloc OF((uInt size));
  81847. extern voidp calloc OF((uInt items, uInt size));
  81848. extern void free OF((voidpf ptr));
  81849. #endif
  81850. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81851. {
  81852. if (opaque) items += size - size; /* make compiler happy */
  81853. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  81854. (voidpf)calloc(items, size);
  81855. }
  81856. void zcfree (voidpf opaque, voidpf ptr)
  81857. {
  81858. free(ptr);
  81859. if (opaque) return; /* make compiler happy */
  81860. }
  81861. #endif /* MY_ZCALLOC */
  81862. /********* End of inlined file: zutil.c *********/
  81863. #undef Byte
  81864. }
  81865. #else
  81866. #include <zlib.h>
  81867. #endif
  81868. }
  81869. #if JUCE_MSVC
  81870. #pragma warning (pop)
  81871. #endif
  81872. BEGIN_JUCE_NAMESPACE
  81873. using namespace zlibNamespace;
  81874. // internal helper object that holds the zlib structures so they don't have to be
  81875. // included publicly.
  81876. class GZIPDecompressHelper
  81877. {
  81878. private:
  81879. z_stream* stream;
  81880. uint8* data;
  81881. int dataSize;
  81882. public:
  81883. bool finished, needsDictionary, error;
  81884. GZIPDecompressHelper (const bool noWrap) throw()
  81885. : data (0),
  81886. dataSize (0),
  81887. finished (false),
  81888. needsDictionary (false),
  81889. error (false)
  81890. {
  81891. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  81892. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  81893. : MAX_WBITS) != Z_OK)
  81894. {
  81895. juce_free (stream);
  81896. stream = 0;
  81897. error = true;
  81898. finished = true;
  81899. }
  81900. }
  81901. ~GZIPDecompressHelper() throw()
  81902. {
  81903. if (stream != 0)
  81904. {
  81905. inflateEnd (stream);
  81906. juce_free (stream);
  81907. }
  81908. }
  81909. bool needsInput() const throw() { return dataSize <= 0; }
  81910. void setInput (uint8* const data_, const int size) throw()
  81911. {
  81912. data = data_;
  81913. dataSize = size;
  81914. }
  81915. int doNextBlock (uint8* const dest, const int destSize) throw()
  81916. {
  81917. if (stream != 0 && data != 0 && ! finished)
  81918. {
  81919. stream->next_in = data;
  81920. stream->next_out = dest;
  81921. stream->avail_in = dataSize;
  81922. stream->avail_out = destSize;
  81923. switch (inflate (stream, Z_PARTIAL_FLUSH))
  81924. {
  81925. case Z_STREAM_END:
  81926. finished = true;
  81927. // deliberate fall-through
  81928. case Z_OK:
  81929. data += dataSize - stream->avail_in;
  81930. dataSize = stream->avail_in;
  81931. return destSize - stream->avail_out;
  81932. case Z_NEED_DICT:
  81933. needsDictionary = true;
  81934. data += dataSize - stream->avail_in;
  81935. dataSize = stream->avail_in;
  81936. break;
  81937. case Z_DATA_ERROR:
  81938. case Z_MEM_ERROR:
  81939. error = true;
  81940. default:
  81941. break;
  81942. }
  81943. }
  81944. return 0;
  81945. }
  81946. };
  81947. const int gzipDecompBufferSize = 32768;
  81948. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  81949. const bool deleteSourceWhenDestroyed_,
  81950. const bool noWrap_,
  81951. const int64 uncompressedStreamLength_)
  81952. : sourceStream (sourceStream_),
  81953. uncompressedStreamLength (uncompressedStreamLength_),
  81954. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  81955. noWrap (noWrap_),
  81956. isEof (false),
  81957. activeBufferSize (0),
  81958. originalSourcePos (sourceStream_->getPosition()),
  81959. currentPos (0)
  81960. {
  81961. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  81962. helper = new GZIPDecompressHelper (noWrap_);
  81963. }
  81964. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  81965. {
  81966. juce_free (buffer);
  81967. if (deleteSourceWhenDestroyed)
  81968. delete sourceStream;
  81969. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81970. delete h;
  81971. }
  81972. int64 GZIPDecompressorInputStream::getTotalLength()
  81973. {
  81974. return uncompressedStreamLength;
  81975. }
  81976. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  81977. {
  81978. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81979. if ((howMany > 0) && ! isEof)
  81980. {
  81981. jassert (destBuffer != 0);
  81982. if (destBuffer != 0)
  81983. {
  81984. int numRead = 0;
  81985. uint8* d = (uint8*) destBuffer;
  81986. while (! h->error)
  81987. {
  81988. const int n = h->doNextBlock (d, howMany);
  81989. currentPos += n;
  81990. if (n == 0)
  81991. {
  81992. if (h->finished || h->needsDictionary)
  81993. {
  81994. isEof = true;
  81995. return numRead;
  81996. }
  81997. if (h->needsInput())
  81998. {
  81999. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  82000. if (activeBufferSize > 0)
  82001. {
  82002. h->setInput ((uint8*) buffer, activeBufferSize);
  82003. }
  82004. else
  82005. {
  82006. isEof = true;
  82007. return numRead;
  82008. }
  82009. }
  82010. }
  82011. else
  82012. {
  82013. numRead += n;
  82014. howMany -= n;
  82015. d += n;
  82016. if (howMany <= 0)
  82017. return numRead;
  82018. }
  82019. }
  82020. }
  82021. }
  82022. return 0;
  82023. }
  82024. bool GZIPDecompressorInputStream::isExhausted()
  82025. {
  82026. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  82027. return h->error || isEof;
  82028. }
  82029. int64 GZIPDecompressorInputStream::getPosition()
  82030. {
  82031. return currentPos;
  82032. }
  82033. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  82034. {
  82035. if (newPos != currentPos)
  82036. {
  82037. if (newPos > currentPos)
  82038. {
  82039. skipNextBytes (newPos - currentPos);
  82040. }
  82041. else
  82042. {
  82043. // reset the stream and start again..
  82044. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  82045. delete h;
  82046. isEof = false;
  82047. activeBufferSize = 0;
  82048. currentPos = 0;
  82049. helper = new GZIPDecompressHelper (noWrap);
  82050. sourceStream->setPosition (originalSourcePos);
  82051. skipNextBytes (newPos);
  82052. }
  82053. }
  82054. return true;
  82055. }
  82056. END_JUCE_NAMESPACE
  82057. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  82058. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  82059. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  82060. #if JUCE_USE_FLAC
  82061. #if JUCE_WINDOWS
  82062. #include <windows.h>
  82063. #endif
  82064. #ifdef _MSC_VER
  82065. #pragma warning (disable : 4505)
  82066. #pragma warning (push)
  82067. #endif
  82068. namespace FlacNamespace
  82069. {
  82070. #if JUCE_INCLUDE_FLAC_CODE
  82071. #define FLAC__NO_DLL 1
  82072. #if ! defined (SIZE_MAX)
  82073. #define SIZE_MAX 0xffffffff
  82074. #endif
  82075. #define __STDC_LIMIT_MACROS 1
  82076. /********* Start of inlined file: all.h *********/
  82077. #ifndef FLAC__ALL_H
  82078. #define FLAC__ALL_H
  82079. /********* Start of inlined file: export.h *********/
  82080. #ifndef FLAC__EXPORT_H
  82081. #define FLAC__EXPORT_H
  82082. /** \file include/FLAC/export.h
  82083. *
  82084. * \brief
  82085. * This module contains #defines and symbols for exporting function
  82086. * calls, and providing version information and compiled-in features.
  82087. *
  82088. * See the \link flac_export export \endlink module.
  82089. */
  82090. /** \defgroup flac_export FLAC/export.h: export symbols
  82091. * \ingroup flac
  82092. *
  82093. * \brief
  82094. * This module contains #defines and symbols for exporting function
  82095. * calls, and providing version information and compiled-in features.
  82096. *
  82097. * If you are compiling with MSVC and will link to the static library
  82098. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  82099. * make sure the symbols are exported properly.
  82100. *
  82101. * \{
  82102. */
  82103. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  82104. #define FLAC_API
  82105. #else
  82106. #ifdef FLAC_API_EXPORTS
  82107. #define FLAC_API _declspec(dllexport)
  82108. #else
  82109. #define FLAC_API _declspec(dllimport)
  82110. #endif
  82111. #endif
  82112. /** These #defines will mirror the libtool-based library version number, see
  82113. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  82114. */
  82115. #define FLAC_API_VERSION_CURRENT 10
  82116. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  82117. #define FLAC_API_VERSION_AGE 2 /**< see above */
  82118. #ifdef __cplusplus
  82119. extern "C" {
  82120. #endif
  82121. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  82122. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  82123. #ifdef __cplusplus
  82124. }
  82125. #endif
  82126. /* \} */
  82127. #endif
  82128. /********* End of inlined file: export.h *********/
  82129. /********* Start of inlined file: assert.h *********/
  82130. #ifndef FLAC__ASSERT_H
  82131. #define FLAC__ASSERT_H
  82132. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  82133. #ifdef DEBUG
  82134. #include <assert.h>
  82135. #define FLAC__ASSERT(x) assert(x)
  82136. #define FLAC__ASSERT_DECLARATION(x) x
  82137. #else
  82138. #define FLAC__ASSERT(x)
  82139. #define FLAC__ASSERT_DECLARATION(x)
  82140. #endif
  82141. #endif
  82142. /********* End of inlined file: assert.h *********/
  82143. /********* Start of inlined file: callback.h *********/
  82144. #ifndef FLAC__CALLBACK_H
  82145. #define FLAC__CALLBACK_H
  82146. /********* Start of inlined file: ordinals.h *********/
  82147. #ifndef FLAC__ORDINALS_H
  82148. #define FLAC__ORDINALS_H
  82149. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  82150. #include <inttypes.h>
  82151. #endif
  82152. typedef signed char FLAC__int8;
  82153. typedef unsigned char FLAC__uint8;
  82154. #if defined(_MSC_VER) || defined(__BORLANDC__)
  82155. typedef __int16 FLAC__int16;
  82156. typedef __int32 FLAC__int32;
  82157. typedef __int64 FLAC__int64;
  82158. typedef unsigned __int16 FLAC__uint16;
  82159. typedef unsigned __int32 FLAC__uint32;
  82160. typedef unsigned __int64 FLAC__uint64;
  82161. #elif defined(__EMX__)
  82162. typedef short FLAC__int16;
  82163. typedef long FLAC__int32;
  82164. typedef long long FLAC__int64;
  82165. typedef unsigned short FLAC__uint16;
  82166. typedef unsigned long FLAC__uint32;
  82167. typedef unsigned long long FLAC__uint64;
  82168. #else
  82169. typedef int16_t FLAC__int16;
  82170. typedef int32_t FLAC__int32;
  82171. typedef int64_t FLAC__int64;
  82172. typedef uint16_t FLAC__uint16;
  82173. typedef uint32_t FLAC__uint32;
  82174. typedef uint64_t FLAC__uint64;
  82175. #endif
  82176. typedef int FLAC__bool;
  82177. typedef FLAC__uint8 FLAC__byte;
  82178. #ifdef true
  82179. #undef true
  82180. #endif
  82181. #ifdef false
  82182. #undef false
  82183. #endif
  82184. #ifndef __cplusplus
  82185. #define true 1
  82186. #define false 0
  82187. #endif
  82188. #endif
  82189. /********* End of inlined file: ordinals.h *********/
  82190. #include <stdlib.h> /* for size_t */
  82191. /** \file include/FLAC/callback.h
  82192. *
  82193. * \brief
  82194. * This module defines the structures for describing I/O callbacks
  82195. * to the other FLAC interfaces.
  82196. *
  82197. * See the detailed documentation for callbacks in the
  82198. * \link flac_callbacks callbacks \endlink module.
  82199. */
  82200. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  82201. * \ingroup flac
  82202. *
  82203. * \brief
  82204. * This module defines the structures for describing I/O callbacks
  82205. * to the other FLAC interfaces.
  82206. *
  82207. * The purpose of the I/O callback functions is to create a common way
  82208. * for the metadata interfaces to handle I/O.
  82209. *
  82210. * Originally the metadata interfaces required filenames as the way of
  82211. * specifying FLAC files to operate on. This is problematic in some
  82212. * environments so there is an additional option to specify a set of
  82213. * callbacks for doing I/O on the FLAC file, instead of the filename.
  82214. *
  82215. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  82216. * opaque structure for a data source.
  82217. *
  82218. * The callback function prototypes are similar (but not identical) to the
  82219. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  82220. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  82221. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  82222. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  82223. * is required. \warning You generally CANNOT directly use fseek or ftell
  82224. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  82225. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  82226. * large files. You will have to find an equivalent function (e.g. ftello),
  82227. * or write a wrapper. The same is true for feof() since this is usually
  82228. * implemented as a macro, not as a function whose address can be taken.
  82229. *
  82230. * \{
  82231. */
  82232. #ifdef __cplusplus
  82233. extern "C" {
  82234. #endif
  82235. /** This is the opaque handle type used by the callbacks. Typically
  82236. * this is a \c FILE* or address of a file descriptor.
  82237. */
  82238. typedef void* FLAC__IOHandle;
  82239. /** Signature for the read callback.
  82240. * The signature and semantics match POSIX fread() implementations
  82241. * and can generally be used interchangeably.
  82242. *
  82243. * \param ptr The address of the read buffer.
  82244. * \param size The size of the records to be read.
  82245. * \param nmemb The number of records to be read.
  82246. * \param handle The handle to the data source.
  82247. * \retval size_t
  82248. * The number of records read.
  82249. */
  82250. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82251. /** Signature for the write callback.
  82252. * The signature and semantics match POSIX fwrite() implementations
  82253. * and can generally be used interchangeably.
  82254. *
  82255. * \param ptr The address of the write buffer.
  82256. * \param size The size of the records to be written.
  82257. * \param nmemb The number of records to be written.
  82258. * \param handle The handle to the data source.
  82259. * \retval size_t
  82260. * The number of records written.
  82261. */
  82262. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82263. /** Signature for the seek callback.
  82264. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  82265. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  82266. * and 32-bits wide.
  82267. *
  82268. * \param handle The handle to the data source.
  82269. * \param offset The new position, relative to \a whence
  82270. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  82271. * \retval int
  82272. * \c 0 on success, \c -1 on error.
  82273. */
  82274. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  82275. /** Signature for the tell callback.
  82276. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  82277. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  82278. * and 32-bits wide.
  82279. *
  82280. * \param handle The handle to the data source.
  82281. * \retval FLAC__int64
  82282. * The current position on success, \c -1 on error.
  82283. */
  82284. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  82285. /** Signature for the EOF callback.
  82286. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  82287. * on many systems, feof() is a macro, so in this case a wrapper function
  82288. * must be provided instead.
  82289. *
  82290. * \param handle The handle to the data source.
  82291. * \retval int
  82292. * \c 0 if not at end of file, nonzero if at end of file.
  82293. */
  82294. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  82295. /** Signature for the close callback.
  82296. * The signature and semantics match POSIX fclose() implementations
  82297. * and can generally be used interchangeably.
  82298. *
  82299. * \param handle The handle to the data source.
  82300. * \retval int
  82301. * \c 0 on success, \c EOF on error.
  82302. */
  82303. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  82304. /** A structure for holding a set of callbacks.
  82305. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  82306. * describe which of the callbacks are required. The ones that are not
  82307. * required may be set to NULL.
  82308. *
  82309. * If the seek requirement for an interface is optional, you can signify that
  82310. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  82311. */
  82312. typedef struct {
  82313. FLAC__IOCallback_Read read;
  82314. FLAC__IOCallback_Write write;
  82315. FLAC__IOCallback_Seek seek;
  82316. FLAC__IOCallback_Tell tell;
  82317. FLAC__IOCallback_Eof eof;
  82318. FLAC__IOCallback_Close close;
  82319. } FLAC__IOCallbacks;
  82320. /* \} */
  82321. #ifdef __cplusplus
  82322. }
  82323. #endif
  82324. #endif
  82325. /********* End of inlined file: callback.h *********/
  82326. /********* Start of inlined file: format.h *********/
  82327. #ifndef FLAC__FORMAT_H
  82328. #define FLAC__FORMAT_H
  82329. #ifdef __cplusplus
  82330. extern "C" {
  82331. #endif
  82332. /** \file include/FLAC/format.h
  82333. *
  82334. * \brief
  82335. * This module contains structure definitions for the representation
  82336. * of FLAC format components in memory. These are the basic
  82337. * structures used by the rest of the interfaces.
  82338. *
  82339. * See the detailed documentation in the
  82340. * \link flac_format format \endlink module.
  82341. */
  82342. /** \defgroup flac_format FLAC/format.h: format components
  82343. * \ingroup flac
  82344. *
  82345. * \brief
  82346. * This module contains structure definitions for the representation
  82347. * of FLAC format components in memory. These are the basic
  82348. * structures used by the rest of the interfaces.
  82349. *
  82350. * First, you should be familiar with the
  82351. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  82352. * follow directly from the specification. As a user of libFLAC, the
  82353. * interesting parts really are the structures that describe the frame
  82354. * header and metadata blocks.
  82355. *
  82356. * The format structures here are very primitive, designed to store
  82357. * information in an efficient way. Reading information from the
  82358. * structures is easy but creating or modifying them directly is
  82359. * more complex. For the most part, as a user of a library, editing
  82360. * is not necessary; however, for metadata blocks it is, so there are
  82361. * convenience functions provided in the \link flac_metadata metadata
  82362. * module \endlink to simplify the manipulation of metadata blocks.
  82363. *
  82364. * \note
  82365. * It's not the best convention, but symbols ending in _LEN are in bits
  82366. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  82367. * global variables because they are usually used when declaring byte
  82368. * arrays and some compilers require compile-time knowledge of array
  82369. * sizes when declared on the stack.
  82370. *
  82371. * \{
  82372. */
  82373. /*
  82374. Most of the values described in this file are defined by the FLAC
  82375. format specification. There is nothing to tune here.
  82376. */
  82377. /** The largest legal metadata type code. */
  82378. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  82379. /** The minimum block size, in samples, permitted by the format. */
  82380. #define FLAC__MIN_BLOCK_SIZE (16u)
  82381. /** The maximum block size, in samples, permitted by the format. */
  82382. #define FLAC__MAX_BLOCK_SIZE (65535u)
  82383. /** The maximum block size, in samples, permitted by the FLAC subset for
  82384. * sample rates up to 48kHz. */
  82385. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  82386. /** The maximum number of channels permitted by the format. */
  82387. #define FLAC__MAX_CHANNELS (8u)
  82388. /** The minimum sample resolution permitted by the format. */
  82389. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  82390. /** The maximum sample resolution permitted by the format. */
  82391. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  82392. /** The maximum sample resolution permitted by libFLAC.
  82393. *
  82394. * \warning
  82395. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  82396. * the reference encoder/decoder is currently limited to 24 bits because
  82397. * of prevalent 32-bit math, so make sure and use this value when
  82398. * appropriate.
  82399. */
  82400. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  82401. /** The maximum sample rate permitted by the format. The value is
  82402. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  82403. * as to why.
  82404. */
  82405. #define FLAC__MAX_SAMPLE_RATE (655350u)
  82406. /** The maximum LPC order permitted by the format. */
  82407. #define FLAC__MAX_LPC_ORDER (32u)
  82408. /** The maximum LPC order permitted by the FLAC subset for sample rates
  82409. * up to 48kHz. */
  82410. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  82411. /** The minimum quantized linear predictor coefficient precision
  82412. * permitted by the format.
  82413. */
  82414. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  82415. /** The maximum quantized linear predictor coefficient precision
  82416. * permitted by the format.
  82417. */
  82418. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  82419. /** The maximum order of the fixed predictors permitted by the format. */
  82420. #define FLAC__MAX_FIXED_ORDER (4u)
  82421. /** The maximum Rice partition order permitted by the format. */
  82422. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  82423. /** The maximum Rice partition order permitted by the FLAC Subset. */
  82424. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  82425. /** The version string of the release, stamped onto the libraries and binaries.
  82426. *
  82427. * \note
  82428. * This does not correspond to the shared library version number, which
  82429. * is used to determine binary compatibility.
  82430. */
  82431. extern FLAC_API const char *FLAC__VERSION_STRING;
  82432. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  82433. * This is a NUL-terminated ASCII string; when inserted into the
  82434. * VORBIS_COMMENT the trailing null is stripped.
  82435. */
  82436. extern FLAC_API const char *FLAC__VENDOR_STRING;
  82437. /** The byte string representation of the beginning of a FLAC stream. */
  82438. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  82439. /** The 32-bit integer big-endian representation of the beginning of
  82440. * a FLAC stream.
  82441. */
  82442. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  82443. /** The length of the FLAC signature in bits. */
  82444. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  82445. /** The length of the FLAC signature in bytes. */
  82446. #define FLAC__STREAM_SYNC_LENGTH (4u)
  82447. /*****************************************************************************
  82448. *
  82449. * Subframe structures
  82450. *
  82451. *****************************************************************************/
  82452. /*****************************************************************************/
  82453. /** An enumeration of the available entropy coding methods. */
  82454. typedef enum {
  82455. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  82456. /**< Residual is coded by partitioning into contexts, each with it's own
  82457. * 4-bit Rice parameter. */
  82458. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  82459. /**< Residual is coded by partitioning into contexts, each with it's own
  82460. * 5-bit Rice parameter. */
  82461. } FLAC__EntropyCodingMethodType;
  82462. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  82463. *
  82464. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  82465. * give the string equivalent. The contents should not be modified.
  82466. */
  82467. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  82468. /** Contents of a Rice partitioned residual
  82469. */
  82470. typedef struct {
  82471. unsigned *parameters;
  82472. /**< The Rice parameters for each context. */
  82473. unsigned *raw_bits;
  82474. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  82475. * partitions and zero for unescaped partitions.
  82476. */
  82477. unsigned capacity_by_order;
  82478. /**< The capacity of the \a parameters and \a raw_bits arrays
  82479. * specified as an order, i.e. the number of array elements
  82480. * allocated is 2 ^ \a capacity_by_order.
  82481. */
  82482. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  82483. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  82484. */
  82485. typedef struct {
  82486. unsigned order;
  82487. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  82488. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  82489. /**< The context's Rice parameters and/or raw bits. */
  82490. } FLAC__EntropyCodingMethod_PartitionedRice;
  82491. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  82492. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  82493. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  82494. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  82495. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  82496. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  82497. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  82498. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  82499. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  82500. */
  82501. typedef struct {
  82502. FLAC__EntropyCodingMethodType type;
  82503. union {
  82504. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  82505. } data;
  82506. } FLAC__EntropyCodingMethod;
  82507. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  82508. /*****************************************************************************/
  82509. /** An enumeration of the available subframe types. */
  82510. typedef enum {
  82511. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  82512. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  82513. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  82514. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  82515. } FLAC__SubframeType;
  82516. /** Maps a FLAC__SubframeType to a C string.
  82517. *
  82518. * Using a FLAC__SubframeType as the index to this array will
  82519. * give the string equivalent. The contents should not be modified.
  82520. */
  82521. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  82522. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  82523. */
  82524. typedef struct {
  82525. FLAC__int32 value; /**< The constant signal value. */
  82526. } FLAC__Subframe_Constant;
  82527. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  82528. */
  82529. typedef struct {
  82530. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  82531. } FLAC__Subframe_Verbatim;
  82532. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  82533. */
  82534. typedef struct {
  82535. FLAC__EntropyCodingMethod entropy_coding_method;
  82536. /**< The residual coding method. */
  82537. unsigned order;
  82538. /**< The polynomial order. */
  82539. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  82540. /**< Warmup samples to prime the predictor, length == order. */
  82541. const FLAC__int32 *residual;
  82542. /**< The residual signal, length == (blocksize minus order) samples. */
  82543. } FLAC__Subframe_Fixed;
  82544. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  82545. */
  82546. typedef struct {
  82547. FLAC__EntropyCodingMethod entropy_coding_method;
  82548. /**< The residual coding method. */
  82549. unsigned order;
  82550. /**< The FIR order. */
  82551. unsigned qlp_coeff_precision;
  82552. /**< Quantized FIR filter coefficient precision in bits. */
  82553. int quantization_level;
  82554. /**< The qlp coeff shift needed. */
  82555. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  82556. /**< FIR filter coefficients. */
  82557. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  82558. /**< Warmup samples to prime the predictor, length == order. */
  82559. const FLAC__int32 *residual;
  82560. /**< The residual signal, length == (blocksize minus order) samples. */
  82561. } FLAC__Subframe_LPC;
  82562. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  82563. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  82564. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  82565. */
  82566. typedef struct {
  82567. FLAC__SubframeType type;
  82568. union {
  82569. FLAC__Subframe_Constant constant;
  82570. FLAC__Subframe_Fixed fixed;
  82571. FLAC__Subframe_LPC lpc;
  82572. FLAC__Subframe_Verbatim verbatim;
  82573. } data;
  82574. unsigned wasted_bits;
  82575. } FLAC__Subframe;
  82576. /** == 1 (bit)
  82577. *
  82578. * This used to be a zero-padding bit (hence the name
  82579. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  82580. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  82581. * to mean something else.
  82582. */
  82583. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  82584. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  82585. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  82586. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  82587. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  82588. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  82589. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  82590. /*****************************************************************************/
  82591. /*****************************************************************************
  82592. *
  82593. * Frame structures
  82594. *
  82595. *****************************************************************************/
  82596. /** An enumeration of the available channel assignments. */
  82597. typedef enum {
  82598. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  82599. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  82600. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  82601. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  82602. } FLAC__ChannelAssignment;
  82603. /** Maps a FLAC__ChannelAssignment to a C string.
  82604. *
  82605. * Using a FLAC__ChannelAssignment as the index to this array will
  82606. * give the string equivalent. The contents should not be modified.
  82607. */
  82608. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  82609. /** An enumeration of the possible frame numbering methods. */
  82610. typedef enum {
  82611. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  82612. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  82613. } FLAC__FrameNumberType;
  82614. /** Maps a FLAC__FrameNumberType to a C string.
  82615. *
  82616. * Using a FLAC__FrameNumberType as the index to this array will
  82617. * give the string equivalent. The contents should not be modified.
  82618. */
  82619. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  82620. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  82621. */
  82622. typedef struct {
  82623. unsigned blocksize;
  82624. /**< The number of samples per subframe. */
  82625. unsigned sample_rate;
  82626. /**< The sample rate in Hz. */
  82627. unsigned channels;
  82628. /**< The number of channels (== number of subframes). */
  82629. FLAC__ChannelAssignment channel_assignment;
  82630. /**< The channel assignment for the frame. */
  82631. unsigned bits_per_sample;
  82632. /**< The sample resolution. */
  82633. FLAC__FrameNumberType number_type;
  82634. /**< The numbering scheme used for the frame. As a convenience, the
  82635. * decoder will always convert a frame number to a sample number because
  82636. * the rules are complex. */
  82637. union {
  82638. FLAC__uint32 frame_number;
  82639. FLAC__uint64 sample_number;
  82640. } number;
  82641. /**< The frame number or sample number of first sample in frame;
  82642. * use the \a number_type value to determine which to use. */
  82643. FLAC__uint8 crc;
  82644. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  82645. * of the raw frame header bytes, meaning everything before the CRC byte
  82646. * including the sync code.
  82647. */
  82648. } FLAC__FrameHeader;
  82649. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  82650. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  82651. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  82652. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  82653. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  82654. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  82655. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  82656. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  82657. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  82658. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  82659. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  82660. */
  82661. typedef struct {
  82662. FLAC__uint16 crc;
  82663. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  82664. * 0) of the bytes before the crc, back to and including the frame header
  82665. * sync code.
  82666. */
  82667. } FLAC__FrameFooter;
  82668. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  82669. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  82670. */
  82671. typedef struct {
  82672. FLAC__FrameHeader header;
  82673. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  82674. FLAC__FrameFooter footer;
  82675. } FLAC__Frame;
  82676. /*****************************************************************************/
  82677. /*****************************************************************************
  82678. *
  82679. * Meta-data structures
  82680. *
  82681. *****************************************************************************/
  82682. /** An enumeration of the available metadata block types. */
  82683. typedef enum {
  82684. FLAC__METADATA_TYPE_STREAMINFO = 0,
  82685. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  82686. FLAC__METADATA_TYPE_PADDING = 1,
  82687. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  82688. FLAC__METADATA_TYPE_APPLICATION = 2,
  82689. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  82690. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  82691. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  82692. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  82693. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  82694. FLAC__METADATA_TYPE_CUESHEET = 5,
  82695. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  82696. FLAC__METADATA_TYPE_PICTURE = 6,
  82697. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  82698. FLAC__METADATA_TYPE_UNDEFINED = 7
  82699. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  82700. } FLAC__MetadataType;
  82701. /** Maps a FLAC__MetadataType to a C string.
  82702. *
  82703. * Using a FLAC__MetadataType as the index to this array will
  82704. * give the string equivalent. The contents should not be modified.
  82705. */
  82706. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  82707. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  82708. */
  82709. typedef struct {
  82710. unsigned min_blocksize, max_blocksize;
  82711. unsigned min_framesize, max_framesize;
  82712. unsigned sample_rate;
  82713. unsigned channels;
  82714. unsigned bits_per_sample;
  82715. FLAC__uint64 total_samples;
  82716. FLAC__byte md5sum[16];
  82717. } FLAC__StreamMetadata_StreamInfo;
  82718. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82719. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82720. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82721. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82722. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  82723. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  82724. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  82725. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  82726. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  82727. /** The total stream length of the STREAMINFO block in bytes. */
  82728. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  82729. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  82730. */
  82731. typedef struct {
  82732. int dummy;
  82733. /**< Conceptually this is an empty struct since we don't store the
  82734. * padding bytes. Empty structs are not allowed by some C compilers,
  82735. * hence the dummy.
  82736. */
  82737. } FLAC__StreamMetadata_Padding;
  82738. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  82739. */
  82740. typedef struct {
  82741. FLAC__byte id[4];
  82742. FLAC__byte *data;
  82743. } FLAC__StreamMetadata_Application;
  82744. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  82745. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  82746. */
  82747. typedef struct {
  82748. FLAC__uint64 sample_number;
  82749. /**< The sample number of the target frame. */
  82750. FLAC__uint64 stream_offset;
  82751. /**< The offset, in bytes, of the target frame with respect to
  82752. * beginning of the first frame. */
  82753. unsigned frame_samples;
  82754. /**< The number of samples in the target frame. */
  82755. } FLAC__StreamMetadata_SeekPoint;
  82756. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  82757. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  82758. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  82759. /** The total stream length of a seek point in bytes. */
  82760. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  82761. /** The value used in the \a sample_number field of
  82762. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  82763. * point (== 0xffffffffffffffff).
  82764. */
  82765. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  82766. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  82767. *
  82768. * \note From the format specification:
  82769. * - The seek points must be sorted by ascending sample number.
  82770. * - Each seek point's sample number must be the first sample of the
  82771. * target frame.
  82772. * - Each seek point's sample number must be unique within the table.
  82773. * - Existence of a SEEKTABLE block implies a correct setting of
  82774. * total_samples in the stream_info block.
  82775. * - Behavior is undefined when more than one SEEKTABLE block is
  82776. * present in a stream.
  82777. */
  82778. typedef struct {
  82779. unsigned num_points;
  82780. FLAC__StreamMetadata_SeekPoint *points;
  82781. } FLAC__StreamMetadata_SeekTable;
  82782. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82783. *
  82784. * For convenience, the APIs maintain a trailing NUL character at the end of
  82785. * \a entry which is not counted toward \a length, i.e.
  82786. * \code strlen(entry) == length \endcode
  82787. */
  82788. typedef struct {
  82789. FLAC__uint32 length;
  82790. FLAC__byte *entry;
  82791. } FLAC__StreamMetadata_VorbisComment_Entry;
  82792. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  82793. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82794. */
  82795. typedef struct {
  82796. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  82797. FLAC__uint32 num_comments;
  82798. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  82799. } FLAC__StreamMetadata_VorbisComment;
  82800. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  82801. /** FLAC CUESHEET track index structure. (See the
  82802. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  82803. * the full description of each field.)
  82804. */
  82805. typedef struct {
  82806. FLAC__uint64 offset;
  82807. /**< Offset in samples, relative to the track offset, of the index
  82808. * point.
  82809. */
  82810. FLAC__byte number;
  82811. /**< The index point number. */
  82812. } FLAC__StreamMetadata_CueSheet_Index;
  82813. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  82814. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  82815. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  82816. /** FLAC CUESHEET track structure. (See the
  82817. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  82818. * the full description of each field.)
  82819. */
  82820. typedef struct {
  82821. FLAC__uint64 offset;
  82822. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  82823. FLAC__byte number;
  82824. /**< The track number. */
  82825. char isrc[13];
  82826. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  82827. unsigned type:1;
  82828. /**< The track type: 0 for audio, 1 for non-audio. */
  82829. unsigned pre_emphasis:1;
  82830. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  82831. FLAC__byte num_indices;
  82832. /**< The number of track index points. */
  82833. FLAC__StreamMetadata_CueSheet_Index *indices;
  82834. /**< NULL if num_indices == 0, else pointer to array of index points. */
  82835. } FLAC__StreamMetadata_CueSheet_Track;
  82836. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  82837. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  82838. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  82839. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  82840. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  82841. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  82842. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  82843. /** FLAC CUESHEET structure. (See the
  82844. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  82845. * for the full description of each field.)
  82846. */
  82847. typedef struct {
  82848. char media_catalog_number[129];
  82849. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  82850. * general, the media catalog number may be 0 to 128 bytes long; any
  82851. * unused characters should be right-padded with NUL characters.
  82852. */
  82853. FLAC__uint64 lead_in;
  82854. /**< The number of lead-in samples. */
  82855. FLAC__bool is_cd;
  82856. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  82857. unsigned num_tracks;
  82858. /**< The number of tracks. */
  82859. FLAC__StreamMetadata_CueSheet_Track *tracks;
  82860. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  82861. } FLAC__StreamMetadata_CueSheet;
  82862. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  82863. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  82864. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  82865. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  82866. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  82867. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  82868. typedef enum {
  82869. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  82870. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  82871. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  82872. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  82873. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  82874. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  82875. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  82876. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  82877. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  82878. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  82879. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  82880. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  82881. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  82882. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  82883. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  82884. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  82885. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  82886. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  82887. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  82888. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  82889. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  82890. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  82891. } FLAC__StreamMetadata_Picture_Type;
  82892. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  82893. *
  82894. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  82895. * will give the string equivalent. The contents should not be
  82896. * modified.
  82897. */
  82898. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  82899. /** FLAC PICTURE structure. (See the
  82900. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  82901. * for the full description of each field.)
  82902. */
  82903. typedef struct {
  82904. FLAC__StreamMetadata_Picture_Type type;
  82905. /**< The kind of picture stored. */
  82906. char *mime_type;
  82907. /**< Picture data's MIME type, in ASCII printable characters
  82908. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  82909. * use picture data of MIME type \c image/jpeg or \c image/png. A
  82910. * MIME type of '-->' is also allowed, in which case the picture
  82911. * data should be a complete URL. In file storage, the MIME type is
  82912. * stored as a 32-bit length followed by the ASCII string with no NUL
  82913. * terminator, but is converted to a plain C string in this structure
  82914. * for convenience.
  82915. */
  82916. FLAC__byte *description;
  82917. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  82918. * the description is stored as a 32-bit length followed by the UTF-8
  82919. * string with no NUL terminator, but is converted to a plain C string
  82920. * in this structure for convenience.
  82921. */
  82922. FLAC__uint32 width;
  82923. /**< Picture's width in pixels. */
  82924. FLAC__uint32 height;
  82925. /**< Picture's height in pixels. */
  82926. FLAC__uint32 depth;
  82927. /**< Picture's color depth in bits-per-pixel. */
  82928. FLAC__uint32 colors;
  82929. /**< For indexed palettes (like GIF), picture's number of colors (the
  82930. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  82931. */
  82932. FLAC__uint32 data_length;
  82933. /**< Length of binary picture data in bytes. */
  82934. FLAC__byte *data;
  82935. /**< Binary picture data. */
  82936. } FLAC__StreamMetadata_Picture;
  82937. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  82938. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  82939. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  82940. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  82941. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  82942. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  82943. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  82944. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  82945. /** Structure that is used when a metadata block of unknown type is loaded.
  82946. * The contents are opaque. The structure is used only internally to
  82947. * correctly handle unknown metadata.
  82948. */
  82949. typedef struct {
  82950. FLAC__byte *data;
  82951. } FLAC__StreamMetadata_Unknown;
  82952. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  82953. */
  82954. typedef struct {
  82955. FLAC__MetadataType type;
  82956. /**< The type of the metadata block; used determine which member of the
  82957. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  82958. * then \a data.unknown must be used. */
  82959. FLAC__bool is_last;
  82960. /**< \c true if this metadata block is the last, else \a false */
  82961. unsigned length;
  82962. /**< Length, in bytes, of the block data as it appears in the stream. */
  82963. union {
  82964. FLAC__StreamMetadata_StreamInfo stream_info;
  82965. FLAC__StreamMetadata_Padding padding;
  82966. FLAC__StreamMetadata_Application application;
  82967. FLAC__StreamMetadata_SeekTable seek_table;
  82968. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  82969. FLAC__StreamMetadata_CueSheet cue_sheet;
  82970. FLAC__StreamMetadata_Picture picture;
  82971. FLAC__StreamMetadata_Unknown unknown;
  82972. } data;
  82973. /**< Polymorphic block data; use the \a type value to determine which
  82974. * to use. */
  82975. } FLAC__StreamMetadata;
  82976. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  82977. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  82978. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  82979. /** The total stream length of a metadata block header in bytes. */
  82980. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  82981. /*****************************************************************************/
  82982. /*****************************************************************************
  82983. *
  82984. * Utility functions
  82985. *
  82986. *****************************************************************************/
  82987. /** Tests that a sample rate is valid for FLAC.
  82988. *
  82989. * \param sample_rate The sample rate to test for compliance.
  82990. * \retval FLAC__bool
  82991. * \c true if the given sample rate conforms to the specification, else
  82992. * \c false.
  82993. */
  82994. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  82995. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  82996. * for valid sample rates are slightly more complex since the rate has to
  82997. * be expressible completely in the frame header.
  82998. *
  82999. * \param sample_rate The sample rate to test for compliance.
  83000. * \retval FLAC__bool
  83001. * \c true if the given sample rate conforms to the specification for the
  83002. * subset, else \c false.
  83003. */
  83004. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  83005. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  83006. * comment specification.
  83007. *
  83008. * Vorbis comment names must be composed only of characters from
  83009. * [0x20-0x3C,0x3E-0x7D].
  83010. *
  83011. * \param name A NUL-terminated string to be checked.
  83012. * \assert
  83013. * \code name != NULL \endcode
  83014. * \retval FLAC__bool
  83015. * \c false if entry name is illegal, else \c true.
  83016. */
  83017. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  83018. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  83019. * comment specification.
  83020. *
  83021. * Vorbis comment values must be valid UTF-8 sequences.
  83022. *
  83023. * \param value A string to be checked.
  83024. * \param length A the length of \a value in bytes. May be
  83025. * \c (unsigned)(-1) to indicate that \a value is a plain
  83026. * UTF-8 NUL-terminated string.
  83027. * \assert
  83028. * \code value != NULL \endcode
  83029. * \retval FLAC__bool
  83030. * \c false if entry name is illegal, else \c true.
  83031. */
  83032. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  83033. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  83034. * comment specification.
  83035. *
  83036. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  83037. * 'value' must be legal according to
  83038. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  83039. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  83040. *
  83041. * \param entry An entry to be checked.
  83042. * \param length The length of \a entry in bytes.
  83043. * \assert
  83044. * \code value != NULL \endcode
  83045. * \retval FLAC__bool
  83046. * \c false if entry name is illegal, else \c true.
  83047. */
  83048. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  83049. /** Check a seek table to see if it conforms to the FLAC specification.
  83050. * See the format specification for limits on the contents of the
  83051. * seek table.
  83052. *
  83053. * \param seek_table A pointer to a seek table to be checked.
  83054. * \assert
  83055. * \code seek_table != NULL \endcode
  83056. * \retval FLAC__bool
  83057. * \c false if seek table is illegal, else \c true.
  83058. */
  83059. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  83060. /** Sort a seek table's seek points according to the format specification.
  83061. * This includes a "unique-ification" step to remove duplicates, i.e.
  83062. * seek points with identical \a sample_number values. Duplicate seek
  83063. * points are converted into placeholder points and sorted to the end of
  83064. * the table.
  83065. *
  83066. * \param seek_table A pointer to a seek table to be sorted.
  83067. * \assert
  83068. * \code seek_table != NULL \endcode
  83069. * \retval unsigned
  83070. * The number of duplicate seek points converted into placeholders.
  83071. */
  83072. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  83073. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83074. * See the format specification for limits on the contents of the
  83075. * cue sheet.
  83076. *
  83077. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  83078. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83079. * stringent requirements for a CD-DA (audio) disc.
  83080. * \param violation Address of a pointer to a string. If there is a
  83081. * violation, a pointer to a string explanation of the
  83082. * violation will be returned here. \a violation may be
  83083. * \c NULL if you don't need the returned string. Do not
  83084. * free the returned string; it will always point to static
  83085. * data.
  83086. * \assert
  83087. * \code cue_sheet != NULL \endcode
  83088. * \retval FLAC__bool
  83089. * \c false if cue sheet is illegal, else \c true.
  83090. */
  83091. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  83092. /** Check picture data to see if it conforms to the FLAC specification.
  83093. * See the format specification for limits on the contents of the
  83094. * PICTURE block.
  83095. *
  83096. * \param picture A pointer to existing picture data to be checked.
  83097. * \param violation Address of a pointer to a string. If there is a
  83098. * violation, a pointer to a string explanation of the
  83099. * violation will be returned here. \a violation may be
  83100. * \c NULL if you don't need the returned string. Do not
  83101. * free the returned string; it will always point to static
  83102. * data.
  83103. * \assert
  83104. * \code picture != NULL \endcode
  83105. * \retval FLAC__bool
  83106. * \c false if picture data is illegal, else \c true.
  83107. */
  83108. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  83109. /* \} */
  83110. #ifdef __cplusplus
  83111. }
  83112. #endif
  83113. #endif
  83114. /********* End of inlined file: format.h *********/
  83115. /********* Start of inlined file: metadata.h *********/
  83116. #ifndef FLAC__METADATA_H
  83117. #define FLAC__METADATA_H
  83118. #include <sys/types.h> /* for off_t */
  83119. /* --------------------------------------------------------------------
  83120. (For an example of how all these routines are used, see the source
  83121. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  83122. metaflac in src/metaflac/)
  83123. ------------------------------------------------------------------*/
  83124. /** \file include/FLAC/metadata.h
  83125. *
  83126. * \brief
  83127. * This module provides functions for creating and manipulating FLAC
  83128. * metadata blocks in memory, and three progressively more powerful
  83129. * interfaces for traversing and editing metadata in FLAC files.
  83130. *
  83131. * See the detailed documentation for each interface in the
  83132. * \link flac_metadata metadata \endlink module.
  83133. */
  83134. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  83135. * \ingroup flac
  83136. *
  83137. * \brief
  83138. * This module provides functions for creating and manipulating FLAC
  83139. * metadata blocks in memory, and three progressively more powerful
  83140. * interfaces for traversing and editing metadata in native FLAC files.
  83141. * Note that currently only the Chain interface (level 2) supports Ogg
  83142. * FLAC files, and it is read-only i.e. no writing back changed
  83143. * metadata to file.
  83144. *
  83145. * There are three metadata interfaces of increasing complexity:
  83146. *
  83147. * Level 0:
  83148. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  83149. * PICTURE blocks.
  83150. *
  83151. * Level 1:
  83152. * Read-write access to all metadata blocks. This level is write-
  83153. * efficient in most cases (more on this below), and uses less memory
  83154. * than level 2.
  83155. *
  83156. * Level 2:
  83157. * Read-write access to all metadata blocks. This level is write-
  83158. * efficient in all cases, but uses more memory since all metadata for
  83159. * the whole file is read into memory and manipulated before writing
  83160. * out again.
  83161. *
  83162. * What do we mean by efficient? Since FLAC metadata appears at the
  83163. * beginning of the file, when writing metadata back to a FLAC file
  83164. * it is possible to grow or shrink the metadata such that the entire
  83165. * file must be rewritten. However, if the size remains the same during
  83166. * changes or PADDING blocks are utilized, only the metadata needs to be
  83167. * overwritten, which is much faster.
  83168. *
  83169. * Efficient means the whole file is rewritten at most one time, and only
  83170. * when necessary. Level 1 is not efficient only in the case that you
  83171. * cause more than one metadata block to grow or shrink beyond what can
  83172. * be accomodated by padding. In this case you should probably use level
  83173. * 2, which allows you to edit all the metadata for a file in memory and
  83174. * write it out all at once.
  83175. *
  83176. * All levels know how to skip over and not disturb an ID3v2 tag at the
  83177. * front of the file.
  83178. *
  83179. * All levels access files via their filenames. In addition, level 2
  83180. * has additional alternative read and write functions that take an I/O
  83181. * handle and callbacks, for situations where access by filename is not
  83182. * possible.
  83183. *
  83184. * In addition to the three interfaces, this module defines functions for
  83185. * creating and manipulating various metadata objects in memory. As we see
  83186. * from the Format module, FLAC metadata blocks in memory are very primitive
  83187. * structures for storing information in an efficient way. Reading
  83188. * information from the structures is easy but creating or modifying them
  83189. * directly is more complex. The metadata object routines here facilitate
  83190. * this by taking care of the consistency and memory management drudgery.
  83191. *
  83192. * Unless you will be using the level 1 or 2 interfaces to modify existing
  83193. * metadata however, you will not probably not need these.
  83194. *
  83195. * From a dependency standpoint, none of the encoders or decoders require
  83196. * the metadata module. This is so that embedded users can strip out the
  83197. * metadata module from libFLAC to reduce the size and complexity.
  83198. */
  83199. #ifdef __cplusplus
  83200. extern "C" {
  83201. #endif
  83202. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  83203. * \ingroup flac_metadata
  83204. *
  83205. * \brief
  83206. * The level 0 interface consists of individual routines to read the
  83207. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  83208. * only a filename.
  83209. *
  83210. * They try to skip any ID3v2 tag at the head of the file.
  83211. *
  83212. * \{
  83213. */
  83214. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  83215. * will try to skip any ID3v2 tag at the head of the file.
  83216. *
  83217. * \param filename The path to the FLAC file to read.
  83218. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  83219. * FLAC__StreamMetadata is a simple structure with no
  83220. * memory allocation involved, you pass the address of
  83221. * an existing structure. It need not be initialized.
  83222. * \assert
  83223. * \code filename != NULL \endcode
  83224. * \code streaminfo != NULL \endcode
  83225. * \retval FLAC__bool
  83226. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  83227. * \c false if there was a memory allocation error, a file decoder error,
  83228. * or the file contained no STREAMINFO block. (A memory allocation error
  83229. * is possible because this function must set up a file decoder.)
  83230. */
  83231. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  83232. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  83233. * function will try to skip any ID3v2 tag at the head of the file.
  83234. *
  83235. * \param filename The path to the FLAC file to read.
  83236. * \param tags The address where the returned pointer will be
  83237. * stored. The \a tags object must be deleted by
  83238. * the caller using FLAC__metadata_object_delete().
  83239. * \assert
  83240. * \code filename != NULL \endcode
  83241. * \code tags != NULL \endcode
  83242. * \retval FLAC__bool
  83243. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  83244. * and \a *tags will be set to the address of the metadata structure.
  83245. * Returns \c false if there was a memory allocation error, a file
  83246. * decoder error, or the file contained no VORBIS_COMMENT block, and
  83247. * \a *tags will be set to \c NULL.
  83248. */
  83249. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  83250. /** Read the CUESHEET metadata block of the given FLAC file. This
  83251. * function will try to skip any ID3v2 tag at the head of the file.
  83252. *
  83253. * \param filename The path to the FLAC file to read.
  83254. * \param cuesheet The address where the returned pointer will be
  83255. * stored. The \a cuesheet object must be deleted by
  83256. * the caller using FLAC__metadata_object_delete().
  83257. * \assert
  83258. * \code filename != NULL \endcode
  83259. * \code cuesheet != NULL \endcode
  83260. * \retval FLAC__bool
  83261. * \c true if a valid CUESHEET block was read from \a filename,
  83262. * and \a *cuesheet will be set to the address of the metadata
  83263. * structure. Returns \c false if there was a memory allocation
  83264. * error, a file decoder error, or the file contained no CUESHEET
  83265. * block, and \a *cuesheet will be set to \c NULL.
  83266. */
  83267. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  83268. /** Read a PICTURE metadata block of the given FLAC file. This
  83269. * function will try to skip any ID3v2 tag at the head of the file.
  83270. * Since there can be more than one PICTURE block in a file, this
  83271. * function takes a number of parameters that act as constraints to
  83272. * the search. The PICTURE block with the largest area matching all
  83273. * the constraints will be returned, or \a *picture will be set to
  83274. * \c NULL if there was no such block.
  83275. *
  83276. * \param filename The path to the FLAC file to read.
  83277. * \param picture The address where the returned pointer will be
  83278. * stored. The \a picture object must be deleted by
  83279. * the caller using FLAC__metadata_object_delete().
  83280. * \param type The desired picture type. Use \c -1 to mean
  83281. * "any type".
  83282. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  83283. * string will be matched exactly. Use \c NULL to
  83284. * mean "any MIME type".
  83285. * \param description The desired description. The string will be
  83286. * matched exactly. Use \c NULL to mean "any
  83287. * description".
  83288. * \param max_width The maximum width in pixels desired. Use
  83289. * \c (unsigned)(-1) to mean "any width".
  83290. * \param max_height The maximum height in pixels desired. Use
  83291. * \c (unsigned)(-1) to mean "any height".
  83292. * \param max_depth The maximum color depth in bits-per-pixel desired.
  83293. * Use \c (unsigned)(-1) to mean "any depth".
  83294. * \param max_colors The maximum number of colors desired. Use
  83295. * \c (unsigned)(-1) to mean "any number of colors".
  83296. * \assert
  83297. * \code filename != NULL \endcode
  83298. * \code picture != NULL \endcode
  83299. * \retval FLAC__bool
  83300. * \c true if a valid PICTURE block was read from \a filename,
  83301. * and \a *picture will be set to the address of the metadata
  83302. * structure. Returns \c false if there was a memory allocation
  83303. * error, a file decoder error, or the file contained no PICTURE
  83304. * block, and \a *picture will be set to \c NULL.
  83305. */
  83306. 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);
  83307. /* \} */
  83308. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  83309. * \ingroup flac_metadata
  83310. *
  83311. * \brief
  83312. * The level 1 interface provides read-write access to FLAC file metadata and
  83313. * operates directly on the FLAC file.
  83314. *
  83315. * The general usage of this interface is:
  83316. *
  83317. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  83318. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  83319. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  83320. * see if the file is writable, or only read access is allowed.
  83321. * - Use FLAC__metadata_simple_iterator_next() and
  83322. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  83323. * This is does not read the actual blocks themselves.
  83324. * FLAC__metadata_simple_iterator_next() is relatively fast.
  83325. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  83326. * forward from the front of the file.
  83327. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  83328. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  83329. * the current iterator position. The returned object is yours to modify
  83330. * and free.
  83331. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  83332. * back. You must have write permission to the original file. Make sure to
  83333. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  83334. * below.
  83335. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  83336. * Use the object creation functions from
  83337. * \link flac_metadata_object here \endlink to generate new objects.
  83338. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  83339. * currently referred to by the iterator, or replace it with padding.
  83340. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  83341. * finished.
  83342. *
  83343. * \note
  83344. * The FLAC file remains open the whole time between
  83345. * FLAC__metadata_simple_iterator_init() and
  83346. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  83347. * the file during this time.
  83348. *
  83349. * \note
  83350. * Do not modify the \a is_last, \a length, or \a type fields of returned
  83351. * FLAC__StreamMetadata objects. These are managed automatically.
  83352. *
  83353. * \note
  83354. * If any of the modification functions
  83355. * (FLAC__metadata_simple_iterator_set_block(),
  83356. * FLAC__metadata_simple_iterator_delete_block(),
  83357. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  83358. * you should delete the iterator as it may no longer be valid.
  83359. *
  83360. * \{
  83361. */
  83362. struct FLAC__Metadata_SimpleIterator;
  83363. /** The opaque structure definition for the level 1 iterator type.
  83364. * See the
  83365. * \link flac_metadata_level1 metadata level 1 module \endlink
  83366. * for a detailed description.
  83367. */
  83368. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  83369. /** Status type for FLAC__Metadata_SimpleIterator.
  83370. *
  83371. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  83372. */
  83373. typedef enum {
  83374. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  83375. /**< The iterator is in the normal OK state */
  83376. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  83377. /**< The data passed into a function violated the function's usage criteria */
  83378. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  83379. /**< The iterator could not open the target file */
  83380. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  83381. /**< The iterator could not find the FLAC signature at the start of the file */
  83382. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  83383. /**< The iterator tried to write to a file that was not writable */
  83384. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  83385. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  83386. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  83387. /**< The iterator encountered an error while reading the FLAC file */
  83388. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  83389. /**< The iterator encountered an error while seeking in the FLAC file */
  83390. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  83391. /**< The iterator encountered an error while writing the FLAC file */
  83392. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  83393. /**< The iterator encountered an error renaming the FLAC file */
  83394. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  83395. /**< The iterator encountered an error removing the temporary file */
  83396. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  83397. /**< Memory allocation failed */
  83398. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  83399. /**< The caller violated an assertion or an unexpected error occurred */
  83400. } FLAC__Metadata_SimpleIteratorStatus;
  83401. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  83402. *
  83403. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  83404. * will give the string equivalent. The contents should not be modified.
  83405. */
  83406. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  83407. /** Create a new iterator instance.
  83408. *
  83409. * \retval FLAC__Metadata_SimpleIterator*
  83410. * \c NULL if there was an error allocating memory, else the new instance.
  83411. */
  83412. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  83413. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83414. *
  83415. * \param iterator A pointer to an existing iterator.
  83416. * \assert
  83417. * \code iterator != NULL \endcode
  83418. */
  83419. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  83420. /** Get the current status of the iterator. Call this after a function
  83421. * returns \c false to get the reason for the error. Also resets the status
  83422. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  83423. *
  83424. * \param iterator A pointer to an existing iterator.
  83425. * \assert
  83426. * \code iterator != NULL \endcode
  83427. * \retval FLAC__Metadata_SimpleIteratorStatus
  83428. * The current status of the iterator.
  83429. */
  83430. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  83431. /** Initialize the iterator to point to the first metadata block in the
  83432. * given FLAC file.
  83433. *
  83434. * \param iterator A pointer to an existing iterator.
  83435. * \param filename The path to the FLAC file.
  83436. * \param read_only If \c true, the FLAC file will be opened
  83437. * in read-only mode; if \c false, the FLAC
  83438. * file will be opened for edit even if no
  83439. * edits are performed.
  83440. * \param preserve_file_stats If \c true, the owner and modification
  83441. * time will be preserved even if the FLAC
  83442. * file is written to.
  83443. * \assert
  83444. * \code iterator != NULL \endcode
  83445. * \code filename != NULL \endcode
  83446. * \retval FLAC__bool
  83447. * \c false if a memory allocation error occurs, the file can't be
  83448. * opened, or another error occurs, else \c true.
  83449. */
  83450. 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);
  83451. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  83452. * FLAC__metadata_simple_iterator_set_block() and
  83453. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  83454. *
  83455. * \param iterator A pointer to an existing iterator.
  83456. * \assert
  83457. * \code iterator != NULL \endcode
  83458. * \retval FLAC__bool
  83459. * See above.
  83460. */
  83461. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  83462. /** Moves the iterator forward one metadata block, returning \c false if
  83463. * already at the end.
  83464. *
  83465. * \param iterator A pointer to an existing initialized iterator.
  83466. * \assert
  83467. * \code iterator != NULL \endcode
  83468. * \a iterator has been successfully initialized with
  83469. * FLAC__metadata_simple_iterator_init()
  83470. * \retval FLAC__bool
  83471. * \c false if already at the last metadata block of the chain, else
  83472. * \c true.
  83473. */
  83474. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  83475. /** Moves the iterator backward one metadata block, returning \c false if
  83476. * already at the beginning.
  83477. *
  83478. * \param iterator A pointer to an existing initialized iterator.
  83479. * \assert
  83480. * \code iterator != NULL \endcode
  83481. * \a iterator has been successfully initialized with
  83482. * FLAC__metadata_simple_iterator_init()
  83483. * \retval FLAC__bool
  83484. * \c false if already at the first metadata block of the chain, else
  83485. * \c true.
  83486. */
  83487. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  83488. /** Returns a flag telling if the current metadata block is the last.
  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 FLAC__bool
  83496. * \c true if the current metadata block is the last in the file,
  83497. * else \c false.
  83498. */
  83499. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  83500. /** Get the offset of the metadata block at the current position. This
  83501. * avoids reading the actual block data which can save time for large
  83502. * blocks.
  83503. *
  83504. * \param iterator A pointer to an existing initialized iterator.
  83505. * \assert
  83506. * \code iterator != NULL \endcode
  83507. * \a iterator has been successfully initialized with
  83508. * FLAC__metadata_simple_iterator_init()
  83509. * \retval off_t
  83510. * The offset of the metadata block at the current iterator position.
  83511. * This is the byte offset relative to the beginning of the file of
  83512. * the current metadata block's header.
  83513. */
  83514. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  83515. /** Get the type of the metadata block at the current position. This
  83516. * avoids reading the actual block data which can save time for large
  83517. * blocks.
  83518. *
  83519. * \param iterator A pointer to an existing initialized iterator.
  83520. * \assert
  83521. * \code iterator != NULL \endcode
  83522. * \a iterator has been successfully initialized with
  83523. * FLAC__metadata_simple_iterator_init()
  83524. * \retval FLAC__MetadataType
  83525. * The type of the metadata block at the current iterator position.
  83526. */
  83527. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  83528. /** Get the length of the metadata block at the current position. This
  83529. * avoids reading the actual block data which can save time for large
  83530. * blocks.
  83531. *
  83532. * \param iterator A pointer to an existing initialized iterator.
  83533. * \assert
  83534. * \code iterator != NULL \endcode
  83535. * \a iterator has been successfully initialized with
  83536. * FLAC__metadata_simple_iterator_init()
  83537. * \retval unsigned
  83538. * The length of the metadata block at the current iterator position.
  83539. * The is same length as that in the
  83540. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  83541. * i.e. the length of the metadata body that follows the header.
  83542. */
  83543. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  83544. /** Get the application ID of the \c APPLICATION block at the current
  83545. * position. This avoids reading the actual block data which can save
  83546. * time for large blocks.
  83547. *
  83548. * \param iterator A pointer to an existing initialized iterator.
  83549. * \param id A pointer to a buffer of at least \c 4 bytes where
  83550. * the ID will be stored.
  83551. * \assert
  83552. * \code iterator != NULL \endcode
  83553. * \code id != NULL \endcode
  83554. * \a iterator has been successfully initialized with
  83555. * FLAC__metadata_simple_iterator_init()
  83556. * \retval FLAC__bool
  83557. * \c true if the ID was successfully read, else \c false, in which
  83558. * case you should check FLAC__metadata_simple_iterator_status() to
  83559. * find out why. If the status is
  83560. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  83561. * current metadata block is not an \c APPLICATION block. Otherwise
  83562. * if the status is
  83563. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  83564. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  83565. * occurred and the iterator can no longer be used.
  83566. */
  83567. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  83568. /** Get the metadata block at the current position. You can modify the
  83569. * block but must use FLAC__metadata_simple_iterator_set_block() to
  83570. * write it back to the FLAC file.
  83571. *
  83572. * You must call FLAC__metadata_object_delete() on the returned object
  83573. * when you are finished with it.
  83574. *
  83575. * \param iterator A pointer to an existing initialized iterator.
  83576. * \assert
  83577. * \code iterator != NULL \endcode
  83578. * \a iterator has been successfully initialized with
  83579. * FLAC__metadata_simple_iterator_init()
  83580. * \retval FLAC__StreamMetadata*
  83581. * The current metadata block, or \c NULL if there was a memory
  83582. * allocation error.
  83583. */
  83584. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  83585. /** Write a block back to the FLAC file. This function tries to be
  83586. * as efficient as possible; how the block is actually written is
  83587. * shown by the following:
  83588. *
  83589. * Existing block is a STREAMINFO block and the new block is a
  83590. * STREAMINFO block: the new block is written in place. Make sure
  83591. * you know what you're doing when changing the values of a
  83592. * STREAMINFO block.
  83593. *
  83594. * Existing block is a STREAMINFO block and the new block is a
  83595. * not a STREAMINFO block: this is an error since the first block
  83596. * must be a STREAMINFO block. Returns \c false without altering the
  83597. * file.
  83598. *
  83599. * Existing block is not a STREAMINFO block and the new block is a
  83600. * STREAMINFO block: this is an error since there may be only one
  83601. * STREAMINFO block. Returns \c false without altering the file.
  83602. *
  83603. * Existing block and new block are the same length: the existing
  83604. * block will be replaced by the new block, written in place.
  83605. *
  83606. * Existing block is longer than new block: if use_padding is \c true,
  83607. * the existing block will be overwritten in place with the new
  83608. * block followed by a PADDING block, if possible, to make the total
  83609. * size the same as the existing block. Remember that a padding
  83610. * block requires at least four bytes so if the difference in size
  83611. * between the new block and existing block is less than that, the
  83612. * entire file will have to be rewritten, using the new block's
  83613. * exact size. If use_padding is \c false, the entire file will be
  83614. * rewritten, replacing the existing block by the new block.
  83615. *
  83616. * Existing block is shorter than new block: if use_padding is \c true,
  83617. * the function will try and expand the new block into the following
  83618. * PADDING block, if it exists and doing so won't shrink the PADDING
  83619. * block to less than 4 bytes. If there is no following PADDING
  83620. * block, or it will shrink to less than 4 bytes, or use_padding is
  83621. * \c false, the entire file is rewritten, replacing the existing block
  83622. * with the new block. Note that in this case any following PADDING
  83623. * block is preserved as is.
  83624. *
  83625. * After writing the block, the iterator will remain in the same
  83626. * place, i.e. pointing to the new block.
  83627. *
  83628. * \param iterator A pointer to an existing initialized iterator.
  83629. * \param block The block to set.
  83630. * \param use_padding See above.
  83631. * \assert
  83632. * \code iterator != NULL \endcode
  83633. * \a iterator has been successfully initialized with
  83634. * FLAC__metadata_simple_iterator_init()
  83635. * \code block != NULL \endcode
  83636. * \retval FLAC__bool
  83637. * \c true if successful, else \c false.
  83638. */
  83639. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83640. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  83641. * except that instead of writing over an existing block, it appends
  83642. * a block after the existing block. \a use_padding is again used to
  83643. * tell the function to try an expand into following padding in an
  83644. * attempt to avoid rewriting the entire file.
  83645. *
  83646. * This function will fail and return \c false if given a STREAMINFO
  83647. * block.
  83648. *
  83649. * After writing the block, the iterator will be pointing to the
  83650. * new block.
  83651. *
  83652. * \param iterator A pointer to an existing initialized iterator.
  83653. * \param block The block to set.
  83654. * \param use_padding See above.
  83655. * \assert
  83656. * \code iterator != NULL \endcode
  83657. * \a iterator has been successfully initialized with
  83658. * FLAC__metadata_simple_iterator_init()
  83659. * \code block != NULL \endcode
  83660. * \retval FLAC__bool
  83661. * \c true if successful, else \c false.
  83662. */
  83663. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83664. /** Deletes the block at the current position. This will cause the
  83665. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  83666. * in which case the block will be replaced by an equal-sized PADDING
  83667. * block. The iterator will be left pointing to the block before the
  83668. * one just deleted.
  83669. *
  83670. * You may not delete the STREAMINFO block.
  83671. *
  83672. * \param iterator A pointer to an existing initialized iterator.
  83673. * \param use_padding See above.
  83674. * \assert
  83675. * \code iterator != NULL \endcode
  83676. * \a iterator has been successfully initialized with
  83677. * FLAC__metadata_simple_iterator_init()
  83678. * \retval FLAC__bool
  83679. * \c true if successful, else \c false.
  83680. */
  83681. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  83682. /* \} */
  83683. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  83684. * \ingroup flac_metadata
  83685. *
  83686. * \brief
  83687. * The level 2 interface provides read-write access to FLAC file metadata;
  83688. * all metadata is read into memory, operated on in memory, and then written
  83689. * to file, which is more efficient than level 1 when editing multiple blocks.
  83690. *
  83691. * Currently Ogg FLAC is supported for read only, via
  83692. * FLAC__metadata_chain_read_ogg() but a subsequent
  83693. * FLAC__metadata_chain_write() will fail.
  83694. *
  83695. * The general usage of this interface is:
  83696. *
  83697. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  83698. * linked list of FLAC metadata blocks.
  83699. * - Read all metadata into the the chain from a FLAC file using
  83700. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  83701. * check the status.
  83702. * - Optionally, consolidate the padding using
  83703. * FLAC__metadata_chain_merge_padding() or
  83704. * FLAC__metadata_chain_sort_padding().
  83705. * - Create a new iterator using FLAC__metadata_iterator_new()
  83706. * - Initialize the iterator to point to the first element in the chain
  83707. * using FLAC__metadata_iterator_init()
  83708. * - Traverse the chain using FLAC__metadata_iterator_next and
  83709. * FLAC__metadata_iterator_prev().
  83710. * - Get a block for reading or modification using
  83711. * FLAC__metadata_iterator_get_block(). The pointer to the object
  83712. * inside the chain is returned, so the block is yours to modify.
  83713. * Changes will be reflected in the FLAC file when you write the
  83714. * chain. You can also add and delete blocks (see functions below).
  83715. * - When done, write out the chain using FLAC__metadata_chain_write().
  83716. * Make sure to read the whole comment to the function below.
  83717. * - Delete the chain using FLAC__metadata_chain_delete().
  83718. *
  83719. * \note
  83720. * Even though the FLAC file is not open while the chain is being
  83721. * manipulated, you must not alter the file externally during
  83722. * this time. The chain assumes the FLAC file will not change
  83723. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  83724. * and FLAC__metadata_chain_write().
  83725. *
  83726. * \note
  83727. * Do not modify the is_last, length, or type fields of returned
  83728. * FLAC__StreamMetadata objects. These are managed automatically.
  83729. *
  83730. * \note
  83731. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  83732. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  83733. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  83734. * become owned by the chain and they will be deleted when the chain is
  83735. * deleted.
  83736. *
  83737. * \{
  83738. */
  83739. struct FLAC__Metadata_Chain;
  83740. /** The opaque structure definition for the level 2 chain type.
  83741. */
  83742. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  83743. struct FLAC__Metadata_Iterator;
  83744. /** The opaque structure definition for the level 2 iterator type.
  83745. */
  83746. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  83747. typedef enum {
  83748. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  83749. /**< The chain is in the normal OK state */
  83750. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  83751. /**< The data passed into a function violated the function's usage criteria */
  83752. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  83753. /**< The chain could not open the target file */
  83754. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  83755. /**< The chain could not find the FLAC signature at the start of the file */
  83756. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  83757. /**< The chain tried to write to a file that was not writable */
  83758. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  83759. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  83760. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  83761. /**< The chain encountered an error while reading the FLAC file */
  83762. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  83763. /**< The chain encountered an error while seeking in the FLAC file */
  83764. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  83765. /**< The chain encountered an error while writing the FLAC file */
  83766. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  83767. /**< The chain encountered an error renaming the FLAC file */
  83768. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  83769. /**< The chain encountered an error removing the temporary file */
  83770. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  83771. /**< Memory allocation failed */
  83772. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  83773. /**< The caller violated an assertion or an unexpected error occurred */
  83774. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  83775. /**< One or more of the required callbacks was NULL */
  83776. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  83777. /**< FLAC__metadata_chain_write() was called on a chain read by
  83778. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83779. * or
  83780. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  83781. * was called on a chain read by
  83782. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83783. * Matching read/write methods must always be used. */
  83784. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  83785. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  83786. * chain write requires a tempfile; use
  83787. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  83788. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  83789. * called when the chain write does not require a tempfile; use
  83790. * FLAC__metadata_chain_write_with_callbacks() instead.
  83791. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  83792. * before writing via callbacks. */
  83793. } FLAC__Metadata_ChainStatus;
  83794. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  83795. *
  83796. * Using a FLAC__Metadata_ChainStatus as the index to this array
  83797. * will give the string equivalent. The contents should not be modified.
  83798. */
  83799. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  83800. /*********** FLAC__Metadata_Chain ***********/
  83801. /** Create a new chain instance.
  83802. *
  83803. * \retval FLAC__Metadata_Chain*
  83804. * \c NULL if there was an error allocating memory, else the new instance.
  83805. */
  83806. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  83807. /** Free a chain instance. Deletes the object pointed to by \a chain.
  83808. *
  83809. * \param chain A pointer to an existing chain.
  83810. * \assert
  83811. * \code chain != NULL \endcode
  83812. */
  83813. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  83814. /** Get the current status of the chain. Call this after a function
  83815. * returns \c false to get the reason for the error. Also resets the
  83816. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  83817. *
  83818. * \param chain A pointer to an existing chain.
  83819. * \assert
  83820. * \code chain != NULL \endcode
  83821. * \retval FLAC__Metadata_ChainStatus
  83822. * The current status of the chain.
  83823. */
  83824. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  83825. /** Read all metadata from a FLAC file into the chain.
  83826. *
  83827. * \param chain A pointer to an existing chain.
  83828. * \param filename The path to the FLAC file to read.
  83829. * \assert
  83830. * \code chain != NULL \endcode
  83831. * \code filename != NULL \endcode
  83832. * \retval FLAC__bool
  83833. * \c true if a valid list of metadata blocks was read from
  83834. * \a filename, else \c false. On failure, check the status with
  83835. * FLAC__metadata_chain_status().
  83836. */
  83837. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  83838. /** Read all metadata from an Ogg FLAC file into the chain.
  83839. *
  83840. * \note Ogg FLAC metadata data writing is not supported yet and
  83841. * FLAC__metadata_chain_write() will fail.
  83842. *
  83843. * \param chain A pointer to an existing chain.
  83844. * \param filename The path to the Ogg FLAC file to read.
  83845. * \assert
  83846. * \code chain != NULL \endcode
  83847. * \code filename != NULL \endcode
  83848. * \retval FLAC__bool
  83849. * \c true if a valid list of metadata blocks was read from
  83850. * \a filename, else \c false. On failure, check the status with
  83851. * FLAC__metadata_chain_status().
  83852. */
  83853. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  83854. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  83855. *
  83856. * The \a handle need only be open for reading, but must be seekable.
  83857. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83858. * for Windows).
  83859. *
  83860. * \param chain A pointer to an existing chain.
  83861. * \param handle The I/O handle of the FLAC stream to read. The
  83862. * handle will NOT be closed after the metadata is read;
  83863. * that is the duty of the caller.
  83864. * \param callbacks
  83865. * A set of callbacks to use for I/O. The mandatory
  83866. * callbacks are \a read, \a seek, and \a tell.
  83867. * \assert
  83868. * \code chain != NULL \endcode
  83869. * \retval FLAC__bool
  83870. * \c true if a valid list of metadata blocks was read from
  83871. * \a handle, else \c false. On failure, check the status with
  83872. * FLAC__metadata_chain_status().
  83873. */
  83874. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83875. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  83876. *
  83877. * The \a handle need only be open for reading, but must be seekable.
  83878. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83879. * for Windows).
  83880. *
  83881. * \note Ogg FLAC metadata data writing is not supported yet and
  83882. * FLAC__metadata_chain_write() will fail.
  83883. *
  83884. * \param chain A pointer to an existing chain.
  83885. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  83886. * handle will NOT be closed after the metadata is read;
  83887. * that is the duty of the caller.
  83888. * \param callbacks
  83889. * A set of callbacks to use for I/O. The mandatory
  83890. * callbacks are \a read, \a seek, and \a tell.
  83891. * \assert
  83892. * \code chain != NULL \endcode
  83893. * \retval FLAC__bool
  83894. * \c true if a valid list of metadata blocks was read from
  83895. * \a handle, else \c false. On failure, check the status with
  83896. * FLAC__metadata_chain_status().
  83897. */
  83898. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83899. /** Checks if writing the given chain would require the use of a
  83900. * temporary file, or if it could be written in place.
  83901. *
  83902. * Under certain conditions, padding can be utilized so that writing
  83903. * edited metadata back to the FLAC file does not require rewriting the
  83904. * entire file. If rewriting is required, then a temporary workfile is
  83905. * required. When writing metadata using callbacks, you must check
  83906. * this function to know whether to call
  83907. * FLAC__metadata_chain_write_with_callbacks() or
  83908. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  83909. * writing with FLAC__metadata_chain_write(), the temporary file is
  83910. * handled internally.
  83911. *
  83912. * \param chain A pointer to an existing chain.
  83913. * \param use_padding
  83914. * Whether or not padding will be allowed to be used
  83915. * during the write. The value of \a use_padding given
  83916. * here must match the value later passed to
  83917. * FLAC__metadata_chain_write_with_callbacks() or
  83918. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  83919. * \assert
  83920. * \code chain != NULL \endcode
  83921. * \retval FLAC__bool
  83922. * \c true if writing the current chain would require a tempfile, or
  83923. * \c false if metadata can be written in place.
  83924. */
  83925. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  83926. /** Write all metadata out to the FLAC file. This function tries to be as
  83927. * efficient as possible; how the metadata is actually written is shown by
  83928. * the following:
  83929. *
  83930. * If the current chain is the same size as the existing metadata, the new
  83931. * data is written in place.
  83932. *
  83933. * If the current chain is longer than the existing metadata, and
  83934. * \a use_padding is \c true, and the last block is a PADDING block of
  83935. * sufficient length, the function will truncate the final padding block
  83936. * so that the overall size of the metadata is the same as the existing
  83937. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  83938. * the above conditions are met, the entire FLAC file must be rewritten.
  83939. * If you want to use padding this way it is a good idea to call
  83940. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  83941. * amount of padding to work with, unless you need to preserve ordering
  83942. * of the PADDING blocks for some reason.
  83943. *
  83944. * If the current chain is shorter than the existing metadata, and
  83945. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  83946. * is extended to make the overall size the same as the existing data. If
  83947. * \a use_padding is \c true and the last block is not a PADDING block, a new
  83948. * PADDING block is added to the end of the new data to make it the same
  83949. * size as the existing data (if possible, see the note to
  83950. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  83951. * and the new data is written in place. If none of the above apply or
  83952. * \a use_padding is \c false, the entire FLAC file is rewritten.
  83953. *
  83954. * If \a preserve_file_stats is \c true, the owner and modification time will
  83955. * be preserved even if the FLAC file is written.
  83956. *
  83957. * For this write function to be used, the chain must have been read with
  83958. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  83959. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  83960. *
  83961. * \param chain A pointer to an existing chain.
  83962. * \param use_padding See above.
  83963. * \param preserve_file_stats See above.
  83964. * \assert
  83965. * \code chain != NULL \endcode
  83966. * \retval FLAC__bool
  83967. * \c true if the write succeeded, else \c false. On failure,
  83968. * check the status with FLAC__metadata_chain_status().
  83969. */
  83970. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  83971. /** Write all metadata out to a FLAC stream via callbacks.
  83972. *
  83973. * (See FLAC__metadata_chain_write() for the details on how padding is
  83974. * used to write metadata in place if possible.)
  83975. *
  83976. * The \a handle must be open for updating and be seekable. The
  83977. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  83978. * for Windows).
  83979. *
  83980. * For this write function to be used, the chain must have been read with
  83981. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83982. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83983. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83984. * \c false.
  83985. *
  83986. * \param chain A pointer to an existing chain.
  83987. * \param use_padding See FLAC__metadata_chain_write()
  83988. * \param handle The I/O handle of the FLAC stream to write. The
  83989. * handle will NOT be closed after the metadata is
  83990. * written; that is the duty of the caller.
  83991. * \param callbacks A set of callbacks to use for I/O. The mandatory
  83992. * callbacks are \a write and \a seek.
  83993. * \assert
  83994. * \code chain != NULL \endcode
  83995. * \retval FLAC__bool
  83996. * \c true if the write succeeded, else \c false. On failure,
  83997. * check the status with FLAC__metadata_chain_status().
  83998. */
  83999. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  84000. /** Write all metadata out to a FLAC stream via callbacks.
  84001. *
  84002. * (See FLAC__metadata_chain_write() for the details on how padding is
  84003. * used to write metadata in place if possible.)
  84004. *
  84005. * This version of the write-with-callbacks function must be used when
  84006. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  84007. * this function, you must supply an I/O handle corresponding to the
  84008. * FLAC file to edit, and a temporary handle to which the new FLAC
  84009. * file will be written. It is the caller's job to move this temporary
  84010. * FLAC file on top of the original FLAC file to complete the metadata
  84011. * edit.
  84012. *
  84013. * The \a handle must be open for reading and be seekable. The
  84014. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  84015. * for Windows).
  84016. *
  84017. * The \a temp_handle must be open for writing. The
  84018. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  84019. * for Windows). It should be an empty stream, or at least positioned
  84020. * at the start-of-file (in which case it is the caller's duty to
  84021. * truncate it on return).
  84022. *
  84023. * For this write function to be used, the chain must have been read with
  84024. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  84025. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  84026. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  84027. * \c true.
  84028. *
  84029. * \param chain A pointer to an existing chain.
  84030. * \param use_padding See FLAC__metadata_chain_write()
  84031. * \param handle The I/O handle of the original FLAC stream to read.
  84032. * The handle will NOT be closed after the metadata is
  84033. * written; that is the duty of the caller.
  84034. * \param callbacks A set of callbacks to use for I/O on \a handle.
  84035. * The mandatory callbacks are \a read, \a seek, and
  84036. * \a eof.
  84037. * \param temp_handle The I/O handle of the FLAC stream to write. The
  84038. * handle will NOT be closed after the metadata is
  84039. * written; that is the duty of the caller.
  84040. * \param temp_callbacks
  84041. * A set of callbacks to use for I/O on temp_handle.
  84042. * The only mandatory callback is \a write.
  84043. * \assert
  84044. * \code chain != NULL \endcode
  84045. * \retval FLAC__bool
  84046. * \c true if the write succeeded, else \c false. On failure,
  84047. * check the status with FLAC__metadata_chain_status().
  84048. */
  84049. 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);
  84050. /** Merge adjacent PADDING blocks into a single block.
  84051. *
  84052. * \note This function does not write to the FLAC file, it only
  84053. * modifies the chain.
  84054. *
  84055. * \warning Any iterator on the current chain will become invalid after this
  84056. * call. You should delete the iterator and get a new one.
  84057. *
  84058. * \param chain A pointer to an existing chain.
  84059. * \assert
  84060. * \code chain != NULL \endcode
  84061. */
  84062. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  84063. /** This function will move all PADDING blocks to the end on the metadata,
  84064. * then merge them into a single block.
  84065. *
  84066. * \note This function does not write to the FLAC file, it only
  84067. * modifies the chain.
  84068. *
  84069. * \warning Any iterator on the current chain will become invalid after this
  84070. * call. You should delete the iterator and get a new one.
  84071. *
  84072. * \param chain A pointer to an existing chain.
  84073. * \assert
  84074. * \code chain != NULL \endcode
  84075. */
  84076. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  84077. /*********** FLAC__Metadata_Iterator ***********/
  84078. /** Create a new iterator instance.
  84079. *
  84080. * \retval FLAC__Metadata_Iterator*
  84081. * \c NULL if there was an error allocating memory, else the new instance.
  84082. */
  84083. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  84084. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  84085. *
  84086. * \param iterator A pointer to an existing iterator.
  84087. * \assert
  84088. * \code iterator != NULL \endcode
  84089. */
  84090. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  84091. /** Initialize the iterator to point to the first metadata block in the
  84092. * given chain.
  84093. *
  84094. * \param iterator A pointer to an existing iterator.
  84095. * \param chain A pointer to an existing and initialized (read) chain.
  84096. * \assert
  84097. * \code iterator != NULL \endcode
  84098. * \code chain != NULL \endcode
  84099. */
  84100. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  84101. /** Moves the iterator forward one metadata block, returning \c false if
  84102. * already at the end.
  84103. *
  84104. * \param iterator A pointer to an existing initialized iterator.
  84105. * \assert
  84106. * \code iterator != NULL \endcode
  84107. * \a iterator has been successfully initialized with
  84108. * FLAC__metadata_iterator_init()
  84109. * \retval FLAC__bool
  84110. * \c false if already at the last metadata block of the chain, else
  84111. * \c true.
  84112. */
  84113. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  84114. /** Moves the iterator backward one metadata block, returning \c false if
  84115. * already at the beginning.
  84116. *
  84117. * \param iterator A pointer to an existing initialized iterator.
  84118. * \assert
  84119. * \code iterator != NULL \endcode
  84120. * \a iterator has been successfully initialized with
  84121. * FLAC__metadata_iterator_init()
  84122. * \retval FLAC__bool
  84123. * \c false if already at the first metadata block of the chain, else
  84124. * \c true.
  84125. */
  84126. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  84127. /** Get the type of the metadata block at the current position.
  84128. *
  84129. * \param iterator A pointer to an existing initialized iterator.
  84130. * \assert
  84131. * \code iterator != NULL \endcode
  84132. * \a iterator has been successfully initialized with
  84133. * FLAC__metadata_iterator_init()
  84134. * \retval FLAC__MetadataType
  84135. * The type of the metadata block at the current iterator position.
  84136. */
  84137. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  84138. /** Get the metadata block at the current position. You can modify
  84139. * the block in place but must write the chain before the changes
  84140. * are reflected to the FLAC file. You do not need to call
  84141. * FLAC__metadata_iterator_set_block() to reflect the changes;
  84142. * the pointer returned by FLAC__metadata_iterator_get_block()
  84143. * points directly into the chain.
  84144. *
  84145. * \warning
  84146. * Do not call FLAC__metadata_object_delete() on the returned object;
  84147. * to delete a block use FLAC__metadata_iterator_delete_block().
  84148. *
  84149. * \param iterator A pointer to an existing initialized iterator.
  84150. * \assert
  84151. * \code iterator != NULL \endcode
  84152. * \a iterator has been successfully initialized with
  84153. * FLAC__metadata_iterator_init()
  84154. * \retval FLAC__StreamMetadata*
  84155. * The current metadata block.
  84156. */
  84157. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  84158. /** Set the metadata block at the current position, replacing the existing
  84159. * block. The new block passed in becomes owned by the chain and it will be
  84160. * deleted when the chain is deleted.
  84161. *
  84162. * \param iterator A pointer to an existing initialized iterator.
  84163. * \param block A pointer to a metadata block.
  84164. * \assert
  84165. * \code iterator != NULL \endcode
  84166. * \a iterator has been successfully initialized with
  84167. * FLAC__metadata_iterator_init()
  84168. * \code block != NULL \endcode
  84169. * \retval FLAC__bool
  84170. * \c false if the conditions in the above description are not met, or
  84171. * a memory allocation error occurs, otherwise \c true.
  84172. */
  84173. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84174. /** Removes the current block from the chain. If \a replace_with_padding is
  84175. * \c true, the block will instead be replaced with a padding block of equal
  84176. * size. You can not delete the STREAMINFO block. The iterator will be
  84177. * left pointing to the block before the one just "deleted", even if
  84178. * \a replace_with_padding is \c true.
  84179. *
  84180. * \param iterator A pointer to an existing initialized iterator.
  84181. * \param replace_with_padding See above.
  84182. * \assert
  84183. * \code iterator != NULL \endcode
  84184. * \a iterator has been successfully initialized with
  84185. * FLAC__metadata_iterator_init()
  84186. * \retval FLAC__bool
  84187. * \c false if the conditions in the above description are not met,
  84188. * otherwise \c true.
  84189. */
  84190. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  84191. /** Insert a new block before the current block. You cannot insert a block
  84192. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  84193. * as there can be only one, the one that already exists at the head when you
  84194. * read in a chain. The chain takes ownership of the new block and it will be
  84195. * deleted when the chain is deleted. The iterator will be left pointing to
  84196. * the new block.
  84197. *
  84198. * \param iterator A pointer to an existing initialized iterator.
  84199. * \param block A pointer to a metadata block to insert.
  84200. * \assert
  84201. * \code iterator != NULL \endcode
  84202. * \a iterator has been successfully initialized with
  84203. * FLAC__metadata_iterator_init()
  84204. * \retval FLAC__bool
  84205. * \c false if the conditions in the above description are not met, or
  84206. * a memory allocation error occurs, otherwise \c true.
  84207. */
  84208. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84209. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  84210. * block as there can be only one, the one that already exists at the head when
  84211. * you read in a chain. The chain takes ownership of the new block and it will
  84212. * be deleted when the chain is deleted. The iterator will be left pointing to
  84213. * the new block.
  84214. *
  84215. * \param iterator A pointer to an existing initialized iterator.
  84216. * \param block A pointer to a metadata block to insert.
  84217. * \assert
  84218. * \code iterator != NULL \endcode
  84219. * \a iterator has been successfully initialized with
  84220. * FLAC__metadata_iterator_init()
  84221. * \retval FLAC__bool
  84222. * \c false if the conditions in the above description are not met, or
  84223. * a memory allocation error occurs, otherwise \c true.
  84224. */
  84225. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84226. /* \} */
  84227. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  84228. * \ingroup flac_metadata
  84229. *
  84230. * \brief
  84231. * This module contains methods for manipulating FLAC metadata objects.
  84232. *
  84233. * Since many are variable length we have to be careful about the memory
  84234. * management. We decree that all pointers to data in the object are
  84235. * owned by the object and memory-managed by the object.
  84236. *
  84237. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  84238. * functions to create all instances. When using the
  84239. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  84240. * \a copy to \c true to have the function make it's own copy of the data, or
  84241. * to \c false to give the object ownership of your data. In the latter case
  84242. * your pointer must be freeable by free() and will be free()d when the object
  84243. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  84244. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  84245. * the length argument is 0 and the \a copy argument is \c false.
  84246. *
  84247. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  84248. * will return \c NULL in the case of a memory allocation error, otherwise a new
  84249. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  84250. * case of a memory allocation error.
  84251. *
  84252. * We don't have the convenience of C++ here, so note that the library relies
  84253. * on you to keep the types straight. In other words, if you pass, for
  84254. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  84255. * FLAC__metadata_object_application_set_data(), you will get an assertion
  84256. * failure.
  84257. *
  84258. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  84259. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  84260. * toward the length or stored in the stream, but it can make working with plain
  84261. * comments (those that don't contain embedded-NULs in the value) easier.
  84262. * Entries passed into these functions have trailing NULs added if missing, and
  84263. * returned entries are guaranteed to have a trailing NUL.
  84264. *
  84265. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  84266. * comment entry/name/value will first validate that it complies with the Vorbis
  84267. * comment specification and return false if it does not.
  84268. *
  84269. * There is no need to recalculate the length field on metadata blocks you
  84270. * have modified. They will be calculated automatically before they are
  84271. * written back to a file.
  84272. *
  84273. * \{
  84274. */
  84275. /** Create a new metadata object instance of the given type.
  84276. *
  84277. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  84278. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  84279. * the vendor string set (but zero comments).
  84280. *
  84281. * Do not pass in a value greater than or equal to
  84282. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  84283. * doing.
  84284. *
  84285. * \param type Type of object to create
  84286. * \retval FLAC__StreamMetadata*
  84287. * \c NULL if there was an error allocating memory or the type code is
  84288. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  84289. */
  84290. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  84291. /** Create a copy of an existing metadata object.
  84292. *
  84293. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84294. * object is also copied. The caller takes ownership of the new block and
  84295. * is responsible for freeing it with FLAC__metadata_object_delete().
  84296. *
  84297. * \param object Pointer to object to copy.
  84298. * \assert
  84299. * \code object != NULL \endcode
  84300. * \retval FLAC__StreamMetadata*
  84301. * \c NULL if there was an error allocating memory, else the new instance.
  84302. */
  84303. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  84304. /** Free a metadata object. Deletes the object pointed to by \a object.
  84305. *
  84306. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  84307. * object is also deleted.
  84308. *
  84309. * \param object A pointer to an existing object.
  84310. * \assert
  84311. * \code object != NULL \endcode
  84312. */
  84313. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  84314. /** Compares two metadata objects.
  84315. *
  84316. * The compare is "deep", i.e. dynamically allocated data within the
  84317. * object is also compared.
  84318. *
  84319. * \param block1 A pointer to an existing object.
  84320. * \param block2 A pointer to an existing object.
  84321. * \assert
  84322. * \code block1 != NULL \endcode
  84323. * \code block2 != NULL \endcode
  84324. * \retval FLAC__bool
  84325. * \c true if objects are identical, else \c false.
  84326. */
  84327. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  84328. /** Sets the application data of an APPLICATION block.
  84329. *
  84330. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84331. * takes ownership of the pointer. The existing data will be freed if this
  84332. * function is successful, otherwise the original data will remain if \a copy
  84333. * is \c true and malloc() fails.
  84334. *
  84335. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84336. *
  84337. * \param object A pointer to an existing APPLICATION object.
  84338. * \param data A pointer to the data to set.
  84339. * \param length The length of \a data in bytes.
  84340. * \param copy See above.
  84341. * \assert
  84342. * \code object != NULL \endcode
  84343. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  84344. * \code (data != NULL && length > 0) ||
  84345. * (data == NULL && length == 0 && copy == false) \endcode
  84346. * \retval FLAC__bool
  84347. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84348. */
  84349. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  84350. /** Resize the seekpoint array.
  84351. *
  84352. * If the size shrinks, elements will truncated; if it grows, new placeholder
  84353. * points will be added to the end.
  84354. *
  84355. * \param object A pointer to an existing SEEKTABLE object.
  84356. * \param new_num_points The desired length of the array; may be \c 0.
  84357. * \assert
  84358. * \code object != NULL \endcode
  84359. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84360. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  84361. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  84362. * \retval FLAC__bool
  84363. * \c false if memory allocation error, else \c true.
  84364. */
  84365. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  84366. /** Set a seekpoint in a seektable.
  84367. *
  84368. * \param object A pointer to an existing SEEKTABLE object.
  84369. * \param point_num Index into seekpoint array to set.
  84370. * \param point The point to set.
  84371. * \assert
  84372. * \code object != NULL \endcode
  84373. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84374. * \code object->data.seek_table.num_points > point_num \endcode
  84375. */
  84376. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84377. /** Insert a seekpoint into a seektable.
  84378. *
  84379. * \param object A pointer to an existing SEEKTABLE object.
  84380. * \param point_num Index into seekpoint array to set.
  84381. * \param point The point to set.
  84382. * \assert
  84383. * \code object != NULL \endcode
  84384. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84385. * \code object->data.seek_table.num_points >= point_num \endcode
  84386. * \retval FLAC__bool
  84387. * \c false if memory allocation error, else \c true.
  84388. */
  84389. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84390. /** Delete a seekpoint from a seektable.
  84391. *
  84392. * \param object A pointer to an existing SEEKTABLE object.
  84393. * \param point_num Index into seekpoint array to set.
  84394. * \assert
  84395. * \code object != NULL \endcode
  84396. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84397. * \code object->data.seek_table.num_points > point_num \endcode
  84398. * \retval FLAC__bool
  84399. * \c false if memory allocation error, else \c true.
  84400. */
  84401. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  84402. /** Check a seektable to see if it conforms to the FLAC specification.
  84403. * See the format specification for limits on the contents of the
  84404. * seektable.
  84405. *
  84406. * \param object A pointer to an existing SEEKTABLE object.
  84407. * \assert
  84408. * \code object != NULL \endcode
  84409. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84410. * \retval FLAC__bool
  84411. * \c false if seek table is illegal, else \c true.
  84412. */
  84413. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  84414. /** Append a number of placeholder points to the end of a seek table.
  84415. *
  84416. * \note
  84417. * As with the other ..._seektable_template_... functions, you should
  84418. * call FLAC__metadata_object_seektable_template_sort() when finished
  84419. * to make the seek table legal.
  84420. *
  84421. * \param object A pointer to an existing SEEKTABLE object.
  84422. * \param num The number of placeholder points to append.
  84423. * \assert
  84424. * \code object != NULL \endcode
  84425. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84426. * \retval FLAC__bool
  84427. * \c false if memory allocation fails, else \c true.
  84428. */
  84429. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  84430. /** Append a specific seek point template to the end of a seek table.
  84431. *
  84432. * \note
  84433. * As with the other ..._seektable_template_... functions, you should
  84434. * call FLAC__metadata_object_seektable_template_sort() when finished
  84435. * to make the seek table legal.
  84436. *
  84437. * \param object A pointer to an existing SEEKTABLE object.
  84438. * \param sample_number The sample number of the seek point template.
  84439. * \assert
  84440. * \code object != NULL \endcode
  84441. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84442. * \retval FLAC__bool
  84443. * \c false if memory allocation fails, else \c true.
  84444. */
  84445. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  84446. /** Append specific seek point templates to the end of a seek table.
  84447. *
  84448. * \note
  84449. * As with the other ..._seektable_template_... functions, you should
  84450. * call FLAC__metadata_object_seektable_template_sort() when finished
  84451. * to make the seek table legal.
  84452. *
  84453. * \param object A pointer to an existing SEEKTABLE object.
  84454. * \param sample_numbers An array of sample numbers for the seek points.
  84455. * \param num The number of seek point templates to append.
  84456. * \assert
  84457. * \code object != NULL \endcode
  84458. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84459. * \retval FLAC__bool
  84460. * \c false if memory allocation fails, else \c true.
  84461. */
  84462. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  84463. /** Append a set of evenly-spaced seek point templates to the end of a
  84464. * seek table.
  84465. *
  84466. * \note
  84467. * As with the other ..._seektable_template_... functions, you should
  84468. * call FLAC__metadata_object_seektable_template_sort() when finished
  84469. * to make the seek table legal.
  84470. *
  84471. * \param object A pointer to an existing SEEKTABLE object.
  84472. * \param num The number of placeholder points to append.
  84473. * \param total_samples The total number of samples to be encoded;
  84474. * the seekpoints will be spaced approximately
  84475. * \a total_samples / \a num samples apart.
  84476. * \assert
  84477. * \code object != NULL \endcode
  84478. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84479. * \code total_samples > 0 \endcode
  84480. * \retval FLAC__bool
  84481. * \c false if memory allocation fails, else \c true.
  84482. */
  84483. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  84484. /** Append a set of evenly-spaced seek point templates to the end of a
  84485. * seek table.
  84486. *
  84487. * \note
  84488. * As with the other ..._seektable_template_... functions, you should
  84489. * call FLAC__metadata_object_seektable_template_sort() when finished
  84490. * to make the seek table legal.
  84491. *
  84492. * \param object A pointer to an existing SEEKTABLE object.
  84493. * \param samples The number of samples apart to space the placeholder
  84494. * points. The first point will be at sample \c 0, the
  84495. * second at sample \a samples, then 2*\a samples, and
  84496. * so on. As long as \a samples and \a total_samples
  84497. * are greater than \c 0, there will always be at least
  84498. * one seekpoint at sample \c 0.
  84499. * \param total_samples The total number of samples to be encoded;
  84500. * the seekpoints will be spaced
  84501. * \a samples samples apart.
  84502. * \assert
  84503. * \code object != NULL \endcode
  84504. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84505. * \code samples > 0 \endcode
  84506. * \code total_samples > 0 \endcode
  84507. * \retval FLAC__bool
  84508. * \c false if memory allocation fails, else \c true.
  84509. */
  84510. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  84511. /** Sort a seek table's seek points according to the format specification,
  84512. * removing duplicates.
  84513. *
  84514. * \param object A pointer to a seek table to be sorted.
  84515. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  84516. * If \c true, duplicates are deleted and the seek table is
  84517. * shrunk appropriately; the number of placeholder points
  84518. * present in the seek table will be the same after the call
  84519. * as before.
  84520. * \assert
  84521. * \code object != NULL \endcode
  84522. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84523. * \retval FLAC__bool
  84524. * \c false if realloc() fails, else \c true.
  84525. */
  84526. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  84527. /** Sets the vendor string in a VORBIS_COMMENT block.
  84528. *
  84529. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84530. * one already.
  84531. *
  84532. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84533. * takes ownership of the \c entry.entry pointer.
  84534. *
  84535. * \note If this function returns \c false, the caller still owns the
  84536. * pointer.
  84537. *
  84538. * \param object A pointer to an existing VORBIS_COMMENT object.
  84539. * \param entry The entry to set the vendor string to.
  84540. * \param copy See above.
  84541. * \assert
  84542. * \code object != NULL \endcode
  84543. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \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_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84551. /** Resize the comment array.
  84552. *
  84553. * If the size shrinks, elements will truncated; if it grows, new empty
  84554. * fields will be added to the end.
  84555. *
  84556. * \param object A pointer to an existing VORBIS_COMMENT object.
  84557. * \param new_num_comments The desired length of the array; may be \c 0.
  84558. * \assert
  84559. * \code object != NULL \endcode
  84560. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84561. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  84562. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  84563. * \retval FLAC__bool
  84564. * \c false if memory allocation fails, else \c true.
  84565. */
  84566. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  84567. /** Sets a comment in a VORBIS_COMMENT block.
  84568. *
  84569. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84570. * one already.
  84571. *
  84572. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84573. * takes ownership of the \c entry.entry pointer.
  84574. *
  84575. * \note If this function returns \c false, the caller still owns the
  84576. * pointer.
  84577. *
  84578. * \param object A pointer to an existing VORBIS_COMMENT object.
  84579. * \param comment_num Index into comment array to set.
  84580. * \param entry The entry to set the comment to.
  84581. * \param copy See above.
  84582. * \assert
  84583. * \code object != NULL \endcode
  84584. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84585. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  84586. * \code (entry.entry != NULL && entry.length > 0) ||
  84587. * (entry.entry == NULL && entry.length == 0) \endcode
  84588. * \retval FLAC__bool
  84589. * \c false if memory allocation fails or \a entry does not comply with the
  84590. * Vorbis comment specification, else \c true.
  84591. */
  84592. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84593. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  84594. *
  84595. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84596. * one already.
  84597. *
  84598. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84599. * takes ownership of the \c entry.entry pointer.
  84600. *
  84601. * \note If this function returns \c false, the caller still owns the
  84602. * pointer.
  84603. *
  84604. * \param object A pointer to an existing VORBIS_COMMENT object.
  84605. * \param comment_num The index at which to insert the comment. The comments
  84606. * at and after \a comment_num move right one position.
  84607. * To append a comment to the end, set \a comment_num to
  84608. * \c object->data.vorbis_comment.num_comments .
  84609. * \param entry The comment to insert.
  84610. * \param copy See above.
  84611. * \assert
  84612. * \code object != NULL \endcode
  84613. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84614. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  84615. * \code (entry.entry != NULL && entry.length > 0) ||
  84616. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84617. * \retval FLAC__bool
  84618. * \c false if memory allocation fails or \a entry does not comply with the
  84619. * Vorbis comment specification, else \c true.
  84620. */
  84621. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84622. /** Appends a comment to a VORBIS_COMMENT block.
  84623. *
  84624. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84625. * one already.
  84626. *
  84627. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84628. * takes ownership of the \c entry.entry pointer.
  84629. *
  84630. * \note If this function returns \c false, the caller still owns the
  84631. * pointer.
  84632. *
  84633. * \param object A pointer to an existing VORBIS_COMMENT object.
  84634. * \param entry The comment to insert.
  84635. * \param copy See above.
  84636. * \assert
  84637. * \code object != NULL \endcode
  84638. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84639. * \code (entry.entry != NULL && entry.length > 0) ||
  84640. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84641. * \retval FLAC__bool
  84642. * \c false if memory allocation fails or \a entry does not comply with the
  84643. * Vorbis comment specification, else \c true.
  84644. */
  84645. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84646. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  84647. *
  84648. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84649. * one already.
  84650. *
  84651. * Depending on the the value of \a all, either all or just the first comment
  84652. * whose field name(s) match the given entry's name will be replaced by the
  84653. * given entry. If no comments match, \a entry will simply be appended.
  84654. *
  84655. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84656. * takes ownership of the \c entry.entry pointer.
  84657. *
  84658. * \note If this function returns \c false, the caller still owns the
  84659. * pointer.
  84660. *
  84661. * \param object A pointer to an existing VORBIS_COMMENT object.
  84662. * \param entry The comment to insert.
  84663. * \param all If \c true, all comments whose field name matches
  84664. * \a entry's field name will be removed, and \a entry will
  84665. * be inserted at the position of the first matching
  84666. * comment. If \c false, only the first comment whose
  84667. * field name matches \a entry's field name will be
  84668. * replaced with \a entry.
  84669. * \param copy See above.
  84670. * \assert
  84671. * \code object != NULL \endcode
  84672. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84673. * \code (entry.entry != NULL && entry.length > 0) ||
  84674. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84675. * \retval FLAC__bool
  84676. * \c false if memory allocation fails or \a entry does not comply with the
  84677. * Vorbis comment specification, else \c true.
  84678. */
  84679. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  84680. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  84681. *
  84682. * \param object A pointer to an existing VORBIS_COMMENT object.
  84683. * \param comment_num The index of the comment to delete.
  84684. * \assert
  84685. * \code object != NULL \endcode
  84686. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84687. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  84688. * \retval FLAC__bool
  84689. * \c false if realloc() fails, else \c true.
  84690. */
  84691. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  84692. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  84693. *
  84694. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  84695. * memory and shall be owned by the caller. For convenience the entry will
  84696. * have a terminating NUL.
  84697. *
  84698. * \param entry A pointer to a Vorbis comment entry. The entry's
  84699. * \c entry pointer should not point to allocated
  84700. * memory as it will be overwritten.
  84701. * \param field_name The field name in ASCII, \c NUL terminated.
  84702. * \param field_value The field value in UTF-8, \c NUL terminated.
  84703. * \assert
  84704. * \code entry != NULL \endcode
  84705. * \code field_name != NULL \endcode
  84706. * \code field_value != NULL \endcode
  84707. * \retval FLAC__bool
  84708. * \c false if malloc() fails, or if \a field_name or \a field_value does
  84709. * not comply with the Vorbis comment specification, else \c true.
  84710. */
  84711. 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);
  84712. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  84713. *
  84714. * The returned pointers to name and value will be allocated by malloc()
  84715. * and shall be owned by the caller.
  84716. *
  84717. * \param entry An existing Vorbis comment entry.
  84718. * \param field_name The address of where the returned pointer to the
  84719. * field name will be stored.
  84720. * \param field_value The address of where the returned pointer to the
  84721. * field value will be stored.
  84722. * \assert
  84723. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84724. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  84725. * \code field_name != NULL \endcode
  84726. * \code field_value != NULL \endcode
  84727. * \retval FLAC__bool
  84728. * \c false if memory allocation fails or \a entry does not comply with the
  84729. * Vorbis comment specification, else \c true.
  84730. */
  84731. 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);
  84732. /** Check if the given Vorbis comment entry's field name matches the given
  84733. * field name.
  84734. *
  84735. * \param entry An existing Vorbis comment entry.
  84736. * \param field_name The field name to check.
  84737. * \param field_name_length The length of \a field_name, not including the
  84738. * terminating \c NUL.
  84739. * \assert
  84740. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84741. * \retval FLAC__bool
  84742. * \c true if the field names match, else \c false
  84743. */
  84744. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  84745. /** Find a Vorbis comment with the given field name.
  84746. *
  84747. * The search begins at entry number \a offset; use an offset of 0 to
  84748. * search from the beginning of the comment array.
  84749. *
  84750. * \param object A pointer to an existing VORBIS_COMMENT object.
  84751. * \param offset The offset into the comment array from where to start
  84752. * the search.
  84753. * \param field_name The field name of the comment to find.
  84754. * \assert
  84755. * \code object != NULL \endcode
  84756. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84757. * \code field_name != NULL \endcode
  84758. * \retval int
  84759. * The offset in the comment array of the first comment whose field
  84760. * name matches \a field_name, or \c -1 if no match was found.
  84761. */
  84762. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  84763. /** Remove first Vorbis comment matching the given field name.
  84764. *
  84765. * \param object A pointer to an existing VORBIS_COMMENT object.
  84766. * \param field_name The field name of comment to delete.
  84767. * \assert
  84768. * \code object != NULL \endcode
  84769. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84770. * \retval int
  84771. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84772. * \c 1 for one matching entry deleted.
  84773. */
  84774. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  84775. /** Remove all Vorbis comments matching the given field name.
  84776. *
  84777. * \param object A pointer to an existing VORBIS_COMMENT object.
  84778. * \param field_name The field name of comments to delete.
  84779. * \assert
  84780. * \code object != NULL \endcode
  84781. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84782. * \retval int
  84783. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84784. * else the number of matching entries deleted.
  84785. */
  84786. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  84787. /** Create a new CUESHEET track instance.
  84788. *
  84789. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  84790. *
  84791. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84792. * \c NULL if there was an error allocating memory, else the new instance.
  84793. */
  84794. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  84795. /** Create a copy of an existing CUESHEET track object.
  84796. *
  84797. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84798. * object is also copied. The caller takes ownership of the new object and
  84799. * is responsible for freeing it with
  84800. * FLAC__metadata_object_cuesheet_track_delete().
  84801. *
  84802. * \param object Pointer to object to copy.
  84803. * \assert
  84804. * \code object != NULL \endcode
  84805. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84806. * \c NULL if there was an error allocating memory, else the new instance.
  84807. */
  84808. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  84809. /** Delete a CUESHEET track object
  84810. *
  84811. * \param object A pointer to an existing CUESHEET track object.
  84812. * \assert
  84813. * \code object != NULL \endcode
  84814. */
  84815. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  84816. /** Resize a track's index point array.
  84817. *
  84818. * If the size shrinks, elements will truncated; if it grows, new blank
  84819. * indices will be added to the end.
  84820. *
  84821. * \param object A pointer to an existing CUESHEET object.
  84822. * \param track_num The index of the track to modify. NOTE: this is not
  84823. * necessarily the same as the track's \a number field.
  84824. * \param new_num_indices The desired length of the array; may be \c 0.
  84825. * \assert
  84826. * \code object != NULL \endcode
  84827. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84828. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84829. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  84830. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  84831. * \retval FLAC__bool
  84832. * \c false if memory allocation error, else \c true.
  84833. */
  84834. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  84835. /** Insert an index point in a CUESHEET track at the given index.
  84836. *
  84837. * \param object A pointer to an existing CUESHEET object.
  84838. * \param track_num The index of the track to modify. NOTE: this is not
  84839. * necessarily the same as the track's \a number field.
  84840. * \param index_num The index into the track's index array at which to
  84841. * insert the index point. NOTE: this is not necessarily
  84842. * the same as the index point's \a number field. The
  84843. * indices at and after \a index_num move right one
  84844. * position. To append an index point to the end, set
  84845. * \a index_num to
  84846. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84847. * \param index The index point to insert.
  84848. * \assert
  84849. * \code object != NULL \endcode
  84850. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84851. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84852. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84853. * \retval FLAC__bool
  84854. * \c false if realloc() fails, else \c true.
  84855. */
  84856. 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);
  84857. /** Insert a blank index point in a CUESHEET track at the given index.
  84858. *
  84859. * A blank index point is one in which all field values are zero.
  84860. *
  84861. * \param object A pointer to an existing CUESHEET object.
  84862. * \param track_num The index of the track to modify. NOTE: this is not
  84863. * necessarily the same as the track's \a number field.
  84864. * \param index_num The index into the track's index array at which to
  84865. * insert the index point. NOTE: this is not necessarily
  84866. * the same as the index point's \a number field. The
  84867. * indices at and after \a index_num move right one
  84868. * position. To append an index point to the end, set
  84869. * \a index_num to
  84870. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84871. * \assert
  84872. * \code object != NULL \endcode
  84873. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84874. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84875. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84876. * \retval FLAC__bool
  84877. * \c false if realloc() fails, else \c true.
  84878. */
  84879. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84880. /** Delete an index point in a CUESHEET track at the given index.
  84881. *
  84882. * \param object A pointer to an existing CUESHEET object.
  84883. * \param track_num The index into the track array of the track to
  84884. * modify. NOTE: this is not necessarily the same
  84885. * as the track's \a number field.
  84886. * \param index_num The index into the track's index array of the index
  84887. * to delete. NOTE: this is not necessarily the same
  84888. * as the index's \a number field.
  84889. * \assert
  84890. * \code object != NULL \endcode
  84891. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84892. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84893. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  84894. * \retval FLAC__bool
  84895. * \c false if realloc() fails, else \c true.
  84896. */
  84897. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84898. /** Resize the track array.
  84899. *
  84900. * If the size shrinks, elements will truncated; if it grows, new blank
  84901. * tracks will be added to the end.
  84902. *
  84903. * \param object A pointer to an existing CUESHEET object.
  84904. * \param new_num_tracks The desired length of the array; may be \c 0.
  84905. * \assert
  84906. * \code object != NULL \endcode
  84907. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84908. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  84909. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  84910. * \retval FLAC__bool
  84911. * \c false if memory allocation error, else \c true.
  84912. */
  84913. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  84914. /** Sets a track in a CUESHEET block.
  84915. *
  84916. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84917. * takes ownership of the \a track pointer.
  84918. *
  84919. * \param object A pointer to an existing CUESHEET object.
  84920. * \param track_num Index into track array to set. NOTE: this is not
  84921. * necessarily the same as the track's \a number field.
  84922. * \param track The track to set the track to. You may safely pass in
  84923. * a const pointer if \a copy is \c true.
  84924. * \param copy See above.
  84925. * \assert
  84926. * \code object != NULL \endcode
  84927. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84928. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  84929. * \code (track->indices != NULL && track->num_indices > 0) ||
  84930. * (track->indices == NULL && track->num_indices == 0)
  84931. * \retval FLAC__bool
  84932. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84933. */
  84934. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84935. /** Insert a track in a CUESHEET block at the given index.
  84936. *
  84937. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84938. * takes ownership of the \a track pointer.
  84939. *
  84940. * \param object A pointer to an existing CUESHEET object.
  84941. * \param track_num The index at which to insert the track. NOTE: this
  84942. * is not necessarily the same as the track's \a number
  84943. * field. The tracks at and after \a track_num move right
  84944. * one position. To append a track to the end, set
  84945. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84946. * \param track The track to insert. You may safely pass in a const
  84947. * pointer if \a copy is \c true.
  84948. * \param copy See above.
  84949. * \assert
  84950. * \code object != NULL \endcode
  84951. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84952. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84953. * \retval FLAC__bool
  84954. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84955. */
  84956. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84957. /** Insert a blank track in a CUESHEET block at the given index.
  84958. *
  84959. * A blank track is one in which all field values are zero.
  84960. *
  84961. * \param object A pointer to an existing CUESHEET object.
  84962. * \param track_num The index at which to insert the track. NOTE: this
  84963. * is not necessarily the same as the track's \a number
  84964. * field. The tracks at and after \a track_num move right
  84965. * one position. To append a track to the end, set
  84966. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84967. * \assert
  84968. * \code object != NULL \endcode
  84969. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84970. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84971. * \retval FLAC__bool
  84972. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84973. */
  84974. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  84975. /** Delete a track in a CUESHEET block at the given index.
  84976. *
  84977. * \param object A pointer to an existing CUESHEET object.
  84978. * \param track_num The index into the track array of the track to
  84979. * delete. NOTE: this is not necessarily the same
  84980. * as the track's \a number field.
  84981. * \assert
  84982. * \code object != NULL \endcode
  84983. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84984. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84985. * \retval FLAC__bool
  84986. * \c false if realloc() fails, else \c true.
  84987. */
  84988. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  84989. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84990. * See the format specification for limits on the contents of the
  84991. * cue sheet.
  84992. *
  84993. * \param object A pointer to an existing CUESHEET object.
  84994. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84995. * stringent requirements for a CD-DA (audio) disc.
  84996. * \param violation Address of a pointer to a string. If there is a
  84997. * violation, a pointer to a string explanation of the
  84998. * violation will be returned here. \a violation may be
  84999. * \c NULL if you don't need the returned string. Do not
  85000. * free the returned string; it will always point to static
  85001. * data.
  85002. * \assert
  85003. * \code object != NULL \endcode
  85004. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85005. * \retval FLAC__bool
  85006. * \c false if cue sheet is illegal, else \c true.
  85007. */
  85008. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  85009. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  85010. * assumes the cue sheet corresponds to a CD; the result is undefined
  85011. * if the cuesheet's is_cd bit is not set.
  85012. *
  85013. * \param object A pointer to an existing CUESHEET object.
  85014. * \assert
  85015. * \code object != NULL \endcode
  85016. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  85017. * \retval FLAC__uint32
  85018. * The unsigned integer representation of the CDDB/freedb ID
  85019. */
  85020. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  85021. /** Sets the MIME type of a PICTURE block.
  85022. *
  85023. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  85024. * takes ownership of the pointer. The existing string will be freed if this
  85025. * function is successful, otherwise the original string will remain if \a copy
  85026. * is \c true and malloc() fails.
  85027. *
  85028. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  85029. *
  85030. * \param object A pointer to an existing PICTURE object.
  85031. * \param mime_type A pointer to the MIME type string. The string must be
  85032. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  85033. * is done.
  85034. * \param copy See above.
  85035. * \assert
  85036. * \code object != NULL \endcode
  85037. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85038. * \code (mime_type != NULL) \endcode
  85039. * \retval FLAC__bool
  85040. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85041. */
  85042. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  85043. /** Sets the description of a PICTURE block.
  85044. *
  85045. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  85046. * takes ownership of the pointer. The existing string will be freed if this
  85047. * function is successful, otherwise the original string will remain if \a copy
  85048. * is \c true and malloc() fails.
  85049. *
  85050. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  85051. *
  85052. * \param object A pointer to an existing PICTURE object.
  85053. * \param description A pointer to the description string. The string must be
  85054. * valid UTF-8, NUL-terminated. No validation is done.
  85055. * \param copy See above.
  85056. * \assert
  85057. * \code object != NULL \endcode
  85058. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85059. * \code (description != NULL) \endcode
  85060. * \retval FLAC__bool
  85061. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85062. */
  85063. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  85064. /** Sets the picture data of a PICTURE block.
  85065. *
  85066. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  85067. * takes ownership of the pointer. Also sets the \a data_length field of the
  85068. * metadata object to what is passed in as the \a length parameter. The
  85069. * existing data will be freed if this function is successful, otherwise the
  85070. * original data and data_length will remain if \a copy is \c true and
  85071. * malloc() fails.
  85072. *
  85073. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  85074. *
  85075. * \param object A pointer to an existing PICTURE object.
  85076. * \param data A pointer to the data to set.
  85077. * \param length The length of \a data in bytes.
  85078. * \param copy See above.
  85079. * \assert
  85080. * \code object != NULL \endcode
  85081. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85082. * \code (data != NULL && length > 0) ||
  85083. * (data == NULL && length == 0 && copy == false) \endcode
  85084. * \retval FLAC__bool
  85085. * \c false if \a copy is \c true and malloc() fails, else \c true.
  85086. */
  85087. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  85088. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  85089. * See the format specification for limits on the contents of the
  85090. * PICTURE block.
  85091. *
  85092. * \param object A pointer to existing PICTURE block to be checked.
  85093. * \param violation Address of a pointer to a string. If there is a
  85094. * violation, a pointer to a string explanation of the
  85095. * violation will be returned here. \a violation may be
  85096. * \c NULL if you don't need the returned string. Do not
  85097. * free the returned string; it will always point to static
  85098. * data.
  85099. * \assert
  85100. * \code object != NULL \endcode
  85101. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  85102. * \retval FLAC__bool
  85103. * \c false if PICTURE block is illegal, else \c true.
  85104. */
  85105. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  85106. /* \} */
  85107. #ifdef __cplusplus
  85108. }
  85109. #endif
  85110. #endif
  85111. /********* End of inlined file: metadata.h *********/
  85112. /********* Start of inlined file: stream_decoder.h *********/
  85113. #ifndef FLAC__STREAM_DECODER_H
  85114. #define FLAC__STREAM_DECODER_H
  85115. #include <stdio.h> /* for FILE */
  85116. #ifdef __cplusplus
  85117. extern "C" {
  85118. #endif
  85119. /** \file include/FLAC/stream_decoder.h
  85120. *
  85121. * \brief
  85122. * This module contains the functions which implement the stream
  85123. * decoder.
  85124. *
  85125. * See the detailed documentation in the
  85126. * \link flac_stream_decoder stream decoder \endlink module.
  85127. */
  85128. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  85129. * \ingroup flac
  85130. *
  85131. * \brief
  85132. * This module describes the decoder layers provided by libFLAC.
  85133. *
  85134. * The stream decoder can be used to decode complete streams either from
  85135. * the client via callbacks, or directly from a file, depending on how
  85136. * it is initialized. When decoding via callbacks, the client provides
  85137. * callbacks for reading FLAC data and writing decoded samples, and
  85138. * handling metadata and errors. If the client also supplies seek-related
  85139. * callback, the decoder function for sample-accurate seeking within the
  85140. * FLAC input is also available. When decoding from a file, the client
  85141. * needs only supply a filename or open \c FILE* and write/metadata/error
  85142. * callbacks; the rest of the callbacks are supplied internally. For more
  85143. * info see the \link flac_stream_decoder stream decoder \endlink module.
  85144. */
  85145. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  85146. * \ingroup flac_decoder
  85147. *
  85148. * \brief
  85149. * This module contains the functions which implement the stream
  85150. * decoder.
  85151. *
  85152. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  85153. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  85154. *
  85155. * The basic usage of this decoder is as follows:
  85156. * - The program creates an instance of a decoder using
  85157. * FLAC__stream_decoder_new().
  85158. * - The program overrides the default settings using
  85159. * FLAC__stream_decoder_set_*() functions.
  85160. * - The program initializes the instance to validate the settings and
  85161. * prepare for decoding using
  85162. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  85163. * or FLAC__stream_decoder_init_file() for native FLAC,
  85164. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  85165. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  85166. * - The program calls the FLAC__stream_decoder_process_*() functions
  85167. * to decode data, which subsequently calls the callbacks.
  85168. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  85169. * which flushes the input and output and resets the decoder to the
  85170. * uninitialized state.
  85171. * - The instance may be used again or deleted with
  85172. * FLAC__stream_decoder_delete().
  85173. *
  85174. * In more detail, the program will create a new instance by calling
  85175. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  85176. * functions to override the default decoder options, and call
  85177. * one of the FLAC__stream_decoder_init_*() functions.
  85178. *
  85179. * There are three initialization functions for native FLAC, one for
  85180. * setting up the decoder to decode FLAC data from the client via
  85181. * callbacks, and two for decoding directly from a FLAC file.
  85182. *
  85183. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  85184. * You must also supply several callbacks for handling I/O. Some (like
  85185. * seeking) are optional, depending on the capabilities of the input.
  85186. *
  85187. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  85188. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  85189. * \c FILE* or filename and fewer callbacks; the decoder will handle
  85190. * the other callbacks internally.
  85191. *
  85192. * There are three similarly-named init functions for decoding from Ogg
  85193. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85194. * library has been built with Ogg support.
  85195. *
  85196. * Once the decoder is initialized, your program will call one of several
  85197. * functions to start the decoding process:
  85198. *
  85199. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  85200. * most one metadata block or audio frame and return, calling either the
  85201. * metadata callback or write callback, respectively, once. If the decoder
  85202. * loses sync it will return with only the error callback being called.
  85203. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  85204. * to process the stream from the current location and stop upon reaching
  85205. * the first audio frame. The client will get one metadata, write, or error
  85206. * callback per metadata block, audio frame, or sync error, respectively.
  85207. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  85208. * to process the stream from the current location until the read callback
  85209. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  85210. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  85211. * write, or error callback per metadata block, audio frame, or sync error,
  85212. * respectively.
  85213. *
  85214. * When the decoder has finished decoding (normally or through an abort),
  85215. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  85216. * ensures the decoder is in the correct state and frees memory. Then the
  85217. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  85218. * again to decode another stream.
  85219. *
  85220. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  85221. * At any point after the stream decoder has been initialized, the client can
  85222. * call this function to seek to an exact sample within the stream.
  85223. * Subsequently, the first time the write callback is called it will be
  85224. * passed a (possibly partial) block starting at that sample.
  85225. *
  85226. * If the client cannot seek via the callback interface provided, but still
  85227. * has another way of seeking, it can flush the decoder using
  85228. * FLAC__stream_decoder_flush() and start feeding data from the new position
  85229. * through the read callback.
  85230. *
  85231. * The stream decoder also provides MD5 signature checking. If this is
  85232. * turned on before initialization, FLAC__stream_decoder_finish() will
  85233. * report when the decoded MD5 signature does not match the one stored
  85234. * in the STREAMINFO block. MD5 checking is automatically turned off
  85235. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  85236. * in the STREAMINFO block or when a seek is attempted.
  85237. *
  85238. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  85239. * attention. By default, the decoder only calls the metadata_callback for
  85240. * the STREAMINFO block. These functions allow you to tell the decoder
  85241. * explicitly which blocks to parse and return via the metadata_callback
  85242. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  85243. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  85244. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  85245. * which blocks to return. Remember that metadata blocks can potentially
  85246. * be big (for example, cover art) so filtering out the ones you don't
  85247. * use can reduce the memory requirements of the decoder. Also note the
  85248. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  85249. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  85250. * filtering APPLICATION blocks based on the application ID.
  85251. *
  85252. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  85253. * they still can legally be filtered from the metadata_callback.
  85254. *
  85255. * \note
  85256. * The "set" functions may only be called when the decoder is in the
  85257. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  85258. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  85259. * before FLAC__stream_decoder_init_*(). If this is the case they will
  85260. * return \c true, otherwise \c false.
  85261. *
  85262. * \note
  85263. * FLAC__stream_decoder_finish() resets all settings to the constructor
  85264. * defaults, including the callbacks.
  85265. *
  85266. * \{
  85267. */
  85268. /** State values for a FLAC__StreamDecoder
  85269. *
  85270. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  85271. */
  85272. typedef enum {
  85273. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  85274. /**< The decoder is ready to search for metadata. */
  85275. FLAC__STREAM_DECODER_READ_METADATA,
  85276. /**< The decoder is ready to or is in the process of reading metadata. */
  85277. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  85278. /**< The decoder is ready to or is in the process of searching for the
  85279. * frame sync code.
  85280. */
  85281. FLAC__STREAM_DECODER_READ_FRAME,
  85282. /**< The decoder is ready to or is in the process of reading a frame. */
  85283. FLAC__STREAM_DECODER_END_OF_STREAM,
  85284. /**< The decoder has reached the end of the stream. */
  85285. FLAC__STREAM_DECODER_OGG_ERROR,
  85286. /**< An error occurred in the underlying Ogg layer. */
  85287. FLAC__STREAM_DECODER_SEEK_ERROR,
  85288. /**< An error occurred while seeking. The decoder must be flushed
  85289. * with FLAC__stream_decoder_flush() or reset with
  85290. * FLAC__stream_decoder_reset() before decoding can continue.
  85291. */
  85292. FLAC__STREAM_DECODER_ABORTED,
  85293. /**< The decoder was aborted by the read callback. */
  85294. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  85295. /**< An error occurred allocating memory. The decoder is in an invalid
  85296. * state and can no longer be used.
  85297. */
  85298. FLAC__STREAM_DECODER_UNINITIALIZED
  85299. /**< The decoder is in the uninitialized state; one of the
  85300. * FLAC__stream_decoder_init_*() functions must be called before samples
  85301. * can be processed.
  85302. */
  85303. } FLAC__StreamDecoderState;
  85304. /** Maps a FLAC__StreamDecoderState to a C string.
  85305. *
  85306. * Using a FLAC__StreamDecoderState as the index to this array
  85307. * will give the string equivalent. The contents should not be modified.
  85308. */
  85309. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  85310. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  85311. */
  85312. typedef enum {
  85313. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  85314. /**< Initialization was successful. */
  85315. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85316. /**< The library was not compiled with support for the given container
  85317. * format.
  85318. */
  85319. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  85320. /**< A required callback was not supplied. */
  85321. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  85322. /**< An error occurred allocating memory. */
  85323. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  85324. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  85325. * FLAC__stream_decoder_init_ogg_file(). */
  85326. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  85327. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  85328. * already initialized, usually because
  85329. * FLAC__stream_decoder_finish() was not called.
  85330. */
  85331. } FLAC__StreamDecoderInitStatus;
  85332. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  85333. *
  85334. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  85335. * will give the string equivalent. The contents should not be modified.
  85336. */
  85337. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  85338. /** Return values for the FLAC__StreamDecoder read callback.
  85339. */
  85340. typedef enum {
  85341. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  85342. /**< The read was OK and decoding can continue. */
  85343. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  85344. /**< The read was attempted while at the end of the stream. Note that
  85345. * the client must only return this value when the read callback was
  85346. * called when already at the end of the stream. Otherwise, if the read
  85347. * itself moves to the end of the stream, the client should still return
  85348. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  85349. * the next read callback it should return
  85350. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  85351. * of \c 0.
  85352. */
  85353. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  85354. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85355. } FLAC__StreamDecoderReadStatus;
  85356. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  85357. *
  85358. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  85359. * will give the string equivalent. The contents should not be modified.
  85360. */
  85361. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  85362. /** Return values for the FLAC__StreamDecoder seek callback.
  85363. */
  85364. typedef enum {
  85365. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  85366. /**< The seek was OK and decoding can continue. */
  85367. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  85368. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85369. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85370. /**< Client does not support seeking. */
  85371. } FLAC__StreamDecoderSeekStatus;
  85372. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  85373. *
  85374. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  85375. * will give the string equivalent. The contents should not be modified.
  85376. */
  85377. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  85378. /** Return values for the FLAC__StreamDecoder tell callback.
  85379. */
  85380. typedef enum {
  85381. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  85382. /**< The tell was OK and decoding can continue. */
  85383. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  85384. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85385. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85386. /**< Client does not support telling the position. */
  85387. } FLAC__StreamDecoderTellStatus;
  85388. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  85389. *
  85390. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  85391. * will give the string equivalent. The contents should not be modified.
  85392. */
  85393. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  85394. /** Return values for the FLAC__StreamDecoder length callback.
  85395. */
  85396. typedef enum {
  85397. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  85398. /**< The length call was OK and decoding can continue. */
  85399. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  85400. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85401. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85402. /**< Client does not support reporting the length. */
  85403. } FLAC__StreamDecoderLengthStatus;
  85404. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  85405. *
  85406. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  85407. * will give the string equivalent. The contents should not be modified.
  85408. */
  85409. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  85410. /** Return values for the FLAC__StreamDecoder write callback.
  85411. */
  85412. typedef enum {
  85413. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  85414. /**< The write was OK and decoding can continue. */
  85415. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  85416. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85417. } FLAC__StreamDecoderWriteStatus;
  85418. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  85419. *
  85420. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  85421. * will give the string equivalent. The contents should not be modified.
  85422. */
  85423. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  85424. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  85425. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  85426. * all. The rest could be caused by bad sync (false synchronization on
  85427. * data that is not the start of a frame) or corrupted data. The error
  85428. * itself is the decoder's best guess at what happened assuming a correct
  85429. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  85430. * could be caused by a correct sync on the start of a frame, but some
  85431. * data in the frame header was corrupted. Or it could be the result of
  85432. * syncing on a point the stream that looked like the starting of a frame
  85433. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85434. * could be because the decoder encountered a valid frame made by a future
  85435. * version of the encoder which it cannot parse, or because of a false
  85436. * sync making it appear as though an encountered frame was generated by
  85437. * a future encoder.
  85438. */
  85439. typedef enum {
  85440. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  85441. /**< An error in the stream caused the decoder to lose synchronization. */
  85442. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  85443. /**< The decoder encountered a corrupted frame header. */
  85444. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  85445. /**< The frame's data did not match the CRC in the footer. */
  85446. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85447. /**< The decoder encountered reserved fields in use in the stream. */
  85448. } FLAC__StreamDecoderErrorStatus;
  85449. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  85450. *
  85451. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  85452. * will give the string equivalent. The contents should not be modified.
  85453. */
  85454. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  85455. /***********************************************************************
  85456. *
  85457. * class FLAC__StreamDecoder
  85458. *
  85459. ***********************************************************************/
  85460. struct FLAC__StreamDecoderProtected;
  85461. struct FLAC__StreamDecoderPrivate;
  85462. /** The opaque structure definition for the stream decoder type.
  85463. * See the \link flac_stream_decoder stream decoder module \endlink
  85464. * for a detailed description.
  85465. */
  85466. typedef struct {
  85467. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85468. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85469. } FLAC__StreamDecoder;
  85470. /** Signature for the read callback.
  85471. *
  85472. * A function pointer matching this signature must be passed to
  85473. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85474. * called when the decoder needs more input data. The address of the
  85475. * buffer to be filled is supplied, along with the number of bytes the
  85476. * buffer can hold. The callback may choose to supply less data and
  85477. * modify the byte count but must be careful not to overflow the buffer.
  85478. * The callback then returns a status code chosen from
  85479. * FLAC__StreamDecoderReadStatus.
  85480. *
  85481. * Here is an example of a read callback for stdio streams:
  85482. * \code
  85483. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85484. * {
  85485. * FILE *file = ((MyClientData*)client_data)->file;
  85486. * if(*bytes > 0) {
  85487. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85488. * if(ferror(file))
  85489. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  85490. * else if(*bytes == 0)
  85491. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  85492. * else
  85493. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  85494. * }
  85495. * else
  85496. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  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 buffer A pointer to a location for the callee to store
  85505. * data to be decoded.
  85506. * \param bytes A pointer to the size of the buffer. On entry
  85507. * to the callback, it contains the maximum number
  85508. * of bytes that may be stored in \a buffer. The
  85509. * callee must set it to the actual number of bytes
  85510. * stored (0 in case of error or end-of-stream) before
  85511. * returning.
  85512. * \param client_data The callee's client data set through
  85513. * FLAC__stream_decoder_init_*().
  85514. * \retval FLAC__StreamDecoderReadStatus
  85515. * The callee's return status. Note that the callback should return
  85516. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  85517. * zero bytes were read and there is no more data to be read.
  85518. */
  85519. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85520. /** Signature for the seek callback.
  85521. *
  85522. * A function pointer matching this signature may be passed to
  85523. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85524. * called when the decoder needs to seek the input stream. The decoder
  85525. * will pass the absolute byte offset to seek to, 0 meaning the
  85526. * beginning of the stream.
  85527. *
  85528. * Here is an example of a seek callback for stdio streams:
  85529. * \code
  85530. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85531. * {
  85532. * FILE *file = ((MyClientData*)client_data)->file;
  85533. * if(file == stdin)
  85534. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  85535. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85536. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  85537. * else
  85538. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  85539. * }
  85540. * \endcode
  85541. *
  85542. * \note In general, FLAC__StreamDecoder functions which change the
  85543. * state should not be called on the \a decoder while in the callback.
  85544. *
  85545. * \param decoder The decoder instance calling the callback.
  85546. * \param absolute_byte_offset The offset from the beginning of the stream
  85547. * to seek to.
  85548. * \param client_data The callee's client data set through
  85549. * FLAC__stream_decoder_init_*().
  85550. * \retval FLAC__StreamDecoderSeekStatus
  85551. * The callee's return status.
  85552. */
  85553. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85554. /** Signature for the tell callback.
  85555. *
  85556. * A function pointer matching this signature may be passed to
  85557. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85558. * called when the decoder wants to know the current position of the
  85559. * stream. The callback should return the byte offset from the
  85560. * beginning of the stream.
  85561. *
  85562. * Here is an example of a tell callback for stdio streams:
  85563. * \code
  85564. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85565. * {
  85566. * FILE *file = ((MyClientData*)client_data)->file;
  85567. * off_t pos;
  85568. * if(file == stdin)
  85569. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  85570. * else if((pos = ftello(file)) < 0)
  85571. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  85572. * else {
  85573. * *absolute_byte_offset = (FLAC__uint64)pos;
  85574. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  85575. * }
  85576. * }
  85577. * \endcode
  85578. *
  85579. * \note In general, FLAC__StreamDecoder functions which change the
  85580. * state should not be called on the \a decoder while in the callback.
  85581. *
  85582. * \param decoder The decoder instance calling the callback.
  85583. * \param absolute_byte_offset A pointer to storage for the current offset
  85584. * from the beginning of the stream.
  85585. * \param client_data The callee's client data set through
  85586. * FLAC__stream_decoder_init_*().
  85587. * \retval FLAC__StreamDecoderTellStatus
  85588. * The callee's return status.
  85589. */
  85590. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85591. /** Signature for the length callback.
  85592. *
  85593. * A function pointer matching this signature may be passed to
  85594. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85595. * called when the decoder wants to know the total length of the stream
  85596. * in bytes.
  85597. *
  85598. * Here is an example of a length callback for stdio streams:
  85599. * \code
  85600. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  85601. * {
  85602. * FILE *file = ((MyClientData*)client_data)->file;
  85603. * struct stat filestats;
  85604. *
  85605. * if(file == stdin)
  85606. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  85607. * else if(fstat(fileno(file), &filestats) != 0)
  85608. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  85609. * else {
  85610. * *stream_length = (FLAC__uint64)filestats.st_size;
  85611. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  85612. * }
  85613. * }
  85614. * \endcode
  85615. *
  85616. * \note In general, FLAC__StreamDecoder functions which change the
  85617. * state should not be called on the \a decoder while in the callback.
  85618. *
  85619. * \param decoder The decoder instance calling the callback.
  85620. * \param stream_length A pointer to storage for the length of the stream
  85621. * in bytes.
  85622. * \param client_data The callee's client data set through
  85623. * FLAC__stream_decoder_init_*().
  85624. * \retval FLAC__StreamDecoderLengthStatus
  85625. * The callee's return status.
  85626. */
  85627. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  85628. /** Signature for the EOF callback.
  85629. *
  85630. * A function pointer matching this signature may be passed to
  85631. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85632. * called when the decoder needs to know if the end of the stream has
  85633. * been reached.
  85634. *
  85635. * Here is an example of a EOF callback for stdio streams:
  85636. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  85637. * \code
  85638. * {
  85639. * FILE *file = ((MyClientData*)client_data)->file;
  85640. * return feof(file)? true : false;
  85641. * }
  85642. * \endcode
  85643. *
  85644. * \note In general, FLAC__StreamDecoder functions which change the
  85645. * state should not be called on the \a decoder while in the callback.
  85646. *
  85647. * \param decoder The decoder instance calling the callback.
  85648. * \param client_data The callee's client data set through
  85649. * FLAC__stream_decoder_init_*().
  85650. * \retval FLAC__bool
  85651. * \c true if the currently at the end of the stream, else \c false.
  85652. */
  85653. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  85654. /** Signature for the write callback.
  85655. *
  85656. * A function pointer matching this signature must be passed to one of
  85657. * the FLAC__stream_decoder_init_*() functions.
  85658. * The supplied function will be called when the decoder has decoded a
  85659. * single audio frame. The decoder will pass the frame metadata as well
  85660. * as an array of pointers (one for each channel) pointing to the
  85661. * decoded audio.
  85662. *
  85663. * \note In general, FLAC__StreamDecoder functions which change the
  85664. * state should not be called on the \a decoder while in the callback.
  85665. *
  85666. * \param decoder The decoder instance calling the callback.
  85667. * \param frame The description of the decoded frame. See
  85668. * FLAC__Frame.
  85669. * \param buffer An array of pointers to decoded channels of data.
  85670. * Each pointer will point to an array of signed
  85671. * samples of length \a frame->header.blocksize.
  85672. * Channels will be ordered according to the FLAC
  85673. * specification; see the documentation for the
  85674. * <A HREF="../format.html#frame_header">frame header</A>.
  85675. * \param client_data The callee's client data set through
  85676. * FLAC__stream_decoder_init_*().
  85677. * \retval FLAC__StreamDecoderWriteStatus
  85678. * The callee's return status.
  85679. */
  85680. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  85681. /** Signature for the metadata callback.
  85682. *
  85683. * A function pointer matching this signature must be passed to one of
  85684. * the FLAC__stream_decoder_init_*() functions.
  85685. * The supplied function will be called when the decoder has decoded a
  85686. * metadata block. In a valid FLAC file there will always be one
  85687. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  85688. * These will be supplied by the decoder in the same order as they
  85689. * appear in the stream and always before the first audio frame (i.e.
  85690. * write callback). The metadata block that is passed in must not be
  85691. * modified, and it doesn't live beyond the callback, so you should make
  85692. * a copy of it with FLAC__metadata_object_clone() if you will need it
  85693. * elsewhere. Since metadata blocks can potentially be large, by
  85694. * default the decoder only calls the metadata callback for the
  85695. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  85696. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  85697. *
  85698. * \note In general, FLAC__StreamDecoder functions which change the
  85699. * state should not be called on the \a decoder while in the callback.
  85700. *
  85701. * \param decoder The decoder instance calling the callback.
  85702. * \param metadata The decoded metadata block.
  85703. * \param client_data The callee's client data set through
  85704. * FLAC__stream_decoder_init_*().
  85705. */
  85706. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85707. /** Signature for the error callback.
  85708. *
  85709. * A function pointer matching this signature must be passed to one of
  85710. * the FLAC__stream_decoder_init_*() functions.
  85711. * The supplied function will be called whenever an error occurs during
  85712. * decoding.
  85713. *
  85714. * \note In general, FLAC__StreamDecoder functions which change the
  85715. * state should not be called on the \a decoder while in the callback.
  85716. *
  85717. * \param decoder The decoder instance calling the callback.
  85718. * \param status The error encountered by the decoder.
  85719. * \param client_data The callee's client data set through
  85720. * FLAC__stream_decoder_init_*().
  85721. */
  85722. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  85723. /***********************************************************************
  85724. *
  85725. * Class constructor/destructor
  85726. *
  85727. ***********************************************************************/
  85728. /** Create a new stream decoder instance. The instance is created with
  85729. * default settings; see the individual FLAC__stream_decoder_set_*()
  85730. * functions for each setting's default.
  85731. *
  85732. * \retval FLAC__StreamDecoder*
  85733. * \c NULL if there was an error allocating memory, else the new instance.
  85734. */
  85735. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  85736. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  85737. *
  85738. * \param decoder A pointer to an existing decoder.
  85739. * \assert
  85740. * \code decoder != NULL \endcode
  85741. */
  85742. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  85743. /***********************************************************************
  85744. *
  85745. * Public class method prototypes
  85746. *
  85747. ***********************************************************************/
  85748. /** Set the serial number for the FLAC stream within the Ogg container.
  85749. * The default behavior is to use the serial number of the first Ogg
  85750. * page. Setting a serial number here will explicitly specify which
  85751. * stream is to be decoded.
  85752. *
  85753. * \note
  85754. * This does not need to be set for native FLAC decoding.
  85755. *
  85756. * \default \c use serial number of first page
  85757. * \param decoder A decoder instance to set.
  85758. * \param serial_number See above.
  85759. * \assert
  85760. * \code decoder != NULL \endcode
  85761. * \retval FLAC__bool
  85762. * \c false if the decoder is already initialized, else \c true.
  85763. */
  85764. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  85765. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  85766. * compute the MD5 signature of the unencoded audio data while decoding
  85767. * and compare it to the signature from the STREAMINFO block, if it
  85768. * exists, during FLAC__stream_decoder_finish().
  85769. *
  85770. * MD5 signature checking will be turned off (until the next
  85771. * FLAC__stream_decoder_reset()) if there is no signature in the
  85772. * STREAMINFO block or when a seek is attempted.
  85773. *
  85774. * Clients that do not use the MD5 check should leave this off to speed
  85775. * up decoding.
  85776. *
  85777. * \default \c false
  85778. * \param decoder A decoder instance to set.
  85779. * \param value Flag value (see above).
  85780. * \assert
  85781. * \code decoder != NULL \endcode
  85782. * \retval FLAC__bool
  85783. * \c false if the decoder is already initialized, else \c true.
  85784. */
  85785. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  85786. /** Direct the decoder to pass on all metadata blocks of type \a type.
  85787. *
  85788. * \default By default, only the \c STREAMINFO block is returned via the
  85789. * metadata callback.
  85790. * \param decoder A decoder instance to set.
  85791. * \param type See above.
  85792. * \assert
  85793. * \code decoder != NULL \endcode
  85794. * \a type is valid
  85795. * \retval FLAC__bool
  85796. * \c false if the decoder is already initialized, else \c true.
  85797. */
  85798. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85799. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  85800. * given \a id.
  85801. *
  85802. * \default By default, only the \c STREAMINFO block is returned via the
  85803. * metadata callback.
  85804. * \param decoder A decoder instance to set.
  85805. * \param id See above.
  85806. * \assert
  85807. * \code decoder != NULL \endcode
  85808. * \code id != NULL \endcode
  85809. * \retval FLAC__bool
  85810. * \c false if the decoder is already initialized, else \c true.
  85811. */
  85812. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85813. /** Direct the decoder to pass on all metadata blocks of any type.
  85814. *
  85815. * \default By default, only the \c STREAMINFO block is returned via the
  85816. * metadata callback.
  85817. * \param decoder A decoder instance to set.
  85818. * \assert
  85819. * \code decoder != NULL \endcode
  85820. * \retval FLAC__bool
  85821. * \c false if the decoder is already initialized, else \c true.
  85822. */
  85823. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  85824. /** Direct the decoder to filter out all metadata blocks of type \a type.
  85825. *
  85826. * \default By default, only the \c STREAMINFO block is returned via the
  85827. * metadata callback.
  85828. * \param decoder A decoder instance to set.
  85829. * \param type See above.
  85830. * \assert
  85831. * \code decoder != NULL \endcode
  85832. * \a type is valid
  85833. * \retval FLAC__bool
  85834. * \c false if the decoder is already initialized, else \c true.
  85835. */
  85836. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85837. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  85838. * the given \a id.
  85839. *
  85840. * \default By default, only the \c STREAMINFO block is returned via the
  85841. * metadata callback.
  85842. * \param decoder A decoder instance to set.
  85843. * \param id See above.
  85844. * \assert
  85845. * \code decoder != NULL \endcode
  85846. * \code id != NULL \endcode
  85847. * \retval FLAC__bool
  85848. * \c false if the decoder is already initialized, else \c true.
  85849. */
  85850. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85851. /** Direct the decoder to filter out all metadata blocks of any type.
  85852. *
  85853. * \default By default, only the \c STREAMINFO block is returned via the
  85854. * metadata callback.
  85855. * \param decoder A decoder instance to set.
  85856. * \assert
  85857. * \code decoder != NULL \endcode
  85858. * \retval FLAC__bool
  85859. * \c false if the decoder is already initialized, else \c true.
  85860. */
  85861. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  85862. /** Get the current decoder state.
  85863. *
  85864. * \param decoder A decoder instance to query.
  85865. * \assert
  85866. * \code decoder != NULL \endcode
  85867. * \retval FLAC__StreamDecoderState
  85868. * The current decoder state.
  85869. */
  85870. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  85871. /** Get the current decoder state as a C string.
  85872. *
  85873. * \param decoder A decoder instance to query.
  85874. * \assert
  85875. * \code decoder != NULL \endcode
  85876. * \retval const char *
  85877. * The decoder state as a C string. Do not modify the contents.
  85878. */
  85879. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  85880. /** Get the "MD5 signature checking" flag.
  85881. * This is the value of the setting, not whether or not the decoder is
  85882. * currently checking the MD5 (remember, it can be turned off automatically
  85883. * by a seek). When the decoder is reset the flag will be restored to the
  85884. * value returned by this function.
  85885. *
  85886. * \param decoder A decoder instance to query.
  85887. * \assert
  85888. * \code decoder != NULL \endcode
  85889. * \retval FLAC__bool
  85890. * See above.
  85891. */
  85892. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  85893. /** Get the total number of samples in the stream being decoded.
  85894. * Will only be valid after decoding has started and will contain the
  85895. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  85896. *
  85897. * \param decoder A decoder instance to query.
  85898. * \assert
  85899. * \code decoder != NULL \endcode
  85900. * \retval unsigned
  85901. * See above.
  85902. */
  85903. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  85904. /** Get the current number of channels in the stream being decoded.
  85905. * Will only be valid after decoding has started and will contain the
  85906. * value from the most recently decoded frame header.
  85907. *
  85908. * \param decoder A decoder instance to query.
  85909. * \assert
  85910. * \code decoder != NULL \endcode
  85911. * \retval unsigned
  85912. * See above.
  85913. */
  85914. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  85915. /** Get the current channel assignment in the stream being decoded.
  85916. * Will only be valid after decoding has started and will contain the
  85917. * value from the most recently decoded frame header.
  85918. *
  85919. * \param decoder A decoder instance to query.
  85920. * \assert
  85921. * \code decoder != NULL \endcode
  85922. * \retval FLAC__ChannelAssignment
  85923. * See above.
  85924. */
  85925. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  85926. /** Get the current sample resolution in the stream being decoded.
  85927. * Will only be valid after decoding has started and will contain the
  85928. * value from the most recently decoded frame header.
  85929. *
  85930. * \param decoder A decoder instance to query.
  85931. * \assert
  85932. * \code decoder != NULL \endcode
  85933. * \retval unsigned
  85934. * See above.
  85935. */
  85936. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  85937. /** Get the current sample rate in Hz of the stream being decoded.
  85938. * Will only be valid after decoding has started and will contain the
  85939. * value from the most recently decoded frame header.
  85940. *
  85941. * \param decoder A decoder instance to query.
  85942. * \assert
  85943. * \code decoder != NULL \endcode
  85944. * \retval unsigned
  85945. * See above.
  85946. */
  85947. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  85948. /** Get the current blocksize of the stream being decoded.
  85949. * Will only be valid after decoding has started and will contain the
  85950. * value from the most recently decoded frame header.
  85951. *
  85952. * \param decoder A decoder instance to query.
  85953. * \assert
  85954. * \code decoder != NULL \endcode
  85955. * \retval unsigned
  85956. * See above.
  85957. */
  85958. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  85959. /** Returns the decoder's current read position within the stream.
  85960. * The position is the byte offset from the start of the stream.
  85961. * Bytes before this position have been fully decoded. Note that
  85962. * there may still be undecoded bytes in the decoder's read FIFO.
  85963. * The returned position is correct even after a seek.
  85964. *
  85965. * \warning This function currently only works for native FLAC,
  85966. * not Ogg FLAC streams.
  85967. *
  85968. * \param decoder A decoder instance to query.
  85969. * \param position Address at which to return the desired position.
  85970. * \assert
  85971. * \code decoder != NULL \endcode
  85972. * \code position != NULL \endcode
  85973. * \retval FLAC__bool
  85974. * \c true if successful, \c false if the stream is not native FLAC,
  85975. * or there was an error from the 'tell' callback or it returned
  85976. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  85977. */
  85978. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  85979. /** Initialize the decoder instance to decode native FLAC streams.
  85980. *
  85981. * This flavor of initialization sets up the decoder to decode from a
  85982. * native FLAC stream. I/O is performed via callbacks to the client.
  85983. * For decoding from a plain file via filename or open FILE*,
  85984. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  85985. * provide a simpler interface.
  85986. *
  85987. * This function should be called after FLAC__stream_decoder_new() and
  85988. * FLAC__stream_decoder_set_*() but before any of the
  85989. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85990. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85991. * if initialization succeeded.
  85992. *
  85993. * \param decoder An uninitialized decoder instance.
  85994. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85995. * pointer must not be \c NULL.
  85996. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85997. * pointer may be \c NULL if seeking is not
  85998. * supported. If \a seek_callback is not \c NULL then a
  85999. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  86000. * Alternatively, a dummy seek callback that just
  86001. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86002. * may also be supplied, all though this is slightly
  86003. * less efficient for the decoder.
  86004. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  86005. * pointer may be \c NULL if not supported by the client. If
  86006. * \a seek_callback is not \c NULL then a
  86007. * \a tell_callback must also be supplied.
  86008. * Alternatively, a dummy tell callback that just
  86009. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86010. * may also be supplied, all though this is slightly
  86011. * less efficient for the decoder.
  86012. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  86013. * pointer may be \c NULL if not supported by the client. If
  86014. * \a seek_callback is not \c NULL then a
  86015. * \a length_callback must also be supplied.
  86016. * Alternatively, a dummy length callback that just
  86017. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86018. * may also be supplied, all though this is slightly
  86019. * less efficient for the decoder.
  86020. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  86021. * pointer may be \c NULL if not supported by the client. If
  86022. * \a seek_callback is not \c NULL then a
  86023. * \a eof_callback must also be supplied.
  86024. * Alternatively, a dummy length callback that just
  86025. * returns \c false
  86026. * may also be supplied, all though this is slightly
  86027. * less efficient for the decoder.
  86028. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86029. * pointer must not be \c NULL.
  86030. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86031. * pointer may be \c NULL if the callback is not
  86032. * desired.
  86033. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86034. * pointer must not be \c NULL.
  86035. * \param client_data This value will be supplied to callbacks in their
  86036. * \a client_data argument.
  86037. * \assert
  86038. * \code decoder != NULL \endcode
  86039. * \retval FLAC__StreamDecoderInitStatus
  86040. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86041. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86042. */
  86043. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  86044. FLAC__StreamDecoder *decoder,
  86045. FLAC__StreamDecoderReadCallback read_callback,
  86046. FLAC__StreamDecoderSeekCallback seek_callback,
  86047. FLAC__StreamDecoderTellCallback tell_callback,
  86048. FLAC__StreamDecoderLengthCallback length_callback,
  86049. FLAC__StreamDecoderEofCallback eof_callback,
  86050. FLAC__StreamDecoderWriteCallback write_callback,
  86051. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86052. FLAC__StreamDecoderErrorCallback error_callback,
  86053. void *client_data
  86054. );
  86055. /** Initialize the decoder instance to decode Ogg FLAC streams.
  86056. *
  86057. * This flavor of initialization sets up the decoder to decode from a
  86058. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  86059. * client. For decoding from a plain file via filename or open FILE*,
  86060. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  86061. * provide a simpler interface.
  86062. *
  86063. * This function should be called after FLAC__stream_decoder_new() and
  86064. * FLAC__stream_decoder_set_*() but before any of the
  86065. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86066. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86067. * if initialization succeeded.
  86068. *
  86069. * \note Support for Ogg FLAC in the library is optional. If this
  86070. * library has been built without support for Ogg FLAC, this function
  86071. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86072. *
  86073. * \param decoder An uninitialized decoder instance.
  86074. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  86075. * pointer must not be \c NULL.
  86076. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  86077. * pointer may be \c NULL if seeking is not
  86078. * supported. If \a seek_callback is not \c NULL then a
  86079. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  86080. * Alternatively, a dummy seek callback that just
  86081. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  86082. * may also be supplied, all though this is slightly
  86083. * less efficient for the decoder.
  86084. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  86085. * pointer may be \c NULL if not supported by the client. If
  86086. * \a seek_callback is not \c NULL then a
  86087. * \a tell_callback must also be supplied.
  86088. * Alternatively, a dummy tell callback that just
  86089. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  86090. * may also be supplied, all though this is slightly
  86091. * less efficient for the decoder.
  86092. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  86093. * pointer may be \c NULL if not supported by the client. If
  86094. * \a seek_callback is not \c NULL then a
  86095. * \a length_callback must also be supplied.
  86096. * Alternatively, a dummy length callback that just
  86097. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  86098. * may also be supplied, all though this is slightly
  86099. * less efficient for the decoder.
  86100. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  86101. * pointer may be \c NULL if not supported by the client. If
  86102. * \a seek_callback is not \c NULL then a
  86103. * \a eof_callback must also be supplied.
  86104. * Alternatively, a dummy length callback that just
  86105. * returns \c false
  86106. * may also be supplied, all though this is slightly
  86107. * less efficient for the decoder.
  86108. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86109. * pointer must not be \c NULL.
  86110. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86111. * pointer may be \c NULL if the callback is not
  86112. * desired.
  86113. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86114. * pointer must not be \c NULL.
  86115. * \param client_data This value will be supplied to callbacks in their
  86116. * \a client_data argument.
  86117. * \assert
  86118. * \code decoder != NULL \endcode
  86119. * \retval FLAC__StreamDecoderInitStatus
  86120. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86121. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86122. */
  86123. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  86124. FLAC__StreamDecoder *decoder,
  86125. FLAC__StreamDecoderReadCallback read_callback,
  86126. FLAC__StreamDecoderSeekCallback seek_callback,
  86127. FLAC__StreamDecoderTellCallback tell_callback,
  86128. FLAC__StreamDecoderLengthCallback length_callback,
  86129. FLAC__StreamDecoderEofCallback eof_callback,
  86130. FLAC__StreamDecoderWriteCallback write_callback,
  86131. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86132. FLAC__StreamDecoderErrorCallback error_callback,
  86133. void *client_data
  86134. );
  86135. /** Initialize the decoder instance to decode native FLAC files.
  86136. *
  86137. * This flavor of initialization sets up the decoder to decode from a
  86138. * plain native FLAC file. For non-stdio streams, you must use
  86139. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  86140. *
  86141. * This function should be called after FLAC__stream_decoder_new() and
  86142. * FLAC__stream_decoder_set_*() but before any of the
  86143. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86144. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86145. * if initialization succeeded.
  86146. *
  86147. * \param decoder An uninitialized decoder instance.
  86148. * \param file An open FLAC file. The file should have been
  86149. * opened with mode \c "rb" and rewound. The file
  86150. * becomes owned by the decoder and should not be
  86151. * manipulated by the client while decoding.
  86152. * Unless \a file is \c stdin, it will be closed
  86153. * when FLAC__stream_decoder_finish() is called.
  86154. * Note however that seeking will not work when
  86155. * decoding from \c stdout since it is not seekable.
  86156. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86157. * pointer must not be \c NULL.
  86158. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86159. * pointer may be \c NULL if the callback is not
  86160. * desired.
  86161. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86162. * pointer must not be \c NULL.
  86163. * \param client_data This value will be supplied to callbacks in their
  86164. * \a client_data argument.
  86165. * \assert
  86166. * \code decoder != NULL \endcode
  86167. * \code file != NULL \endcode
  86168. * \retval FLAC__StreamDecoderInitStatus
  86169. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86170. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86171. */
  86172. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  86173. FLAC__StreamDecoder *decoder,
  86174. FILE *file,
  86175. FLAC__StreamDecoderWriteCallback write_callback,
  86176. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86177. FLAC__StreamDecoderErrorCallback error_callback,
  86178. void *client_data
  86179. );
  86180. /** Initialize the decoder instance to decode Ogg FLAC files.
  86181. *
  86182. * This flavor of initialization sets up the decoder to decode from a
  86183. * plain Ogg FLAC file. For non-stdio streams, you must use
  86184. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  86185. *
  86186. * This function should be called after FLAC__stream_decoder_new() and
  86187. * FLAC__stream_decoder_set_*() but before any of the
  86188. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86189. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86190. * if initialization succeeded.
  86191. *
  86192. * \note Support for Ogg FLAC in the library is optional. If this
  86193. * library has been built without support for Ogg FLAC, this function
  86194. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86195. *
  86196. * \param decoder An uninitialized decoder instance.
  86197. * \param file An open FLAC file. The file should have been
  86198. * opened with mode \c "rb" and rewound. The file
  86199. * becomes owned by the decoder and should not be
  86200. * manipulated by the client while decoding.
  86201. * Unless \a file is \c stdin, it will be closed
  86202. * when FLAC__stream_decoder_finish() is called.
  86203. * Note however that seeking will not work when
  86204. * decoding from \c stdout since it 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. * \code file != NULL \endcode
  86217. * \retval FLAC__StreamDecoderInitStatus
  86218. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86219. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86220. */
  86221. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  86222. FLAC__StreamDecoder *decoder,
  86223. FILE *file,
  86224. FLAC__StreamDecoderWriteCallback write_callback,
  86225. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86226. FLAC__StreamDecoderErrorCallback error_callback,
  86227. void *client_data
  86228. );
  86229. /** Initialize the decoder instance to decode native FLAC files.
  86230. *
  86231. * This flavor of initialization sets up the decoder to decode from a plain
  86232. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86233. * example, with Unicode filenames on Windows), you must use
  86234. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  86235. * and provide callbacks for the I/O.
  86236. *
  86237. * This function should be called after FLAC__stream_decoder_new() and
  86238. * FLAC__stream_decoder_set_*() but before any of the
  86239. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86240. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86241. * if initialization succeeded.
  86242. *
  86243. * \param decoder An uninitialized decoder instance.
  86244. * \param filename The name of the file to decode from. The file will
  86245. * be opened with fopen(). Use \c NULL to decode from
  86246. * \c stdin. Note that \c stdin is not seekable.
  86247. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86248. * pointer must not be \c NULL.
  86249. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86250. * pointer may be \c NULL if the callback is not
  86251. * desired.
  86252. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86253. * pointer must not be \c NULL.
  86254. * \param client_data This value will be supplied to callbacks in their
  86255. * \a client_data argument.
  86256. * \assert
  86257. * \code decoder != NULL \endcode
  86258. * \retval FLAC__StreamDecoderInitStatus
  86259. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86260. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86261. */
  86262. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  86263. FLAC__StreamDecoder *decoder,
  86264. const char *filename,
  86265. FLAC__StreamDecoderWriteCallback write_callback,
  86266. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86267. FLAC__StreamDecoderErrorCallback error_callback,
  86268. void *client_data
  86269. );
  86270. /** Initialize the decoder instance to decode Ogg FLAC files.
  86271. *
  86272. * This flavor of initialization sets up the decoder to decode from a plain
  86273. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86274. * example, with Unicode filenames on Windows), you must use
  86275. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  86276. * and provide callbacks for the I/O.
  86277. *
  86278. * This function should be called after FLAC__stream_decoder_new() and
  86279. * FLAC__stream_decoder_set_*() but before any of the
  86280. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86281. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86282. * if initialization succeeded.
  86283. *
  86284. * \note Support for Ogg FLAC in the library is optional. If this
  86285. * library has been built without support for Ogg FLAC, this function
  86286. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86287. *
  86288. * \param decoder An uninitialized decoder instance.
  86289. * \param filename The name of the file to decode from. The file will
  86290. * be opened with fopen(). Use \c NULL to decode from
  86291. * \c stdin. Note that \c stdin is not seekable.
  86292. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86293. * pointer must not be \c NULL.
  86294. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86295. * pointer may be \c NULL if the callback is not
  86296. * desired.
  86297. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86298. * pointer must not be \c NULL.
  86299. * \param client_data This value will be supplied to callbacks in their
  86300. * \a client_data argument.
  86301. * \assert
  86302. * \code decoder != NULL \endcode
  86303. * \retval FLAC__StreamDecoderInitStatus
  86304. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86305. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86306. */
  86307. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  86308. FLAC__StreamDecoder *decoder,
  86309. const char *filename,
  86310. FLAC__StreamDecoderWriteCallback write_callback,
  86311. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86312. FLAC__StreamDecoderErrorCallback error_callback,
  86313. void *client_data
  86314. );
  86315. /** Finish the decoding process.
  86316. * Flushes the decoding buffer, releases resources, resets the decoder
  86317. * settings to their defaults, and returns the decoder state to
  86318. * FLAC__STREAM_DECODER_UNINITIALIZED.
  86319. *
  86320. * In the event of a prematurely-terminated decode, it is not strictly
  86321. * necessary to call this immediately before FLAC__stream_decoder_delete()
  86322. * but it is good practice to match every FLAC__stream_decoder_init_*()
  86323. * with a FLAC__stream_decoder_finish().
  86324. *
  86325. * \param decoder An uninitialized decoder instance.
  86326. * \assert
  86327. * \code decoder != NULL \endcode
  86328. * \retval FLAC__bool
  86329. * \c false if MD5 checking is on AND a STREAMINFO block was available
  86330. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  86331. * signature does not match the one computed by the decoder; else
  86332. * \c true.
  86333. */
  86334. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  86335. /** Flush the stream input.
  86336. * The decoder's input buffer will be cleared and the state set to
  86337. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  86338. * off MD5 checking.
  86339. *
  86340. * \param decoder A decoder instance.
  86341. * \assert
  86342. * \code decoder != NULL \endcode
  86343. * \retval FLAC__bool
  86344. * \c true if successful, else \c false if a memory allocation
  86345. * error occurs (in which case the state will be set to
  86346. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  86347. */
  86348. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  86349. /** Reset the decoding process.
  86350. * The decoder's input buffer will be cleared and the state set to
  86351. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  86352. * FLAC__stream_decoder_finish() except that the settings are
  86353. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  86354. * before decoding again. MD5 checking will be restored to its original
  86355. * setting.
  86356. *
  86357. * If the decoder is seekable, or was initialized with
  86358. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  86359. * the decoder will also attempt to seek to the beginning of the file.
  86360. * If this rewind fails, this function will return \c false. It follows
  86361. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  86362. * \c stdin.
  86363. *
  86364. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  86365. * and is not seekable (i.e. no seek callback was provided or the seek
  86366. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  86367. * is the duty of the client to start feeding data from the beginning of
  86368. * the stream on the next FLAC__stream_decoder_process() or
  86369. * FLAC__stream_decoder_process_interleaved() call.
  86370. *
  86371. * \param decoder A decoder instance.
  86372. * \assert
  86373. * \code decoder != NULL \endcode
  86374. * \retval FLAC__bool
  86375. * \c true if successful, else \c false if a memory allocation occurs
  86376. * (in which case the state will be set to
  86377. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  86378. * occurs (the state will be unchanged).
  86379. */
  86380. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  86381. /** Decode one metadata block or audio frame.
  86382. * This version instructs the decoder to decode a either a single metadata
  86383. * block or a single frame and stop, unless the callbacks return a fatal
  86384. * error or the read callback returns
  86385. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86386. *
  86387. * As the decoder needs more input it will call the read callback.
  86388. * Depending on what was decoded, the metadata or write callback will be
  86389. * called with the decoded metadata block or audio frame.
  86390. *
  86391. * Unless there is a fatal read error or end of stream, this function
  86392. * will return once one whole frame is decoded. In other words, if the
  86393. * stream is not synchronized or points to a corrupt frame header, the
  86394. * decoder will continue to try and resync until it gets to a valid
  86395. * frame, then decode one frame, then return. If the decoder points to
  86396. * a frame whose frame CRC in the frame footer does not match the
  86397. * computed frame CRC, this function will issue a
  86398. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  86399. * error callback, and return, having decoded one complete, although
  86400. * corrupt, frame. (Such corrupted frames are sent as silence of the
  86401. * correct length to the write callback.)
  86402. *
  86403. * \param decoder An initialized decoder instance.
  86404. * \assert
  86405. * \code decoder != NULL \endcode
  86406. * \retval FLAC__bool
  86407. * \c false if any fatal read, write, or memory allocation error
  86408. * occurred (meaning decoding must stop), else \c true; for more
  86409. * information about the decoder, check the decoder state with
  86410. * FLAC__stream_decoder_get_state().
  86411. */
  86412. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  86413. /** Decode until the end of the metadata.
  86414. * This version instructs the decoder to decode from the current position
  86415. * and continue until all the metadata has been read, or until the
  86416. * callbacks return a fatal error or the read callback returns
  86417. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86418. *
  86419. * As the decoder needs more input it will call the read callback.
  86420. * As each metadata block is decoded, the metadata callback will be called
  86421. * with the decoded metadata.
  86422. *
  86423. * \param decoder An initialized decoder instance.
  86424. * \assert
  86425. * \code decoder != NULL \endcode
  86426. * \retval FLAC__bool
  86427. * \c false if any fatal read, write, or memory allocation error
  86428. * occurred (meaning decoding must stop), else \c true; for more
  86429. * information about the decoder, check the decoder state with
  86430. * FLAC__stream_decoder_get_state().
  86431. */
  86432. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  86433. /** Decode until the end of the stream.
  86434. * This version instructs the decoder to decode from the current position
  86435. * and continue until the end of stream (the read callback returns
  86436. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  86437. * callbacks return a fatal error.
  86438. *
  86439. * As the decoder needs more input it will call the read callback.
  86440. * As each metadata block and frame is decoded, the metadata or write
  86441. * callback will be called with the decoded metadata or frame.
  86442. *
  86443. * \param decoder An initialized decoder instance.
  86444. * \assert
  86445. * \code decoder != NULL \endcode
  86446. * \retval FLAC__bool
  86447. * \c false if any fatal read, write, or memory allocation error
  86448. * occurred (meaning decoding must stop), else \c true; for more
  86449. * information about the decoder, check the decoder state with
  86450. * FLAC__stream_decoder_get_state().
  86451. */
  86452. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  86453. /** Skip one audio frame.
  86454. * This version instructs the decoder to 'skip' a single frame and stop,
  86455. * unless the callbacks return a fatal error or the read callback returns
  86456. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86457. *
  86458. * The decoding flow is the same as what occurs when
  86459. * FLAC__stream_decoder_process_single() is called to process an audio
  86460. * frame, except that this function does not decode the parsed data into
  86461. * PCM or call the write callback. The integrity of the frame is still
  86462. * checked the same way as in the other process functions.
  86463. *
  86464. * This function will return once one whole frame is skipped, in the
  86465. * same way that FLAC__stream_decoder_process_single() will return once
  86466. * one whole frame is decoded.
  86467. *
  86468. * This function can be used in more quickly determining FLAC frame
  86469. * boundaries when decoding of the actual data is not needed, for
  86470. * example when an application is separating a FLAC stream into frames
  86471. * for editing or storing in a container. To do this, the application
  86472. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  86473. * to the next frame, then use
  86474. * FLAC__stream_decoder_get_decode_position() to find the new frame
  86475. * boundary.
  86476. *
  86477. * This function should only be called when the stream has advanced
  86478. * past all the metadata, otherwise it will return \c false.
  86479. *
  86480. * \param decoder An initialized decoder instance not in a metadata
  86481. * state.
  86482. * \assert
  86483. * \code decoder != NULL \endcode
  86484. * \retval FLAC__bool
  86485. * \c false if any fatal read, write, or memory allocation error
  86486. * occurred (meaning decoding must stop), or if the decoder
  86487. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  86488. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  86489. * information about the decoder, check the decoder state with
  86490. * FLAC__stream_decoder_get_state().
  86491. */
  86492. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  86493. /** Flush the input and seek to an absolute sample.
  86494. * Decoding will resume at the given sample. Note that because of
  86495. * this, the next write callback may contain a partial block. The
  86496. * client must support seeking the input or this function will fail
  86497. * and return \c false. Furthermore, if the decoder state is
  86498. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  86499. * with FLAC__stream_decoder_flush() or reset with
  86500. * FLAC__stream_decoder_reset() before decoding can continue.
  86501. *
  86502. * \param decoder A decoder instance.
  86503. * \param sample The target sample number to seek to.
  86504. * \assert
  86505. * \code decoder != NULL \endcode
  86506. * \retval FLAC__bool
  86507. * \c true if successful, else \c false.
  86508. */
  86509. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  86510. /* \} */
  86511. #ifdef __cplusplus
  86512. }
  86513. #endif
  86514. #endif
  86515. /********* End of inlined file: stream_decoder.h *********/
  86516. /********* Start of inlined file: stream_encoder.h *********/
  86517. #ifndef FLAC__STREAM_ENCODER_H
  86518. #define FLAC__STREAM_ENCODER_H
  86519. #include <stdio.h> /* for FILE */
  86520. #ifdef __cplusplus
  86521. extern "C" {
  86522. #endif
  86523. /** \file include/FLAC/stream_encoder.h
  86524. *
  86525. * \brief
  86526. * This module contains the functions which implement the stream
  86527. * encoder.
  86528. *
  86529. * See the detailed documentation in the
  86530. * \link flac_stream_encoder stream encoder \endlink module.
  86531. */
  86532. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  86533. * \ingroup flac
  86534. *
  86535. * \brief
  86536. * This module describes the encoder layers provided by libFLAC.
  86537. *
  86538. * The stream encoder can be used to encode complete streams either to the
  86539. * client via callbacks, or directly to a file, depending on how it is
  86540. * initialized. When encoding via callbacks, the client provides a write
  86541. * callback which will be called whenever FLAC data is ready to be written.
  86542. * If the client also supplies a seek callback, the encoder will also
  86543. * automatically handle the writing back of metadata discovered while
  86544. * encoding, like stream info, seek points offsets, etc. When encoding to
  86545. * a file, the client needs only supply a filename or open \c FILE* and an
  86546. * optional progress callback for periodic notification of progress; the
  86547. * write and seek callbacks are supplied internally. For more info see the
  86548. * \link flac_stream_encoder stream encoder \endlink module.
  86549. */
  86550. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  86551. * \ingroup flac_encoder
  86552. *
  86553. * \brief
  86554. * This module contains the functions which implement the stream
  86555. * encoder.
  86556. *
  86557. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  86558. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  86559. *
  86560. * The basic usage of this encoder is as follows:
  86561. * - The program creates an instance of an encoder using
  86562. * FLAC__stream_encoder_new().
  86563. * - The program overrides the default settings using
  86564. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  86565. * functions should be called:
  86566. * - FLAC__stream_encoder_set_channels()
  86567. * - FLAC__stream_encoder_set_bits_per_sample()
  86568. * - FLAC__stream_encoder_set_sample_rate()
  86569. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  86570. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  86571. * - If the application wants to control the compression level or set its own
  86572. * metadata, then the following should also be called:
  86573. * - FLAC__stream_encoder_set_compression_level()
  86574. * - FLAC__stream_encoder_set_verify()
  86575. * - FLAC__stream_encoder_set_metadata()
  86576. * - The rest of the set functions should only be called if the client needs
  86577. * exact control over how the audio is compressed; thorough understanding
  86578. * of the FLAC format is necessary to achieve good results.
  86579. * - The program initializes the instance to validate the settings and
  86580. * prepare for encoding using
  86581. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  86582. * or FLAC__stream_encoder_init_file() for native FLAC
  86583. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  86584. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  86585. * - The program calls FLAC__stream_encoder_process() or
  86586. * FLAC__stream_encoder_process_interleaved() to encode data, which
  86587. * subsequently calls the callbacks when there is encoder data ready
  86588. * to be written.
  86589. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  86590. * which causes the encoder to encode any data still in its input pipe,
  86591. * update the metadata with the final encoding statistics if output
  86592. * seeking is possible, and finally reset the encoder to the
  86593. * uninitialized state.
  86594. * - The instance may be used again or deleted with
  86595. * FLAC__stream_encoder_delete().
  86596. *
  86597. * In more detail, the stream encoder functions similarly to the
  86598. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  86599. * callbacks and more options. Typically the client will create a new
  86600. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  86601. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  86602. * calling one of the FLAC__stream_encoder_init_*() functions.
  86603. *
  86604. * Unlike the decoders, the stream encoder has many options that can
  86605. * affect the speed and compression ratio. When setting these parameters
  86606. * you should have some basic knowledge of the format (see the
  86607. * <A HREF="../documentation.html#format">user-level documentation</A>
  86608. * or the <A HREF="../format.html">formal description</A>). The
  86609. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  86610. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  86611. * functions will do this, so make sure to pay attention to the state
  86612. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  86613. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  86614. * before FLAC__stream_encoder_init_*() will take on the defaults from
  86615. * the constructor.
  86616. *
  86617. * There are three initialization functions for native FLAC, one for
  86618. * setting up the encoder to encode FLAC data to the client via
  86619. * callbacks, and two for encoding directly to a file.
  86620. *
  86621. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  86622. * You must also supply a write callback which will be called anytime
  86623. * there is raw encoded data to write. If the client can seek the output
  86624. * it is best to also supply seek and tell callbacks, as this allows the
  86625. * encoder to go back after encoding is finished to write back
  86626. * information that was collected while encoding, like seek point offsets,
  86627. * frame sizes, etc.
  86628. *
  86629. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  86630. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  86631. * filename or open \c FILE*; the encoder will handle all the callbacks
  86632. * internally. You may also supply a progress callback for periodic
  86633. * notification of the encoding progress.
  86634. *
  86635. * There are three similarly-named init functions for encoding to Ogg
  86636. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  86637. * library has been built with Ogg support.
  86638. *
  86639. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  86640. * call the write callback several times, once with the \c fLaC signature,
  86641. * and once for each encoded metadata block. Note that for Ogg FLAC
  86642. * encoding you will usually get at least twice the number of callbacks than
  86643. * with native FLAC, one for the Ogg page header and one for the page body.
  86644. *
  86645. * After initializing the instance, the client may feed audio data to the
  86646. * encoder in one of two ways:
  86647. *
  86648. * - Channel separate, through FLAC__stream_encoder_process() - The client
  86649. * will pass an array of pointers to buffers, one for each channel, to
  86650. * the encoder, each of the same length. The samples need not be
  86651. * block-aligned, but each channel should have the same number of samples.
  86652. * - Channel interleaved, through
  86653. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  86654. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  86655. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86656. * Again, the samples need not be block-aligned but they must be
  86657. * sample-aligned, i.e. the first value should be channel0_sample0 and
  86658. * the last value channelN_sampleM.
  86659. *
  86660. * Note that for either process call, each sample in the buffers should be a
  86661. * signed integer, right-justified to the resolution set by
  86662. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  86663. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  86664. *
  86665. * When the client is finished encoding data, it calls
  86666. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  86667. * data still in its input pipe, and call the metadata callback with the
  86668. * final encoding statistics. Then the instance may be deleted with
  86669. * FLAC__stream_encoder_delete() or initialized again to encode another
  86670. * stream.
  86671. *
  86672. * For programs that write their own metadata, but that do not know the
  86673. * actual metadata until after encoding, it is advantageous to instruct
  86674. * the encoder to write a PADDING block of the correct size, so that
  86675. * instead of rewriting the whole stream after encoding, the program can
  86676. * just overwrite the PADDING block. If only the maximum size of the
  86677. * metadata is known, the program can write a slightly larger padding
  86678. * block, then split it after encoding.
  86679. *
  86680. * Make sure you understand how lengths are calculated. All FLAC metadata
  86681. * blocks have a 4 byte header which contains the type and length. This
  86682. * length does not include the 4 bytes of the header. See the format page
  86683. * for the specification of metadata blocks and their lengths.
  86684. *
  86685. * \note
  86686. * If you are writing the FLAC data to a file via callbacks, make sure it
  86687. * is open for update (e.g. mode "w+" for stdio streams). This is because
  86688. * after the first encoding pass, the encoder will try to seek back to the
  86689. * beginning of the stream, to the STREAMINFO block, to write some data
  86690. * there. (If using FLAC__stream_encoder_init*_file() or
  86691. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  86692. *
  86693. * \note
  86694. * The "set" functions may only be called when the encoder is in the
  86695. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  86696. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  86697. * before FLAC__stream_encoder_init_*(). If this is the case they will
  86698. * return \c true, otherwise \c false.
  86699. *
  86700. * \note
  86701. * FLAC__stream_encoder_finish() resets all settings to the constructor
  86702. * defaults.
  86703. *
  86704. * \{
  86705. */
  86706. /** State values for a FLAC__StreamEncoder.
  86707. *
  86708. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  86709. *
  86710. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  86711. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  86712. * must be deleted with FLAC__stream_encoder_delete().
  86713. */
  86714. typedef enum {
  86715. FLAC__STREAM_ENCODER_OK = 0,
  86716. /**< The encoder is in the normal OK state and samples can be processed. */
  86717. FLAC__STREAM_ENCODER_UNINITIALIZED,
  86718. /**< The encoder is in the uninitialized state; one of the
  86719. * FLAC__stream_encoder_init_*() functions must be called before samples
  86720. * can be processed.
  86721. */
  86722. FLAC__STREAM_ENCODER_OGG_ERROR,
  86723. /**< An error occurred in the underlying Ogg layer. */
  86724. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  86725. /**< An error occurred in the underlying verify stream decoder;
  86726. * check FLAC__stream_encoder_get_verify_decoder_state().
  86727. */
  86728. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  86729. /**< The verify decoder detected a mismatch between the original
  86730. * audio signal and the decoded audio signal.
  86731. */
  86732. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  86733. /**< One of the callbacks returned a fatal error. */
  86734. FLAC__STREAM_ENCODER_IO_ERROR,
  86735. /**< An I/O error occurred while opening/reading/writing a file.
  86736. * Check \c errno.
  86737. */
  86738. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  86739. /**< An error occurred while writing the stream; usually, the
  86740. * write_callback returned an error.
  86741. */
  86742. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  86743. /**< Memory allocation failed. */
  86744. } FLAC__StreamEncoderState;
  86745. /** Maps a FLAC__StreamEncoderState to a C string.
  86746. *
  86747. * Using a FLAC__StreamEncoderState as the index to this array
  86748. * will give the string equivalent. The contents should not be modified.
  86749. */
  86750. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  86751. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  86752. */
  86753. typedef enum {
  86754. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  86755. /**< Initialization was successful. */
  86756. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  86757. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  86758. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86759. /**< The library was not compiled with support for the given container
  86760. * format.
  86761. */
  86762. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  86763. /**< A required callback was not supplied. */
  86764. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  86765. /**< The encoder has an invalid setting for number of channels. */
  86766. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  86767. /**< The encoder has an invalid setting for bits-per-sample.
  86768. * FLAC supports 4-32 bps but the reference encoder currently supports
  86769. * only up to 24 bps.
  86770. */
  86771. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  86772. /**< The encoder has an invalid setting for the input sample rate. */
  86773. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  86774. /**< The encoder has an invalid setting for the block size. */
  86775. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  86776. /**< The encoder has an invalid setting for the maximum LPC order. */
  86777. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  86778. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  86779. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  86780. /**< The specified block size is less than the maximum LPC order. */
  86781. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  86782. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  86783. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  86784. /**< The metadata input to the encoder is invalid, in one of the following ways:
  86785. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  86786. * - One of the metadata blocks contains an undefined type
  86787. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  86788. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  86789. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  86790. */
  86791. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  86792. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  86793. * already initialized, usually because
  86794. * FLAC__stream_encoder_finish() was not called.
  86795. */
  86796. } FLAC__StreamEncoderInitStatus;
  86797. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  86798. *
  86799. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  86800. * will give the string equivalent. The contents should not be modified.
  86801. */
  86802. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  86803. /** Return values for the FLAC__StreamEncoder read callback.
  86804. */
  86805. typedef enum {
  86806. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  86807. /**< The read was OK and decoding can continue. */
  86808. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  86809. /**< The read was attempted at the end of the stream. */
  86810. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  86811. /**< An unrecoverable error occurred. */
  86812. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  86813. /**< Client does not support reading back from the output. */
  86814. } FLAC__StreamEncoderReadStatus;
  86815. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  86816. *
  86817. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  86818. * will give the string equivalent. The contents should not be modified.
  86819. */
  86820. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  86821. /** Return values for the FLAC__StreamEncoder write callback.
  86822. */
  86823. typedef enum {
  86824. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  86825. /**< The write was OK and encoding can continue. */
  86826. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  86827. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  86828. } FLAC__StreamEncoderWriteStatus;
  86829. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  86830. *
  86831. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  86832. * will give the string equivalent. The contents should not be modified.
  86833. */
  86834. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  86835. /** Return values for the FLAC__StreamEncoder seek callback.
  86836. */
  86837. typedef enum {
  86838. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  86839. /**< The seek was OK and encoding can continue. */
  86840. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  86841. /**< An unrecoverable error occurred. */
  86842. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86843. /**< Client does not support seeking. */
  86844. } FLAC__StreamEncoderSeekStatus;
  86845. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  86846. *
  86847. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  86848. * will give the string equivalent. The contents should not be modified.
  86849. */
  86850. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  86851. /** Return values for the FLAC__StreamEncoder tell callback.
  86852. */
  86853. typedef enum {
  86854. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  86855. /**< The tell was OK and encoding can continue. */
  86856. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  86857. /**< An unrecoverable error occurred. */
  86858. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86859. /**< Client does not support seeking. */
  86860. } FLAC__StreamEncoderTellStatus;
  86861. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  86862. *
  86863. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  86864. * will give the string equivalent. The contents should not be modified.
  86865. */
  86866. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  86867. /***********************************************************************
  86868. *
  86869. * class FLAC__StreamEncoder
  86870. *
  86871. ***********************************************************************/
  86872. struct FLAC__StreamEncoderProtected;
  86873. struct FLAC__StreamEncoderPrivate;
  86874. /** The opaque structure definition for the stream encoder type.
  86875. * See the \link flac_stream_encoder stream encoder module \endlink
  86876. * for a detailed description.
  86877. */
  86878. typedef struct {
  86879. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86880. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86881. } FLAC__StreamEncoder;
  86882. /** Signature for the read callback.
  86883. *
  86884. * A function pointer matching this signature must be passed to
  86885. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  86886. * The supplied function will be called when the encoder needs to read back
  86887. * encoded data. This happens during the metadata callback, when the encoder
  86888. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  86889. * while encoding. The address of the buffer to be filled is supplied, along
  86890. * with the number of bytes the buffer can hold. The callback may choose to
  86891. * supply less data and modify the byte count but must be careful not to
  86892. * overflow the buffer. The callback then returns a status code chosen from
  86893. * FLAC__StreamEncoderReadStatus.
  86894. *
  86895. * Here is an example of a read callback for stdio streams:
  86896. * \code
  86897. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86898. * {
  86899. * FILE *file = ((MyClientData*)client_data)->file;
  86900. * if(*bytes > 0) {
  86901. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86902. * if(ferror(file))
  86903. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86904. * else if(*bytes == 0)
  86905. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  86906. * else
  86907. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  86908. * }
  86909. * else
  86910. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86911. * }
  86912. * \endcode
  86913. *
  86914. * \note In general, FLAC__StreamEncoder functions which change the
  86915. * state should not be called on the \a encoder while in the callback.
  86916. *
  86917. * \param encoder The encoder instance calling the callback.
  86918. * \param buffer A pointer to a location for the callee to store
  86919. * data to be encoded.
  86920. * \param bytes A pointer to the size of the buffer. On entry
  86921. * to the callback, it contains the maximum number
  86922. * of bytes that may be stored in \a buffer. The
  86923. * callee must set it to the actual number of bytes
  86924. * stored (0 in case of error or end-of-stream) before
  86925. * returning.
  86926. * \param client_data The callee's client data set through
  86927. * FLAC__stream_encoder_set_client_data().
  86928. * \retval FLAC__StreamEncoderReadStatus
  86929. * The callee's return status.
  86930. */
  86931. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86932. /** Signature for the write callback.
  86933. *
  86934. * A function pointer matching this signature must be passed to
  86935. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86936. * by the encoder anytime there is raw encoded data ready to write. It may
  86937. * include metadata mixed with encoded audio frames and the data is not
  86938. * guaranteed to be aligned on frame or metadata block boundaries.
  86939. *
  86940. * The only duty of the callback is to write out the \a bytes worth of data
  86941. * in \a buffer to the current position in the output stream. The arguments
  86942. * \a samples and \a current_frame are purely informational. If \a samples
  86943. * is greater than \c 0, then \a current_frame will hold the current frame
  86944. * number that is being written; otherwise it indicates that the write
  86945. * callback is being called to write metadata.
  86946. *
  86947. * \note
  86948. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  86949. * write callback will be called twice when writing each audio
  86950. * frame; once for the page header, and once for the page body.
  86951. * When writing the page header, the \a samples argument to the
  86952. * write callback will be \c 0.
  86953. *
  86954. * \note In general, FLAC__StreamEncoder functions which change the
  86955. * state should not be called on the \a encoder while in the callback.
  86956. *
  86957. * \param encoder The encoder instance calling the callback.
  86958. * \param buffer An array of encoded data of length \a bytes.
  86959. * \param bytes The byte length of \a buffer.
  86960. * \param samples The number of samples encoded by \a buffer.
  86961. * \c 0 has a special meaning; see above.
  86962. * \param current_frame The number of the current frame being encoded.
  86963. * \param client_data The callee's client data set through
  86964. * FLAC__stream_encoder_init_*().
  86965. * \retval FLAC__StreamEncoderWriteStatus
  86966. * The callee's return status.
  86967. */
  86968. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  86969. /** Signature for the seek callback.
  86970. *
  86971. * A function pointer matching this signature may be passed to
  86972. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86973. * when the encoder needs to seek the output stream. The encoder will pass
  86974. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  86975. *
  86976. * Here is an example of a seek callback for stdio streams:
  86977. * \code
  86978. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86979. * {
  86980. * FILE *file = ((MyClientData*)client_data)->file;
  86981. * if(file == stdin)
  86982. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  86983. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86984. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  86985. * else
  86986. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  86987. * }
  86988. * \endcode
  86989. *
  86990. * \note In general, FLAC__StreamEncoder functions which change the
  86991. * state should not be called on the \a encoder while in the callback.
  86992. *
  86993. * \param encoder The encoder instance calling the callback.
  86994. * \param absolute_byte_offset The offset from the beginning of the stream
  86995. * to seek to.
  86996. * \param client_data The callee's client data set through
  86997. * FLAC__stream_encoder_init_*().
  86998. * \retval FLAC__StreamEncoderSeekStatus
  86999. * The callee's return status.
  87000. */
  87001. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  87002. /** Signature for the tell callback.
  87003. *
  87004. * A function pointer matching this signature may be passed to
  87005. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87006. * when the encoder needs to know the current position of the output stream.
  87007. *
  87008. * \warning
  87009. * The callback must return the true current byte offset of the output to
  87010. * which the encoder is writing. If you are buffering the output, make
  87011. * sure and take this into account. If you are writing directly to a
  87012. * FILE* from your write callback, ftell() is sufficient. If you are
  87013. * writing directly to a file descriptor from your write callback, you
  87014. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  87015. * these points to rewrite metadata after encoding.
  87016. *
  87017. * Here is an example of a tell callback for stdio streams:
  87018. * \code
  87019. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  87020. * {
  87021. * FILE *file = ((MyClientData*)client_data)->file;
  87022. * off_t pos;
  87023. * if(file == stdin)
  87024. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  87025. * else if((pos = ftello(file)) < 0)
  87026. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  87027. * else {
  87028. * *absolute_byte_offset = (FLAC__uint64)pos;
  87029. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  87030. * }
  87031. * }
  87032. * \endcode
  87033. *
  87034. * \note In general, FLAC__StreamEncoder functions which change the
  87035. * state should not be called on the \a encoder while in the callback.
  87036. *
  87037. * \param encoder The encoder instance calling the callback.
  87038. * \param absolute_byte_offset The address at which to store the current
  87039. * position of the output.
  87040. * \param client_data The callee's client data set through
  87041. * FLAC__stream_encoder_init_*().
  87042. * \retval FLAC__StreamEncoderTellStatus
  87043. * The callee's return status.
  87044. */
  87045. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  87046. /** Signature for the metadata callback.
  87047. *
  87048. * A function pointer matching this signature may be passed to
  87049. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  87050. * once at the end of encoding with the populated STREAMINFO structure. This
  87051. * is so the client can seek back to the beginning of the file and write the
  87052. * STREAMINFO block with the correct statistics after encoding (like
  87053. * minimum/maximum frame size and total samples).
  87054. *
  87055. * \note In general, FLAC__StreamEncoder functions which change the
  87056. * state should not be called on the \a encoder while in the callback.
  87057. *
  87058. * \param encoder The encoder instance calling the callback.
  87059. * \param metadata The final populated STREAMINFO block.
  87060. * \param client_data The callee's client data set through
  87061. * FLAC__stream_encoder_init_*().
  87062. */
  87063. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  87064. /** Signature for the progress callback.
  87065. *
  87066. * A function pointer matching this signature may be passed to
  87067. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  87068. * The supplied function will be called when the encoder has finished
  87069. * writing a frame. The \c total_frames_estimate argument to the
  87070. * callback will be based on the value from
  87071. * FLAC__stream_encoder_set_total_samples_estimate().
  87072. *
  87073. * \note In general, FLAC__StreamEncoder functions which change the
  87074. * state should not be called on the \a encoder while in the callback.
  87075. *
  87076. * \param encoder The encoder instance calling the callback.
  87077. * \param bytes_written Bytes written so far.
  87078. * \param samples_written Samples written so far.
  87079. * \param frames_written Frames written so far.
  87080. * \param total_frames_estimate The estimate of the total number of
  87081. * frames to be written.
  87082. * \param client_data The callee's client data set through
  87083. * FLAC__stream_encoder_init_*().
  87084. */
  87085. 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);
  87086. /***********************************************************************
  87087. *
  87088. * Class constructor/destructor
  87089. *
  87090. ***********************************************************************/
  87091. /** Create a new stream encoder instance. The instance is created with
  87092. * default settings; see the individual FLAC__stream_encoder_set_*()
  87093. * functions for each setting's default.
  87094. *
  87095. * \retval FLAC__StreamEncoder*
  87096. * \c NULL if there was an error allocating memory, else the new instance.
  87097. */
  87098. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  87099. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  87100. *
  87101. * \param encoder A pointer to an existing encoder.
  87102. * \assert
  87103. * \code encoder != NULL \endcode
  87104. */
  87105. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  87106. /***********************************************************************
  87107. *
  87108. * Public class method prototypes
  87109. *
  87110. ***********************************************************************/
  87111. /** Set the serial number for the FLAC stream to use in the Ogg container.
  87112. *
  87113. * \note
  87114. * This does not need to be set for native FLAC encoding.
  87115. *
  87116. * \note
  87117. * It is recommended to set a serial number explicitly as the default of '0'
  87118. * may collide with other streams.
  87119. *
  87120. * \default \c 0
  87121. * \param encoder An encoder instance to set.
  87122. * \param serial_number See above.
  87123. * \assert
  87124. * \code encoder != NULL \endcode
  87125. * \retval FLAC__bool
  87126. * \c false if the encoder is already initialized, else \c true.
  87127. */
  87128. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  87129. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  87130. * encoded output by feeding it through an internal decoder and comparing
  87131. * the original signal against the decoded signal. If a mismatch occurs,
  87132. * the process call will return \c false. Note that this will slow the
  87133. * encoding process by the extra time required for decoding and comparison.
  87134. *
  87135. * \default \c false
  87136. * \param encoder An encoder instance to set.
  87137. * \param value Flag value (see above).
  87138. * \assert
  87139. * \code encoder != NULL \endcode
  87140. * \retval FLAC__bool
  87141. * \c false if the encoder is already initialized, else \c true.
  87142. */
  87143. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87144. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  87145. * the encoder will comply with the Subset and will check the
  87146. * settings during FLAC__stream_encoder_init_*() to see if all settings
  87147. * comply. If \c false, the settings may take advantage of the full
  87148. * range that the format allows.
  87149. *
  87150. * Make sure you know what it entails before setting this to \c false.
  87151. *
  87152. * \default \c true
  87153. * \param encoder An encoder instance to set.
  87154. * \param value Flag value (see above).
  87155. * \assert
  87156. * \code encoder != NULL \endcode
  87157. * \retval FLAC__bool
  87158. * \c false if the encoder is already initialized, else \c true.
  87159. */
  87160. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87161. /** Set the number of channels to be encoded.
  87162. *
  87163. * \default \c 2
  87164. * \param encoder An encoder instance to set.
  87165. * \param value See above.
  87166. * \assert
  87167. * \code encoder != NULL \endcode
  87168. * \retval FLAC__bool
  87169. * \c false if the encoder is already initialized, else \c true.
  87170. */
  87171. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  87172. /** Set the sample resolution of the input to be encoded.
  87173. *
  87174. * \warning
  87175. * Do not feed the encoder data that is wider than the value you
  87176. * set here or you will generate an invalid stream.
  87177. *
  87178. * \default \c 16
  87179. * \param encoder An encoder instance to set.
  87180. * \param value See above.
  87181. * \assert
  87182. * \code encoder != NULL \endcode
  87183. * \retval FLAC__bool
  87184. * \c false if the encoder is already initialized, else \c true.
  87185. */
  87186. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  87187. /** Set the sample rate (in Hz) of the input to be encoded.
  87188. *
  87189. * \default \c 44100
  87190. * \param encoder An encoder instance to set.
  87191. * \param value See above.
  87192. * \assert
  87193. * \code encoder != NULL \endcode
  87194. * \retval FLAC__bool
  87195. * \c false if the encoder is already initialized, else \c true.
  87196. */
  87197. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  87198. /** Set the compression level
  87199. *
  87200. * The compression level is roughly proportional to the amount of effort
  87201. * the encoder expends to compress the file. A higher level usually
  87202. * means more computation but higher compression. The default level is
  87203. * suitable for most applications.
  87204. *
  87205. * Currently the levels range from \c 0 (fastest, least compression) to
  87206. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  87207. * treated as \c 8.
  87208. *
  87209. * This function automatically calls the following other \c _set_
  87210. * functions with appropriate values, so the client does not need to
  87211. * unless it specifically wants to override them:
  87212. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  87213. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  87214. * - FLAC__stream_encoder_set_apodization()
  87215. * - FLAC__stream_encoder_set_max_lpc_order()
  87216. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  87217. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  87218. * - FLAC__stream_encoder_set_do_escape_coding()
  87219. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  87220. * - FLAC__stream_encoder_set_min_residual_partition_order()
  87221. * - FLAC__stream_encoder_set_max_residual_partition_order()
  87222. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  87223. *
  87224. * The actual values set for each level are:
  87225. * <table>
  87226. * <tr>
  87227. * <td><b>level</b><td>
  87228. * <td>do mid-side stereo<td>
  87229. * <td>loose mid-side stereo<td>
  87230. * <td>apodization<td>
  87231. * <td>max lpc order<td>
  87232. * <td>qlp coeff precision<td>
  87233. * <td>qlp coeff prec search<td>
  87234. * <td>escape coding<td>
  87235. * <td>exhaustive model search<td>
  87236. * <td>min residual partition order<td>
  87237. * <td>max residual partition order<td>
  87238. * <td>rice parameter search dist<td>
  87239. * </tr>
  87240. * <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>
  87241. * <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>
  87242. * <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>
  87243. * <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>
  87244. * <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>
  87245. * <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>
  87246. * <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>
  87247. * <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>
  87248. * <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>
  87249. * </table>
  87250. *
  87251. * \default \c 5
  87252. * \param encoder An encoder instance to set.
  87253. * \param 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_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  87260. /** Set the blocksize to use while encoding.
  87261. *
  87262. * The number of samples to use per frame. Use \c 0 to let the encoder
  87263. * estimate a blocksize; this is usually best.
  87264. *
  87265. * \default \c 0
  87266. * \param encoder An encoder instance to set.
  87267. * \param value See above.
  87268. * \assert
  87269. * \code encoder != NULL \endcode
  87270. * \retval FLAC__bool
  87271. * \c false if the encoder is already initialized, else \c true.
  87272. */
  87273. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  87274. /** Set to \c true to enable mid-side encoding on stereo input. The
  87275. * number of channels must be 2 for this to have any effect. Set to
  87276. * \c false to use only independent channel coding.
  87277. *
  87278. * \default \c false
  87279. * \param encoder An encoder instance to set.
  87280. * \param value Flag value (see above).
  87281. * \assert
  87282. * \code encoder != NULL \endcode
  87283. * \retval FLAC__bool
  87284. * \c false if the encoder is already initialized, else \c true.
  87285. */
  87286. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87287. /** Set to \c true to enable adaptive switching between mid-side and
  87288. * left-right encoding on stereo input. Set to \c false to use
  87289. * exhaustive searching. Setting this to \c true requires
  87290. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  87291. * \c true in order to have any effect.
  87292. *
  87293. * \default \c false
  87294. * \param encoder An encoder instance to set.
  87295. * \param value Flag value (see above).
  87296. * \assert
  87297. * \code encoder != NULL \endcode
  87298. * \retval FLAC__bool
  87299. * \c false if the encoder is already initialized, else \c true.
  87300. */
  87301. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87302. /** Sets the apodization function(s) the encoder will use when windowing
  87303. * audio data for LPC analysis.
  87304. *
  87305. * The \a specification is a plain ASCII string which specifies exactly
  87306. * which functions to use. There may be more than one (up to 32),
  87307. * separated by \c ';' characters. Some functions take one or more
  87308. * comma-separated arguments in parentheses.
  87309. *
  87310. * The available functions are \c bartlett, \c bartlett_hann,
  87311. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  87312. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  87313. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  87314. *
  87315. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  87316. * (0<STDDEV<=0.5).
  87317. *
  87318. * For \c tukey(P), P specifies the fraction of the window that is
  87319. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  87320. * corresponds to \c hann.
  87321. *
  87322. * Example specifications are \c "blackman" or
  87323. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  87324. *
  87325. * Any function that is specified erroneously is silently dropped. Up
  87326. * to 32 functions are kept, the rest are dropped. If the specification
  87327. * is empty the encoder defaults to \c "tukey(0.5)".
  87328. *
  87329. * When more than one function is specified, then for every subframe the
  87330. * encoder will try each of them separately and choose the window that
  87331. * results in the smallest compressed subframe.
  87332. *
  87333. * Note that each function specified causes the encoder to occupy a
  87334. * floating point array in which to store the window.
  87335. *
  87336. * \default \c "tukey(0.5)"
  87337. * \param encoder An encoder instance to set.
  87338. * \param specification See above.
  87339. * \assert
  87340. * \code encoder != NULL \endcode
  87341. * \code specification != NULL \endcode
  87342. * \retval FLAC__bool
  87343. * \c false if the encoder is already initialized, else \c true.
  87344. */
  87345. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  87346. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  87347. *
  87348. * \default \c 0
  87349. * \param encoder An encoder instance to set.
  87350. * \param value See above.
  87351. * \assert
  87352. * \code encoder != NULL \endcode
  87353. * \retval FLAC__bool
  87354. * \c false if the encoder is already initialized, else \c true.
  87355. */
  87356. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  87357. /** Set the precision, in bits, of the quantized linear predictor
  87358. * coefficients, or \c 0 to let the encoder select it based on the
  87359. * blocksize.
  87360. *
  87361. * \note
  87362. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  87363. * be less than 32.
  87364. *
  87365. * \default \c 0
  87366. * \param encoder An encoder instance to set.
  87367. * \param value See above.
  87368. * \assert
  87369. * \code encoder != NULL \endcode
  87370. * \retval FLAC__bool
  87371. * \c false if the encoder is already initialized, else \c true.
  87372. */
  87373. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  87374. /** Set to \c false to use only the specified quantized linear predictor
  87375. * coefficient precision, or \c true to search neighboring precision
  87376. * values and use the best one.
  87377. *
  87378. * \default \c false
  87379. * \param encoder An encoder instance to set.
  87380. * \param value See above.
  87381. * \assert
  87382. * \code encoder != NULL \endcode
  87383. * \retval FLAC__bool
  87384. * \c false if the encoder is already initialized, else \c true.
  87385. */
  87386. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87387. /** Deprecated. Setting this value has no effect.
  87388. *
  87389. * \default \c false
  87390. * \param encoder An encoder instance to set.
  87391. * \param value See above.
  87392. * \assert
  87393. * \code encoder != NULL \endcode
  87394. * \retval FLAC__bool
  87395. * \c false if the encoder is already initialized, else \c true.
  87396. */
  87397. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87398. /** Set to \c false to let the encoder estimate the best model order
  87399. * based on the residual signal energy, or \c true to force the
  87400. * encoder to evaluate all order models and select the best.
  87401. *
  87402. * \default \c false
  87403. * \param encoder An encoder instance to set.
  87404. * \param value See above.
  87405. * \assert
  87406. * \code encoder != NULL \endcode
  87407. * \retval FLAC__bool
  87408. * \c false if the encoder is already initialized, else \c true.
  87409. */
  87410. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87411. /** Set the minimum partition order to search when coding the residual.
  87412. * This is used in tandem with
  87413. * FLAC__stream_encoder_set_max_residual_partition_order().
  87414. *
  87415. * The partition order determines the context size in the residual.
  87416. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87417. *
  87418. * Set both min and max values to \c 0 to force a single context,
  87419. * whose Rice parameter is based on the residual signal variance.
  87420. * Otherwise, set a min and max order, and the encoder will search
  87421. * all orders, using the mean of each context for its Rice parameter,
  87422. * and use the best.
  87423. *
  87424. * \default \c 0
  87425. * \param encoder An encoder instance to set.
  87426. * \param value See above.
  87427. * \assert
  87428. * \code encoder != NULL \endcode
  87429. * \retval FLAC__bool
  87430. * \c false if the encoder is already initialized, else \c true.
  87431. */
  87432. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87433. /** Set the maximum partition order to search when coding the residual.
  87434. * This is used in tandem with
  87435. * FLAC__stream_encoder_set_min_residual_partition_order().
  87436. *
  87437. * The partition order determines the context size in the residual.
  87438. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87439. *
  87440. * Set both min and max values to \c 0 to force a single context,
  87441. * whose Rice parameter is based on the residual signal variance.
  87442. * Otherwise, set a min and max order, and the encoder will search
  87443. * all orders, using the mean of each context for its Rice parameter,
  87444. * and use the best.
  87445. *
  87446. * \default \c 0
  87447. * \param encoder An encoder instance to set.
  87448. * \param value See above.
  87449. * \assert
  87450. * \code encoder != NULL \endcode
  87451. * \retval FLAC__bool
  87452. * \c false if the encoder is already initialized, else \c true.
  87453. */
  87454. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87455. /** Deprecated. Setting this value has no effect.
  87456. *
  87457. * \default \c 0
  87458. * \param encoder An encoder instance to set.
  87459. * \param value See above.
  87460. * \assert
  87461. * \code encoder != NULL \endcode
  87462. * \retval FLAC__bool
  87463. * \c false if the encoder is already initialized, else \c true.
  87464. */
  87465. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  87466. /** Set an estimate of the total samples that will be encoded.
  87467. * This is merely an estimate and may be set to \c 0 if unknown.
  87468. * This value will be written to the STREAMINFO block before encoding,
  87469. * and can remove the need for the caller to rewrite the value later
  87470. * if the value is known before encoding.
  87471. *
  87472. * \default \c 0
  87473. * \param encoder An encoder instance to set.
  87474. * \param value See above.
  87475. * \assert
  87476. * \code encoder != NULL \endcode
  87477. * \retval FLAC__bool
  87478. * \c false if the encoder is already initialized, else \c true.
  87479. */
  87480. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  87481. /** Set the metadata blocks to be emitted to the stream before encoding.
  87482. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  87483. * array of pointers to metadata blocks. The array is non-const since
  87484. * the encoder may need to change the \a is_last flag inside them, and
  87485. * in some cases update seek point offsets. Otherwise, the encoder will
  87486. * not modify or free the blocks. It is up to the caller to free the
  87487. * metadata blocks after encoding finishes.
  87488. *
  87489. * \note
  87490. * The encoder stores only copies of the pointers in the \a metadata array;
  87491. * the metadata blocks themselves must survive at least until after
  87492. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  87493. *
  87494. * \note
  87495. * The STREAMINFO block is always written and no STREAMINFO block may
  87496. * occur in the supplied array.
  87497. *
  87498. * \note
  87499. * By default the encoder does not create a SEEKTABLE. If one is supplied
  87500. * in the \a metadata array, but the client has specified that it does not
  87501. * support seeking, then the SEEKTABLE will be written verbatim. However
  87502. * by itself this is not very useful as the client will not know the stream
  87503. * offsets for the seekpoints ahead of time. In order to get a proper
  87504. * seektable the client must support seeking. See next note.
  87505. *
  87506. * \note
  87507. * SEEKTABLE blocks are handled specially. Since you will not know
  87508. * the values for the seek point stream offsets, you should pass in
  87509. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  87510. * required sample numbers (or placeholder points), with \c 0 for the
  87511. * \a frame_samples and \a stream_offset fields for each point. If the
  87512. * client has specified that it supports seeking by providing a seek
  87513. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  87514. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  87515. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  87516. * then while it is encoding the encoder will fill the stream offsets in
  87517. * for you and when encoding is finished, it will seek back and write the
  87518. * real values into the SEEKTABLE block in the stream. There are helper
  87519. * routines for manipulating seektable template blocks; see metadata.h:
  87520. * FLAC__metadata_object_seektable_template_*(). If the client does
  87521. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  87522. * will slow down or remove the ability to seek in the FLAC stream.
  87523. *
  87524. * \note
  87525. * The encoder instance \b will modify the first \c SEEKTABLE block
  87526. * as it transforms the template to a valid seektable while encoding,
  87527. * but it is still up to the caller to free all metadata blocks after
  87528. * encoding.
  87529. *
  87530. * \note
  87531. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  87532. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  87533. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  87534. * will simply write it's own into the stream. If no VORBIS_COMMENT
  87535. * block is present in the \a metadata array, libFLAC will write an
  87536. * empty one, containing only the vendor string.
  87537. *
  87538. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  87539. * the second metadata block of the stream. The encoder already supplies
  87540. * the STREAMINFO block automatically. If \a metadata does not contain a
  87541. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  87542. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  87543. * first, the init function will reorder \a metadata by moving the
  87544. * VORBIS_COMMENT block to the front; the relative ordering of the other
  87545. * blocks will remain as they were.
  87546. *
  87547. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  87548. * stream to \c 65535. If \a num_blocks exceeds this the function will
  87549. * return \c false.
  87550. *
  87551. * \default \c NULL, 0
  87552. * \param encoder An encoder instance to set.
  87553. * \param metadata See above.
  87554. * \param num_blocks See above.
  87555. * \assert
  87556. * \code encoder != NULL \endcode
  87557. * \retval FLAC__bool
  87558. * \c false if the encoder is already initialized, else \c true.
  87559. * \c false if the encoder is already initialized, or if
  87560. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  87561. */
  87562. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  87563. /** Get the current encoder state.
  87564. *
  87565. * \param encoder An encoder instance to query.
  87566. * \assert
  87567. * \code encoder != NULL \endcode
  87568. * \retval FLAC__StreamEncoderState
  87569. * The current encoder state.
  87570. */
  87571. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  87572. /** Get the state of the verify stream decoder.
  87573. * Useful when the stream encoder state is
  87574. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  87575. *
  87576. * \param encoder An encoder instance to query.
  87577. * \assert
  87578. * \code encoder != NULL \endcode
  87579. * \retval FLAC__StreamDecoderState
  87580. * The verify stream decoder state.
  87581. */
  87582. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  87583. /** Get the current encoder state as a C string.
  87584. * This version automatically resolves
  87585. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  87586. * verify decoder's state.
  87587. *
  87588. * \param encoder A encoder instance to query.
  87589. * \assert
  87590. * \code encoder != NULL \endcode
  87591. * \retval const char *
  87592. * The encoder state as a C string. Do not modify the contents.
  87593. */
  87594. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  87595. /** Get relevant values about the nature of a verify decoder error.
  87596. * Useful when the stream encoder state is
  87597. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  87598. * be addresses in which the stats will be returned, or NULL if value
  87599. * is not desired.
  87600. *
  87601. * \param encoder An encoder instance to query.
  87602. * \param absolute_sample The absolute sample number of the mismatch.
  87603. * \param frame_number The number of the frame in which the mismatch occurred.
  87604. * \param channel The channel in which the mismatch occurred.
  87605. * \param sample The number of the sample (relative to the frame) in
  87606. * which the mismatch occurred.
  87607. * \param expected The expected value for the sample in question.
  87608. * \param got The actual value returned by the decoder.
  87609. * \assert
  87610. * \code encoder != NULL \endcode
  87611. */
  87612. 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);
  87613. /** Get the "verify" flag.
  87614. *
  87615. * \param encoder An encoder instance to query.
  87616. * \assert
  87617. * \code encoder != NULL \endcode
  87618. * \retval FLAC__bool
  87619. * See FLAC__stream_encoder_set_verify().
  87620. */
  87621. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  87622. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  87623. *
  87624. * \param encoder An encoder instance to query.
  87625. * \assert
  87626. * \code encoder != NULL \endcode
  87627. * \retval FLAC__bool
  87628. * See FLAC__stream_encoder_set_streamable_subset().
  87629. */
  87630. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  87631. /** Get the number of input channels being processed.
  87632. *
  87633. * \param encoder An encoder instance to query.
  87634. * \assert
  87635. * \code encoder != NULL \endcode
  87636. * \retval unsigned
  87637. * See FLAC__stream_encoder_set_channels().
  87638. */
  87639. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  87640. /** Get the input sample resolution setting.
  87641. *
  87642. * \param encoder An encoder instance to query.
  87643. * \assert
  87644. * \code encoder != NULL \endcode
  87645. * \retval unsigned
  87646. * See FLAC__stream_encoder_set_bits_per_sample().
  87647. */
  87648. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  87649. /** Get the input sample rate setting.
  87650. *
  87651. * \param encoder An encoder instance to query.
  87652. * \assert
  87653. * \code encoder != NULL \endcode
  87654. * \retval unsigned
  87655. * See FLAC__stream_encoder_set_sample_rate().
  87656. */
  87657. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  87658. /** Get the blocksize setting.
  87659. *
  87660. * \param encoder An encoder instance to query.
  87661. * \assert
  87662. * \code encoder != NULL \endcode
  87663. * \retval unsigned
  87664. * See FLAC__stream_encoder_set_blocksize().
  87665. */
  87666. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  87667. /** Get the "mid/side stereo coding" flag.
  87668. *
  87669. * \param encoder An encoder instance to query.
  87670. * \assert
  87671. * \code encoder != NULL \endcode
  87672. * \retval FLAC__bool
  87673. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  87674. */
  87675. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87676. /** Get the "adaptive mid/side switching" flag.
  87677. *
  87678. * \param encoder An encoder instance to query.
  87679. * \assert
  87680. * \code encoder != NULL \endcode
  87681. * \retval FLAC__bool
  87682. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  87683. */
  87684. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87685. /** Get the maximum LPC order setting.
  87686. *
  87687. * \param encoder An encoder instance to query.
  87688. * \assert
  87689. * \code encoder != NULL \endcode
  87690. * \retval unsigned
  87691. * See FLAC__stream_encoder_set_max_lpc_order().
  87692. */
  87693. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  87694. /** Get the quantized linear predictor coefficient precision setting.
  87695. *
  87696. * \param encoder An encoder instance to query.
  87697. * \assert
  87698. * \code encoder != NULL \endcode
  87699. * \retval unsigned
  87700. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  87701. */
  87702. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  87703. /** Get the qlp coefficient precision search flag.
  87704. *
  87705. * \param encoder An encoder instance to query.
  87706. * \assert
  87707. * \code encoder != NULL \endcode
  87708. * \retval FLAC__bool
  87709. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  87710. */
  87711. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  87712. /** Get the "escape coding" flag.
  87713. *
  87714. * \param encoder An encoder instance to query.
  87715. * \assert
  87716. * \code encoder != NULL \endcode
  87717. * \retval FLAC__bool
  87718. * See FLAC__stream_encoder_set_do_escape_coding().
  87719. */
  87720. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  87721. /** Get the exhaustive model search flag.
  87722. *
  87723. * \param encoder An encoder instance to query.
  87724. * \assert
  87725. * \code encoder != NULL \endcode
  87726. * \retval FLAC__bool
  87727. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  87728. */
  87729. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  87730. /** Get the minimum residual partition order setting.
  87731. *
  87732. * \param encoder An encoder instance to query.
  87733. * \assert
  87734. * \code encoder != NULL \endcode
  87735. * \retval unsigned
  87736. * See FLAC__stream_encoder_set_min_residual_partition_order().
  87737. */
  87738. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87739. /** Get maximum residual partition order setting.
  87740. *
  87741. * \param encoder An encoder instance to query.
  87742. * \assert
  87743. * \code encoder != NULL \endcode
  87744. * \retval unsigned
  87745. * See FLAC__stream_encoder_set_max_residual_partition_order().
  87746. */
  87747. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87748. /** Get the Rice parameter search distance setting.
  87749. *
  87750. * \param encoder An encoder instance to query.
  87751. * \assert
  87752. * \code encoder != NULL \endcode
  87753. * \retval unsigned
  87754. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  87755. */
  87756. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  87757. /** Get the previously set estimate of the total samples to be encoded.
  87758. * The encoder merely mimics back the value given to
  87759. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  87760. * other way of knowing how many samples the client will encode.
  87761. *
  87762. * \param encoder An encoder instance to set.
  87763. * \assert
  87764. * \code encoder != NULL \endcode
  87765. * \retval FLAC__uint64
  87766. * See FLAC__stream_encoder_get_total_samples_estimate().
  87767. */
  87768. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  87769. /** Initialize the encoder instance to encode native FLAC streams.
  87770. *
  87771. * This flavor of initialization sets up the encoder to encode to a
  87772. * native FLAC stream. I/O is performed via callbacks to the client.
  87773. * For encoding to a plain file via filename or open \c FILE*,
  87774. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  87775. * provide a simpler interface.
  87776. *
  87777. * This function should be called after FLAC__stream_encoder_new() and
  87778. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87779. * or FLAC__stream_encoder_process_interleaved().
  87780. * initialization succeeded.
  87781. *
  87782. * The call to FLAC__stream_encoder_init_stream() currently will also
  87783. * immediately call the write callback several times, once with the \c fLaC
  87784. * signature, and once for each encoded metadata block.
  87785. *
  87786. * \param encoder An uninitialized encoder instance.
  87787. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87788. * pointer must not be \c NULL.
  87789. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87790. * pointer may be \c NULL if seeking is not
  87791. * supported. The encoder uses seeking to go back
  87792. * and write some some stream statistics to the
  87793. * STREAMINFO block; this is recommended but not
  87794. * necessary to create a valid FLAC stream. If
  87795. * \a seek_callback is not \c NULL then a
  87796. * \a tell_callback must also be supplied.
  87797. * Alternatively, a dummy seek callback that just
  87798. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87799. * may also be supplied, all though this is slightly
  87800. * less efficient for the encoder.
  87801. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87802. * pointer may be \c NULL if seeking is not
  87803. * supported. If \a seek_callback is \c NULL then
  87804. * this argument will be ignored. If
  87805. * \a seek_callback is not \c NULL then a
  87806. * \a tell_callback must also be supplied.
  87807. * Alternatively, a dummy tell callback that just
  87808. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87809. * may also be supplied, all though this is slightly
  87810. * less efficient for the encoder.
  87811. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87812. * pointer may be \c NULL if the callback is not
  87813. * desired. If the client provides a seek callback,
  87814. * this function is not necessary as the encoder
  87815. * will automatically seek back and update the
  87816. * STREAMINFO block. It may also be \c NULL if the
  87817. * client does not support seeking, since it will
  87818. * have no way of going back to update the
  87819. * STREAMINFO. However the client can still supply
  87820. * a callback if it would like to know the details
  87821. * from the STREAMINFO.
  87822. * \param client_data This value will be supplied to callbacks in their
  87823. * \a client_data argument.
  87824. * \assert
  87825. * \code encoder != NULL \endcode
  87826. * \retval FLAC__StreamEncoderInitStatus
  87827. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87828. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87829. */
  87830. 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);
  87831. /** Initialize the encoder instance to encode Ogg FLAC streams.
  87832. *
  87833. * This flavor of initialization sets up the encoder to encode to a FLAC
  87834. * stream in an Ogg container. I/O is performed via callbacks to the
  87835. * client. For encoding to a plain file via filename or open \c FILE*,
  87836. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  87837. * provide a simpler interface.
  87838. *
  87839. * This function should be called after FLAC__stream_encoder_new() and
  87840. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87841. * or FLAC__stream_encoder_process_interleaved().
  87842. * initialization succeeded.
  87843. *
  87844. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  87845. * immediately call the write callback several times to write the metadata
  87846. * packets.
  87847. *
  87848. * \param encoder An uninitialized encoder instance.
  87849. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  87850. * pointer must not be \c NULL if \a seek_callback
  87851. * is non-NULL since they are both needed to be
  87852. * able to write data back to the Ogg FLAC stream
  87853. * in the post-encode phase.
  87854. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87855. * pointer must not be \c NULL.
  87856. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87857. * pointer may be \c NULL if seeking is not
  87858. * supported. The encoder uses seeking to go back
  87859. * and write some some stream statistics to the
  87860. * STREAMINFO block; this is recommended but not
  87861. * necessary to create a valid FLAC stream. If
  87862. * \a seek_callback is not \c NULL then a
  87863. * \a tell_callback must also be supplied.
  87864. * Alternatively, a dummy seek callback that just
  87865. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87866. * may also be supplied, all though this is slightly
  87867. * less efficient for the encoder.
  87868. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87869. * pointer may be \c NULL if seeking is not
  87870. * supported. If \a seek_callback is \c NULL then
  87871. * this argument will be ignored. If
  87872. * \a seek_callback is not \c NULL then a
  87873. * \a tell_callback must also be supplied.
  87874. * Alternatively, a dummy tell callback that just
  87875. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87876. * may also be supplied, all though this is slightly
  87877. * less efficient for the encoder.
  87878. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87879. * pointer may be \c NULL if the callback is not
  87880. * desired. If the client provides a seek callback,
  87881. * this function is not necessary as the encoder
  87882. * will automatically seek back and update the
  87883. * STREAMINFO block. It may also be \c NULL if the
  87884. * client does not support seeking, since it will
  87885. * have no way of going back to update the
  87886. * STREAMINFO. However the client can still supply
  87887. * a callback if it would like to know the details
  87888. * from the STREAMINFO.
  87889. * \param client_data This value will be supplied to callbacks in their
  87890. * \a client_data argument.
  87891. * \assert
  87892. * \code encoder != NULL \endcode
  87893. * \retval FLAC__StreamEncoderInitStatus
  87894. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87895. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87896. */
  87897. 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);
  87898. /** Initialize the encoder instance to encode native FLAC files.
  87899. *
  87900. * This flavor of initialization sets up the encoder to encode to a
  87901. * plain native FLAC file. For non-stdio streams, you must use
  87902. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  87903. *
  87904. * This function should be called after FLAC__stream_encoder_new() and
  87905. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87906. * or FLAC__stream_encoder_process_interleaved().
  87907. * initialization succeeded.
  87908. *
  87909. * \param encoder An uninitialized encoder instance.
  87910. * \param file An open file. The file should have been opened
  87911. * with mode \c "w+b" and rewound. The file
  87912. * becomes owned by the encoder and should not be
  87913. * manipulated by the client while encoding.
  87914. * Unless \a file is \c stdout, it will be closed
  87915. * when FLAC__stream_encoder_finish() is called.
  87916. * Note however that a proper SEEKTABLE cannot be
  87917. * created when encoding to \c stdout since it is
  87918. * not seekable.
  87919. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87920. * pointer may be \c NULL if the callback is not
  87921. * desired.
  87922. * \param client_data This value will be supplied to callbacks in their
  87923. * \a client_data argument.
  87924. * \assert
  87925. * \code encoder != NULL \endcode
  87926. * \code file != NULL \endcode
  87927. * \retval FLAC__StreamEncoderInitStatus
  87928. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87929. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87930. */
  87931. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87932. /** Initialize the encoder instance to encode Ogg FLAC files.
  87933. *
  87934. * This flavor of initialization sets up the encoder to encode to a
  87935. * plain Ogg FLAC file. For non-stdio streams, you must use
  87936. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  87937. *
  87938. * This function should be called after FLAC__stream_encoder_new() and
  87939. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87940. * or FLAC__stream_encoder_process_interleaved().
  87941. * initialization succeeded.
  87942. *
  87943. * \param encoder An uninitialized encoder instance.
  87944. * \param file An open file. The file should have been opened
  87945. * with mode \c "w+b" and rewound. The file
  87946. * becomes owned by the encoder and should not be
  87947. * manipulated by the client while encoding.
  87948. * Unless \a file is \c stdout, it will be closed
  87949. * when FLAC__stream_encoder_finish() is called.
  87950. * Note however that a proper SEEKTABLE cannot be
  87951. * created when encoding to \c stdout since it is
  87952. * not seekable.
  87953. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87954. * pointer may be \c NULL if the callback is not
  87955. * desired.
  87956. * \param client_data This value will be supplied to callbacks in their
  87957. * \a client_data argument.
  87958. * \assert
  87959. * \code encoder != NULL \endcode
  87960. * \code file != NULL \endcode
  87961. * \retval FLAC__StreamEncoderInitStatus
  87962. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87963. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87964. */
  87965. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87966. /** Initialize the encoder instance to encode native FLAC files.
  87967. *
  87968. * This flavor of initialization sets up the encoder to encode to a plain
  87969. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87970. * with Unicode filenames on Windows), you must use
  87971. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  87972. * and provide callbacks for the I/O.
  87973. *
  87974. * This function should be called after FLAC__stream_encoder_new() and
  87975. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87976. * or FLAC__stream_encoder_process_interleaved().
  87977. * initialization succeeded.
  87978. *
  87979. * \param encoder An uninitialized encoder instance.
  87980. * \param filename The name of the file to encode to. The file will
  87981. * be opened with fopen(). Use \c NULL to encode to
  87982. * \c stdout. Note however that a proper SEEKTABLE
  87983. * cannot be created when encoding to \c stdout since
  87984. * it is not seekable.
  87985. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87986. * pointer may be \c NULL if the callback is not
  87987. * desired.
  87988. * \param client_data This value will be supplied to callbacks in their
  87989. * \a client_data argument.
  87990. * \assert
  87991. * \code encoder != NULL \endcode
  87992. * \retval FLAC__StreamEncoderInitStatus
  87993. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87994. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87995. */
  87996. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87997. /** Initialize the encoder instance to encode Ogg FLAC files.
  87998. *
  87999. * This flavor of initialization sets up the encoder to encode to a plain
  88000. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  88001. * with Unicode filenames on Windows), you must use
  88002. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  88003. * and provide callbacks for the I/O.
  88004. *
  88005. * This function should be called after FLAC__stream_encoder_new() and
  88006. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  88007. * or FLAC__stream_encoder_process_interleaved().
  88008. * initialization succeeded.
  88009. *
  88010. * \param encoder An uninitialized encoder instance.
  88011. * \param filename The name of the file to encode to. The file will
  88012. * be opened with fopen(). Use \c NULL to encode to
  88013. * \c stdout. Note however that a proper SEEKTABLE
  88014. * cannot be created when encoding to \c stdout since
  88015. * it is not seekable.
  88016. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  88017. * pointer may be \c NULL if the callback is not
  88018. * desired.
  88019. * \param client_data This value will be supplied to callbacks in their
  88020. * \a client_data argument.
  88021. * \assert
  88022. * \code encoder != NULL \endcode
  88023. * \retval FLAC__StreamEncoderInitStatus
  88024. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  88025. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  88026. */
  88027. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  88028. /** Finish the encoding process.
  88029. * Flushes the encoding buffer, releases resources, resets the encoder
  88030. * settings to their defaults, and returns the encoder state to
  88031. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  88032. * one or more write callbacks before returning, and will generate
  88033. * a metadata callback.
  88034. *
  88035. * Note that in the course of processing the last frame, errors can
  88036. * occur, so the caller should be sure to check the return value to
  88037. * ensure the file was encoded properly.
  88038. *
  88039. * In the event of a prematurely-terminated encode, it is not strictly
  88040. * necessary to call this immediately before FLAC__stream_encoder_delete()
  88041. * but it is good practice to match every FLAC__stream_encoder_init_*()
  88042. * with a FLAC__stream_encoder_finish().
  88043. *
  88044. * \param encoder An uninitialized encoder instance.
  88045. * \assert
  88046. * \code encoder != NULL \endcode
  88047. * \retval FLAC__bool
  88048. * \c false if an error occurred processing the last frame; or if verify
  88049. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  88050. * verify mismatch; else \c true. If \c false, caller should check the
  88051. * state with FLAC__stream_encoder_get_state() for more information
  88052. * about the error.
  88053. */
  88054. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  88055. /** Submit data for encoding.
  88056. * This version allows you to supply the input data via an array of
  88057. * pointers, each pointer pointing to an array of \a samples samples
  88058. * representing one channel. The samples need not be block-aligned,
  88059. * but each channel should have the same number of samples. Each sample
  88060. * should be a signed integer, right-justified to the resolution set by
  88061. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88062. * resolution is 16 bits per sample, the samples should all be in the
  88063. * range [-32768,32767].
  88064. *
  88065. * For applications where channel order is important, channels must
  88066. * follow the order as described in the
  88067. * <A HREF="../format.html#frame_header">frame header</A>.
  88068. *
  88069. * \param encoder An initialized encoder instance in the OK state.
  88070. * \param buffer An array of pointers to each channel's signal.
  88071. * \param samples The number of samples in one channel.
  88072. * \assert
  88073. * \code encoder != NULL \endcode
  88074. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88075. * \retval FLAC__bool
  88076. * \c true if successful, else \c false; in this case, check the
  88077. * encoder state with FLAC__stream_encoder_get_state() to see what
  88078. * went wrong.
  88079. */
  88080. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  88081. /** Submit data for encoding.
  88082. * This version allows you to supply the input data where the channels
  88083. * are interleaved into a single array (i.e. channel0_sample0,
  88084. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  88085. * The samples need not be block-aligned but they must be
  88086. * sample-aligned, i.e. the first value should be channel0_sample0
  88087. * and the last value channelN_sampleM. Each sample should be a signed
  88088. * integer, right-justified to the resolution set by
  88089. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  88090. * resolution is 16 bits per sample, the samples should all be in the
  88091. * range [-32768,32767].
  88092. *
  88093. * For applications where channel order is important, channels must
  88094. * follow the order as described in the
  88095. * <A HREF="../format.html#frame_header">frame header</A>.
  88096. *
  88097. * \param encoder An initialized encoder instance in the OK state.
  88098. * \param buffer An array of channel-interleaved data (see above).
  88099. * \param samples The number of samples in one channel, the same as for
  88100. * FLAC__stream_encoder_process(). For example, if
  88101. * encoding two channels, \c 1000 \a samples corresponds
  88102. * to a \a buffer of 2000 values.
  88103. * \assert
  88104. * \code encoder != NULL \endcode
  88105. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  88106. * \retval FLAC__bool
  88107. * \c true if successful, else \c false; in this case, check the
  88108. * encoder state with FLAC__stream_encoder_get_state() to see what
  88109. * went wrong.
  88110. */
  88111. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  88112. /* \} */
  88113. #ifdef __cplusplus
  88114. }
  88115. #endif
  88116. #endif
  88117. /********* End of inlined file: stream_encoder.h *********/
  88118. #ifdef _MSC_VER
  88119. /* OPT: an MSVC built-in would be better */
  88120. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  88121. {
  88122. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  88123. return (x>>16) | (x<<16);
  88124. }
  88125. #endif
  88126. #if defined(_MSC_VER) && defined(_X86_)
  88127. /* OPT: an MSVC built-in would be better */
  88128. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  88129. {
  88130. __asm {
  88131. mov edx, start
  88132. mov ecx, len
  88133. test ecx, ecx
  88134. loop1:
  88135. jz done1
  88136. mov eax, [edx]
  88137. bswap eax
  88138. mov [edx], eax
  88139. add edx, 4
  88140. dec ecx
  88141. jmp short loop1
  88142. done1:
  88143. }
  88144. }
  88145. #endif
  88146. /** \mainpage
  88147. *
  88148. * \section intro Introduction
  88149. *
  88150. * This is the documentation for the FLAC C and C++ APIs. It is
  88151. * highly interconnected; this introduction should give you a top
  88152. * level idea of the structure and how to find the information you
  88153. * need. As a prerequisite you should have at least a basic
  88154. * knowledge of the FLAC format, documented
  88155. * <A HREF="../format.html">here</A>.
  88156. *
  88157. * \section c_api FLAC C API
  88158. *
  88159. * The FLAC C API is the interface to libFLAC, a set of structures
  88160. * describing the components of FLAC streams, and functions for
  88161. * encoding and decoding streams, as well as manipulating FLAC
  88162. * metadata in files. The public include files will be installed
  88163. * in your include area (for example /usr/include/FLAC/...).
  88164. *
  88165. * By writing a little code and linking against libFLAC, it is
  88166. * relatively easy to add FLAC support to another program. The
  88167. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  88168. * Complete source code of libFLAC as well as the command-line
  88169. * encoder and plugins is available and is a useful source of
  88170. * examples.
  88171. *
  88172. * Aside from encoders and decoders, libFLAC provides a powerful
  88173. * metadata interface for manipulating metadata in FLAC files. It
  88174. * allows the user to add, delete, and modify FLAC metadata blocks
  88175. * and it can automatically take advantage of PADDING blocks to avoid
  88176. * rewriting the entire FLAC file when changing the size of the
  88177. * metadata.
  88178. *
  88179. * libFLAC usually only requires the standard C library and C math
  88180. * library. In particular, threading is not used so there is no
  88181. * dependency on a thread library. However, libFLAC does not use
  88182. * global variables and should be thread-safe.
  88183. *
  88184. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  88185. * However the metadata editing interfaces currently have limited
  88186. * read-only support for Ogg FLAC files.
  88187. *
  88188. * \section cpp_api FLAC C++ API
  88189. *
  88190. * The FLAC C++ API is a set of classes that encapsulate the
  88191. * structures and functions in libFLAC. They provide slightly more
  88192. * functionality with respect to metadata but are otherwise
  88193. * equivalent. For the most part, they share the same usage as
  88194. * their counterparts in libFLAC, and the FLAC C API documentation
  88195. * can be used as a supplement. The public include files
  88196. * for the C++ API will be installed in your include area (for
  88197. * example /usr/include/FLAC++/...).
  88198. *
  88199. * libFLAC++ is also licensed under
  88200. * <A HREF="../license.html">Xiph's BSD license</A>.
  88201. *
  88202. * \section getting_started Getting Started
  88203. *
  88204. * A good starting point for learning the API is to browse through
  88205. * the <A HREF="modules.html">modules</A>. Modules are logical
  88206. * groupings of related functions or classes, which correspond roughly
  88207. * to header files or sections of header files. Each module includes a
  88208. * detailed description of the general usage of its functions or
  88209. * classes.
  88210. *
  88211. * From there you can go on to look at the documentation of
  88212. * individual functions. You can see different views of the individual
  88213. * functions through the links in top bar across this page.
  88214. *
  88215. * If you prefer a more hands-on approach, you can jump right to some
  88216. * <A HREF="../documentation_example_code.html">example code</A>.
  88217. *
  88218. * \section porting_guide Porting Guide
  88219. *
  88220. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  88221. * has been introduced which gives detailed instructions on how to
  88222. * port your code to newer versions of FLAC.
  88223. *
  88224. * \section embedded_developers Embedded Developers
  88225. *
  88226. * libFLAC has grown larger over time as more functionality has been
  88227. * included, but much of it may be unnecessary for a particular embedded
  88228. * implementation. Unused parts may be pruned by some simple editing of
  88229. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  88230. * metadata interface are all independent from each other.
  88231. *
  88232. * It is easiest to just describe the dependencies:
  88233. *
  88234. * - All modules depend on the \link flac_format Format \endlink module.
  88235. * - The decoders and encoders depend on the bitbuffer.
  88236. * - The decoder is independent of the encoder. The encoder uses the
  88237. * decoder because of the verify feature, but this can be removed if
  88238. * not needed.
  88239. * - Parts of the metadata interface require the stream decoder (but not
  88240. * the encoder).
  88241. * - Ogg support is selectable through the compile time macro
  88242. * \c FLAC__HAS_OGG.
  88243. *
  88244. * For example, if your application only requires the stream decoder, no
  88245. * encoder, and no metadata interface, you can remove the stream encoder
  88246. * and the metadata interface, which will greatly reduce the size of the
  88247. * library.
  88248. *
  88249. * Also, there are several places in the libFLAC code with comments marked
  88250. * with "OPT:" where a #define can be changed to enable code that might be
  88251. * faster on a specific platform. Experimenting with these can yield faster
  88252. * binaries.
  88253. */
  88254. /** \defgroup porting Porting Guide for New Versions
  88255. *
  88256. * This module describes differences in the library interfaces from
  88257. * version to version. It assists in the porting of code that uses
  88258. * the libraries to newer versions of FLAC.
  88259. *
  88260. * One simple facility for making porting easier that has been added
  88261. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  88262. * library's includes (e.g. \c include/FLAC/export.h). The
  88263. * \c #defines mirror the libraries'
  88264. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  88265. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  88266. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  88267. * These can be used to support multiple versions of an API during the
  88268. * transition phase, e.g.
  88269. *
  88270. * \code
  88271. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  88272. * legacy code
  88273. * #else
  88274. * new code
  88275. * #endif
  88276. * \endcode
  88277. *
  88278. * The the source will work for multiple versions and the legacy code can
  88279. * easily be removed when the transition is complete.
  88280. *
  88281. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  88282. * include/FLAC/export.h), which can be used to determine whether or not
  88283. * the library has been compiled with support for Ogg FLAC. This is
  88284. * simpler than trying to call an Ogg init function and catching the
  88285. * error.
  88286. */
  88287. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  88288. * \ingroup porting
  88289. *
  88290. * \brief
  88291. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  88292. *
  88293. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  88294. * been simplified. First, libOggFLAC has been merged into libFLAC and
  88295. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  88296. * decoding layers and three encoding layers have been merged into a
  88297. * single stream decoder and stream encoder. That is, the functionality
  88298. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  88299. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  88300. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  88301. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  88302. * is there is now a single API that can be used to encode or decode
  88303. * streams to/from native FLAC or Ogg FLAC and the single API can work
  88304. * on both seekable and non-seekable streams.
  88305. *
  88306. * Instead of creating an encoder or decoder of a certain layer, now the
  88307. * client will always create a FLAC__StreamEncoder or
  88308. * FLAC__StreamDecoder. The old layers are now differentiated by the
  88309. * initialization function. For example, for the decoder,
  88310. * FLAC__stream_decoder_init() has been replaced by
  88311. * FLAC__stream_decoder_init_stream(). This init function takes
  88312. * callbacks for the I/O, and the seeking callbacks are optional. This
  88313. * allows the client to use the same object for seekable and
  88314. * non-seekable streams. For decoding a FLAC file directly, the client
  88315. * can use FLAC__stream_decoder_init_file() and pass just a filename
  88316. * and fewer callbacks; most of the other callbacks are supplied
  88317. * internally. For situations where fopen()ing by filename is not
  88318. * possible (e.g. Unicode filenames on Windows) the client can instead
  88319. * open the file itself and supply the FILE* to
  88320. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  88321. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  88322. * Since the callbacks and client data are now passed to the init
  88323. * function, the FLAC__stream_decoder_set_*_callback() functions and
  88324. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  88325. * rest of the calls to the decoder are the same as before.
  88326. *
  88327. * There are counterpart init functions for Ogg FLAC, e.g.
  88328. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  88329. * and callbacks are the same as for native FLAC.
  88330. *
  88331. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  88332. * been set up like so:
  88333. *
  88334. * \code
  88335. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  88336. * if(decoder == NULL) do_something;
  88337. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  88338. * [... other settings ...]
  88339. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  88340. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  88341. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  88342. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  88343. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  88344. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  88345. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  88346. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  88347. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  88348. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  88349. * \endcode
  88350. *
  88351. * In FLAC 1.1.3 it is like this:
  88352. *
  88353. * \code
  88354. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  88355. * if(decoder == NULL) do_something;
  88356. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  88357. * [... other settings ...]
  88358. * if(FLAC__stream_decoder_init_stream(
  88359. * decoder,
  88360. * my_read_callback,
  88361. * my_seek_callback, // or NULL
  88362. * my_tell_callback, // or NULL
  88363. * my_length_callback, // or NULL
  88364. * my_eof_callback, // or NULL
  88365. * my_write_callback,
  88366. * my_metadata_callback, // or NULL
  88367. * my_error_callback,
  88368. * my_client_data
  88369. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88370. * \endcode
  88371. *
  88372. * or you could do;
  88373. *
  88374. * \code
  88375. * [...]
  88376. * FILE *file = fopen("somefile.flac","rb");
  88377. * if(file == NULL) do_somthing;
  88378. * if(FLAC__stream_decoder_init_FILE(
  88379. * decoder,
  88380. * file,
  88381. * my_write_callback,
  88382. * my_metadata_callback, // or NULL
  88383. * my_error_callback,
  88384. * my_client_data
  88385. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88386. * \endcode
  88387. *
  88388. * or just:
  88389. *
  88390. * \code
  88391. * [...]
  88392. * if(FLAC__stream_decoder_init_file(
  88393. * decoder,
  88394. * "somefile.flac",
  88395. * my_write_callback,
  88396. * my_metadata_callback, // or NULL
  88397. * my_error_callback,
  88398. * my_client_data
  88399. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88400. * \endcode
  88401. *
  88402. * Another small change to the decoder is in how it handles unparseable
  88403. * streams. Before, when the decoder found an unparseable stream
  88404. * (reserved for when the decoder encounters a stream from a future
  88405. * encoder that it can't parse), it changed the state to
  88406. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  88407. * drops sync and calls the error callback with a new error code
  88408. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  88409. * more robust. If your error callback does not discriminate on the the
  88410. * error state, your code does not need to be changed.
  88411. *
  88412. * The encoder now has a new setting:
  88413. * FLAC__stream_encoder_set_apodization(). This is for setting the
  88414. * method used to window the data before LPC analysis. You only need to
  88415. * add a call to this function if the default is not suitable. There
  88416. * are also two new convenience functions that may be useful:
  88417. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  88418. * FLAC__metadata_get_cuesheet().
  88419. *
  88420. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  88421. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  88422. * is now \c size_t instead of \c unsigned.
  88423. */
  88424. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  88425. * \ingroup porting
  88426. *
  88427. * \brief
  88428. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  88429. *
  88430. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  88431. * There was a slight change in the implementation of
  88432. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  88433. * of the \a metadata array of pointers so the client no longer needs
  88434. * to maintain it after the call. The objects themselves that are
  88435. * pointed to by the array are still not copied though and must be
  88436. * maintained until the call to FLAC__stream_encoder_finish().
  88437. */
  88438. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  88439. * \ingroup porting
  88440. *
  88441. * \brief
  88442. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  88443. *
  88444. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  88445. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  88446. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  88447. *
  88448. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  88449. * has changed to reflect the conversion of one of the reserved bits
  88450. * into active use. It used to be \c 2 and now is \c 1. However the
  88451. * FLAC frame header length has not changed, so to skip the proper
  88452. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  88453. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  88454. */
  88455. /** \defgroup flac FLAC C API
  88456. *
  88457. * The FLAC C API is the interface to libFLAC, a set of structures
  88458. * describing the components of FLAC streams, and functions for
  88459. * encoding and decoding streams, as well as manipulating FLAC
  88460. * metadata in files.
  88461. *
  88462. * You should start with the format components as all other modules
  88463. * are dependent on it.
  88464. */
  88465. #endif
  88466. /********* End of inlined file: all.h *********/
  88467. /********* Start of inlined file: bitmath.c *********/
  88468. /********* Start of inlined file: juce_FlacHeader.h *********/
  88469. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88470. // tasks..
  88471. #define VERSION "1.2.1"
  88472. #define FLAC__NO_DLL 1
  88473. #if JUCE_MSVC
  88474. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88475. #endif
  88476. #if JUCE_MAC
  88477. #define FLAC__SYS_DARWIN 1
  88478. #endif
  88479. /********* End of inlined file: juce_FlacHeader.h *********/
  88480. #if JUCE_USE_FLAC
  88481. #if HAVE_CONFIG_H
  88482. # include <config.h>
  88483. #endif
  88484. /********* Start of inlined file: bitmath.h *********/
  88485. #ifndef FLAC__PRIVATE__BITMATH_H
  88486. #define FLAC__PRIVATE__BITMATH_H
  88487. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  88488. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  88489. unsigned FLAC__bitmath_silog2(int v);
  88490. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  88491. #endif
  88492. /********* End of inlined file: bitmath.h *********/
  88493. /* An example of what FLAC__bitmath_ilog2() computes:
  88494. *
  88495. * ilog2( 0) = assertion failure
  88496. * ilog2( 1) = 0
  88497. * ilog2( 2) = 1
  88498. * ilog2( 3) = 1
  88499. * ilog2( 4) = 2
  88500. * ilog2( 5) = 2
  88501. * ilog2( 6) = 2
  88502. * ilog2( 7) = 2
  88503. * ilog2( 8) = 3
  88504. * ilog2( 9) = 3
  88505. * ilog2(10) = 3
  88506. * ilog2(11) = 3
  88507. * ilog2(12) = 3
  88508. * ilog2(13) = 3
  88509. * ilog2(14) = 3
  88510. * ilog2(15) = 3
  88511. * ilog2(16) = 4
  88512. * ilog2(17) = 4
  88513. * ilog2(18) = 4
  88514. */
  88515. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  88516. {
  88517. unsigned l = 0;
  88518. FLAC__ASSERT(v > 0);
  88519. while(v >>= 1)
  88520. l++;
  88521. return l;
  88522. }
  88523. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  88524. {
  88525. unsigned l = 0;
  88526. FLAC__ASSERT(v > 0);
  88527. while(v >>= 1)
  88528. l++;
  88529. return l;
  88530. }
  88531. /* An example of what FLAC__bitmath_silog2() computes:
  88532. *
  88533. * silog2(-10) = 5
  88534. * silog2(- 9) = 5
  88535. * silog2(- 8) = 4
  88536. * silog2(- 7) = 4
  88537. * silog2(- 6) = 4
  88538. * silog2(- 5) = 4
  88539. * silog2(- 4) = 3
  88540. * silog2(- 3) = 3
  88541. * silog2(- 2) = 2
  88542. * silog2(- 1) = 2
  88543. * silog2( 0) = 0
  88544. * silog2( 1) = 2
  88545. * silog2( 2) = 3
  88546. * silog2( 3) = 3
  88547. * silog2( 4) = 4
  88548. * silog2( 5) = 4
  88549. * silog2( 6) = 4
  88550. * silog2( 7) = 4
  88551. * silog2( 8) = 5
  88552. * silog2( 9) = 5
  88553. * silog2( 10) = 5
  88554. */
  88555. unsigned FLAC__bitmath_silog2(int v)
  88556. {
  88557. while(1) {
  88558. if(v == 0) {
  88559. return 0;
  88560. }
  88561. else if(v > 0) {
  88562. unsigned l = 0;
  88563. while(v) {
  88564. l++;
  88565. v >>= 1;
  88566. }
  88567. return l+1;
  88568. }
  88569. else if(v == -1) {
  88570. return 2;
  88571. }
  88572. else {
  88573. v++;
  88574. v = -v;
  88575. }
  88576. }
  88577. }
  88578. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  88579. {
  88580. while(1) {
  88581. if(v == 0) {
  88582. return 0;
  88583. }
  88584. else if(v > 0) {
  88585. unsigned l = 0;
  88586. while(v) {
  88587. l++;
  88588. v >>= 1;
  88589. }
  88590. return l+1;
  88591. }
  88592. else if(v == -1) {
  88593. return 2;
  88594. }
  88595. else {
  88596. v++;
  88597. v = -v;
  88598. }
  88599. }
  88600. }
  88601. #endif
  88602. /********* End of inlined file: bitmath.c *********/
  88603. /********* Start of inlined file: bitreader.c *********/
  88604. /********* Start of inlined file: juce_FlacHeader.h *********/
  88605. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88606. // tasks..
  88607. #define VERSION "1.2.1"
  88608. #define FLAC__NO_DLL 1
  88609. #if JUCE_MSVC
  88610. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88611. #endif
  88612. #if JUCE_MAC
  88613. #define FLAC__SYS_DARWIN 1
  88614. #endif
  88615. /********* End of inlined file: juce_FlacHeader.h *********/
  88616. #if JUCE_USE_FLAC
  88617. #if HAVE_CONFIG_H
  88618. # include <config.h>
  88619. #endif
  88620. #include <stdlib.h> /* for malloc() */
  88621. #include <string.h> /* for memcpy(), memset() */
  88622. #ifdef _MSC_VER
  88623. #include <winsock.h> /* for ntohl() */
  88624. #elif defined FLAC__SYS_DARWIN
  88625. #include <machine/endian.h> /* for ntohl() */
  88626. #elif defined __MINGW32__
  88627. #include <winsock.h> /* for ntohl() */
  88628. #else
  88629. #include <netinet/in.h> /* for ntohl() */
  88630. #endif
  88631. /********* Start of inlined file: bitreader.h *********/
  88632. #ifndef FLAC__PRIVATE__BITREADER_H
  88633. #define FLAC__PRIVATE__BITREADER_H
  88634. #include <stdio.h> /* for FILE */
  88635. /********* Start of inlined file: cpu.h *********/
  88636. #ifndef FLAC__PRIVATE__CPU_H
  88637. #define FLAC__PRIVATE__CPU_H
  88638. #ifdef HAVE_CONFIG_H
  88639. #include <config.h>
  88640. #endif
  88641. typedef enum {
  88642. FLAC__CPUINFO_TYPE_IA32,
  88643. FLAC__CPUINFO_TYPE_PPC,
  88644. FLAC__CPUINFO_TYPE_UNKNOWN
  88645. } FLAC__CPUInfo_Type;
  88646. typedef struct {
  88647. FLAC__bool cpuid;
  88648. FLAC__bool bswap;
  88649. FLAC__bool cmov;
  88650. FLAC__bool mmx;
  88651. FLAC__bool fxsr;
  88652. FLAC__bool sse;
  88653. FLAC__bool sse2;
  88654. FLAC__bool sse3;
  88655. FLAC__bool ssse3;
  88656. FLAC__bool _3dnow;
  88657. FLAC__bool ext3dnow;
  88658. FLAC__bool extmmx;
  88659. } FLAC__CPUInfo_IA32;
  88660. typedef struct {
  88661. FLAC__bool altivec;
  88662. FLAC__bool ppc64;
  88663. } FLAC__CPUInfo_PPC;
  88664. typedef struct {
  88665. FLAC__bool use_asm;
  88666. FLAC__CPUInfo_Type type;
  88667. union {
  88668. FLAC__CPUInfo_IA32 ia32;
  88669. FLAC__CPUInfo_PPC ppc;
  88670. } data;
  88671. } FLAC__CPUInfo;
  88672. void FLAC__cpu_info(FLAC__CPUInfo *info);
  88673. #ifndef FLAC__NO_ASM
  88674. #ifdef FLAC__CPU_IA32
  88675. #ifdef FLAC__HAS_NASM
  88676. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  88677. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  88678. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  88679. #endif
  88680. #endif
  88681. #endif
  88682. #endif
  88683. /********* End of inlined file: cpu.h *********/
  88684. /*
  88685. * opaque structure definition
  88686. */
  88687. struct FLAC__BitReader;
  88688. typedef struct FLAC__BitReader FLAC__BitReader;
  88689. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  88690. /*
  88691. * construction, deletion, initialization, etc functions
  88692. */
  88693. FLAC__BitReader *FLAC__bitreader_new(void);
  88694. void FLAC__bitreader_delete(FLAC__BitReader *br);
  88695. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  88696. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  88697. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  88698. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  88699. /*
  88700. * CRC functions
  88701. */
  88702. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  88703. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  88704. /*
  88705. * info functions
  88706. */
  88707. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  88708. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  88709. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  88710. /*
  88711. * read functions
  88712. */
  88713. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  88714. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  88715. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  88716. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  88717. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  88718. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  88719. 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! */
  88720. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  88721. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88722. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88723. #ifndef FLAC__NO_ASM
  88724. # ifdef FLAC__CPU_IA32
  88725. # ifdef FLAC__HAS_NASM
  88726. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88727. # endif
  88728. # endif
  88729. #endif
  88730. #if 0 /* UNUSED */
  88731. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88732. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  88733. #endif
  88734. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  88735. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  88736. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  88737. #endif
  88738. /********* End of inlined file: bitreader.h *********/
  88739. /********* Start of inlined file: crc.h *********/
  88740. #ifndef FLAC__PRIVATE__CRC_H
  88741. #define FLAC__PRIVATE__CRC_H
  88742. /* 8 bit CRC generator, MSB shifted first
  88743. ** polynomial = x^8 + x^2 + x^1 + x^0
  88744. ** init = 0
  88745. */
  88746. extern FLAC__byte const FLAC__crc8_table[256];
  88747. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  88748. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  88749. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  88750. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  88751. /* 16 bit CRC generator, MSB shifted first
  88752. ** polynomial = x^16 + x^15 + x^2 + x^0
  88753. ** init = 0
  88754. */
  88755. extern unsigned FLAC__crc16_table[256];
  88756. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  88757. /* this alternate may be faster on some systems/compilers */
  88758. #if 0
  88759. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  88760. #endif
  88761. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  88762. #endif
  88763. /********* End of inlined file: crc.h *********/
  88764. /* Things should be fastest when this matches the machine word size */
  88765. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  88766. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  88767. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  88768. typedef FLAC__uint32 brword;
  88769. #define FLAC__BYTES_PER_WORD 4
  88770. #define FLAC__BITS_PER_WORD 32
  88771. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88772. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  88773. #if WORDS_BIGENDIAN
  88774. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88775. #else
  88776. #if defined (_MSC_VER) && defined (_X86_)
  88777. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88778. #else
  88779. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88780. #endif
  88781. #endif
  88782. /* counts the # of zero MSBs in a word */
  88783. #define COUNT_ZERO_MSBS(word) ( \
  88784. (word) <= 0xffff ? \
  88785. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  88786. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  88787. )
  88788. /* this alternate might be slightly faster on some systems/compilers: */
  88789. #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])) )
  88790. /*
  88791. * This should be at least twice as large as the largest number of words
  88792. * required to represent any 'number' (in any encoding) you are going to
  88793. * read. With FLAC this is on the order of maybe a few hundred bits.
  88794. * If the buffer is smaller than that, the decoder won't be able to read
  88795. * in a whole number that is in a variable length encoding (e.g. Rice).
  88796. * But to be practical it should be at least 1K bytes.
  88797. *
  88798. * Increase this number to decrease the number of read callbacks, at the
  88799. * expense of using more memory. Or decrease for the reverse effect,
  88800. * keeping in mind the limit from the first paragraph. The optimal size
  88801. * also depends on the CPU cache size and other factors; some twiddling
  88802. * may be necessary to squeeze out the best performance.
  88803. */
  88804. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  88805. static const unsigned char byte_to_unary_table[] = {
  88806. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  88807. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  88808. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88809. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88810. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88811. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88812. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88813. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  88822. };
  88823. #ifdef min
  88824. #undef min
  88825. #endif
  88826. #define min(x,y) ((x)<(y)?(x):(y))
  88827. #ifdef max
  88828. #undef max
  88829. #endif
  88830. #define max(x,y) ((x)>(y)?(x):(y))
  88831. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88832. #ifdef _MSC_VER
  88833. #define FLAC__U64L(x) x
  88834. #else
  88835. #define FLAC__U64L(x) x##LLU
  88836. #endif
  88837. #ifndef FLaC__INLINE
  88838. #define FLaC__INLINE
  88839. #endif
  88840. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  88841. struct FLAC__BitReader {
  88842. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  88843. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  88844. brword *buffer;
  88845. unsigned capacity; /* in words */
  88846. unsigned words; /* # of completed words in buffer */
  88847. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  88848. unsigned consumed_words; /* #words ... */
  88849. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  88850. unsigned read_crc16; /* the running frame CRC */
  88851. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  88852. FLAC__BitReaderReadCallback read_callback;
  88853. void *client_data;
  88854. FLAC__CPUInfo cpu_info;
  88855. };
  88856. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  88857. {
  88858. register unsigned crc = br->read_crc16;
  88859. #if FLAC__BYTES_PER_WORD == 4
  88860. switch(br->crc16_align) {
  88861. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  88862. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88863. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88864. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88865. }
  88866. #elif FLAC__BYTES_PER_WORD == 8
  88867. switch(br->crc16_align) {
  88868. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  88869. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  88870. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  88871. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  88872. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  88873. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88874. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88875. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88876. }
  88877. #else
  88878. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  88879. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  88880. br->read_crc16 = crc;
  88881. #endif
  88882. br->crc16_align = 0;
  88883. }
  88884. /* would be static except it needs to be called by asm routines */
  88885. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  88886. {
  88887. unsigned start, end;
  88888. size_t bytes;
  88889. FLAC__byte *target;
  88890. /* first shift the unconsumed buffer data toward the front as much as possible */
  88891. if(br->consumed_words > 0) {
  88892. start = br->consumed_words;
  88893. end = br->words + (br->bytes? 1:0);
  88894. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  88895. br->words -= start;
  88896. br->consumed_words = 0;
  88897. }
  88898. /*
  88899. * set the target for reading, taking into account word alignment and endianness
  88900. */
  88901. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  88902. if(bytes == 0)
  88903. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  88904. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  88905. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  88906. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  88907. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  88908. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  88909. * ^^-------target, bytes=3
  88910. * on LE machines, have to byteswap the odd tail word so nothing is
  88911. * overwritten:
  88912. */
  88913. #if WORDS_BIGENDIAN
  88914. #else
  88915. if(br->bytes)
  88916. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  88917. #endif
  88918. /* now it looks like:
  88919. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  88920. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  88921. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  88922. * ^^-------target, bytes=3
  88923. */
  88924. /* read in the data; note that the callback may return a smaller number of bytes */
  88925. if(!br->read_callback(target, &bytes, br->client_data))
  88926. return false;
  88927. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  88928. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88929. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88930. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  88931. * now have to byteswap on LE machines:
  88932. */
  88933. #if WORDS_BIGENDIAN
  88934. #else
  88935. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  88936. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  88937. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  88938. start = br->words;
  88939. local_swap32_block_(br->buffer + start, end - start);
  88940. }
  88941. else
  88942. # endif
  88943. for(start = br->words; start < end; start++)
  88944. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  88945. #endif
  88946. /* now it looks like:
  88947. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88948. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88949. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  88950. * finally we'll update the reader values:
  88951. */
  88952. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  88953. br->words = end / FLAC__BYTES_PER_WORD;
  88954. br->bytes = end % FLAC__BYTES_PER_WORD;
  88955. return true;
  88956. }
  88957. /***********************************************************************
  88958. *
  88959. * Class constructor/destructor
  88960. *
  88961. ***********************************************************************/
  88962. FLAC__BitReader *FLAC__bitreader_new(void)
  88963. {
  88964. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  88965. /* calloc() implies:
  88966. memset(br, 0, sizeof(FLAC__BitReader));
  88967. br->buffer = 0;
  88968. br->capacity = 0;
  88969. br->words = br->bytes = 0;
  88970. br->consumed_words = br->consumed_bits = 0;
  88971. br->read_callback = 0;
  88972. br->client_data = 0;
  88973. */
  88974. return br;
  88975. }
  88976. void FLAC__bitreader_delete(FLAC__BitReader *br)
  88977. {
  88978. FLAC__ASSERT(0 != br);
  88979. FLAC__bitreader_free(br);
  88980. free(br);
  88981. }
  88982. /***********************************************************************
  88983. *
  88984. * Public class methods
  88985. *
  88986. ***********************************************************************/
  88987. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  88988. {
  88989. FLAC__ASSERT(0 != br);
  88990. br->words = br->bytes = 0;
  88991. br->consumed_words = br->consumed_bits = 0;
  88992. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  88993. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  88994. if(br->buffer == 0)
  88995. return false;
  88996. br->read_callback = rcb;
  88997. br->client_data = cd;
  88998. br->cpu_info = cpu;
  88999. return true;
  89000. }
  89001. void FLAC__bitreader_free(FLAC__BitReader *br)
  89002. {
  89003. FLAC__ASSERT(0 != br);
  89004. if(0 != br->buffer)
  89005. free(br->buffer);
  89006. br->buffer = 0;
  89007. br->capacity = 0;
  89008. br->words = br->bytes = 0;
  89009. br->consumed_words = br->consumed_bits = 0;
  89010. br->read_callback = 0;
  89011. br->client_data = 0;
  89012. }
  89013. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  89014. {
  89015. br->words = br->bytes = 0;
  89016. br->consumed_words = br->consumed_bits = 0;
  89017. return true;
  89018. }
  89019. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  89020. {
  89021. unsigned i, j;
  89022. if(br == 0) {
  89023. fprintf(out, "bitreader is NULL\n");
  89024. }
  89025. else {
  89026. 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);
  89027. for(i = 0; i < br->words; i++) {
  89028. fprintf(out, "%08X: ", i);
  89029. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  89030. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  89031. fprintf(out, ".");
  89032. else
  89033. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  89034. fprintf(out, "\n");
  89035. }
  89036. if(br->bytes > 0) {
  89037. fprintf(out, "%08X: ", i);
  89038. for(j = 0; j < br->bytes*8; j++)
  89039. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  89040. fprintf(out, ".");
  89041. else
  89042. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  89043. fprintf(out, "\n");
  89044. }
  89045. }
  89046. }
  89047. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  89048. {
  89049. FLAC__ASSERT(0 != br);
  89050. FLAC__ASSERT(0 != br->buffer);
  89051. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89052. br->read_crc16 = (unsigned)seed;
  89053. br->crc16_align = br->consumed_bits;
  89054. }
  89055. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  89056. {
  89057. FLAC__ASSERT(0 != br);
  89058. FLAC__ASSERT(0 != br->buffer);
  89059. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  89060. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  89061. /* CRC any tail bytes in a partially-consumed word */
  89062. if(br->consumed_bits) {
  89063. const brword tail = br->buffer[br->consumed_words];
  89064. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  89065. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  89066. }
  89067. return br->read_crc16;
  89068. }
  89069. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  89070. {
  89071. return ((br->consumed_bits & 7) == 0);
  89072. }
  89073. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  89074. {
  89075. return 8 - (br->consumed_bits & 7);
  89076. }
  89077. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  89078. {
  89079. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  89080. }
  89081. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  89082. {
  89083. FLAC__ASSERT(0 != br);
  89084. FLAC__ASSERT(0 != br->buffer);
  89085. FLAC__ASSERT(bits <= 32);
  89086. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  89087. FLAC__ASSERT(br->consumed_words <= br->words);
  89088. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89089. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89090. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  89091. *val = 0;
  89092. return true;
  89093. }
  89094. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  89095. if(!bitreader_read_from_client_(br))
  89096. return false;
  89097. }
  89098. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89099. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89100. if(br->consumed_bits) {
  89101. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89102. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  89103. const brword word = br->buffer[br->consumed_words];
  89104. if(bits < n) {
  89105. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  89106. br->consumed_bits += bits;
  89107. return true;
  89108. }
  89109. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  89110. bits -= n;
  89111. crc16_update_word_(br, word);
  89112. br->consumed_words++;
  89113. br->consumed_bits = 0;
  89114. 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 */
  89115. *val <<= bits;
  89116. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  89117. br->consumed_bits = bits;
  89118. }
  89119. return true;
  89120. }
  89121. else {
  89122. const brword word = br->buffer[br->consumed_words];
  89123. if(bits < FLAC__BITS_PER_WORD) {
  89124. *val = word >> (FLAC__BITS_PER_WORD-bits);
  89125. br->consumed_bits = bits;
  89126. return true;
  89127. }
  89128. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  89129. *val = word;
  89130. crc16_update_word_(br, word);
  89131. br->consumed_words++;
  89132. return true;
  89133. }
  89134. }
  89135. else {
  89136. /* in this case we're starting our read at a partial tail word;
  89137. * the reader has guaranteed that we have at least 'bits' bits
  89138. * available to read, which makes this case simpler.
  89139. */
  89140. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  89141. if(br->consumed_bits) {
  89142. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89143. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  89144. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  89145. br->consumed_bits += bits;
  89146. return true;
  89147. }
  89148. else {
  89149. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  89150. br->consumed_bits += bits;
  89151. return true;
  89152. }
  89153. }
  89154. }
  89155. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  89156. {
  89157. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  89158. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  89159. return false;
  89160. /* sign-extend: */
  89161. *val <<= (32-bits);
  89162. *val >>= (32-bits);
  89163. return true;
  89164. }
  89165. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  89166. {
  89167. FLAC__uint32 hi, lo;
  89168. if(bits > 32) {
  89169. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  89170. return false;
  89171. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  89172. return false;
  89173. *val = hi;
  89174. *val <<= 32;
  89175. *val |= lo;
  89176. }
  89177. else {
  89178. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  89179. return false;
  89180. *val = lo;
  89181. }
  89182. return true;
  89183. }
  89184. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  89185. {
  89186. FLAC__uint32 x8, x32 = 0;
  89187. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89188. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  89189. return false;
  89190. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89191. return false;
  89192. x32 |= (x8 << 8);
  89193. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89194. return false;
  89195. x32 |= (x8 << 16);
  89196. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89197. return false;
  89198. x32 |= (x8 << 24);
  89199. *val = x32;
  89200. return true;
  89201. }
  89202. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  89203. {
  89204. /*
  89205. * OPT: a faster implementation is possible but probably not that useful
  89206. * since this is only called a couple of times in the metadata readers.
  89207. */
  89208. FLAC__ASSERT(0 != br);
  89209. FLAC__ASSERT(0 != br->buffer);
  89210. if(bits > 0) {
  89211. const unsigned n = br->consumed_bits & 7;
  89212. unsigned m;
  89213. FLAC__uint32 x;
  89214. if(n != 0) {
  89215. m = min(8-n, bits);
  89216. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  89217. return false;
  89218. bits -= m;
  89219. }
  89220. m = bits / 8;
  89221. if(m > 0) {
  89222. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  89223. return false;
  89224. bits %= 8;
  89225. }
  89226. if(bits > 0) {
  89227. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  89228. return false;
  89229. }
  89230. }
  89231. return true;
  89232. }
  89233. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  89234. {
  89235. FLAC__uint32 x;
  89236. FLAC__ASSERT(0 != br);
  89237. FLAC__ASSERT(0 != br->buffer);
  89238. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89239. /* step 1: skip over partial head word to get word aligned */
  89240. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89241. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89242. return false;
  89243. nvals--;
  89244. }
  89245. if(0 == nvals)
  89246. return true;
  89247. /* step 2: skip whole words in chunks */
  89248. while(nvals >= FLAC__BYTES_PER_WORD) {
  89249. if(br->consumed_words < br->words) {
  89250. br->consumed_words++;
  89251. nvals -= FLAC__BYTES_PER_WORD;
  89252. }
  89253. else if(!bitreader_read_from_client_(br))
  89254. return false;
  89255. }
  89256. /* step 3: skip any remainder from partial tail bytes */
  89257. while(nvals) {
  89258. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89259. return false;
  89260. nvals--;
  89261. }
  89262. return true;
  89263. }
  89264. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  89265. {
  89266. FLAC__uint32 x;
  89267. FLAC__ASSERT(0 != br);
  89268. FLAC__ASSERT(0 != br->buffer);
  89269. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89270. /* step 1: read from partial head word to get word aligned */
  89271. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89272. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89273. return false;
  89274. *val++ = (FLAC__byte)x;
  89275. nvals--;
  89276. }
  89277. if(0 == nvals)
  89278. return true;
  89279. /* step 2: read whole words in chunks */
  89280. while(nvals >= FLAC__BYTES_PER_WORD) {
  89281. if(br->consumed_words < br->words) {
  89282. const brword word = br->buffer[br->consumed_words++];
  89283. #if FLAC__BYTES_PER_WORD == 4
  89284. val[0] = (FLAC__byte)(word >> 24);
  89285. val[1] = (FLAC__byte)(word >> 16);
  89286. val[2] = (FLAC__byte)(word >> 8);
  89287. val[3] = (FLAC__byte)word;
  89288. #elif FLAC__BYTES_PER_WORD == 8
  89289. val[0] = (FLAC__byte)(word >> 56);
  89290. val[1] = (FLAC__byte)(word >> 48);
  89291. val[2] = (FLAC__byte)(word >> 40);
  89292. val[3] = (FLAC__byte)(word >> 32);
  89293. val[4] = (FLAC__byte)(word >> 24);
  89294. val[5] = (FLAC__byte)(word >> 16);
  89295. val[6] = (FLAC__byte)(word >> 8);
  89296. val[7] = (FLAC__byte)word;
  89297. #else
  89298. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  89299. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  89300. #endif
  89301. val += FLAC__BYTES_PER_WORD;
  89302. nvals -= FLAC__BYTES_PER_WORD;
  89303. }
  89304. else if(!bitreader_read_from_client_(br))
  89305. return false;
  89306. }
  89307. /* step 3: read any remainder from partial tail bytes */
  89308. while(nvals) {
  89309. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89310. return false;
  89311. *val++ = (FLAC__byte)x;
  89312. nvals--;
  89313. }
  89314. return true;
  89315. }
  89316. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  89317. #if 0 /* slow but readable version */
  89318. {
  89319. unsigned bit;
  89320. FLAC__ASSERT(0 != br);
  89321. FLAC__ASSERT(0 != br->buffer);
  89322. *val = 0;
  89323. while(1) {
  89324. if(!FLAC__bitreader_read_bit(br, &bit))
  89325. return false;
  89326. if(bit)
  89327. break;
  89328. else
  89329. *val++;
  89330. }
  89331. return true;
  89332. }
  89333. #else
  89334. {
  89335. unsigned i;
  89336. FLAC__ASSERT(0 != br);
  89337. FLAC__ASSERT(0 != br->buffer);
  89338. *val = 0;
  89339. while(1) {
  89340. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89341. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  89342. if(b) {
  89343. i = COUNT_ZERO_MSBS(b);
  89344. *val += i;
  89345. i++;
  89346. br->consumed_bits += i;
  89347. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  89348. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89349. br->consumed_words++;
  89350. br->consumed_bits = 0;
  89351. }
  89352. return true;
  89353. }
  89354. else {
  89355. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  89356. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89357. br->consumed_words++;
  89358. br->consumed_bits = 0;
  89359. /* didn't find stop bit yet, have to keep going... */
  89360. }
  89361. }
  89362. /* at this point we've eaten up all the whole words; have to try
  89363. * reading through any tail bytes before calling the read callback.
  89364. * this is a repeat of the above logic adjusted for the fact we
  89365. * don't have a whole word. note though if the client is feeding
  89366. * us data a byte at a time (unlikely), br->consumed_bits may not
  89367. * be zero.
  89368. */
  89369. if(br->bytes) {
  89370. const unsigned end = br->bytes * 8;
  89371. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  89372. if(b) {
  89373. i = COUNT_ZERO_MSBS(b);
  89374. *val += i;
  89375. i++;
  89376. br->consumed_bits += i;
  89377. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89378. return true;
  89379. }
  89380. else {
  89381. *val += end - br->consumed_bits;
  89382. br->consumed_bits += end;
  89383. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89384. /* didn't find stop bit yet, have to keep going... */
  89385. }
  89386. }
  89387. if(!bitreader_read_from_client_(br))
  89388. return false;
  89389. }
  89390. }
  89391. #endif
  89392. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89393. {
  89394. FLAC__uint32 lsbs = 0, msbs = 0;
  89395. unsigned uval;
  89396. FLAC__ASSERT(0 != br);
  89397. FLAC__ASSERT(0 != br->buffer);
  89398. FLAC__ASSERT(parameter <= 31);
  89399. /* read the unary MSBs and end bit */
  89400. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  89401. return false;
  89402. /* read the binary LSBs */
  89403. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  89404. return false;
  89405. /* compose the value */
  89406. uval = (msbs << parameter) | lsbs;
  89407. if(uval & 1)
  89408. *val = -((int)(uval >> 1)) - 1;
  89409. else
  89410. *val = (int)(uval >> 1);
  89411. return true;
  89412. }
  89413. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  89414. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  89415. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  89416. /* OPT: possibly faster version for use with MSVC */
  89417. #ifdef _MSC_VER
  89418. {
  89419. unsigned i;
  89420. unsigned uval = 0;
  89421. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  89422. /* try and get br->consumed_words and br->consumed_bits into register;
  89423. * must remember to flush them back to *br before calling other
  89424. * bitwriter functions that use them, and before returning */
  89425. register unsigned cwords;
  89426. register unsigned cbits;
  89427. FLAC__ASSERT(0 != br);
  89428. FLAC__ASSERT(0 != br->buffer);
  89429. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89430. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89431. FLAC__ASSERT(parameter < 32);
  89432. /* 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 */
  89433. if(nvals == 0)
  89434. return true;
  89435. cbits = br->consumed_bits;
  89436. cwords = br->consumed_words;
  89437. while(1) {
  89438. /* read unary part */
  89439. while(1) {
  89440. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89441. brword b = br->buffer[cwords] << cbits;
  89442. if(b) {
  89443. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  89444. __asm {
  89445. bsr eax, b
  89446. not eax
  89447. and eax, 31
  89448. mov i, eax
  89449. }
  89450. #else
  89451. i = COUNT_ZERO_MSBS(b);
  89452. #endif
  89453. uval += i;
  89454. bits = parameter;
  89455. i++;
  89456. cbits += i;
  89457. if(cbits == FLAC__BITS_PER_WORD) {
  89458. crc16_update_word_(br, br->buffer[cwords]);
  89459. cwords++;
  89460. cbits = 0;
  89461. }
  89462. goto break1;
  89463. }
  89464. else {
  89465. uval += FLAC__BITS_PER_WORD - cbits;
  89466. crc16_update_word_(br, br->buffer[cwords]);
  89467. cwords++;
  89468. cbits = 0;
  89469. /* didn't find stop bit yet, have to keep going... */
  89470. }
  89471. }
  89472. /* at this point we've eaten up all the whole words; have to try
  89473. * reading through any tail bytes before calling the read callback.
  89474. * this is a repeat of the above logic adjusted for the fact we
  89475. * don't have a whole word. note though if the client is feeding
  89476. * us data a byte at a time (unlikely), br->consumed_bits may not
  89477. * be zero.
  89478. */
  89479. if(br->bytes) {
  89480. const unsigned end = br->bytes * 8;
  89481. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  89482. if(b) {
  89483. i = COUNT_ZERO_MSBS(b);
  89484. uval += i;
  89485. bits = parameter;
  89486. i++;
  89487. cbits += i;
  89488. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89489. goto break1;
  89490. }
  89491. else {
  89492. uval += end - cbits;
  89493. cbits += end;
  89494. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89495. /* didn't find stop bit yet, have to keep going... */
  89496. }
  89497. }
  89498. /* flush registers and read; bitreader_read_from_client_() does
  89499. * not touch br->consumed_bits at all but we still need to set
  89500. * it in case it fails and we have to return false.
  89501. */
  89502. br->consumed_bits = cbits;
  89503. br->consumed_words = cwords;
  89504. if(!bitreader_read_from_client_(br))
  89505. return false;
  89506. cwords = br->consumed_words;
  89507. }
  89508. break1:
  89509. /* read binary part */
  89510. FLAC__ASSERT(cwords <= br->words);
  89511. if(bits) {
  89512. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  89513. /* flush registers and read; bitreader_read_from_client_() does
  89514. * not touch br->consumed_bits at all but we still need to set
  89515. * it in case it fails and we have to return false.
  89516. */
  89517. br->consumed_bits = cbits;
  89518. br->consumed_words = cwords;
  89519. if(!bitreader_read_from_client_(br))
  89520. return false;
  89521. cwords = br->consumed_words;
  89522. }
  89523. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89524. if(cbits) {
  89525. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89526. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89527. const brword word = br->buffer[cwords];
  89528. if(bits < n) {
  89529. uval <<= bits;
  89530. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  89531. cbits += bits;
  89532. goto break2;
  89533. }
  89534. uval <<= n;
  89535. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89536. bits -= n;
  89537. crc16_update_word_(br, word);
  89538. cwords++;
  89539. cbits = 0;
  89540. 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 */
  89541. uval <<= bits;
  89542. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  89543. cbits = bits;
  89544. }
  89545. goto break2;
  89546. }
  89547. else {
  89548. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  89549. uval <<= bits;
  89550. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89551. cbits = bits;
  89552. goto break2;
  89553. }
  89554. }
  89555. else {
  89556. /* in this case we're starting our read at a partial tail word;
  89557. * the reader has guaranteed that we have at least 'bits' bits
  89558. * available to read, which makes this case simpler.
  89559. */
  89560. uval <<= bits;
  89561. if(cbits) {
  89562. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89563. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  89564. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  89565. cbits += bits;
  89566. goto break2;
  89567. }
  89568. else {
  89569. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89570. cbits += bits;
  89571. goto break2;
  89572. }
  89573. }
  89574. }
  89575. break2:
  89576. /* compose the value */
  89577. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89578. /* are we done? */
  89579. --nvals;
  89580. if(nvals == 0) {
  89581. br->consumed_bits = cbits;
  89582. br->consumed_words = cwords;
  89583. return true;
  89584. }
  89585. uval = 0;
  89586. ++vals;
  89587. }
  89588. }
  89589. #else
  89590. {
  89591. unsigned i;
  89592. unsigned uval = 0;
  89593. /* try and get br->consumed_words and br->consumed_bits into register;
  89594. * must remember to flush them back to *br before calling other
  89595. * bitwriter functions that use them, and before returning */
  89596. register unsigned cwords;
  89597. register unsigned cbits;
  89598. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  89599. FLAC__ASSERT(0 != br);
  89600. FLAC__ASSERT(0 != br->buffer);
  89601. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89602. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89603. FLAC__ASSERT(parameter < 32);
  89604. /* 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 */
  89605. if(nvals == 0)
  89606. return true;
  89607. cbits = br->consumed_bits;
  89608. cwords = br->consumed_words;
  89609. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89610. while(1) {
  89611. /* read unary part */
  89612. while(1) {
  89613. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89614. brword b = br->buffer[cwords] << cbits;
  89615. if(b) {
  89616. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  89617. asm volatile (
  89618. "bsrl %1, %0;"
  89619. "notl %0;"
  89620. "andl $31, %0;"
  89621. : "=r"(i)
  89622. : "r"(b)
  89623. );
  89624. #else
  89625. i = COUNT_ZERO_MSBS(b);
  89626. #endif
  89627. uval += i;
  89628. cbits += i;
  89629. cbits++; /* skip over stop bit */
  89630. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  89631. crc16_update_word_(br, br->buffer[cwords]);
  89632. cwords++;
  89633. cbits = 0;
  89634. }
  89635. goto break1;
  89636. }
  89637. else {
  89638. uval += FLAC__BITS_PER_WORD - cbits;
  89639. crc16_update_word_(br, br->buffer[cwords]);
  89640. cwords++;
  89641. cbits = 0;
  89642. /* didn't find stop bit yet, have to keep going... */
  89643. }
  89644. }
  89645. /* at this point we've eaten up all the whole words; have to try
  89646. * reading through any tail bytes before calling the read callback.
  89647. * this is a repeat of the above logic adjusted for the fact we
  89648. * don't have a whole word. note though if the client is feeding
  89649. * us data a byte at a time (unlikely), br->consumed_bits may not
  89650. * be zero.
  89651. */
  89652. if(br->bytes) {
  89653. const unsigned end = br->bytes * 8;
  89654. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  89655. if(b) {
  89656. i = COUNT_ZERO_MSBS(b);
  89657. uval += i;
  89658. cbits += i;
  89659. cbits++; /* skip over stop bit */
  89660. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89661. goto break1;
  89662. }
  89663. else {
  89664. uval += end - cbits;
  89665. cbits += end;
  89666. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89667. /* didn't find stop bit yet, have to keep going... */
  89668. }
  89669. }
  89670. /* flush registers and read; bitreader_read_from_client_() does
  89671. * not touch br->consumed_bits at all but we still need to set
  89672. * it in case it fails and we have to return false.
  89673. */
  89674. br->consumed_bits = cbits;
  89675. br->consumed_words = cwords;
  89676. if(!bitreader_read_from_client_(br))
  89677. return false;
  89678. cwords = br->consumed_words;
  89679. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  89680. /* + uval to offset our count by the # of unary bits already
  89681. * consumed before the read, because we will add these back
  89682. * in all at once at break1
  89683. */
  89684. }
  89685. break1:
  89686. ucbits -= uval;
  89687. ucbits--; /* account for stop bit */
  89688. /* read binary part */
  89689. FLAC__ASSERT(cwords <= br->words);
  89690. if(parameter) {
  89691. while(ucbits < parameter) {
  89692. /* flush registers and read; bitreader_read_from_client_() does
  89693. * not touch br->consumed_bits at all but we still need to set
  89694. * it in case it fails and we have to return false.
  89695. */
  89696. br->consumed_bits = cbits;
  89697. br->consumed_words = cwords;
  89698. if(!bitreader_read_from_client_(br))
  89699. return false;
  89700. cwords = br->consumed_words;
  89701. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89702. }
  89703. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89704. if(cbits) {
  89705. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  89706. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89707. const brword word = br->buffer[cwords];
  89708. if(parameter < n) {
  89709. uval <<= parameter;
  89710. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  89711. cbits += parameter;
  89712. }
  89713. else {
  89714. uval <<= n;
  89715. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89716. crc16_update_word_(br, word);
  89717. cwords++;
  89718. cbits = parameter - n;
  89719. 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 */
  89720. uval <<= cbits;
  89721. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  89722. }
  89723. }
  89724. }
  89725. else {
  89726. cbits = parameter;
  89727. uval <<= parameter;
  89728. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89729. }
  89730. }
  89731. else {
  89732. /* in this case we're starting our read at a partial tail word;
  89733. * the reader has guaranteed that we have at least 'parameter'
  89734. * bits available to read, which makes this case simpler.
  89735. */
  89736. uval <<= parameter;
  89737. if(cbits) {
  89738. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89739. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  89740. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  89741. cbits += parameter;
  89742. }
  89743. else {
  89744. cbits = parameter;
  89745. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89746. }
  89747. }
  89748. }
  89749. ucbits -= parameter;
  89750. /* compose the value */
  89751. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89752. /* are we done? */
  89753. --nvals;
  89754. if(nvals == 0) {
  89755. br->consumed_bits = cbits;
  89756. br->consumed_words = cwords;
  89757. return true;
  89758. }
  89759. uval = 0;
  89760. ++vals;
  89761. }
  89762. }
  89763. #endif
  89764. #if 0 /* UNUSED */
  89765. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89766. {
  89767. FLAC__uint32 lsbs = 0, msbs = 0;
  89768. unsigned bit, uval, k;
  89769. FLAC__ASSERT(0 != br);
  89770. FLAC__ASSERT(0 != br->buffer);
  89771. k = FLAC__bitmath_ilog2(parameter);
  89772. /* read the unary MSBs and end bit */
  89773. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89774. return false;
  89775. /* read the binary LSBs */
  89776. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89777. return false;
  89778. if(parameter == 1u<<k) {
  89779. /* compose the value */
  89780. uval = (msbs << k) | lsbs;
  89781. }
  89782. else {
  89783. unsigned d = (1 << (k+1)) - parameter;
  89784. if(lsbs >= d) {
  89785. if(!FLAC__bitreader_read_bit(br, &bit))
  89786. return false;
  89787. lsbs <<= 1;
  89788. lsbs |= bit;
  89789. lsbs -= d;
  89790. }
  89791. /* compose the value */
  89792. uval = msbs * parameter + lsbs;
  89793. }
  89794. /* unfold unsigned to signed */
  89795. if(uval & 1)
  89796. *val = -((int)(uval >> 1)) - 1;
  89797. else
  89798. *val = (int)(uval >> 1);
  89799. return true;
  89800. }
  89801. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  89802. {
  89803. FLAC__uint32 lsbs, msbs = 0;
  89804. unsigned bit, k;
  89805. FLAC__ASSERT(0 != br);
  89806. FLAC__ASSERT(0 != br->buffer);
  89807. k = FLAC__bitmath_ilog2(parameter);
  89808. /* read the unary MSBs and end bit */
  89809. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89810. return false;
  89811. /* read the binary LSBs */
  89812. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89813. return false;
  89814. if(parameter == 1u<<k) {
  89815. /* compose the value */
  89816. *val = (msbs << k) | lsbs;
  89817. }
  89818. else {
  89819. unsigned d = (1 << (k+1)) - parameter;
  89820. if(lsbs >= d) {
  89821. if(!FLAC__bitreader_read_bit(br, &bit))
  89822. return false;
  89823. lsbs <<= 1;
  89824. lsbs |= bit;
  89825. lsbs -= d;
  89826. }
  89827. /* compose the value */
  89828. *val = msbs * parameter + lsbs;
  89829. }
  89830. return true;
  89831. }
  89832. #endif /* UNUSED */
  89833. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89834. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  89835. {
  89836. FLAC__uint32 v = 0;
  89837. FLAC__uint32 x;
  89838. unsigned i;
  89839. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89840. return false;
  89841. if(raw)
  89842. raw[(*rawlen)++] = (FLAC__byte)x;
  89843. if(!(x & 0x80)) { /* 0xxxxxxx */
  89844. v = x;
  89845. i = 0;
  89846. }
  89847. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89848. v = x & 0x1F;
  89849. i = 1;
  89850. }
  89851. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89852. v = x & 0x0F;
  89853. i = 2;
  89854. }
  89855. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89856. v = x & 0x07;
  89857. i = 3;
  89858. }
  89859. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89860. v = x & 0x03;
  89861. i = 4;
  89862. }
  89863. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89864. v = x & 0x01;
  89865. i = 5;
  89866. }
  89867. else {
  89868. *val = 0xffffffff;
  89869. return true;
  89870. }
  89871. for( ; i; i--) {
  89872. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89873. return false;
  89874. if(raw)
  89875. raw[(*rawlen)++] = (FLAC__byte)x;
  89876. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89877. *val = 0xffffffff;
  89878. return true;
  89879. }
  89880. v <<= 6;
  89881. v |= (x & 0x3F);
  89882. }
  89883. *val = v;
  89884. return true;
  89885. }
  89886. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89887. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  89888. {
  89889. FLAC__uint64 v = 0;
  89890. FLAC__uint32 x;
  89891. unsigned i;
  89892. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89893. return false;
  89894. if(raw)
  89895. raw[(*rawlen)++] = (FLAC__byte)x;
  89896. if(!(x & 0x80)) { /* 0xxxxxxx */
  89897. v = x;
  89898. i = 0;
  89899. }
  89900. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89901. v = x & 0x1F;
  89902. i = 1;
  89903. }
  89904. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89905. v = x & 0x0F;
  89906. i = 2;
  89907. }
  89908. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89909. v = x & 0x07;
  89910. i = 3;
  89911. }
  89912. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89913. v = x & 0x03;
  89914. i = 4;
  89915. }
  89916. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89917. v = x & 0x01;
  89918. i = 5;
  89919. }
  89920. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  89921. v = 0;
  89922. i = 6;
  89923. }
  89924. else {
  89925. *val = FLAC__U64L(0xffffffffffffffff);
  89926. return true;
  89927. }
  89928. for( ; i; i--) {
  89929. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89930. return false;
  89931. if(raw)
  89932. raw[(*rawlen)++] = (FLAC__byte)x;
  89933. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89934. *val = FLAC__U64L(0xffffffffffffffff);
  89935. return true;
  89936. }
  89937. v <<= 6;
  89938. v |= (x & 0x3F);
  89939. }
  89940. *val = v;
  89941. return true;
  89942. }
  89943. #endif
  89944. /********* End of inlined file: bitreader.c *********/
  89945. /********* Start of inlined file: bitwriter.c *********/
  89946. /********* Start of inlined file: juce_FlacHeader.h *********/
  89947. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89948. // tasks..
  89949. #define VERSION "1.2.1"
  89950. #define FLAC__NO_DLL 1
  89951. #if JUCE_MSVC
  89952. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89953. #endif
  89954. #if JUCE_MAC
  89955. #define FLAC__SYS_DARWIN 1
  89956. #endif
  89957. /********* End of inlined file: juce_FlacHeader.h *********/
  89958. #if JUCE_USE_FLAC
  89959. #if HAVE_CONFIG_H
  89960. # include <config.h>
  89961. #endif
  89962. #include <stdlib.h> /* for malloc() */
  89963. #include <string.h> /* for memcpy(), memset() */
  89964. #ifdef _MSC_VER
  89965. #include <winsock.h> /* for ntohl() */
  89966. #elif defined FLAC__SYS_DARWIN
  89967. #include <machine/endian.h> /* for ntohl() */
  89968. #elif defined __MINGW32__
  89969. #include <winsock.h> /* for ntohl() */
  89970. #else
  89971. #include <netinet/in.h> /* for ntohl() */
  89972. #endif
  89973. #if 0 /* UNUSED */
  89974. #endif
  89975. /********* Start of inlined file: bitwriter.h *********/
  89976. #ifndef FLAC__PRIVATE__BITWRITER_H
  89977. #define FLAC__PRIVATE__BITWRITER_H
  89978. #include <stdio.h> /* for FILE */
  89979. /*
  89980. * opaque structure definition
  89981. */
  89982. struct FLAC__BitWriter;
  89983. typedef struct FLAC__BitWriter FLAC__BitWriter;
  89984. /*
  89985. * construction, deletion, initialization, etc functions
  89986. */
  89987. FLAC__BitWriter *FLAC__bitwriter_new(void);
  89988. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  89989. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  89990. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  89991. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  89992. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  89993. /*
  89994. * CRC functions
  89995. *
  89996. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  89997. */
  89998. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  89999. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  90000. /*
  90001. * info functions
  90002. */
  90003. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  90004. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  90005. /*
  90006. * direct buffer access
  90007. *
  90008. * there may be no calls on the bitwriter between get and release.
  90009. * the bitwriter continues to own the returned buffer.
  90010. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  90011. */
  90012. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  90013. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  90014. /*
  90015. * write functions
  90016. */
  90017. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  90018. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  90019. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  90020. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  90021. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  90022. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  90023. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  90024. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  90025. #if 0 /* UNUSED */
  90026. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  90027. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  90028. #endif
  90029. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  90030. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  90031. #if 0 /* UNUSED */
  90032. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  90033. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  90034. #endif
  90035. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  90036. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  90037. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  90038. #endif
  90039. /********* End of inlined file: bitwriter.h *********/
  90040. /********* Start of inlined file: alloc.h *********/
  90041. #ifndef FLAC__SHARE__ALLOC_H
  90042. #define FLAC__SHARE__ALLOC_H
  90043. #if HAVE_CONFIG_H
  90044. # include <config.h>
  90045. #endif
  90046. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  90047. * before #including this file, otherwise SIZE_MAX might not be defined
  90048. */
  90049. #include <limits.h> /* for SIZE_MAX */
  90050. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  90051. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  90052. #endif
  90053. #include <stdlib.h> /* for size_t, malloc(), etc */
  90054. #ifndef SIZE_MAX
  90055. # ifndef SIZE_T_MAX
  90056. # ifdef _MSC_VER
  90057. # define SIZE_T_MAX UINT_MAX
  90058. # else
  90059. # error
  90060. # endif
  90061. # endif
  90062. # define SIZE_MAX SIZE_T_MAX
  90063. #endif
  90064. #ifndef FLaC__INLINE
  90065. #define FLaC__INLINE
  90066. #endif
  90067. /* avoid malloc()ing 0 bytes, see:
  90068. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  90069. */
  90070. static FLaC__INLINE void *safe_malloc_(size_t size)
  90071. {
  90072. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90073. if(!size)
  90074. size++;
  90075. return malloc(size);
  90076. }
  90077. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  90078. {
  90079. if(!nmemb || !size)
  90080. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90081. return calloc(nmemb, size);
  90082. }
  90083. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  90084. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  90085. {
  90086. size2 += size1;
  90087. if(size2 < size1)
  90088. return 0;
  90089. return safe_malloc_(size2);
  90090. }
  90091. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  90092. {
  90093. size2 += size1;
  90094. if(size2 < size1)
  90095. return 0;
  90096. size3 += size2;
  90097. if(size3 < size2)
  90098. return 0;
  90099. return safe_malloc_(size3);
  90100. }
  90101. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  90102. {
  90103. size2 += size1;
  90104. if(size2 < size1)
  90105. return 0;
  90106. size3 += size2;
  90107. if(size3 < size2)
  90108. return 0;
  90109. size4 += size3;
  90110. if(size4 < size3)
  90111. return 0;
  90112. return safe_malloc_(size4);
  90113. }
  90114. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  90115. #if 0
  90116. needs support for cases where sizeof(size_t) != 4
  90117. {
  90118. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  90119. if(sizeof(size_t) == 4) {
  90120. if ((double)size1 * (double)size2 < 4294967296.0)
  90121. return malloc(size1*size2);
  90122. }
  90123. return 0;
  90124. }
  90125. #else
  90126. /* better? */
  90127. {
  90128. if(!size1 || !size2)
  90129. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90130. if(size1 > SIZE_MAX / size2)
  90131. return 0;
  90132. return malloc(size1*size2);
  90133. }
  90134. #endif
  90135. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  90136. {
  90137. if(!size1 || !size2 || !size3)
  90138. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90139. if(size1 > SIZE_MAX / size2)
  90140. return 0;
  90141. size1 *= size2;
  90142. if(size1 > SIZE_MAX / size3)
  90143. return 0;
  90144. return malloc(size1*size3);
  90145. }
  90146. /* size1*size2 + size3 */
  90147. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  90148. {
  90149. if(!size1 || !size2)
  90150. return safe_malloc_(size3);
  90151. if(size1 > SIZE_MAX / size2)
  90152. return 0;
  90153. return safe_malloc_add_2op_(size1*size2, size3);
  90154. }
  90155. /* size1 * (size2 + size3) */
  90156. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  90157. {
  90158. if(!size1 || (!size2 && !size3))
  90159. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  90160. size2 += size3;
  90161. if(size2 < size3)
  90162. return 0;
  90163. return safe_malloc_mul_2op_(size1, size2);
  90164. }
  90165. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  90166. {
  90167. size2 += size1;
  90168. if(size2 < size1)
  90169. return 0;
  90170. return realloc(ptr, size2);
  90171. }
  90172. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  90173. {
  90174. size2 += size1;
  90175. if(size2 < size1)
  90176. return 0;
  90177. size3 += size2;
  90178. if(size3 < size2)
  90179. return 0;
  90180. return realloc(ptr, size3);
  90181. }
  90182. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  90183. {
  90184. size2 += size1;
  90185. if(size2 < size1)
  90186. return 0;
  90187. size3 += size2;
  90188. if(size3 < size2)
  90189. return 0;
  90190. size4 += size3;
  90191. if(size4 < size3)
  90192. return 0;
  90193. return realloc(ptr, size4);
  90194. }
  90195. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  90196. {
  90197. if(!size1 || !size2)
  90198. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90199. if(size1 > SIZE_MAX / size2)
  90200. return 0;
  90201. return realloc(ptr, size1*size2);
  90202. }
  90203. /* size1 * (size2 + size3) */
  90204. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  90205. {
  90206. if(!size1 || (!size2 && !size3))
  90207. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90208. size2 += size3;
  90209. if(size2 < size3)
  90210. return 0;
  90211. return safe_realloc_mul_2op_(ptr, size1, size2);
  90212. }
  90213. #endif
  90214. /********* End of inlined file: alloc.h *********/
  90215. /* Things should be fastest when this matches the machine word size */
  90216. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  90217. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  90218. typedef FLAC__uint32 bwword;
  90219. #define FLAC__BYTES_PER_WORD 4
  90220. #define FLAC__BITS_PER_WORD 32
  90221. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90222. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  90223. #if WORDS_BIGENDIAN
  90224. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90225. #else
  90226. #ifdef _MSC_VER
  90227. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90228. #else
  90229. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90230. #endif
  90231. #endif
  90232. /*
  90233. * The default capacity here doesn't matter too much. The buffer always grows
  90234. * to hold whatever is written to it. Usually the encoder will stop adding at
  90235. * a frame or metadata block, then write that out and clear the buffer for the
  90236. * next one.
  90237. */
  90238. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  90239. /* When growing, increment 4K at a time */
  90240. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  90241. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  90242. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  90243. #ifdef min
  90244. #undef min
  90245. #endif
  90246. #define min(x,y) ((x)<(y)?(x):(y))
  90247. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90248. #ifdef _MSC_VER
  90249. #define FLAC__U64L(x) x
  90250. #else
  90251. #define FLAC__U64L(x) x##LLU
  90252. #endif
  90253. #ifndef FLaC__INLINE
  90254. #define FLaC__INLINE
  90255. #endif
  90256. struct FLAC__BitWriter {
  90257. bwword *buffer;
  90258. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  90259. unsigned capacity; /* capacity of buffer in words */
  90260. unsigned words; /* # of complete words in buffer */
  90261. unsigned bits; /* # of used bits in accum */
  90262. };
  90263. /* * WATCHOUT: The current implementation only grows the buffer. */
  90264. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  90265. {
  90266. unsigned new_capacity;
  90267. bwword *new_buffer;
  90268. FLAC__ASSERT(0 != bw);
  90269. FLAC__ASSERT(0 != bw->buffer);
  90270. /* calculate total words needed to store 'bits_to_add' additional bits */
  90271. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  90272. /* it's possible (due to pessimism in the growth estimation that
  90273. * leads to this call) that we don't actually need to grow
  90274. */
  90275. if(bw->capacity >= new_capacity)
  90276. return true;
  90277. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  90278. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  90279. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90280. /* make sure we got everything right */
  90281. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90282. FLAC__ASSERT(new_capacity > bw->capacity);
  90283. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  90284. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  90285. if(new_buffer == 0)
  90286. return false;
  90287. bw->buffer = new_buffer;
  90288. bw->capacity = new_capacity;
  90289. return true;
  90290. }
  90291. /***********************************************************************
  90292. *
  90293. * Class constructor/destructor
  90294. *
  90295. ***********************************************************************/
  90296. FLAC__BitWriter *FLAC__bitwriter_new(void)
  90297. {
  90298. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  90299. /* note that calloc() sets all members to 0 for us */
  90300. return bw;
  90301. }
  90302. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  90303. {
  90304. FLAC__ASSERT(0 != bw);
  90305. FLAC__bitwriter_free(bw);
  90306. free(bw);
  90307. }
  90308. /***********************************************************************
  90309. *
  90310. * Public class methods
  90311. *
  90312. ***********************************************************************/
  90313. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  90314. {
  90315. FLAC__ASSERT(0 != bw);
  90316. bw->words = bw->bits = 0;
  90317. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  90318. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  90319. if(bw->buffer == 0)
  90320. return false;
  90321. return true;
  90322. }
  90323. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  90324. {
  90325. FLAC__ASSERT(0 != bw);
  90326. if(0 != bw->buffer)
  90327. free(bw->buffer);
  90328. bw->buffer = 0;
  90329. bw->capacity = 0;
  90330. bw->words = bw->bits = 0;
  90331. }
  90332. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  90333. {
  90334. bw->words = bw->bits = 0;
  90335. }
  90336. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  90337. {
  90338. unsigned i, j;
  90339. if(bw == 0) {
  90340. fprintf(out, "bitwriter is NULL\n");
  90341. }
  90342. else {
  90343. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  90344. for(i = 0; i < bw->words; i++) {
  90345. fprintf(out, "%08X: ", i);
  90346. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  90347. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  90348. fprintf(out, "\n");
  90349. }
  90350. if(bw->bits > 0) {
  90351. fprintf(out, "%08X: ", i);
  90352. for(j = 0; j < bw->bits; j++)
  90353. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  90354. fprintf(out, "\n");
  90355. }
  90356. }
  90357. }
  90358. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  90359. {
  90360. const FLAC__byte *buffer;
  90361. size_t bytes;
  90362. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90363. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90364. return false;
  90365. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  90366. FLAC__bitwriter_release_buffer(bw);
  90367. return true;
  90368. }
  90369. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  90370. {
  90371. const FLAC__byte *buffer;
  90372. size_t bytes;
  90373. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90374. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90375. return false;
  90376. *crc = FLAC__crc8(buffer, bytes);
  90377. FLAC__bitwriter_release_buffer(bw);
  90378. return true;
  90379. }
  90380. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  90381. {
  90382. return ((bw->bits & 7) == 0);
  90383. }
  90384. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  90385. {
  90386. return FLAC__TOTAL_BITS(bw);
  90387. }
  90388. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  90389. {
  90390. FLAC__ASSERT((bw->bits & 7) == 0);
  90391. /* double protection */
  90392. if(bw->bits & 7)
  90393. return false;
  90394. /* if we have bits in the accumulator we have to flush those to the buffer first */
  90395. if(bw->bits) {
  90396. FLAC__ASSERT(bw->words <= bw->capacity);
  90397. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  90398. return false;
  90399. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  90400. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  90401. }
  90402. /* now we can just return what we have */
  90403. *buffer = (FLAC__byte*)bw->buffer;
  90404. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  90405. return true;
  90406. }
  90407. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  90408. {
  90409. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  90410. * get-mode' flag could be added everywhere and then cleared here
  90411. */
  90412. (void)bw;
  90413. }
  90414. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  90415. {
  90416. unsigned n;
  90417. FLAC__ASSERT(0 != bw);
  90418. FLAC__ASSERT(0 != bw->buffer);
  90419. if(bits == 0)
  90420. return true;
  90421. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90422. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90423. return false;
  90424. /* first part gets to word alignment */
  90425. if(bw->bits) {
  90426. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  90427. bw->accum <<= n;
  90428. bits -= n;
  90429. bw->bits += n;
  90430. if(bw->bits == FLAC__BITS_PER_WORD) {
  90431. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90432. bw->bits = 0;
  90433. }
  90434. else
  90435. return true;
  90436. }
  90437. /* do whole words */
  90438. while(bits >= FLAC__BITS_PER_WORD) {
  90439. bw->buffer[bw->words++] = 0;
  90440. bits -= FLAC__BITS_PER_WORD;
  90441. }
  90442. /* do any leftovers */
  90443. if(bits > 0) {
  90444. bw->accum = 0;
  90445. bw->bits = bits;
  90446. }
  90447. return true;
  90448. }
  90449. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  90450. {
  90451. register unsigned left;
  90452. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90453. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90454. FLAC__ASSERT(0 != bw);
  90455. FLAC__ASSERT(0 != bw->buffer);
  90456. FLAC__ASSERT(bits <= 32);
  90457. if(bits == 0)
  90458. return true;
  90459. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90460. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90461. return false;
  90462. left = FLAC__BITS_PER_WORD - bw->bits;
  90463. if(bits < left) {
  90464. bw->accum <<= bits;
  90465. bw->accum |= val;
  90466. bw->bits += bits;
  90467. }
  90468. 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 */
  90469. bw->accum <<= left;
  90470. bw->accum |= val >> (bw->bits = bits - left);
  90471. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90472. bw->accum = val;
  90473. }
  90474. else {
  90475. bw->accum = val;
  90476. bw->bits = 0;
  90477. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  90478. }
  90479. return true;
  90480. }
  90481. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  90482. {
  90483. /* zero-out unused bits */
  90484. if(bits < 32)
  90485. val &= (~(0xffffffff << bits));
  90486. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90487. }
  90488. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  90489. {
  90490. /* this could be a little faster but it's not used for much */
  90491. if(bits > 32) {
  90492. return
  90493. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  90494. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  90495. }
  90496. else
  90497. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90498. }
  90499. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  90500. {
  90501. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  90502. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  90503. return false;
  90504. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  90505. return false;
  90506. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  90507. return false;
  90508. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  90509. return false;
  90510. return true;
  90511. }
  90512. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  90513. {
  90514. unsigned i;
  90515. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  90516. for(i = 0; i < nvals; i++) {
  90517. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  90518. return false;
  90519. }
  90520. return true;
  90521. }
  90522. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  90523. {
  90524. if(val < 32)
  90525. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  90526. else
  90527. return
  90528. FLAC__bitwriter_write_zeroes(bw, val) &&
  90529. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  90530. }
  90531. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  90532. {
  90533. FLAC__uint32 uval;
  90534. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  90535. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90536. uval = (val<<1) ^ (val>>31);
  90537. return 1 + parameter + (uval >> parameter);
  90538. }
  90539. #if 0 /* UNUSED */
  90540. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  90541. {
  90542. unsigned bits, msbs, uval;
  90543. unsigned k;
  90544. FLAC__ASSERT(parameter > 0);
  90545. /* fold signed to unsigned */
  90546. if(val < 0)
  90547. uval = (unsigned)(((-(++val)) << 1) + 1);
  90548. else
  90549. uval = (unsigned)(val << 1);
  90550. k = FLAC__bitmath_ilog2(parameter);
  90551. if(parameter == 1u<<k) {
  90552. FLAC__ASSERT(k <= 30);
  90553. msbs = uval >> k;
  90554. bits = 1 + k + msbs;
  90555. }
  90556. else {
  90557. unsigned q, r, d;
  90558. d = (1 << (k+1)) - parameter;
  90559. q = uval / parameter;
  90560. r = uval - (q * parameter);
  90561. bits = 1 + q + k;
  90562. if(r >= d)
  90563. bits++;
  90564. }
  90565. return bits;
  90566. }
  90567. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  90568. {
  90569. unsigned bits, msbs;
  90570. unsigned k;
  90571. FLAC__ASSERT(parameter > 0);
  90572. k = FLAC__bitmath_ilog2(parameter);
  90573. if(parameter == 1u<<k) {
  90574. FLAC__ASSERT(k <= 30);
  90575. msbs = uval >> k;
  90576. bits = 1 + k + msbs;
  90577. }
  90578. else {
  90579. unsigned q, r, d;
  90580. d = (1 << (k+1)) - parameter;
  90581. q = uval / parameter;
  90582. r = uval - (q * parameter);
  90583. bits = 1 + q + k;
  90584. if(r >= d)
  90585. bits++;
  90586. }
  90587. return bits;
  90588. }
  90589. #endif /* UNUSED */
  90590. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  90591. {
  90592. unsigned total_bits, interesting_bits, msbs;
  90593. FLAC__uint32 uval, pattern;
  90594. FLAC__ASSERT(0 != bw);
  90595. FLAC__ASSERT(0 != bw->buffer);
  90596. FLAC__ASSERT(parameter < 8*sizeof(uval));
  90597. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90598. uval = (val<<1) ^ (val>>31);
  90599. msbs = uval >> parameter;
  90600. interesting_bits = 1 + parameter;
  90601. total_bits = interesting_bits + msbs;
  90602. pattern = 1 << parameter; /* the unary end bit */
  90603. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  90604. if(total_bits <= 32)
  90605. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  90606. else
  90607. return
  90608. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  90609. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  90610. }
  90611. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  90612. {
  90613. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  90614. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  90615. FLAC__uint32 uval;
  90616. unsigned left;
  90617. const unsigned lsbits = 1 + parameter;
  90618. unsigned msbits;
  90619. FLAC__ASSERT(0 != bw);
  90620. FLAC__ASSERT(0 != bw->buffer);
  90621. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  90622. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90623. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90624. while(nvals) {
  90625. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90626. uval = (*vals<<1) ^ (*vals>>31);
  90627. msbits = uval >> parameter;
  90628. #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) */
  90629. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90630. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90631. bw->bits = bw->bits + msbits + lsbits;
  90632. uval |= mask1; /* set stop bit */
  90633. uval &= mask2; /* mask off unused top bits */
  90634. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  90635. bw->accum <<= msbits;
  90636. bw->accum <<= lsbits;
  90637. bw->accum |= uval;
  90638. if(bw->bits == FLAC__BITS_PER_WORD) {
  90639. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90640. bw->bits = 0;
  90641. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  90642. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  90643. FLAC__ASSERT(bw->capacity == bw->words);
  90644. return false;
  90645. }
  90646. }
  90647. }
  90648. else {
  90649. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  90650. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90651. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90652. bw->bits = bw->bits + msbits + lsbits;
  90653. uval |= mask1; /* set stop bit */
  90654. uval &= mask2; /* mask off unused top bits */
  90655. bw->accum <<= msbits + lsbits;
  90656. bw->accum |= uval;
  90657. }
  90658. else {
  90659. #endif
  90660. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90661. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  90662. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  90663. return false;
  90664. if(msbits) {
  90665. /* first part gets to word alignment */
  90666. if(bw->bits) {
  90667. left = FLAC__BITS_PER_WORD - bw->bits;
  90668. if(msbits < left) {
  90669. bw->accum <<= msbits;
  90670. bw->bits += msbits;
  90671. goto break1;
  90672. }
  90673. else {
  90674. bw->accum <<= left;
  90675. msbits -= left;
  90676. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90677. bw->bits = 0;
  90678. }
  90679. }
  90680. /* do whole words */
  90681. while(msbits >= FLAC__BITS_PER_WORD) {
  90682. bw->buffer[bw->words++] = 0;
  90683. msbits -= FLAC__BITS_PER_WORD;
  90684. }
  90685. /* do any leftovers */
  90686. if(msbits > 0) {
  90687. bw->accum = 0;
  90688. bw->bits = msbits;
  90689. }
  90690. }
  90691. break1:
  90692. uval |= mask1; /* set stop bit */
  90693. uval &= mask2; /* mask off unused top bits */
  90694. left = FLAC__BITS_PER_WORD - bw->bits;
  90695. if(lsbits < left) {
  90696. bw->accum <<= lsbits;
  90697. bw->accum |= uval;
  90698. bw->bits += lsbits;
  90699. }
  90700. else {
  90701. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  90702. * be > lsbits (because of previous assertions) so it would have
  90703. * triggered the (lsbits<left) case above.
  90704. */
  90705. FLAC__ASSERT(bw->bits);
  90706. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  90707. bw->accum <<= left;
  90708. bw->accum |= uval >> (bw->bits = lsbits - left);
  90709. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90710. bw->accum = uval;
  90711. }
  90712. #if 1
  90713. }
  90714. #endif
  90715. vals++;
  90716. nvals--;
  90717. }
  90718. return true;
  90719. }
  90720. #if 0 /* UNUSED */
  90721. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  90722. {
  90723. unsigned total_bits, msbs, uval;
  90724. unsigned k;
  90725. FLAC__ASSERT(0 != bw);
  90726. FLAC__ASSERT(0 != bw->buffer);
  90727. FLAC__ASSERT(parameter > 0);
  90728. /* fold signed to unsigned */
  90729. if(val < 0)
  90730. uval = (unsigned)(((-(++val)) << 1) + 1);
  90731. else
  90732. uval = (unsigned)(val << 1);
  90733. k = FLAC__bitmath_ilog2(parameter);
  90734. if(parameter == 1u<<k) {
  90735. unsigned pattern;
  90736. FLAC__ASSERT(k <= 30);
  90737. msbs = uval >> k;
  90738. total_bits = 1 + k + msbs;
  90739. pattern = 1 << k; /* the unary end bit */
  90740. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90741. if(total_bits <= 32) {
  90742. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90743. return false;
  90744. }
  90745. else {
  90746. /* write the unary MSBs */
  90747. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90748. return false;
  90749. /* write the unary end bit and binary LSBs */
  90750. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90751. return false;
  90752. }
  90753. }
  90754. else {
  90755. unsigned q, r, d;
  90756. d = (1 << (k+1)) - parameter;
  90757. q = uval / parameter;
  90758. r = uval - (q * parameter);
  90759. /* write the unary MSBs */
  90760. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90761. return false;
  90762. /* write the unary end bit */
  90763. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90764. return false;
  90765. /* write the binary LSBs */
  90766. if(r >= d) {
  90767. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90768. return false;
  90769. }
  90770. else {
  90771. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90772. return false;
  90773. }
  90774. }
  90775. return true;
  90776. }
  90777. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  90778. {
  90779. unsigned total_bits, msbs;
  90780. unsigned k;
  90781. FLAC__ASSERT(0 != bw);
  90782. FLAC__ASSERT(0 != bw->buffer);
  90783. FLAC__ASSERT(parameter > 0);
  90784. k = FLAC__bitmath_ilog2(parameter);
  90785. if(parameter == 1u<<k) {
  90786. unsigned pattern;
  90787. FLAC__ASSERT(k <= 30);
  90788. msbs = uval >> k;
  90789. total_bits = 1 + k + msbs;
  90790. pattern = 1 << k; /* the unary end bit */
  90791. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90792. if(total_bits <= 32) {
  90793. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90794. return false;
  90795. }
  90796. else {
  90797. /* write the unary MSBs */
  90798. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90799. return false;
  90800. /* write the unary end bit and binary LSBs */
  90801. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90802. return false;
  90803. }
  90804. }
  90805. else {
  90806. unsigned q, r, d;
  90807. d = (1 << (k+1)) - parameter;
  90808. q = uval / parameter;
  90809. r = uval - (q * parameter);
  90810. /* write the unary MSBs */
  90811. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90812. return false;
  90813. /* write the unary end bit */
  90814. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90815. return false;
  90816. /* write the binary LSBs */
  90817. if(r >= d) {
  90818. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90819. return false;
  90820. }
  90821. else {
  90822. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90823. return false;
  90824. }
  90825. }
  90826. return true;
  90827. }
  90828. #endif /* UNUSED */
  90829. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  90830. {
  90831. FLAC__bool ok = 1;
  90832. FLAC__ASSERT(0 != bw);
  90833. FLAC__ASSERT(0 != bw->buffer);
  90834. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  90835. if(val < 0x80) {
  90836. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  90837. }
  90838. else if(val < 0x800) {
  90839. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  90840. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90841. }
  90842. else if(val < 0x10000) {
  90843. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  90844. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90845. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90846. }
  90847. else if(val < 0x200000) {
  90848. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  90849. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90850. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90851. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90852. }
  90853. else if(val < 0x4000000) {
  90854. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  90855. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90856. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90857. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90858. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90859. }
  90860. else {
  90861. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  90862. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  90863. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90864. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90865. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90866. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90867. }
  90868. return ok;
  90869. }
  90870. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  90871. {
  90872. FLAC__bool ok = 1;
  90873. FLAC__ASSERT(0 != bw);
  90874. FLAC__ASSERT(0 != bw->buffer);
  90875. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  90876. if(val < 0x80) {
  90877. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  90878. }
  90879. else if(val < 0x800) {
  90880. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  90881. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90882. }
  90883. else if(val < 0x10000) {
  90884. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  90885. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90886. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90887. }
  90888. else if(val < 0x200000) {
  90889. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  90890. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90891. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90892. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90893. }
  90894. else if(val < 0x4000000) {
  90895. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  90896. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90897. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90898. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90899. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90900. }
  90901. else if(val < 0x80000000) {
  90902. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  90903. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90904. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90905. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90906. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90907. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90908. }
  90909. else {
  90910. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  90911. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  90912. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90913. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90914. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90915. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90916. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90917. }
  90918. return ok;
  90919. }
  90920. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  90921. {
  90922. /* 0-pad to byte boundary */
  90923. if(bw->bits & 7u)
  90924. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  90925. else
  90926. return true;
  90927. }
  90928. #endif
  90929. /********* End of inlined file: bitwriter.c *********/
  90930. /********* Start of inlined file: cpu.c *********/
  90931. /********* Start of inlined file: juce_FlacHeader.h *********/
  90932. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90933. // tasks..
  90934. #define VERSION "1.2.1"
  90935. #define FLAC__NO_DLL 1
  90936. #if JUCE_MSVC
  90937. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90938. #endif
  90939. #if JUCE_MAC
  90940. #define FLAC__SYS_DARWIN 1
  90941. #endif
  90942. /********* End of inlined file: juce_FlacHeader.h *********/
  90943. #if JUCE_USE_FLAC
  90944. #if HAVE_CONFIG_H
  90945. # include <config.h>
  90946. #endif
  90947. #include <stdlib.h>
  90948. #include <stdio.h>
  90949. #if defined FLAC__CPU_IA32
  90950. # include <signal.h>
  90951. #elif defined FLAC__CPU_PPC
  90952. # if !defined FLAC__NO_ASM
  90953. # if defined FLAC__SYS_DARWIN
  90954. # include <sys/sysctl.h>
  90955. # include <mach/mach.h>
  90956. # include <mach/mach_host.h>
  90957. # include <mach/host_info.h>
  90958. # include <mach/machine.h>
  90959. # ifndef CPU_SUBTYPE_POWERPC_970
  90960. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  90961. # endif
  90962. # else /* FLAC__SYS_DARWIN */
  90963. # include <signal.h>
  90964. # include <setjmp.h>
  90965. static sigjmp_buf jmpbuf;
  90966. static volatile sig_atomic_t canjump = 0;
  90967. static void sigill_handler (int sig)
  90968. {
  90969. if (!canjump) {
  90970. signal (sig, SIG_DFL);
  90971. raise (sig);
  90972. }
  90973. canjump = 0;
  90974. siglongjmp (jmpbuf, 1);
  90975. }
  90976. # endif /* FLAC__SYS_DARWIN */
  90977. # endif /* FLAC__NO_ASM */
  90978. #endif /* FLAC__CPU_PPC */
  90979. #if defined (__NetBSD__) || defined(__OpenBSD__)
  90980. #include <sys/param.h>
  90981. #include <sys/sysctl.h>
  90982. #include <machine/cpu.h>
  90983. #endif
  90984. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  90985. #include <sys/types.h>
  90986. #include <sys/sysctl.h>
  90987. #endif
  90988. #if defined(__APPLE__)
  90989. /* how to get sysctlbyname()? */
  90990. #endif
  90991. /* these are flags in EDX of CPUID AX=00000001 */
  90992. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  90993. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  90994. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  90995. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  90996. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  90997. /* these are flags in ECX of CPUID AX=00000001 */
  90998. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  90999. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  91000. /* these are flags in EDX of CPUID AX=80000001 */
  91001. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  91002. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  91003. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  91004. /*
  91005. * Extra stuff needed for detection of OS support for SSE on IA-32
  91006. */
  91007. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  91008. # if defined(__linux__)
  91009. /*
  91010. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  91011. * modify the return address to jump over the offending SSE instruction
  91012. * and also the operation following it that indicates the instruction
  91013. * executed successfully. In this way we use no global variables and
  91014. * stay thread-safe.
  91015. *
  91016. * 3 + 3 + 6:
  91017. * 3 bytes for "xorps xmm0,xmm0"
  91018. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  91019. * 6 bytes extra in case our estimate is wrong
  91020. * 12 bytes puts us in the NOP "landing zone"
  91021. */
  91022. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  91023. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  91024. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  91025. {
  91026. (void)signal;
  91027. sc.eip += 3 + 3 + 6;
  91028. }
  91029. # else
  91030. # include <sys/ucontext.h>
  91031. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  91032. {
  91033. (void)signal, (void)si;
  91034. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  91035. }
  91036. # endif
  91037. # elif defined(_MSC_VER)
  91038. # include <windows.h>
  91039. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  91040. # ifdef USE_TRY_CATCH_FLAVOR
  91041. # else
  91042. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  91043. {
  91044. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  91045. ep->ContextRecord->Eip += 3 + 3 + 6;
  91046. return EXCEPTION_CONTINUE_EXECUTION;
  91047. }
  91048. return EXCEPTION_CONTINUE_SEARCH;
  91049. }
  91050. # endif
  91051. # endif
  91052. #endif
  91053. void FLAC__cpu_info(FLAC__CPUInfo *info)
  91054. {
  91055. /*
  91056. * IA32-specific
  91057. */
  91058. #ifdef FLAC__CPU_IA32
  91059. info->type = FLAC__CPUINFO_TYPE_IA32;
  91060. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  91061. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  91062. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  91063. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  91064. info->data.ia32.cmov = false;
  91065. info->data.ia32.mmx = false;
  91066. info->data.ia32.fxsr = false;
  91067. info->data.ia32.sse = false;
  91068. info->data.ia32.sse2 = false;
  91069. info->data.ia32.sse3 = false;
  91070. info->data.ia32.ssse3 = false;
  91071. info->data.ia32._3dnow = false;
  91072. info->data.ia32.ext3dnow = false;
  91073. info->data.ia32.extmmx = false;
  91074. if(info->data.ia32.cpuid) {
  91075. /* http://www.sandpile.org/ia32/cpuid.htm */
  91076. FLAC__uint32 flags_edx, flags_ecx;
  91077. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  91078. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  91079. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  91080. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  91081. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  91082. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  91083. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  91084. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  91085. #ifdef FLAC__USE_3DNOW
  91086. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  91087. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  91088. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  91089. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  91090. #else
  91091. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  91092. #endif
  91093. #ifdef DEBUG
  91094. fprintf(stderr, "CPU info (IA-32):\n");
  91095. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  91096. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  91097. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  91098. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  91099. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  91100. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91101. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  91102. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  91103. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  91104. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  91105. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  91106. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  91107. #endif
  91108. /*
  91109. * now have to check for OS support of SSE/SSE2
  91110. */
  91111. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  91112. #if defined FLAC__NO_SSE_OS
  91113. /* assume user knows better than us; turn it off */
  91114. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91115. #elif defined FLAC__SSE_OS
  91116. /* assume user knows better than us; leave as detected above */
  91117. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  91118. int sse = 0;
  91119. size_t len;
  91120. /* at least one of these must work: */
  91121. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  91122. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  91123. if(!sse)
  91124. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91125. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  91126. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  91127. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  91128. size_t len = sizeof(val);
  91129. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91130. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91131. else { /* double-check SSE2 */
  91132. mib[1] = CPU_SSE2;
  91133. len = sizeof(val);
  91134. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  91135. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91136. }
  91137. # else
  91138. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91139. # endif
  91140. #elif defined(__linux__)
  91141. int sse = 0;
  91142. struct sigaction sigill_save;
  91143. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  91144. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  91145. #else
  91146. struct sigaction sigill_sse;
  91147. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  91148. __sigemptyset(&sigill_sse.sa_mask);
  91149. 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 */
  91150. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  91151. #endif
  91152. {
  91153. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  91154. /* see sigill_handler_sse_os() for an explanation of the following: */
  91155. asm volatile (
  91156. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  91157. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  91158. "incl %0\n\t" /* SIGILL handler will jump over this */
  91159. /* landing zone */
  91160. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  91161. "nop\n\t"
  91162. "nop\n\t"
  91163. "nop\n\t"
  91164. "nop\n\t"
  91165. "nop\n\t"
  91166. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  91167. "nop\n\t"
  91168. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  91169. : "=r"(sse)
  91170. : "r"(sse)
  91171. );
  91172. sigaction(SIGILL, &sigill_save, NULL);
  91173. }
  91174. if(!sse)
  91175. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91176. #elif defined(_MSC_VER)
  91177. # ifdef USE_TRY_CATCH_FLAVOR
  91178. _try {
  91179. __asm {
  91180. # if _MSC_VER <= 1200
  91181. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91182. _emit 0x0F
  91183. _emit 0x57
  91184. _emit 0xC0
  91185. # else
  91186. xorps xmm0,xmm0
  91187. # endif
  91188. }
  91189. }
  91190. _except(EXCEPTION_EXECUTE_HANDLER) {
  91191. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  91192. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91193. }
  91194. # else
  91195. int sse = 0;
  91196. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  91197. /* see GCC version above for explanation */
  91198. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  91199. /* http://www.codeproject.com/cpp/gccasm.asp */
  91200. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  91201. __asm {
  91202. # if _MSC_VER <= 1200
  91203. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91204. _emit 0x0F
  91205. _emit 0x57
  91206. _emit 0xC0
  91207. # else
  91208. xorps xmm0,xmm0
  91209. # endif
  91210. inc sse
  91211. nop
  91212. nop
  91213. nop
  91214. nop
  91215. nop
  91216. nop
  91217. nop
  91218. nop
  91219. nop
  91220. }
  91221. SetUnhandledExceptionFilter(save);
  91222. if(!sse)
  91223. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91224. # endif
  91225. #else
  91226. /* no way to test, disable to be safe */
  91227. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91228. #endif
  91229. #ifdef DEBUG
  91230. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91231. #endif
  91232. }
  91233. }
  91234. #else
  91235. info->use_asm = false;
  91236. #endif
  91237. /*
  91238. * PPC-specific
  91239. */
  91240. #elif defined FLAC__CPU_PPC
  91241. info->type = FLAC__CPUINFO_TYPE_PPC;
  91242. # if !defined FLAC__NO_ASM
  91243. info->use_asm = true;
  91244. # ifdef FLAC__USE_ALTIVEC
  91245. # if defined FLAC__SYS_DARWIN
  91246. {
  91247. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  91248. size_t len = sizeof(val);
  91249. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  91250. }
  91251. {
  91252. host_basic_info_data_t hostInfo;
  91253. mach_msg_type_number_t infoCount;
  91254. infoCount = HOST_BASIC_INFO_COUNT;
  91255. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  91256. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  91257. }
  91258. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  91259. {
  91260. /* no Darwin, do it the brute-force way */
  91261. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  91262. info->data.ppc.altivec = 0;
  91263. info->data.ppc.ppc64 = 0;
  91264. signal (SIGILL, sigill_handler);
  91265. canjump = 0;
  91266. if (!sigsetjmp (jmpbuf, 1)) {
  91267. canjump = 1;
  91268. asm volatile (
  91269. "mtspr 256, %0\n\t"
  91270. "vand %%v0, %%v0, %%v0"
  91271. :
  91272. : "r" (-1)
  91273. );
  91274. info->data.ppc.altivec = 1;
  91275. }
  91276. canjump = 0;
  91277. if (!sigsetjmp (jmpbuf, 1)) {
  91278. int x = 0;
  91279. canjump = 1;
  91280. /* PPC64 hardware implements the cntlzd instruction */
  91281. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  91282. info->data.ppc.ppc64 = 1;
  91283. }
  91284. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  91285. }
  91286. # endif
  91287. # else /* !FLAC__USE_ALTIVEC */
  91288. info->data.ppc.altivec = 0;
  91289. info->data.ppc.ppc64 = 0;
  91290. # endif
  91291. # else
  91292. info->use_asm = false;
  91293. # endif
  91294. /*
  91295. * unknown CPI
  91296. */
  91297. #else
  91298. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  91299. info->use_asm = false;
  91300. #endif
  91301. }
  91302. #endif
  91303. /********* End of inlined file: cpu.c *********/
  91304. /********* Start of inlined file: crc.c *********/
  91305. /********* Start of inlined file: juce_FlacHeader.h *********/
  91306. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91307. // tasks..
  91308. #define VERSION "1.2.1"
  91309. #define FLAC__NO_DLL 1
  91310. #if JUCE_MSVC
  91311. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91312. #endif
  91313. #if JUCE_MAC
  91314. #define FLAC__SYS_DARWIN 1
  91315. #endif
  91316. /********* End of inlined file: juce_FlacHeader.h *********/
  91317. #if JUCE_USE_FLAC
  91318. #if HAVE_CONFIG_H
  91319. # include <config.h>
  91320. #endif
  91321. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  91322. FLAC__byte const FLAC__crc8_table[256] = {
  91323. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  91324. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  91325. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  91326. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  91327. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  91328. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  91329. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  91330. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  91331. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  91332. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  91333. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  91334. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  91335. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  91336. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  91337. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  91338. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  91339. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  91340. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  91341. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  91342. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  91343. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  91344. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  91345. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  91346. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  91347. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  91348. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  91349. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  91350. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  91351. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  91352. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  91353. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  91354. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  91355. };
  91356. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  91357. unsigned FLAC__crc16_table[256] = {
  91358. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  91359. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  91360. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  91361. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  91362. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  91363. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  91364. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  91365. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  91366. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  91367. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  91368. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  91369. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  91370. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  91371. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  91372. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  91373. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  91374. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  91375. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  91376. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  91377. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  91378. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  91379. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  91380. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  91381. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  91382. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  91383. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  91384. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  91385. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  91386. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  91387. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  91388. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  91389. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  91390. };
  91391. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  91392. {
  91393. *crc = FLAC__crc8_table[*crc ^ data];
  91394. }
  91395. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  91396. {
  91397. while(len--)
  91398. *crc = FLAC__crc8_table[*crc ^ *data++];
  91399. }
  91400. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  91401. {
  91402. FLAC__uint8 crc = 0;
  91403. while(len--)
  91404. crc = FLAC__crc8_table[crc ^ *data++];
  91405. return crc;
  91406. }
  91407. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  91408. {
  91409. unsigned crc = 0;
  91410. while(len--)
  91411. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  91412. return crc;
  91413. }
  91414. #endif
  91415. /********* End of inlined file: crc.c *********/
  91416. /********* Start of inlined file: fixed.c *********/
  91417. /********* Start of inlined file: juce_FlacHeader.h *********/
  91418. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91419. // tasks..
  91420. #define VERSION "1.2.1"
  91421. #define FLAC__NO_DLL 1
  91422. #if JUCE_MSVC
  91423. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91424. #endif
  91425. #if JUCE_MAC
  91426. #define FLAC__SYS_DARWIN 1
  91427. #endif
  91428. /********* End of inlined file: juce_FlacHeader.h *********/
  91429. #if JUCE_USE_FLAC
  91430. #if HAVE_CONFIG_H
  91431. # include <config.h>
  91432. #endif
  91433. #include <math.h>
  91434. #include <string.h>
  91435. /********* Start of inlined file: fixed.h *********/
  91436. #ifndef FLAC__PRIVATE__FIXED_H
  91437. #define FLAC__PRIVATE__FIXED_H
  91438. #ifdef HAVE_CONFIG_H
  91439. #include <config.h>
  91440. #endif
  91441. /********* Start of inlined file: float.h *********/
  91442. #ifndef FLAC__PRIVATE__FLOAT_H
  91443. #define FLAC__PRIVATE__FLOAT_H
  91444. #ifdef HAVE_CONFIG_H
  91445. #include <config.h>
  91446. #endif
  91447. /*
  91448. * These typedefs make it easier to ensure that integer versions of
  91449. * the library really only contain integer operations. All the code
  91450. * in libFLAC should use FLAC__float and FLAC__double in place of
  91451. * float and double, and be protected by checks of the macro
  91452. * FLAC__INTEGER_ONLY_LIBRARY.
  91453. *
  91454. * FLAC__real is the basic floating point type used in LPC analysis.
  91455. */
  91456. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91457. typedef double FLAC__double;
  91458. typedef float FLAC__float;
  91459. /*
  91460. * WATCHOUT: changing FLAC__real will change the signatures of many
  91461. * functions that have assembly language equivalents and break them.
  91462. */
  91463. typedef float FLAC__real;
  91464. #else
  91465. /*
  91466. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  91467. * for the integer part and lower 16 bits for the fractional part.
  91468. */
  91469. typedef FLAC__int32 FLAC__fixedpoint;
  91470. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  91471. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  91472. extern const FLAC__fixedpoint FLAC__FP_ONE;
  91473. extern const FLAC__fixedpoint FLAC__FP_LN2;
  91474. extern const FLAC__fixedpoint FLAC__FP_E;
  91475. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  91476. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  91477. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  91478. /*
  91479. * FLAC__fixedpoint_log2()
  91480. * --------------------------------------------------------------------
  91481. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  91482. * algorithm by Knuth for x >= 1.0
  91483. *
  91484. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  91485. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  91486. *
  91487. * 'precision' roughly limits the number of iterations that are done;
  91488. * use (unsigned)(-1) for maximum precision.
  91489. *
  91490. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  91491. * function will punt and return 0.
  91492. *
  91493. * The return value will also have 'fracbits' fractional bits.
  91494. */
  91495. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  91496. #endif
  91497. #endif
  91498. /********* End of inlined file: float.h *********/
  91499. /********* Start of inlined file: format.h *********/
  91500. #ifndef FLAC__PRIVATE__FORMAT_H
  91501. #define FLAC__PRIVATE__FORMAT_H
  91502. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  91503. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  91504. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  91505. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91506. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91507. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  91508. #endif
  91509. /********* End of inlined file: format.h *********/
  91510. /*
  91511. * FLAC__fixed_compute_best_predictor()
  91512. * --------------------------------------------------------------------
  91513. * Compute the best fixed predictor and the expected bits-per-sample
  91514. * of the residual signal for each order. The _wide() version uses
  91515. * 64-bit integers which is statistically necessary when bits-per-
  91516. * sample + log2(blocksize) > 30
  91517. *
  91518. * IN data[0,data_len-1]
  91519. * IN data_len
  91520. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  91521. */
  91522. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91523. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91524. # ifndef FLAC__NO_ASM
  91525. # ifdef FLAC__CPU_IA32
  91526. # ifdef FLAC__HAS_NASM
  91527. 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]);
  91528. # endif
  91529. # endif
  91530. # endif
  91531. 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]);
  91532. #else
  91533. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91534. 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]);
  91535. #endif
  91536. /*
  91537. * FLAC__fixed_compute_residual()
  91538. * --------------------------------------------------------------------
  91539. * Compute the residual signal obtained from sutracting the predicted
  91540. * signal from the original.
  91541. *
  91542. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91543. * IN data_len length of original signal
  91544. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91545. * OUT residual[0,data_len-1] residual signal
  91546. */
  91547. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  91548. /*
  91549. * FLAC__fixed_restore_signal()
  91550. * --------------------------------------------------------------------
  91551. * Restore the original signal by summing the residual and the
  91552. * predictor.
  91553. *
  91554. * IN residual[0,data_len-1] residual signal
  91555. * IN data_len length of original signal
  91556. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91557. * *** IMPORTANT: the caller must pass in the historical samples:
  91558. * IN data[-order,-1] previously-reconstructed historical samples
  91559. * OUT data[0,data_len-1] original signal
  91560. */
  91561. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  91562. #endif
  91563. /********* End of inlined file: fixed.h *********/
  91564. #ifndef M_LN2
  91565. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91566. #define M_LN2 0.69314718055994530942
  91567. #endif
  91568. #ifdef min
  91569. #undef min
  91570. #endif
  91571. #define min(x,y) ((x) < (y)? (x) : (y))
  91572. #ifdef local_abs
  91573. #undef local_abs
  91574. #endif
  91575. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  91576. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91577. /* rbps stands for residual bits per sample
  91578. *
  91579. * (ln(2) * err)
  91580. * rbps = log (-----------)
  91581. * 2 ( n )
  91582. */
  91583. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  91584. {
  91585. FLAC__uint32 rbps;
  91586. unsigned bits; /* the number of bits required to represent a number */
  91587. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91588. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91589. FLAC__ASSERT(err > 0);
  91590. FLAC__ASSERT(n > 0);
  91591. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91592. if(err <= n)
  91593. return 0;
  91594. /*
  91595. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91596. * These allow us later to know we won't lose too much precision in the
  91597. * fixed-point division (err<<fracbits)/n.
  91598. */
  91599. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  91600. err <<= fracbits;
  91601. err /= n;
  91602. /* err now holds err/n with fracbits fractional bits */
  91603. /*
  91604. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91605. * our purposes.
  91606. */
  91607. FLAC__ASSERT(err > 0);
  91608. bits = FLAC__bitmath_ilog2(err)+1;
  91609. if(bits > 16) {
  91610. err >>= (bits-16);
  91611. fracbits -= (bits-16);
  91612. }
  91613. rbps = (FLAC__uint32)err;
  91614. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91615. rbps *= FLAC__FP_LN2;
  91616. fracbits += 16;
  91617. FLAC__ASSERT(fracbits >= 0);
  91618. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91619. {
  91620. const int f = fracbits & 3;
  91621. if(f) {
  91622. rbps >>= f;
  91623. fracbits -= f;
  91624. }
  91625. }
  91626. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91627. if(rbps == 0)
  91628. return 0;
  91629. /*
  91630. * The return value must have 16 fractional bits. Since the whole part
  91631. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91632. * must be >= -3, these assertion allows us to be able to shift rbps
  91633. * left if necessary to get 16 fracbits without losing any bits of the
  91634. * whole part of rbps.
  91635. *
  91636. * There is a slight chance due to accumulated error that the whole part
  91637. * will require 6 bits, so we use 6 in the assertion. Really though as
  91638. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91639. */
  91640. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91641. FLAC__ASSERT(fracbits >= -3);
  91642. /* now shift the decimal point into place */
  91643. if(fracbits < 16)
  91644. return rbps << (16-fracbits);
  91645. else if(fracbits > 16)
  91646. return rbps >> (fracbits-16);
  91647. else
  91648. return rbps;
  91649. }
  91650. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  91651. {
  91652. FLAC__uint32 rbps;
  91653. unsigned bits; /* the number of bits required to represent a number */
  91654. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91655. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91656. FLAC__ASSERT(err > 0);
  91657. FLAC__ASSERT(n > 0);
  91658. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91659. if(err <= n)
  91660. return 0;
  91661. /*
  91662. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91663. * These allow us later to know we won't lose too much precision in the
  91664. * fixed-point division (err<<fracbits)/n.
  91665. */
  91666. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  91667. err <<= fracbits;
  91668. err /= n;
  91669. /* err now holds err/n with fracbits fractional bits */
  91670. /*
  91671. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91672. * our purposes.
  91673. */
  91674. FLAC__ASSERT(err > 0);
  91675. bits = FLAC__bitmath_ilog2_wide(err)+1;
  91676. if(bits > 16) {
  91677. err >>= (bits-16);
  91678. fracbits -= (bits-16);
  91679. }
  91680. rbps = (FLAC__uint32)err;
  91681. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91682. rbps *= FLAC__FP_LN2;
  91683. fracbits += 16;
  91684. FLAC__ASSERT(fracbits >= 0);
  91685. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91686. {
  91687. const int f = fracbits & 3;
  91688. if(f) {
  91689. rbps >>= f;
  91690. fracbits -= f;
  91691. }
  91692. }
  91693. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91694. if(rbps == 0)
  91695. return 0;
  91696. /*
  91697. * The return value must have 16 fractional bits. Since the whole part
  91698. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91699. * must be >= -3, these assertion allows us to be able to shift rbps
  91700. * left if necessary to get 16 fracbits without losing any bits of the
  91701. * whole part of rbps.
  91702. *
  91703. * There is a slight chance due to accumulated error that the whole part
  91704. * will require 6 bits, so we use 6 in the assertion. Really though as
  91705. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91706. */
  91707. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91708. FLAC__ASSERT(fracbits >= -3);
  91709. /* now shift the decimal point into place */
  91710. if(fracbits < 16)
  91711. return rbps << (16-fracbits);
  91712. else if(fracbits > 16)
  91713. return rbps >> (fracbits-16);
  91714. else
  91715. return rbps;
  91716. }
  91717. #endif
  91718. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91719. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91720. #else
  91721. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91722. #endif
  91723. {
  91724. FLAC__int32 last_error_0 = data[-1];
  91725. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91726. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91727. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91728. FLAC__int32 error, save;
  91729. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91730. unsigned i, order;
  91731. for(i = 0; i < data_len; i++) {
  91732. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91733. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91734. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91735. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91736. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91737. }
  91738. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91739. order = 0;
  91740. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91741. order = 1;
  91742. else if(total_error_2 < min(total_error_3, total_error_4))
  91743. order = 2;
  91744. else if(total_error_3 < total_error_4)
  91745. order = 3;
  91746. else
  91747. order = 4;
  91748. /* Estimate the expected number of bits per residual signal sample. */
  91749. /* 'total_error*' is linearly related to the variance of the residual */
  91750. /* signal, so we use it directly to compute E(|x|) */
  91751. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91752. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91753. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91754. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91755. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91756. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91757. 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);
  91758. 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);
  91759. 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);
  91760. 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);
  91761. 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);
  91762. #else
  91763. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  91764. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  91765. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  91766. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  91767. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  91768. #endif
  91769. return order;
  91770. }
  91771. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91772. 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])
  91773. #else
  91774. 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])
  91775. #endif
  91776. {
  91777. FLAC__int32 last_error_0 = data[-1];
  91778. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91779. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91780. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91781. FLAC__int32 error, save;
  91782. /* total_error_* are 64-bits to avoid overflow when encoding
  91783. * erratic signals when the bits-per-sample and blocksize are
  91784. * large.
  91785. */
  91786. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91787. unsigned i, order;
  91788. for(i = 0; i < data_len; i++) {
  91789. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91790. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91791. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91792. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91793. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91794. }
  91795. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91796. order = 0;
  91797. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91798. order = 1;
  91799. else if(total_error_2 < min(total_error_3, total_error_4))
  91800. order = 2;
  91801. else if(total_error_3 < total_error_4)
  91802. order = 3;
  91803. else
  91804. order = 4;
  91805. /* Estimate the expected number of bits per residual signal sample. */
  91806. /* 'total_error*' is linearly related to the variance of the residual */
  91807. /* signal, so we use it directly to compute E(|x|) */
  91808. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91809. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91810. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91811. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91812. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91813. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91814. #if defined _MSC_VER || defined __MINGW32__
  91815. /* with MSVC you have to spoon feed it the casting */
  91816. 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);
  91817. 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);
  91818. 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);
  91819. 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);
  91820. 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);
  91821. #else
  91822. 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);
  91823. 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);
  91824. 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);
  91825. 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);
  91826. 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);
  91827. #endif
  91828. #else
  91829. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  91830. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  91831. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  91832. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  91833. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  91834. #endif
  91835. return order;
  91836. }
  91837. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  91838. {
  91839. const int idata_len = (int)data_len;
  91840. int i;
  91841. switch(order) {
  91842. case 0:
  91843. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91844. memcpy(residual, data, sizeof(residual[0])*data_len);
  91845. break;
  91846. case 1:
  91847. for(i = 0; i < idata_len; i++)
  91848. residual[i] = data[i] - data[i-1];
  91849. break;
  91850. case 2:
  91851. for(i = 0; i < idata_len; i++)
  91852. #if 1 /* OPT: may be faster with some compilers on some systems */
  91853. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  91854. #else
  91855. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  91856. #endif
  91857. break;
  91858. case 3:
  91859. for(i = 0; i < idata_len; i++)
  91860. #if 1 /* OPT: may be faster with some compilers on some systems */
  91861. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  91862. #else
  91863. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  91864. #endif
  91865. break;
  91866. case 4:
  91867. for(i = 0; i < idata_len; i++)
  91868. #if 1 /* OPT: may be faster with some compilers on some systems */
  91869. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  91870. #else
  91871. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  91872. #endif
  91873. break;
  91874. default:
  91875. FLAC__ASSERT(0);
  91876. }
  91877. }
  91878. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  91879. {
  91880. int i, idata_len = (int)data_len;
  91881. switch(order) {
  91882. case 0:
  91883. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91884. memcpy(data, residual, sizeof(residual[0])*data_len);
  91885. break;
  91886. case 1:
  91887. for(i = 0; i < idata_len; i++)
  91888. data[i] = residual[i] + data[i-1];
  91889. break;
  91890. case 2:
  91891. for(i = 0; i < idata_len; i++)
  91892. #if 1 /* OPT: may be faster with some compilers on some systems */
  91893. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  91894. #else
  91895. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  91896. #endif
  91897. break;
  91898. case 3:
  91899. for(i = 0; i < idata_len; i++)
  91900. #if 1 /* OPT: may be faster with some compilers on some systems */
  91901. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  91902. #else
  91903. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  91904. #endif
  91905. break;
  91906. case 4:
  91907. for(i = 0; i < idata_len; i++)
  91908. #if 1 /* OPT: may be faster with some compilers on some systems */
  91909. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  91910. #else
  91911. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  91912. #endif
  91913. break;
  91914. default:
  91915. FLAC__ASSERT(0);
  91916. }
  91917. }
  91918. #endif
  91919. /********* End of inlined file: fixed.c *********/
  91920. /********* Start of inlined file: float.c *********/
  91921. /********* Start of inlined file: juce_FlacHeader.h *********/
  91922. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91923. // tasks..
  91924. #define VERSION "1.2.1"
  91925. #define FLAC__NO_DLL 1
  91926. #if JUCE_MSVC
  91927. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91928. #endif
  91929. #if JUCE_MAC
  91930. #define FLAC__SYS_DARWIN 1
  91931. #endif
  91932. /********* End of inlined file: juce_FlacHeader.h *********/
  91933. #if JUCE_USE_FLAC
  91934. #if HAVE_CONFIG_H
  91935. # include <config.h>
  91936. #endif
  91937. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91938. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91939. #ifdef _MSC_VER
  91940. #define FLAC__U64L(x) x
  91941. #else
  91942. #define FLAC__U64L(x) x##LLU
  91943. #endif
  91944. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  91945. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  91946. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  91947. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  91948. const FLAC__fixedpoint FLAC__FP_E = 178145;
  91949. /* Lookup tables for Knuth's logarithm algorithm */
  91950. #define LOG2_LOOKUP_PRECISION 16
  91951. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  91952. {
  91953. /*
  91954. * 0 fraction bits
  91955. */
  91956. /* undefined */ 0x00000000,
  91957. /* lg(2/1) = */ 0x00000001,
  91958. /* lg(4/3) = */ 0x00000000,
  91959. /* lg(8/7) = */ 0x00000000,
  91960. /* lg(16/15) = */ 0x00000000,
  91961. /* lg(32/31) = */ 0x00000000,
  91962. /* lg(64/63) = */ 0x00000000,
  91963. /* lg(128/127) = */ 0x00000000,
  91964. /* lg(256/255) = */ 0x00000000,
  91965. /* lg(512/511) = */ 0x00000000,
  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. * 4 fraction bits
  91976. */
  91977. /* undefined */ 0x00000000,
  91978. /* lg(2/1) = */ 0x00000010,
  91979. /* lg(4/3) = */ 0x00000007,
  91980. /* lg(8/7) = */ 0x00000003,
  91981. /* lg(16/15) = */ 0x00000001,
  91982. /* lg(32/31) = */ 0x00000001,
  91983. /* lg(64/63) = */ 0x00000000,
  91984. /* lg(128/127) = */ 0x00000000,
  91985. /* lg(256/255) = */ 0x00000000,
  91986. /* lg(512/511) = */ 0x00000000,
  91987. /* lg(1024/1023) = */ 0x00000000,
  91988. /* lg(2048/2047) = */ 0x00000000,
  91989. /* lg(4096/4095) = */ 0x00000000,
  91990. /* lg(8192/8191) = */ 0x00000000,
  91991. /* lg(16384/16383) = */ 0x00000000,
  91992. /* lg(32768/32767) = */ 0x00000000
  91993. },
  91994. {
  91995. /*
  91996. * 8 fraction bits
  91997. */
  91998. /* undefined */ 0x00000000,
  91999. /* lg(2/1) = */ 0x00000100,
  92000. /* lg(4/3) = */ 0x0000006a,
  92001. /* lg(8/7) = */ 0x00000031,
  92002. /* lg(16/15) = */ 0x00000018,
  92003. /* lg(32/31) = */ 0x0000000c,
  92004. /* lg(64/63) = */ 0x00000006,
  92005. /* lg(128/127) = */ 0x00000003,
  92006. /* lg(256/255) = */ 0x00000001,
  92007. /* lg(512/511) = */ 0x00000001,
  92008. /* lg(1024/1023) = */ 0x00000000,
  92009. /* lg(2048/2047) = */ 0x00000000,
  92010. /* lg(4096/4095) = */ 0x00000000,
  92011. /* lg(8192/8191) = */ 0x00000000,
  92012. /* lg(16384/16383) = */ 0x00000000,
  92013. /* lg(32768/32767) = */ 0x00000000
  92014. },
  92015. {
  92016. /*
  92017. * 12 fraction bits
  92018. */
  92019. /* undefined */ 0x00000000,
  92020. /* lg(2/1) = */ 0x00001000,
  92021. /* lg(4/3) = */ 0x000006a4,
  92022. /* lg(8/7) = */ 0x00000315,
  92023. /* lg(16/15) = */ 0x0000017d,
  92024. /* lg(32/31) = */ 0x000000bc,
  92025. /* lg(64/63) = */ 0x0000005d,
  92026. /* lg(128/127) = */ 0x0000002e,
  92027. /* lg(256/255) = */ 0x00000017,
  92028. /* lg(512/511) = */ 0x0000000c,
  92029. /* lg(1024/1023) = */ 0x00000006,
  92030. /* lg(2048/2047) = */ 0x00000003,
  92031. /* lg(4096/4095) = */ 0x00000001,
  92032. /* lg(8192/8191) = */ 0x00000001,
  92033. /* lg(16384/16383) = */ 0x00000000,
  92034. /* lg(32768/32767) = */ 0x00000000
  92035. },
  92036. {
  92037. /*
  92038. * 16 fraction bits
  92039. */
  92040. /* undefined */ 0x00000000,
  92041. /* lg(2/1) = */ 0x00010000,
  92042. /* lg(4/3) = */ 0x00006a40,
  92043. /* lg(8/7) = */ 0x00003151,
  92044. /* lg(16/15) = */ 0x000017d6,
  92045. /* lg(32/31) = */ 0x00000bba,
  92046. /* lg(64/63) = */ 0x000005d1,
  92047. /* lg(128/127) = */ 0x000002e6,
  92048. /* lg(256/255) = */ 0x00000172,
  92049. /* lg(512/511) = */ 0x000000b9,
  92050. /* lg(1024/1023) = */ 0x0000005c,
  92051. /* lg(2048/2047) = */ 0x0000002e,
  92052. /* lg(4096/4095) = */ 0x00000017,
  92053. /* lg(8192/8191) = */ 0x0000000c,
  92054. /* lg(16384/16383) = */ 0x00000006,
  92055. /* lg(32768/32767) = */ 0x00000003
  92056. },
  92057. {
  92058. /*
  92059. * 20 fraction bits
  92060. */
  92061. /* undefined */ 0x00000000,
  92062. /* lg(2/1) = */ 0x00100000,
  92063. /* lg(4/3) = */ 0x0006a3fe,
  92064. /* lg(8/7) = */ 0x00031513,
  92065. /* lg(16/15) = */ 0x00017d60,
  92066. /* lg(32/31) = */ 0x0000bb9d,
  92067. /* lg(64/63) = */ 0x00005d10,
  92068. /* lg(128/127) = */ 0x00002e59,
  92069. /* lg(256/255) = */ 0x00001721,
  92070. /* lg(512/511) = */ 0x00000b8e,
  92071. /* lg(1024/1023) = */ 0x000005c6,
  92072. /* lg(2048/2047) = */ 0x000002e3,
  92073. /* lg(4096/4095) = */ 0x00000171,
  92074. /* lg(8192/8191) = */ 0x000000b9,
  92075. /* lg(16384/16383) = */ 0x0000005c,
  92076. /* lg(32768/32767) = */ 0x0000002e
  92077. },
  92078. {
  92079. /*
  92080. * 24 fraction bits
  92081. */
  92082. /* undefined */ 0x00000000,
  92083. /* lg(2/1) = */ 0x01000000,
  92084. /* lg(4/3) = */ 0x006a3fe6,
  92085. /* lg(8/7) = */ 0x00315130,
  92086. /* lg(16/15) = */ 0x0017d605,
  92087. /* lg(32/31) = */ 0x000bb9ca,
  92088. /* lg(64/63) = */ 0x0005d0fc,
  92089. /* lg(128/127) = */ 0x0002e58f,
  92090. /* lg(256/255) = */ 0x0001720e,
  92091. /* lg(512/511) = */ 0x0000b8d8,
  92092. /* lg(1024/1023) = */ 0x00005c61,
  92093. /* lg(2048/2047) = */ 0x00002e2d,
  92094. /* lg(4096/4095) = */ 0x00001716,
  92095. /* lg(8192/8191) = */ 0x00000b8b,
  92096. /* lg(16384/16383) = */ 0x000005c5,
  92097. /* lg(32768/32767) = */ 0x000002e3
  92098. },
  92099. {
  92100. /*
  92101. * 28 fraction bits
  92102. */
  92103. /* undefined */ 0x00000000,
  92104. /* lg(2/1) = */ 0x10000000,
  92105. /* lg(4/3) = */ 0x06a3fe5c,
  92106. /* lg(8/7) = */ 0x03151301,
  92107. /* lg(16/15) = */ 0x017d6049,
  92108. /* lg(32/31) = */ 0x00bb9ca6,
  92109. /* lg(64/63) = */ 0x005d0fba,
  92110. /* lg(128/127) = */ 0x002e58f7,
  92111. /* lg(256/255) = */ 0x001720da,
  92112. /* lg(512/511) = */ 0x000b8d87,
  92113. /* lg(1024/1023) = */ 0x0005c60b,
  92114. /* lg(2048/2047) = */ 0x0002e2d7,
  92115. /* lg(4096/4095) = */ 0x00017160,
  92116. /* lg(8192/8191) = */ 0x0000b8ad,
  92117. /* lg(16384/16383) = */ 0x00005c56,
  92118. /* lg(32768/32767) = */ 0x00002e2b
  92119. }
  92120. };
  92121. #if 0
  92122. static const FLAC__uint64 log2_lookup_wide[] = {
  92123. {
  92124. /*
  92125. * 32 fraction bits
  92126. */
  92127. /* undefined */ 0x00000000,
  92128. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  92129. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  92130. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  92131. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  92132. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  92133. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  92134. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  92135. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  92136. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  92137. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  92138. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  92139. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  92140. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  92141. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  92142. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  92143. },
  92144. {
  92145. /*
  92146. * 48 fraction bits
  92147. */
  92148. /* undefined */ 0x00000000,
  92149. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  92150. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  92151. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  92152. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  92153. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  92154. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  92155. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  92156. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  92157. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  92158. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  92159. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  92160. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  92161. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  92162. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  92163. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  92164. }
  92165. };
  92166. #endif
  92167. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  92168. {
  92169. const FLAC__uint32 ONE = (1u << fracbits);
  92170. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  92171. FLAC__ASSERT(fracbits < 32);
  92172. FLAC__ASSERT((fracbits & 0x3) == 0);
  92173. if(x < ONE)
  92174. return 0;
  92175. if(precision > LOG2_LOOKUP_PRECISION)
  92176. precision = LOG2_LOOKUP_PRECISION;
  92177. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  92178. {
  92179. FLAC__uint32 y = 0;
  92180. FLAC__uint32 z = x >> 1, k = 1;
  92181. while (x > ONE && k < precision) {
  92182. if (x - z >= ONE) {
  92183. x -= z;
  92184. z = x >> k;
  92185. y += table[k];
  92186. }
  92187. else {
  92188. z >>= 1;
  92189. k++;
  92190. }
  92191. }
  92192. return y;
  92193. }
  92194. }
  92195. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  92196. #endif
  92197. /********* End of inlined file: float.c *********/
  92198. /********* Start of inlined file: format.c *********/
  92199. /********* Start of inlined file: juce_FlacHeader.h *********/
  92200. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92201. // tasks..
  92202. #define VERSION "1.2.1"
  92203. #define FLAC__NO_DLL 1
  92204. #if JUCE_MSVC
  92205. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92206. #endif
  92207. #if JUCE_MAC
  92208. #define FLAC__SYS_DARWIN 1
  92209. #endif
  92210. /********* End of inlined file: juce_FlacHeader.h *********/
  92211. #if JUCE_USE_FLAC
  92212. #if HAVE_CONFIG_H
  92213. # include <config.h>
  92214. #endif
  92215. #include <stdio.h>
  92216. #include <stdlib.h> /* for qsort() */
  92217. #include <string.h> /* for memset() */
  92218. #ifndef FLaC__INLINE
  92219. #define FLaC__INLINE
  92220. #endif
  92221. #ifdef min
  92222. #undef min
  92223. #endif
  92224. #define min(a,b) ((a)<(b)?(a):(b))
  92225. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92226. #ifdef _MSC_VER
  92227. #define FLAC__U64L(x) x
  92228. #else
  92229. #define FLAC__U64L(x) x##LLU
  92230. #endif
  92231. /* VERSION should come from configure */
  92232. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  92233. ;
  92234. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  92235. /* yet one more hack because of MSVC6: */
  92236. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  92237. #else
  92238. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  92239. #endif
  92240. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  92241. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  92242. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  92243. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  92244. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  92245. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  92246. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  92247. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  92248. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  92249. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  92250. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  92251. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  92252. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  92253. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  92254. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  92255. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  92256. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  92257. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  92258. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  92259. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  92260. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  92261. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  92262. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  92263. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  92264. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  92265. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  92266. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  92267. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  92268. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  92269. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  92270. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  92271. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  92272. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  92273. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  92274. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  92275. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  92276. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  92277. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  92278. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  92279. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  92280. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  92281. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  92282. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  92283. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  92284. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  92285. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  92286. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  92287. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  92288. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  92289. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  92290. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  92291. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  92292. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  92293. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  92294. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  92295. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  92296. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  92297. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  92298. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  92299. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  92300. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  92301. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  92302. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  92303. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  92304. "PARTITIONED_RICE",
  92305. "PARTITIONED_RICE2"
  92306. };
  92307. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  92308. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  92309. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  92310. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  92311. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  92312. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  92313. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  92314. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  92315. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  92316. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  92317. "CONSTANT",
  92318. "VERBATIM",
  92319. "FIXED",
  92320. "LPC"
  92321. };
  92322. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  92323. "INDEPENDENT",
  92324. "LEFT_SIDE",
  92325. "RIGHT_SIDE",
  92326. "MID_SIDE"
  92327. };
  92328. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  92329. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  92330. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  92331. };
  92332. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  92333. "STREAMINFO",
  92334. "PADDING",
  92335. "APPLICATION",
  92336. "SEEKTABLE",
  92337. "VORBIS_COMMENT",
  92338. "CUESHEET",
  92339. "PICTURE"
  92340. };
  92341. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  92342. "Other",
  92343. "32x32 pixels 'file icon' (PNG only)",
  92344. "Other file icon",
  92345. "Cover (front)",
  92346. "Cover (back)",
  92347. "Leaflet page",
  92348. "Media (e.g. label side of CD)",
  92349. "Lead artist/lead performer/soloist",
  92350. "Artist/performer",
  92351. "Conductor",
  92352. "Band/Orchestra",
  92353. "Composer",
  92354. "Lyricist/text writer",
  92355. "Recording Location",
  92356. "During recording",
  92357. "During performance",
  92358. "Movie/video screen capture",
  92359. "A bright coloured fish",
  92360. "Illustration",
  92361. "Band/artist logotype",
  92362. "Publisher/Studio logotype"
  92363. };
  92364. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  92365. {
  92366. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  92367. return false;
  92368. }
  92369. else
  92370. return true;
  92371. }
  92372. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  92373. {
  92374. if(
  92375. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  92376. (
  92377. sample_rate >= (1u << 16) &&
  92378. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  92379. )
  92380. ) {
  92381. return false;
  92382. }
  92383. else
  92384. return true;
  92385. }
  92386. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92387. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  92388. {
  92389. unsigned i;
  92390. FLAC__uint64 prev_sample_number = 0;
  92391. FLAC__bool got_prev = false;
  92392. FLAC__ASSERT(0 != seek_table);
  92393. for(i = 0; i < seek_table->num_points; i++) {
  92394. if(got_prev) {
  92395. if(
  92396. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  92397. seek_table->points[i].sample_number <= prev_sample_number
  92398. )
  92399. return false;
  92400. }
  92401. prev_sample_number = seek_table->points[i].sample_number;
  92402. got_prev = true;
  92403. }
  92404. return true;
  92405. }
  92406. /* used as the sort predicate for qsort() */
  92407. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  92408. {
  92409. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  92410. if(l->sample_number == r->sample_number)
  92411. return 0;
  92412. else if(l->sample_number < r->sample_number)
  92413. return -1;
  92414. else
  92415. return 1;
  92416. }
  92417. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92418. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  92419. {
  92420. unsigned i, j;
  92421. FLAC__bool first;
  92422. FLAC__ASSERT(0 != seek_table);
  92423. /* sort the seekpoints */
  92424. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  92425. /* uniquify the seekpoints */
  92426. first = true;
  92427. for(i = j = 0; i < seek_table->num_points; i++) {
  92428. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  92429. if(!first) {
  92430. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  92431. continue;
  92432. }
  92433. }
  92434. first = false;
  92435. seek_table->points[j++] = seek_table->points[i];
  92436. }
  92437. for(i = j; i < seek_table->num_points; i++) {
  92438. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  92439. seek_table->points[i].stream_offset = 0;
  92440. seek_table->points[i].frame_samples = 0;
  92441. }
  92442. return j;
  92443. }
  92444. /*
  92445. * also disallows non-shortest-form encodings, c.f.
  92446. * http://www.unicode.org/versions/corrigendum1.html
  92447. * and a more clear explanation at the end of this section:
  92448. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  92449. */
  92450. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  92451. {
  92452. FLAC__ASSERT(0 != utf8);
  92453. if ((utf8[0] & 0x80) == 0) {
  92454. return 1;
  92455. }
  92456. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  92457. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  92458. return 0;
  92459. return 2;
  92460. }
  92461. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  92462. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  92463. return 0;
  92464. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  92465. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  92466. return 0;
  92467. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  92468. return 0;
  92469. return 3;
  92470. }
  92471. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  92472. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  92473. return 0;
  92474. return 4;
  92475. }
  92476. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  92477. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  92478. return 0;
  92479. return 5;
  92480. }
  92481. 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) {
  92482. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  92483. return 0;
  92484. return 6;
  92485. }
  92486. else {
  92487. return 0;
  92488. }
  92489. }
  92490. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  92491. {
  92492. char c;
  92493. for(c = *name; c; c = *(++name))
  92494. if(c < 0x20 || c == 0x3d || c > 0x7d)
  92495. return false;
  92496. return true;
  92497. }
  92498. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  92499. {
  92500. if(length == (unsigned)(-1)) {
  92501. while(*value) {
  92502. unsigned n = utf8len_(value);
  92503. if(n == 0)
  92504. return false;
  92505. value += n;
  92506. }
  92507. }
  92508. else {
  92509. const FLAC__byte *end = value + length;
  92510. while(value < end) {
  92511. unsigned n = utf8len_(value);
  92512. if(n == 0)
  92513. return false;
  92514. value += n;
  92515. }
  92516. if(value != end)
  92517. return false;
  92518. }
  92519. return true;
  92520. }
  92521. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  92522. {
  92523. const FLAC__byte *s, *end;
  92524. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  92525. if(*s < 0x20 || *s > 0x7D)
  92526. return false;
  92527. }
  92528. if(s == end)
  92529. return false;
  92530. s++; /* skip '=' */
  92531. while(s < end) {
  92532. unsigned n = utf8len_(s);
  92533. if(n == 0)
  92534. return false;
  92535. s += n;
  92536. }
  92537. if(s != end)
  92538. return false;
  92539. return true;
  92540. }
  92541. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92542. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  92543. {
  92544. unsigned i, j;
  92545. if(check_cd_da_subset) {
  92546. if(cue_sheet->lead_in < 2 * 44100) {
  92547. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  92548. return false;
  92549. }
  92550. if(cue_sheet->lead_in % 588 != 0) {
  92551. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  92552. return false;
  92553. }
  92554. }
  92555. if(cue_sheet->num_tracks == 0) {
  92556. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  92557. return false;
  92558. }
  92559. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  92560. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  92561. return false;
  92562. }
  92563. for(i = 0; i < cue_sheet->num_tracks; i++) {
  92564. if(cue_sheet->tracks[i].number == 0) {
  92565. if(violation) *violation = "cue sheet may not have a track number 0";
  92566. return false;
  92567. }
  92568. if(check_cd_da_subset) {
  92569. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  92570. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  92571. return false;
  92572. }
  92573. }
  92574. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  92575. if(violation) {
  92576. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  92577. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  92578. else
  92579. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  92580. }
  92581. return false;
  92582. }
  92583. if(i < cue_sheet->num_tracks - 1) {
  92584. if(cue_sheet->tracks[i].num_indices == 0) {
  92585. if(violation) *violation = "cue sheet track must have at least one index point";
  92586. return false;
  92587. }
  92588. if(cue_sheet->tracks[i].indices[0].number > 1) {
  92589. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  92590. return false;
  92591. }
  92592. }
  92593. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  92594. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  92595. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  92596. return false;
  92597. }
  92598. if(j > 0) {
  92599. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  92600. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  92601. return false;
  92602. }
  92603. }
  92604. }
  92605. }
  92606. return true;
  92607. }
  92608. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92609. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  92610. {
  92611. char *p;
  92612. FLAC__byte *b;
  92613. for(p = picture->mime_type; *p; p++) {
  92614. if(*p < 0x20 || *p > 0x7e) {
  92615. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  92616. return false;
  92617. }
  92618. }
  92619. for(b = picture->description; *b; ) {
  92620. unsigned n = utf8len_(b);
  92621. if(n == 0) {
  92622. if(violation) *violation = "description string must be valid UTF-8";
  92623. return false;
  92624. }
  92625. b += n;
  92626. }
  92627. return true;
  92628. }
  92629. /*
  92630. * These routines are private to libFLAC
  92631. */
  92632. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  92633. {
  92634. return
  92635. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  92636. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  92637. blocksize,
  92638. predictor_order
  92639. );
  92640. }
  92641. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  92642. {
  92643. unsigned max_rice_partition_order = 0;
  92644. while(!(blocksize & 1)) {
  92645. max_rice_partition_order++;
  92646. blocksize >>= 1;
  92647. }
  92648. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  92649. }
  92650. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  92651. {
  92652. unsigned max_rice_partition_order = limit;
  92653. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  92654. max_rice_partition_order--;
  92655. FLAC__ASSERT(
  92656. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  92657. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  92658. );
  92659. return max_rice_partition_order;
  92660. }
  92661. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92662. {
  92663. FLAC__ASSERT(0 != object);
  92664. object->parameters = 0;
  92665. object->raw_bits = 0;
  92666. object->capacity_by_order = 0;
  92667. }
  92668. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92669. {
  92670. FLAC__ASSERT(0 != object);
  92671. if(0 != object->parameters)
  92672. free(object->parameters);
  92673. if(0 != object->raw_bits)
  92674. free(object->raw_bits);
  92675. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  92676. }
  92677. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  92678. {
  92679. FLAC__ASSERT(0 != object);
  92680. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  92681. if(object->capacity_by_order < max_partition_order) {
  92682. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  92683. return false;
  92684. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  92685. return false;
  92686. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  92687. object->capacity_by_order = max_partition_order;
  92688. }
  92689. return true;
  92690. }
  92691. #endif
  92692. /********* End of inlined file: format.c *********/
  92693. /********* Start of inlined file: lpc_flac.c *********/
  92694. /********* Start of inlined file: juce_FlacHeader.h *********/
  92695. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92696. // tasks..
  92697. #define VERSION "1.2.1"
  92698. #define FLAC__NO_DLL 1
  92699. #if JUCE_MSVC
  92700. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92701. #endif
  92702. #if JUCE_MAC
  92703. #define FLAC__SYS_DARWIN 1
  92704. #endif
  92705. /********* End of inlined file: juce_FlacHeader.h *********/
  92706. #if JUCE_USE_FLAC
  92707. #if HAVE_CONFIG_H
  92708. # include <config.h>
  92709. #endif
  92710. #include <math.h>
  92711. /********* Start of inlined file: lpc.h *********/
  92712. #ifndef FLAC__PRIVATE__LPC_H
  92713. #define FLAC__PRIVATE__LPC_H
  92714. #ifdef HAVE_CONFIG_H
  92715. #include <config.h>
  92716. #endif
  92717. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92718. /*
  92719. * FLAC__lpc_window_data()
  92720. * --------------------------------------------------------------------
  92721. * Applies the given window to the data.
  92722. * OPT: asm implementation
  92723. *
  92724. * IN in[0,data_len-1]
  92725. * IN window[0,data_len-1]
  92726. * OUT out[0,lag-1]
  92727. * IN data_len
  92728. */
  92729. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  92730. /*
  92731. * FLAC__lpc_compute_autocorrelation()
  92732. * --------------------------------------------------------------------
  92733. * Compute the autocorrelation for lags between 0 and lag-1.
  92734. * Assumes data[] outside of [0,data_len-1] == 0.
  92735. * Asserts that lag > 0.
  92736. *
  92737. * IN data[0,data_len-1]
  92738. * IN data_len
  92739. * IN 0 < lag <= data_len
  92740. * OUT autoc[0,lag-1]
  92741. */
  92742. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92743. #ifndef FLAC__NO_ASM
  92744. # ifdef FLAC__CPU_IA32
  92745. # ifdef FLAC__HAS_NASM
  92746. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92747. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92748. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92749. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92750. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92751. # endif
  92752. # endif
  92753. #endif
  92754. /*
  92755. * FLAC__lpc_compute_lp_coefficients()
  92756. * --------------------------------------------------------------------
  92757. * Computes LP coefficients for orders 1..max_order.
  92758. * Do not call if autoc[0] == 0.0. This means the signal is zero
  92759. * and there is no point in calculating a predictor.
  92760. *
  92761. * IN autoc[0,max_order] autocorrelation values
  92762. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  92763. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  92764. * *** IMPORTANT:
  92765. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  92766. * OUT error[0,max_order-1] error for each order (more
  92767. * specifically, the variance of
  92768. * the error signal times # of
  92769. * samples in the signal)
  92770. *
  92771. * Example: if max_order is 9, the LP coefficients for order 9 will be
  92772. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  92773. * in lp_coeff[7][0,7], etc.
  92774. */
  92775. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  92776. /*
  92777. * FLAC__lpc_quantize_coefficients()
  92778. * --------------------------------------------------------------------
  92779. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  92780. * must be less than 32 (sizeof(FLAC__int32)*8).
  92781. *
  92782. * IN lp_coeff[0,order-1] LP coefficients
  92783. * IN order LP order
  92784. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  92785. * desired precision (in bits, including sign
  92786. * bit) of largest coefficient
  92787. * OUT qlp_coeff[0,order-1] quantized coefficients
  92788. * OUT shift # of bits to shift right to get approximated
  92789. * LP coefficients. NOTE: could be negative.
  92790. * RETURN 0 => quantization OK
  92791. * 1 => coefficients require too much shifting for *shift to
  92792. * fit in the LPC subframe header. 'shift' is unset.
  92793. * 2 => coefficients are all zero, which is bad. 'shift' is
  92794. * unset.
  92795. */
  92796. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  92797. /*
  92798. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  92799. * --------------------------------------------------------------------
  92800. * Compute the residual signal obtained from sutracting the predicted
  92801. * signal from the original.
  92802. *
  92803. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92804. * IN data_len length of original signal
  92805. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92806. * IN order > 0 LP order
  92807. * IN lp_quantization quantization of LP coefficients in bits
  92808. * OUT residual[0,data_len-1] residual signal
  92809. */
  92810. 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[]);
  92811. 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[]);
  92812. #ifndef FLAC__NO_ASM
  92813. # ifdef FLAC__CPU_IA32
  92814. # ifdef FLAC__HAS_NASM
  92815. 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[]);
  92816. 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[]);
  92817. # endif
  92818. # endif
  92819. #endif
  92820. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92821. /*
  92822. * FLAC__lpc_restore_signal()
  92823. * --------------------------------------------------------------------
  92824. * Restore the original signal by summing the residual and the
  92825. * predictor.
  92826. *
  92827. * IN residual[0,data_len-1] residual signal
  92828. * IN data_len length of original signal
  92829. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92830. * IN order > 0 LP order
  92831. * IN lp_quantization quantization of LP coefficients in bits
  92832. * *** IMPORTANT: the caller must pass in the historical samples:
  92833. * IN data[-order,-1] previously-reconstructed historical samples
  92834. * OUT data[0,data_len-1] original signal
  92835. */
  92836. 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[]);
  92837. 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[]);
  92838. #ifndef FLAC__NO_ASM
  92839. # ifdef FLAC__CPU_IA32
  92840. # ifdef FLAC__HAS_NASM
  92841. 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[]);
  92842. 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[]);
  92843. # endif /* FLAC__HAS_NASM */
  92844. # elif defined FLAC__CPU_PPC
  92845. 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[]);
  92846. 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[]);
  92847. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  92848. #endif /* FLAC__NO_ASM */
  92849. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92850. /*
  92851. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  92852. * --------------------------------------------------------------------
  92853. * Compute the expected number of bits per residual signal sample
  92854. * based on the LP error (which is related to the residual variance).
  92855. *
  92856. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  92857. * IN total_samples > 0 # of samples in residual signal
  92858. * RETURN expected bits per sample
  92859. */
  92860. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  92861. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  92862. /*
  92863. * FLAC__lpc_compute_best_order()
  92864. * --------------------------------------------------------------------
  92865. * Compute the best order from the array of signal errors returned
  92866. * during coefficient computation.
  92867. *
  92868. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  92869. * IN max_order > 0 max LP order
  92870. * IN total_samples > 0 # of samples in residual signal
  92871. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  92872. * (includes warmup sample size and quantized LP coefficient)
  92873. * RETURN [1,max_order] best order
  92874. */
  92875. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  92876. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92877. #endif
  92878. /********* End of inlined file: lpc.h *********/
  92879. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  92880. #include <stdio.h>
  92881. #endif
  92882. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92883. #ifndef M_LN2
  92884. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92885. #define M_LN2 0.69314718055994530942
  92886. #endif
  92887. /* OPT: #undef'ing this may improve the speed on some architectures */
  92888. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  92889. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  92890. {
  92891. unsigned i;
  92892. for(i = 0; i < data_len; i++)
  92893. out[i] = in[i] * window[i];
  92894. }
  92895. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  92896. {
  92897. /* a readable, but slower, version */
  92898. #if 0
  92899. FLAC__real d;
  92900. unsigned i;
  92901. FLAC__ASSERT(lag > 0);
  92902. FLAC__ASSERT(lag <= data_len);
  92903. /*
  92904. * Technically we should subtract the mean first like so:
  92905. * for(i = 0; i < data_len; i++)
  92906. * data[i] -= mean;
  92907. * but it appears not to make enough of a difference to matter, and
  92908. * most signals are already closely centered around zero
  92909. */
  92910. while(lag--) {
  92911. for(i = lag, d = 0.0; i < data_len; i++)
  92912. d += data[i] * data[i - lag];
  92913. autoc[lag] = d;
  92914. }
  92915. #endif
  92916. /*
  92917. * this version tends to run faster because of better data locality
  92918. * ('data_len' is usually much larger than 'lag')
  92919. */
  92920. FLAC__real d;
  92921. unsigned sample, coeff;
  92922. const unsigned limit = data_len - lag;
  92923. FLAC__ASSERT(lag > 0);
  92924. FLAC__ASSERT(lag <= data_len);
  92925. for(coeff = 0; coeff < lag; coeff++)
  92926. autoc[coeff] = 0.0;
  92927. for(sample = 0; sample <= limit; sample++) {
  92928. d = data[sample];
  92929. for(coeff = 0; coeff < lag; coeff++)
  92930. autoc[coeff] += d * data[sample+coeff];
  92931. }
  92932. for(; sample < data_len; sample++) {
  92933. d = data[sample];
  92934. for(coeff = 0; coeff < data_len - sample; coeff++)
  92935. autoc[coeff] += d * data[sample+coeff];
  92936. }
  92937. }
  92938. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  92939. {
  92940. unsigned i, j;
  92941. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  92942. FLAC__ASSERT(0 != max_order);
  92943. FLAC__ASSERT(0 < *max_order);
  92944. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  92945. FLAC__ASSERT(autoc[0] != 0.0);
  92946. err = autoc[0];
  92947. for(i = 0; i < *max_order; i++) {
  92948. /* Sum up this iteration's reflection coefficient. */
  92949. r = -autoc[i+1];
  92950. for(j = 0; j < i; j++)
  92951. r -= lpc[j] * autoc[i-j];
  92952. ref[i] = (r/=err);
  92953. /* Update LPC coefficients and total error. */
  92954. lpc[i]=r;
  92955. for(j = 0; j < (i>>1); j++) {
  92956. FLAC__double tmp = lpc[j];
  92957. lpc[j] += r * lpc[i-1-j];
  92958. lpc[i-1-j] += r * tmp;
  92959. }
  92960. if(i & 1)
  92961. lpc[j] += lpc[j] * r;
  92962. err *= (1.0 - r * r);
  92963. /* save this order */
  92964. for(j = 0; j <= i; j++)
  92965. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  92966. error[i] = err;
  92967. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  92968. if(err == 0.0) {
  92969. *max_order = i+1;
  92970. return;
  92971. }
  92972. }
  92973. }
  92974. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  92975. {
  92976. unsigned i;
  92977. FLAC__double cmax;
  92978. FLAC__int32 qmax, qmin;
  92979. FLAC__ASSERT(precision > 0);
  92980. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  92981. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  92982. precision--;
  92983. qmax = 1 << precision;
  92984. qmin = -qmax;
  92985. qmax--;
  92986. /* calc cmax = max( |lp_coeff[i]| ) */
  92987. cmax = 0.0;
  92988. for(i = 0; i < order; i++) {
  92989. const FLAC__double d = fabs(lp_coeff[i]);
  92990. if(d > cmax)
  92991. cmax = d;
  92992. }
  92993. if(cmax <= 0.0) {
  92994. /* => coefficients are all 0, which means our constant-detect didn't work */
  92995. return 2;
  92996. }
  92997. else {
  92998. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  92999. const int min_shiftlimit = -max_shiftlimit - 1;
  93000. int log2cmax;
  93001. (void)frexp(cmax, &log2cmax);
  93002. log2cmax--;
  93003. *shift = (int)precision - log2cmax - 1;
  93004. if(*shift > max_shiftlimit)
  93005. *shift = max_shiftlimit;
  93006. else if(*shift < min_shiftlimit)
  93007. return 1;
  93008. }
  93009. if(*shift >= 0) {
  93010. FLAC__double error = 0.0;
  93011. FLAC__int32 q;
  93012. for(i = 0; i < order; i++) {
  93013. error += lp_coeff[i] * (1 << *shift);
  93014. #if 1 /* unfortunately lround() is C99 */
  93015. if(error >= 0.0)
  93016. q = (FLAC__int32)(error + 0.5);
  93017. else
  93018. q = (FLAC__int32)(error - 0.5);
  93019. #else
  93020. q = lround(error);
  93021. #endif
  93022. #ifdef FLAC__OVERFLOW_DETECT
  93023. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93024. 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]);
  93025. else if(q < qmin)
  93026. 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]);
  93027. #endif
  93028. if(q > qmax)
  93029. q = qmax;
  93030. else if(q < qmin)
  93031. q = qmin;
  93032. error -= q;
  93033. qlp_coeff[i] = q;
  93034. }
  93035. }
  93036. /* negative shift is very rare but due to design flaw, negative shift is
  93037. * a NOP in the decoder, so it must be handled specially by scaling down
  93038. * coeffs
  93039. */
  93040. else {
  93041. const int nshift = -(*shift);
  93042. FLAC__double error = 0.0;
  93043. FLAC__int32 q;
  93044. #ifdef DEBUG
  93045. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  93046. #endif
  93047. for(i = 0; i < order; i++) {
  93048. error += lp_coeff[i] / (1 << nshift);
  93049. #if 1 /* unfortunately lround() is C99 */
  93050. if(error >= 0.0)
  93051. q = (FLAC__int32)(error + 0.5);
  93052. else
  93053. q = (FLAC__int32)(error - 0.5);
  93054. #else
  93055. q = lround(error);
  93056. #endif
  93057. #ifdef FLAC__OVERFLOW_DETECT
  93058. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93059. 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]);
  93060. else if(q < qmin)
  93061. 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]);
  93062. #endif
  93063. if(q > qmax)
  93064. q = qmax;
  93065. else if(q < qmin)
  93066. q = qmin;
  93067. error -= q;
  93068. qlp_coeff[i] = q;
  93069. }
  93070. *shift = 0;
  93071. }
  93072. return 0;
  93073. }
  93074. 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[])
  93075. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93076. {
  93077. FLAC__int64 sumo;
  93078. unsigned i, j;
  93079. FLAC__int32 sum;
  93080. const FLAC__int32 *history;
  93081. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93082. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93083. for(i=0;i<order;i++)
  93084. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93085. fprintf(stderr,"\n");
  93086. #endif
  93087. FLAC__ASSERT(order > 0);
  93088. for(i = 0; i < data_len; i++) {
  93089. sumo = 0;
  93090. sum = 0;
  93091. history = data;
  93092. for(j = 0; j < order; j++) {
  93093. sum += qlp_coeff[j] * (*(--history));
  93094. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93095. #if defined _MSC_VER
  93096. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93097. 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);
  93098. #else
  93099. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93100. 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);
  93101. #endif
  93102. }
  93103. *(residual++) = *(data++) - (sum >> lp_quantization);
  93104. }
  93105. /* Here's a slower but clearer version:
  93106. for(i = 0; i < data_len; i++) {
  93107. sum = 0;
  93108. for(j = 0; j < order; j++)
  93109. sum += qlp_coeff[j] * data[i-j-1];
  93110. residual[i] = data[i] - (sum >> lp_quantization);
  93111. }
  93112. */
  93113. }
  93114. #else /* fully unrolled version for normal use */
  93115. {
  93116. int i;
  93117. FLAC__int32 sum;
  93118. FLAC__ASSERT(order > 0);
  93119. FLAC__ASSERT(order <= 32);
  93120. /*
  93121. * We do unique versions up to 12th order since that's the subset limit.
  93122. * Also they are roughly ordered to match frequency of occurrence to
  93123. * minimize branching.
  93124. */
  93125. if(order <= 12) {
  93126. if(order > 8) {
  93127. if(order > 10) {
  93128. if(order == 12) {
  93129. for(i = 0; i < (int)data_len; i++) {
  93130. sum = 0;
  93131. sum += qlp_coeff[11] * data[i-12];
  93132. sum += qlp_coeff[10] * data[i-11];
  93133. sum += qlp_coeff[9] * data[i-10];
  93134. sum += qlp_coeff[8] * data[i-9];
  93135. sum += qlp_coeff[7] * data[i-8];
  93136. sum += qlp_coeff[6] * data[i-7];
  93137. sum += qlp_coeff[5] * data[i-6];
  93138. sum += qlp_coeff[4] * data[i-5];
  93139. sum += qlp_coeff[3] * data[i-4];
  93140. sum += qlp_coeff[2] * data[i-3];
  93141. sum += qlp_coeff[1] * data[i-2];
  93142. sum += qlp_coeff[0] * data[i-1];
  93143. residual[i] = data[i] - (sum >> lp_quantization);
  93144. }
  93145. }
  93146. else { /* order == 11 */
  93147. for(i = 0; i < (int)data_len; i++) {
  93148. sum = 0;
  93149. sum += qlp_coeff[10] * data[i-11];
  93150. sum += qlp_coeff[9] * data[i-10];
  93151. sum += qlp_coeff[8] * data[i-9];
  93152. sum += qlp_coeff[7] * data[i-8];
  93153. sum += qlp_coeff[6] * data[i-7];
  93154. sum += qlp_coeff[5] * data[i-6];
  93155. sum += qlp_coeff[4] * data[i-5];
  93156. sum += qlp_coeff[3] * data[i-4];
  93157. sum += qlp_coeff[2] * data[i-3];
  93158. sum += qlp_coeff[1] * data[i-2];
  93159. sum += qlp_coeff[0] * data[i-1];
  93160. residual[i] = data[i] - (sum >> lp_quantization);
  93161. }
  93162. }
  93163. }
  93164. else {
  93165. if(order == 10) {
  93166. for(i = 0; i < (int)data_len; i++) {
  93167. sum = 0;
  93168. sum += qlp_coeff[9] * data[i-10];
  93169. sum += qlp_coeff[8] * data[i-9];
  93170. sum += qlp_coeff[7] * data[i-8];
  93171. sum += qlp_coeff[6] * data[i-7];
  93172. sum += qlp_coeff[5] * data[i-6];
  93173. sum += qlp_coeff[4] * data[i-5];
  93174. sum += qlp_coeff[3] * data[i-4];
  93175. sum += qlp_coeff[2] * data[i-3];
  93176. sum += qlp_coeff[1] * data[i-2];
  93177. sum += qlp_coeff[0] * data[i-1];
  93178. residual[i] = data[i] - (sum >> lp_quantization);
  93179. }
  93180. }
  93181. else { /* order == 9 */
  93182. for(i = 0; i < (int)data_len; i++) {
  93183. sum = 0;
  93184. sum += qlp_coeff[8] * data[i-9];
  93185. sum += qlp_coeff[7] * data[i-8];
  93186. sum += qlp_coeff[6] * data[i-7];
  93187. sum += qlp_coeff[5] * data[i-6];
  93188. sum += qlp_coeff[4] * data[i-5];
  93189. sum += qlp_coeff[3] * data[i-4];
  93190. sum += qlp_coeff[2] * data[i-3];
  93191. sum += qlp_coeff[1] * data[i-2];
  93192. sum += qlp_coeff[0] * data[i-1];
  93193. residual[i] = data[i] - (sum >> lp_quantization);
  93194. }
  93195. }
  93196. }
  93197. }
  93198. else if(order > 4) {
  93199. if(order > 6) {
  93200. if(order == 8) {
  93201. for(i = 0; i < (int)data_len; i++) {
  93202. sum = 0;
  93203. sum += qlp_coeff[7] * data[i-8];
  93204. sum += qlp_coeff[6] * data[i-7];
  93205. sum += qlp_coeff[5] * data[i-6];
  93206. sum += qlp_coeff[4] * data[i-5];
  93207. sum += qlp_coeff[3] * data[i-4];
  93208. sum += qlp_coeff[2] * data[i-3];
  93209. sum += qlp_coeff[1] * data[i-2];
  93210. sum += qlp_coeff[0] * data[i-1];
  93211. residual[i] = data[i] - (sum >> lp_quantization);
  93212. }
  93213. }
  93214. else { /* order == 7 */
  93215. for(i = 0; i < (int)data_len; i++) {
  93216. sum = 0;
  93217. sum += qlp_coeff[6] * data[i-7];
  93218. sum += qlp_coeff[5] * data[i-6];
  93219. sum += qlp_coeff[4] * data[i-5];
  93220. sum += qlp_coeff[3] * data[i-4];
  93221. sum += qlp_coeff[2] * data[i-3];
  93222. sum += qlp_coeff[1] * data[i-2];
  93223. sum += qlp_coeff[0] * data[i-1];
  93224. residual[i] = data[i] - (sum >> lp_quantization);
  93225. }
  93226. }
  93227. }
  93228. else {
  93229. if(order == 6) {
  93230. for(i = 0; i < (int)data_len; i++) {
  93231. sum = 0;
  93232. sum += qlp_coeff[5] * data[i-6];
  93233. sum += qlp_coeff[4] * data[i-5];
  93234. sum += qlp_coeff[3] * data[i-4];
  93235. sum += qlp_coeff[2] * data[i-3];
  93236. sum += qlp_coeff[1] * data[i-2];
  93237. sum += qlp_coeff[0] * data[i-1];
  93238. residual[i] = data[i] - (sum >> lp_quantization);
  93239. }
  93240. }
  93241. else { /* order == 5 */
  93242. for(i = 0; i < (int)data_len; i++) {
  93243. sum = 0;
  93244. sum += qlp_coeff[4] * data[i-5];
  93245. sum += qlp_coeff[3] * data[i-4];
  93246. sum += qlp_coeff[2] * data[i-3];
  93247. sum += qlp_coeff[1] * data[i-2];
  93248. sum += qlp_coeff[0] * data[i-1];
  93249. residual[i] = data[i] - (sum >> lp_quantization);
  93250. }
  93251. }
  93252. }
  93253. }
  93254. else {
  93255. if(order > 2) {
  93256. if(order == 4) {
  93257. for(i = 0; i < (int)data_len; i++) {
  93258. sum = 0;
  93259. sum += qlp_coeff[3] * data[i-4];
  93260. sum += qlp_coeff[2] * data[i-3];
  93261. sum += qlp_coeff[1] * data[i-2];
  93262. sum += qlp_coeff[0] * data[i-1];
  93263. residual[i] = data[i] - (sum >> lp_quantization);
  93264. }
  93265. }
  93266. else { /* order == 3 */
  93267. for(i = 0; i < (int)data_len; i++) {
  93268. sum = 0;
  93269. sum += qlp_coeff[2] * data[i-3];
  93270. sum += qlp_coeff[1] * data[i-2];
  93271. sum += qlp_coeff[0] * data[i-1];
  93272. residual[i] = data[i] - (sum >> lp_quantization);
  93273. }
  93274. }
  93275. }
  93276. else {
  93277. if(order == 2) {
  93278. for(i = 0; i < (int)data_len; i++) {
  93279. sum = 0;
  93280. sum += qlp_coeff[1] * data[i-2];
  93281. sum += qlp_coeff[0] * data[i-1];
  93282. residual[i] = data[i] - (sum >> lp_quantization);
  93283. }
  93284. }
  93285. else { /* order == 1 */
  93286. for(i = 0; i < (int)data_len; i++)
  93287. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93288. }
  93289. }
  93290. }
  93291. }
  93292. else { /* order > 12 */
  93293. for(i = 0; i < (int)data_len; i++) {
  93294. sum = 0;
  93295. switch(order) {
  93296. case 32: sum += qlp_coeff[31] * data[i-32];
  93297. case 31: sum += qlp_coeff[30] * data[i-31];
  93298. case 30: sum += qlp_coeff[29] * data[i-30];
  93299. case 29: sum += qlp_coeff[28] * data[i-29];
  93300. case 28: sum += qlp_coeff[27] * data[i-28];
  93301. case 27: sum += qlp_coeff[26] * data[i-27];
  93302. case 26: sum += qlp_coeff[25] * data[i-26];
  93303. case 25: sum += qlp_coeff[24] * data[i-25];
  93304. case 24: sum += qlp_coeff[23] * data[i-24];
  93305. case 23: sum += qlp_coeff[22] * data[i-23];
  93306. case 22: sum += qlp_coeff[21] * data[i-22];
  93307. case 21: sum += qlp_coeff[20] * data[i-21];
  93308. case 20: sum += qlp_coeff[19] * data[i-20];
  93309. case 19: sum += qlp_coeff[18] * data[i-19];
  93310. case 18: sum += qlp_coeff[17] * data[i-18];
  93311. case 17: sum += qlp_coeff[16] * data[i-17];
  93312. case 16: sum += qlp_coeff[15] * data[i-16];
  93313. case 15: sum += qlp_coeff[14] * data[i-15];
  93314. case 14: sum += qlp_coeff[13] * data[i-14];
  93315. case 13: sum += qlp_coeff[12] * data[i-13];
  93316. sum += qlp_coeff[11] * data[i-12];
  93317. sum += qlp_coeff[10] * data[i-11];
  93318. sum += qlp_coeff[ 9] * data[i-10];
  93319. sum += qlp_coeff[ 8] * data[i- 9];
  93320. sum += qlp_coeff[ 7] * data[i- 8];
  93321. sum += qlp_coeff[ 6] * data[i- 7];
  93322. sum += qlp_coeff[ 5] * data[i- 6];
  93323. sum += qlp_coeff[ 4] * data[i- 5];
  93324. sum += qlp_coeff[ 3] * data[i- 4];
  93325. sum += qlp_coeff[ 2] * data[i- 3];
  93326. sum += qlp_coeff[ 1] * data[i- 2];
  93327. sum += qlp_coeff[ 0] * data[i- 1];
  93328. }
  93329. residual[i] = data[i] - (sum >> lp_quantization);
  93330. }
  93331. }
  93332. }
  93333. #endif
  93334. 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[])
  93335. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93336. {
  93337. unsigned i, j;
  93338. FLAC__int64 sum;
  93339. const FLAC__int32 *history;
  93340. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93341. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93342. for(i=0;i<order;i++)
  93343. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93344. fprintf(stderr,"\n");
  93345. #endif
  93346. FLAC__ASSERT(order > 0);
  93347. for(i = 0; i < data_len; i++) {
  93348. sum = 0;
  93349. history = data;
  93350. for(j = 0; j < order; j++)
  93351. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93352. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93353. #if defined _MSC_VER
  93354. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93355. #else
  93356. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93357. #endif
  93358. break;
  93359. }
  93360. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  93361. #if defined _MSC_VER
  93362. 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));
  93363. #else
  93364. 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)));
  93365. #endif
  93366. break;
  93367. }
  93368. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  93369. }
  93370. }
  93371. #else /* fully unrolled version for normal use */
  93372. {
  93373. int i;
  93374. FLAC__int64 sum;
  93375. FLAC__ASSERT(order > 0);
  93376. FLAC__ASSERT(order <= 32);
  93377. /*
  93378. * We do unique versions up to 12th order since that's the subset limit.
  93379. * Also they are roughly ordered to match frequency of occurrence to
  93380. * minimize branching.
  93381. */
  93382. if(order <= 12) {
  93383. if(order > 8) {
  93384. if(order > 10) {
  93385. if(order == 12) {
  93386. for(i = 0; i < (int)data_len; i++) {
  93387. sum = 0;
  93388. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93389. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93390. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93391. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93392. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93393. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93394. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93395. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93396. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93397. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93398. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93399. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93400. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93401. }
  93402. }
  93403. else { /* order == 11 */
  93404. for(i = 0; i < (int)data_len; i++) {
  93405. sum = 0;
  93406. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93407. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93408. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93409. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93410. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93411. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93412. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93413. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93414. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93415. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93416. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93417. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93418. }
  93419. }
  93420. }
  93421. else {
  93422. if(order == 10) {
  93423. for(i = 0; i < (int)data_len; i++) {
  93424. sum = 0;
  93425. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93426. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93427. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93428. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93429. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93430. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93431. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93432. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93433. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93434. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93435. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93436. }
  93437. }
  93438. else { /* order == 9 */
  93439. for(i = 0; i < (int)data_len; i++) {
  93440. sum = 0;
  93441. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93442. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93443. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93444. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93445. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93446. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93447. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93448. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93449. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93450. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93451. }
  93452. }
  93453. }
  93454. }
  93455. else if(order > 4) {
  93456. if(order > 6) {
  93457. if(order == 8) {
  93458. for(i = 0; i < (int)data_len; i++) {
  93459. sum = 0;
  93460. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93461. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93462. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93463. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93464. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93465. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93466. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93467. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93468. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93469. }
  93470. }
  93471. else { /* order == 7 */
  93472. for(i = 0; i < (int)data_len; i++) {
  93473. sum = 0;
  93474. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93475. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93476. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93477. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93478. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93479. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93480. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93481. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93482. }
  93483. }
  93484. }
  93485. else {
  93486. if(order == 6) {
  93487. for(i = 0; i < (int)data_len; i++) {
  93488. sum = 0;
  93489. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93490. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93491. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93492. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93493. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93494. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93495. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93496. }
  93497. }
  93498. else { /* order == 5 */
  93499. for(i = 0; i < (int)data_len; i++) {
  93500. sum = 0;
  93501. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93502. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93503. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93504. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93505. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93506. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93507. }
  93508. }
  93509. }
  93510. }
  93511. else {
  93512. if(order > 2) {
  93513. if(order == 4) {
  93514. for(i = 0; i < (int)data_len; i++) {
  93515. sum = 0;
  93516. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93517. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93518. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93519. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93520. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93521. }
  93522. }
  93523. else { /* order == 3 */
  93524. for(i = 0; i < (int)data_len; i++) {
  93525. sum = 0;
  93526. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93527. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93528. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93529. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93530. }
  93531. }
  93532. }
  93533. else {
  93534. if(order == 2) {
  93535. for(i = 0; i < (int)data_len; i++) {
  93536. sum = 0;
  93537. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93538. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93539. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93540. }
  93541. }
  93542. else { /* order == 1 */
  93543. for(i = 0; i < (int)data_len; i++)
  93544. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93545. }
  93546. }
  93547. }
  93548. }
  93549. else { /* order > 12 */
  93550. for(i = 0; i < (int)data_len; i++) {
  93551. sum = 0;
  93552. switch(order) {
  93553. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93554. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93555. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93556. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93557. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93558. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93559. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93560. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93561. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93562. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93563. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93564. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93565. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93566. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93567. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93568. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93569. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93570. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93571. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93572. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93573. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93574. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93575. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93576. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93577. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93578. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93579. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93580. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93581. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93582. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93583. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93584. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93585. }
  93586. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93587. }
  93588. }
  93589. }
  93590. #endif
  93591. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93592. 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[])
  93593. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93594. {
  93595. FLAC__int64 sumo;
  93596. unsigned i, j;
  93597. FLAC__int32 sum;
  93598. const FLAC__int32 *r = residual, *history;
  93599. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93600. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93601. for(i=0;i<order;i++)
  93602. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93603. fprintf(stderr,"\n");
  93604. #endif
  93605. FLAC__ASSERT(order > 0);
  93606. for(i = 0; i < data_len; i++) {
  93607. sumo = 0;
  93608. sum = 0;
  93609. history = data;
  93610. for(j = 0; j < order; j++) {
  93611. sum += qlp_coeff[j] * (*(--history));
  93612. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93613. #if defined _MSC_VER
  93614. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93615. 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);
  93616. #else
  93617. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93618. 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);
  93619. #endif
  93620. }
  93621. *(data++) = *(r++) + (sum >> lp_quantization);
  93622. }
  93623. /* Here's a slower but clearer version:
  93624. for(i = 0; i < data_len; i++) {
  93625. sum = 0;
  93626. for(j = 0; j < order; j++)
  93627. sum += qlp_coeff[j] * data[i-j-1];
  93628. data[i] = residual[i] + (sum >> lp_quantization);
  93629. }
  93630. */
  93631. }
  93632. #else /* fully unrolled version for normal use */
  93633. {
  93634. int i;
  93635. FLAC__int32 sum;
  93636. FLAC__ASSERT(order > 0);
  93637. FLAC__ASSERT(order <= 32);
  93638. /*
  93639. * We do unique versions up to 12th order since that's the subset limit.
  93640. * Also they are roughly ordered to match frequency of occurrence to
  93641. * minimize branching.
  93642. */
  93643. if(order <= 12) {
  93644. if(order > 8) {
  93645. if(order > 10) {
  93646. if(order == 12) {
  93647. for(i = 0; i < (int)data_len; i++) {
  93648. sum = 0;
  93649. sum += qlp_coeff[11] * data[i-12];
  93650. sum += qlp_coeff[10] * data[i-11];
  93651. sum += qlp_coeff[9] * data[i-10];
  93652. sum += qlp_coeff[8] * data[i-9];
  93653. sum += qlp_coeff[7] * data[i-8];
  93654. sum += qlp_coeff[6] * data[i-7];
  93655. sum += qlp_coeff[5] * data[i-6];
  93656. sum += qlp_coeff[4] * data[i-5];
  93657. sum += qlp_coeff[3] * data[i-4];
  93658. sum += qlp_coeff[2] * data[i-3];
  93659. sum += qlp_coeff[1] * data[i-2];
  93660. sum += qlp_coeff[0] * data[i-1];
  93661. data[i] = residual[i] + (sum >> lp_quantization);
  93662. }
  93663. }
  93664. else { /* order == 11 */
  93665. for(i = 0; i < (int)data_len; i++) {
  93666. sum = 0;
  93667. sum += qlp_coeff[10] * data[i-11];
  93668. sum += qlp_coeff[9] * data[i-10];
  93669. sum += qlp_coeff[8] * data[i-9];
  93670. sum += qlp_coeff[7] * data[i-8];
  93671. sum += qlp_coeff[6] * data[i-7];
  93672. sum += qlp_coeff[5] * data[i-6];
  93673. sum += qlp_coeff[4] * data[i-5];
  93674. sum += qlp_coeff[3] * data[i-4];
  93675. sum += qlp_coeff[2] * data[i-3];
  93676. sum += qlp_coeff[1] * data[i-2];
  93677. sum += qlp_coeff[0] * data[i-1];
  93678. data[i] = residual[i] + (sum >> lp_quantization);
  93679. }
  93680. }
  93681. }
  93682. else {
  93683. if(order == 10) {
  93684. for(i = 0; i < (int)data_len; i++) {
  93685. sum = 0;
  93686. sum += qlp_coeff[9] * data[i-10];
  93687. sum += qlp_coeff[8] * data[i-9];
  93688. sum += qlp_coeff[7] * data[i-8];
  93689. sum += qlp_coeff[6] * data[i-7];
  93690. sum += qlp_coeff[5] * data[i-6];
  93691. sum += qlp_coeff[4] * data[i-5];
  93692. sum += qlp_coeff[3] * data[i-4];
  93693. sum += qlp_coeff[2] * data[i-3];
  93694. sum += qlp_coeff[1] * data[i-2];
  93695. sum += qlp_coeff[0] * data[i-1];
  93696. data[i] = residual[i] + (sum >> lp_quantization);
  93697. }
  93698. }
  93699. else { /* order == 9 */
  93700. for(i = 0; i < (int)data_len; i++) {
  93701. sum = 0;
  93702. sum += qlp_coeff[8] * data[i-9];
  93703. sum += qlp_coeff[7] * data[i-8];
  93704. sum += qlp_coeff[6] * data[i-7];
  93705. sum += qlp_coeff[5] * data[i-6];
  93706. sum += qlp_coeff[4] * data[i-5];
  93707. sum += qlp_coeff[3] * data[i-4];
  93708. sum += qlp_coeff[2] * data[i-3];
  93709. sum += qlp_coeff[1] * data[i-2];
  93710. sum += qlp_coeff[0] * data[i-1];
  93711. data[i] = residual[i] + (sum >> lp_quantization);
  93712. }
  93713. }
  93714. }
  93715. }
  93716. else if(order > 4) {
  93717. if(order > 6) {
  93718. if(order == 8) {
  93719. for(i = 0; i < (int)data_len; i++) {
  93720. sum = 0;
  93721. sum += qlp_coeff[7] * data[i-8];
  93722. sum += qlp_coeff[6] * data[i-7];
  93723. sum += qlp_coeff[5] * data[i-6];
  93724. sum += qlp_coeff[4] * data[i-5];
  93725. sum += qlp_coeff[3] * data[i-4];
  93726. sum += qlp_coeff[2] * data[i-3];
  93727. sum += qlp_coeff[1] * data[i-2];
  93728. sum += qlp_coeff[0] * data[i-1];
  93729. data[i] = residual[i] + (sum >> lp_quantization);
  93730. }
  93731. }
  93732. else { /* order == 7 */
  93733. for(i = 0; i < (int)data_len; i++) {
  93734. sum = 0;
  93735. sum += qlp_coeff[6] * data[i-7];
  93736. sum += qlp_coeff[5] * data[i-6];
  93737. sum += qlp_coeff[4] * data[i-5];
  93738. sum += qlp_coeff[3] * data[i-4];
  93739. sum += qlp_coeff[2] * data[i-3];
  93740. sum += qlp_coeff[1] * data[i-2];
  93741. sum += qlp_coeff[0] * data[i-1];
  93742. data[i] = residual[i] + (sum >> lp_quantization);
  93743. }
  93744. }
  93745. }
  93746. else {
  93747. if(order == 6) {
  93748. for(i = 0; i < (int)data_len; i++) {
  93749. sum = 0;
  93750. sum += qlp_coeff[5] * data[i-6];
  93751. sum += qlp_coeff[4] * data[i-5];
  93752. sum += qlp_coeff[3] * data[i-4];
  93753. sum += qlp_coeff[2] * data[i-3];
  93754. sum += qlp_coeff[1] * data[i-2];
  93755. sum += qlp_coeff[0] * data[i-1];
  93756. data[i] = residual[i] + (sum >> lp_quantization);
  93757. }
  93758. }
  93759. else { /* order == 5 */
  93760. for(i = 0; i < (int)data_len; i++) {
  93761. sum = 0;
  93762. sum += qlp_coeff[4] * data[i-5];
  93763. sum += qlp_coeff[3] * data[i-4];
  93764. sum += qlp_coeff[2] * data[i-3];
  93765. sum += qlp_coeff[1] * data[i-2];
  93766. sum += qlp_coeff[0] * data[i-1];
  93767. data[i] = residual[i] + (sum >> lp_quantization);
  93768. }
  93769. }
  93770. }
  93771. }
  93772. else {
  93773. if(order > 2) {
  93774. if(order == 4) {
  93775. for(i = 0; i < (int)data_len; i++) {
  93776. sum = 0;
  93777. sum += qlp_coeff[3] * data[i-4];
  93778. sum += qlp_coeff[2] * data[i-3];
  93779. sum += qlp_coeff[1] * data[i-2];
  93780. sum += qlp_coeff[0] * data[i-1];
  93781. data[i] = residual[i] + (sum >> lp_quantization);
  93782. }
  93783. }
  93784. else { /* order == 3 */
  93785. for(i = 0; i < (int)data_len; i++) {
  93786. sum = 0;
  93787. sum += qlp_coeff[2] * data[i-3];
  93788. sum += qlp_coeff[1] * data[i-2];
  93789. sum += qlp_coeff[0] * data[i-1];
  93790. data[i] = residual[i] + (sum >> lp_quantization);
  93791. }
  93792. }
  93793. }
  93794. else {
  93795. if(order == 2) {
  93796. for(i = 0; i < (int)data_len; i++) {
  93797. sum = 0;
  93798. sum += qlp_coeff[1] * data[i-2];
  93799. sum += qlp_coeff[0] * data[i-1];
  93800. data[i] = residual[i] + (sum >> lp_quantization);
  93801. }
  93802. }
  93803. else { /* order == 1 */
  93804. for(i = 0; i < (int)data_len; i++)
  93805. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93806. }
  93807. }
  93808. }
  93809. }
  93810. else { /* order > 12 */
  93811. for(i = 0; i < (int)data_len; i++) {
  93812. sum = 0;
  93813. switch(order) {
  93814. case 32: sum += qlp_coeff[31] * data[i-32];
  93815. case 31: sum += qlp_coeff[30] * data[i-31];
  93816. case 30: sum += qlp_coeff[29] * data[i-30];
  93817. case 29: sum += qlp_coeff[28] * data[i-29];
  93818. case 28: sum += qlp_coeff[27] * data[i-28];
  93819. case 27: sum += qlp_coeff[26] * data[i-27];
  93820. case 26: sum += qlp_coeff[25] * data[i-26];
  93821. case 25: sum += qlp_coeff[24] * data[i-25];
  93822. case 24: sum += qlp_coeff[23] * data[i-24];
  93823. case 23: sum += qlp_coeff[22] * data[i-23];
  93824. case 22: sum += qlp_coeff[21] * data[i-22];
  93825. case 21: sum += qlp_coeff[20] * data[i-21];
  93826. case 20: sum += qlp_coeff[19] * data[i-20];
  93827. case 19: sum += qlp_coeff[18] * data[i-19];
  93828. case 18: sum += qlp_coeff[17] * data[i-18];
  93829. case 17: sum += qlp_coeff[16] * data[i-17];
  93830. case 16: sum += qlp_coeff[15] * data[i-16];
  93831. case 15: sum += qlp_coeff[14] * data[i-15];
  93832. case 14: sum += qlp_coeff[13] * data[i-14];
  93833. case 13: sum += qlp_coeff[12] * data[i-13];
  93834. sum += qlp_coeff[11] * data[i-12];
  93835. sum += qlp_coeff[10] * data[i-11];
  93836. sum += qlp_coeff[ 9] * data[i-10];
  93837. sum += qlp_coeff[ 8] * data[i- 9];
  93838. sum += qlp_coeff[ 7] * data[i- 8];
  93839. sum += qlp_coeff[ 6] * data[i- 7];
  93840. sum += qlp_coeff[ 5] * data[i- 6];
  93841. sum += qlp_coeff[ 4] * data[i- 5];
  93842. sum += qlp_coeff[ 3] * data[i- 4];
  93843. sum += qlp_coeff[ 2] * data[i- 3];
  93844. sum += qlp_coeff[ 1] * data[i- 2];
  93845. sum += qlp_coeff[ 0] * data[i- 1];
  93846. }
  93847. data[i] = residual[i] + (sum >> lp_quantization);
  93848. }
  93849. }
  93850. }
  93851. #endif
  93852. 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[])
  93853. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93854. {
  93855. unsigned i, j;
  93856. FLAC__int64 sum;
  93857. const FLAC__int32 *r = residual, *history;
  93858. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93859. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93860. for(i=0;i<order;i++)
  93861. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93862. fprintf(stderr,"\n");
  93863. #endif
  93864. FLAC__ASSERT(order > 0);
  93865. for(i = 0; i < data_len; i++) {
  93866. sum = 0;
  93867. history = data;
  93868. for(j = 0; j < order; j++)
  93869. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93870. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93871. #ifdef _MSC_VER
  93872. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93873. #else
  93874. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93875. #endif
  93876. break;
  93877. }
  93878. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  93879. #ifdef _MSC_VER
  93880. 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));
  93881. #else
  93882. 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)));
  93883. #endif
  93884. break;
  93885. }
  93886. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  93887. }
  93888. }
  93889. #else /* fully unrolled version for normal use */
  93890. {
  93891. int i;
  93892. FLAC__int64 sum;
  93893. FLAC__ASSERT(order > 0);
  93894. FLAC__ASSERT(order <= 32);
  93895. /*
  93896. * We do unique versions up to 12th order since that's the subset limit.
  93897. * Also they are roughly ordered to match frequency of occurrence to
  93898. * minimize branching.
  93899. */
  93900. if(order <= 12) {
  93901. if(order > 8) {
  93902. if(order > 10) {
  93903. if(order == 12) {
  93904. for(i = 0; i < (int)data_len; i++) {
  93905. sum = 0;
  93906. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93907. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93908. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93909. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93910. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93911. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93912. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93913. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93914. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93915. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93916. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93917. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93918. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93919. }
  93920. }
  93921. else { /* order == 11 */
  93922. for(i = 0; i < (int)data_len; i++) {
  93923. sum = 0;
  93924. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93925. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93926. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93927. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93928. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93929. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93930. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93931. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93932. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93933. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93934. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93935. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93936. }
  93937. }
  93938. }
  93939. else {
  93940. if(order == 10) {
  93941. for(i = 0; i < (int)data_len; i++) {
  93942. sum = 0;
  93943. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93944. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93945. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93946. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93947. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93948. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93949. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93950. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93951. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93952. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93953. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93954. }
  93955. }
  93956. else { /* order == 9 */
  93957. for(i = 0; i < (int)data_len; i++) {
  93958. sum = 0;
  93959. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93960. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93961. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93962. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93963. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93964. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93965. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93966. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93967. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93968. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93969. }
  93970. }
  93971. }
  93972. }
  93973. else if(order > 4) {
  93974. if(order > 6) {
  93975. if(order == 8) {
  93976. for(i = 0; i < (int)data_len; i++) {
  93977. sum = 0;
  93978. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93979. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93980. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93981. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93982. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93983. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93984. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93985. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93986. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93987. }
  93988. }
  93989. else { /* order == 7 */
  93990. for(i = 0; i < (int)data_len; i++) {
  93991. sum = 0;
  93992. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93993. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93994. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93995. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93996. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93997. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93998. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93999. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94000. }
  94001. }
  94002. }
  94003. else {
  94004. if(order == 6) {
  94005. for(i = 0; i < (int)data_len; i++) {
  94006. sum = 0;
  94007. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94008. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94009. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94010. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94011. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94012. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94013. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94014. }
  94015. }
  94016. else { /* order == 5 */
  94017. for(i = 0; i < (int)data_len; i++) {
  94018. sum = 0;
  94019. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94020. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94021. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94022. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94023. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94024. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94025. }
  94026. }
  94027. }
  94028. }
  94029. else {
  94030. if(order > 2) {
  94031. if(order == 4) {
  94032. for(i = 0; i < (int)data_len; i++) {
  94033. sum = 0;
  94034. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94035. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94036. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94037. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94038. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94039. }
  94040. }
  94041. else { /* order == 3 */
  94042. for(i = 0; i < (int)data_len; i++) {
  94043. sum = 0;
  94044. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94045. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94046. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94047. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94048. }
  94049. }
  94050. }
  94051. else {
  94052. if(order == 2) {
  94053. for(i = 0; i < (int)data_len; i++) {
  94054. sum = 0;
  94055. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94056. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94057. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94058. }
  94059. }
  94060. else { /* order == 1 */
  94061. for(i = 0; i < (int)data_len; i++)
  94062. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94063. }
  94064. }
  94065. }
  94066. }
  94067. else { /* order > 12 */
  94068. for(i = 0; i < (int)data_len; i++) {
  94069. sum = 0;
  94070. switch(order) {
  94071. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94072. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94073. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94074. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94075. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94076. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94077. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94078. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94079. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94080. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94081. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94082. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94083. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94084. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94085. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94086. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94087. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94088. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94089. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94090. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94091. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94092. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94093. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94094. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94095. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94096. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94097. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94098. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94099. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94100. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94101. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94102. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94103. }
  94104. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94105. }
  94106. }
  94107. }
  94108. #endif
  94109. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94110. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  94111. {
  94112. FLAC__double error_scale;
  94113. FLAC__ASSERT(total_samples > 0);
  94114. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94115. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  94116. }
  94117. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  94118. {
  94119. if(lpc_error > 0.0) {
  94120. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  94121. if(bps >= 0.0)
  94122. return bps;
  94123. else
  94124. return 0.0;
  94125. }
  94126. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  94127. return 1e32;
  94128. }
  94129. else {
  94130. return 0.0;
  94131. }
  94132. }
  94133. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  94134. {
  94135. 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 */
  94136. FLAC__double bits, best_bits, error_scale;
  94137. FLAC__ASSERT(max_order > 0);
  94138. FLAC__ASSERT(total_samples > 0);
  94139. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94140. best_index = 0;
  94141. best_bits = (unsigned)(-1);
  94142. for(index = 0, order = 1; index < max_order; index++, order++) {
  94143. 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);
  94144. if(bits < best_bits) {
  94145. best_index = index;
  94146. best_bits = bits;
  94147. }
  94148. }
  94149. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  94150. }
  94151. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94152. #endif
  94153. /********* End of inlined file: lpc_flac.c *********/
  94154. /********* Start of inlined file: md5.c *********/
  94155. /********* Start of inlined file: juce_FlacHeader.h *********/
  94156. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94157. // tasks..
  94158. #define VERSION "1.2.1"
  94159. #define FLAC__NO_DLL 1
  94160. #if JUCE_MSVC
  94161. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94162. #endif
  94163. #if JUCE_MAC
  94164. #define FLAC__SYS_DARWIN 1
  94165. #endif
  94166. /********* End of inlined file: juce_FlacHeader.h *********/
  94167. #if JUCE_USE_FLAC
  94168. #if HAVE_CONFIG_H
  94169. # include <config.h>
  94170. #endif
  94171. #include <stdlib.h> /* for malloc() */
  94172. #include <string.h> /* for memcpy() */
  94173. /********* Start of inlined file: md5.h *********/
  94174. #ifndef FLAC__PRIVATE__MD5_H
  94175. #define FLAC__PRIVATE__MD5_H
  94176. /*
  94177. * This is the header file for the MD5 message-digest algorithm.
  94178. * The algorithm is due to Ron Rivest. This code was
  94179. * written by Colin Plumb in 1993, no copyright is claimed.
  94180. * This code is in the public domain; do with it what you wish.
  94181. *
  94182. * Equivalent code is available from RSA Data Security, Inc.
  94183. * This code has been tested against that, and is equivalent,
  94184. * except that you don't need to include two pages of legalese
  94185. * with every copy.
  94186. *
  94187. * To compute the message digest of a chunk of bytes, declare an
  94188. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94189. * needed on buffers full of bytes, and then call MD5Final, which
  94190. * will fill a supplied 16-byte array with the digest.
  94191. *
  94192. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  94193. * header definitions; now uses stuff from dpkg's config.h
  94194. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94195. * Still in the public domain.
  94196. *
  94197. * Josh Coalson: made some changes to integrate with libFLAC.
  94198. * Still in the public domain, with no warranty.
  94199. */
  94200. typedef struct {
  94201. FLAC__uint32 in[16];
  94202. FLAC__uint32 buf[4];
  94203. FLAC__uint32 bytes[2];
  94204. FLAC__byte *internal_buf;
  94205. size_t capacity;
  94206. } FLAC__MD5Context;
  94207. void FLAC__MD5Init(FLAC__MD5Context *context);
  94208. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  94209. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  94210. #endif
  94211. /********* End of inlined file: md5.h *********/
  94212. #ifndef FLaC__INLINE
  94213. #define FLaC__INLINE
  94214. #endif
  94215. /*
  94216. * This code implements the MD5 message-digest algorithm.
  94217. * The algorithm is due to Ron Rivest. This code was
  94218. * written by Colin Plumb in 1993, no copyright is claimed.
  94219. * This code is in the public domain; do with it what you wish.
  94220. *
  94221. * Equivalent code is available from RSA Data Security, Inc.
  94222. * This code has been tested against that, and is equivalent,
  94223. * except that you don't need to include two pages of legalese
  94224. * with every copy.
  94225. *
  94226. * To compute the message digest of a chunk of bytes, declare an
  94227. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94228. * needed on buffers full of bytes, and then call MD5Final, which
  94229. * will fill a supplied 16-byte array with the digest.
  94230. *
  94231. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  94232. * definitions; now uses stuff from dpkg's config.h.
  94233. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94234. * Still in the public domain.
  94235. *
  94236. * Josh Coalson: made some changes to integrate with libFLAC.
  94237. * Still in the public domain.
  94238. */
  94239. /* The four core functions - F1 is optimized somewhat */
  94240. /* #define F1(x, y, z) (x & y | ~x & z) */
  94241. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  94242. #define F2(x, y, z) F1(z, x, y)
  94243. #define F3(x, y, z) (x ^ y ^ z)
  94244. #define F4(x, y, z) (y ^ (x | ~z))
  94245. /* This is the central step in the MD5 algorithm. */
  94246. #define MD5STEP(f,w,x,y,z,in,s) \
  94247. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  94248. /*
  94249. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  94250. * reflect the addition of 16 longwords of new data. MD5Update blocks
  94251. * the data and converts bytes into longwords for this routine.
  94252. */
  94253. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  94254. {
  94255. register FLAC__uint32 a, b, c, d;
  94256. a = buf[0];
  94257. b = buf[1];
  94258. c = buf[2];
  94259. d = buf[3];
  94260. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  94261. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  94262. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  94263. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  94264. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  94265. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  94266. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  94267. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  94268. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  94269. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  94270. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  94271. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  94272. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  94273. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  94274. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  94275. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  94276. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  94277. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  94278. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  94279. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  94280. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  94281. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  94282. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  94283. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  94284. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  94285. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  94286. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  94287. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  94288. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  94289. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  94290. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  94291. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  94292. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  94293. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  94294. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  94295. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  94296. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  94297. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  94298. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  94299. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  94300. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  94301. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  94302. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  94303. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  94304. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  94305. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  94306. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  94307. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  94308. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  94309. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  94310. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  94311. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  94312. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  94313. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  94314. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  94315. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  94316. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  94317. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  94318. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  94319. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  94320. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  94321. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  94322. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  94323. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  94324. buf[0] += a;
  94325. buf[1] += b;
  94326. buf[2] += c;
  94327. buf[3] += d;
  94328. }
  94329. #if WORDS_BIGENDIAN
  94330. //@@@@@@ OPT: use bswap/intrinsics
  94331. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  94332. {
  94333. register FLAC__uint32 x;
  94334. do {
  94335. x = *buf;
  94336. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  94337. *buf++ = (x >> 16) | (x << 16);
  94338. } while (--words);
  94339. }
  94340. static void byteSwapX16(FLAC__uint32 *buf)
  94341. {
  94342. register FLAC__uint32 x;
  94343. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94344. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94345. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94346. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94347. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94348. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94349. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94350. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94351. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94352. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94353. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94354. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94355. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94356. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94357. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94358. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  94359. }
  94360. #else
  94361. #define byteSwap(buf, words)
  94362. #define byteSwapX16(buf)
  94363. #endif
  94364. /*
  94365. * Update context to reflect the concatenation of another buffer full
  94366. * of bytes.
  94367. */
  94368. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  94369. {
  94370. FLAC__uint32 t;
  94371. /* Update byte count */
  94372. t = ctx->bytes[0];
  94373. if ((ctx->bytes[0] = t + len) < t)
  94374. ctx->bytes[1]++; /* Carry from low to high */
  94375. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  94376. if (t > len) {
  94377. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  94378. return;
  94379. }
  94380. /* First chunk is an odd size */
  94381. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  94382. byteSwapX16(ctx->in);
  94383. FLAC__MD5Transform(ctx->buf, ctx->in);
  94384. buf += t;
  94385. len -= t;
  94386. /* Process data in 64-byte chunks */
  94387. while (len >= 64) {
  94388. memcpy(ctx->in, buf, 64);
  94389. byteSwapX16(ctx->in);
  94390. FLAC__MD5Transform(ctx->buf, ctx->in);
  94391. buf += 64;
  94392. len -= 64;
  94393. }
  94394. /* Handle any remaining bytes of data. */
  94395. memcpy(ctx->in, buf, len);
  94396. }
  94397. /*
  94398. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  94399. * initialization constants.
  94400. */
  94401. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  94402. {
  94403. ctx->buf[0] = 0x67452301;
  94404. ctx->buf[1] = 0xefcdab89;
  94405. ctx->buf[2] = 0x98badcfe;
  94406. ctx->buf[3] = 0x10325476;
  94407. ctx->bytes[0] = 0;
  94408. ctx->bytes[1] = 0;
  94409. ctx->internal_buf = 0;
  94410. ctx->capacity = 0;
  94411. }
  94412. /*
  94413. * Final wrapup - pad to 64-byte boundary with the bit pattern
  94414. * 1 0* (64-bit count of bits processed, MSB-first)
  94415. */
  94416. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  94417. {
  94418. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  94419. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  94420. /* Set the first char of padding to 0x80. There is always room. */
  94421. *p++ = 0x80;
  94422. /* Bytes of padding needed to make 56 bytes (-8..55) */
  94423. count = 56 - 1 - count;
  94424. if (count < 0) { /* Padding forces an extra block */
  94425. memset(p, 0, count + 8);
  94426. byteSwapX16(ctx->in);
  94427. FLAC__MD5Transform(ctx->buf, ctx->in);
  94428. p = (FLAC__byte *)ctx->in;
  94429. count = 56;
  94430. }
  94431. memset(p, 0, count);
  94432. byteSwap(ctx->in, 14);
  94433. /* Append length in bits and transform */
  94434. ctx->in[14] = ctx->bytes[0] << 3;
  94435. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  94436. FLAC__MD5Transform(ctx->buf, ctx->in);
  94437. byteSwap(ctx->buf, 4);
  94438. memcpy(digest, ctx->buf, 16);
  94439. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  94440. if(0 != ctx->internal_buf) {
  94441. free(ctx->internal_buf);
  94442. ctx->internal_buf = 0;
  94443. ctx->capacity = 0;
  94444. }
  94445. }
  94446. /*
  94447. * Convert the incoming audio signal to a byte stream
  94448. */
  94449. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94450. {
  94451. unsigned channel, sample;
  94452. register FLAC__int32 a_word;
  94453. register FLAC__byte *buf_ = buf;
  94454. #if WORDS_BIGENDIAN
  94455. #else
  94456. if(channels == 2 && bytes_per_sample == 2) {
  94457. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  94458. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  94459. for(sample = 0; sample < samples; sample++, buf1_+=2)
  94460. *buf1_ = (FLAC__int16)signal[1][sample];
  94461. }
  94462. else if(channels == 1 && bytes_per_sample == 2) {
  94463. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  94464. for(sample = 0; sample < samples; sample++)
  94465. *buf1_++ = (FLAC__int16)signal[0][sample];
  94466. }
  94467. else
  94468. #endif
  94469. if(bytes_per_sample == 2) {
  94470. if(channels == 2) {
  94471. for(sample = 0; sample < samples; sample++) {
  94472. a_word = signal[0][sample];
  94473. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94474. *buf_++ = (FLAC__byte)a_word;
  94475. a_word = signal[1][sample];
  94476. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94477. *buf_++ = (FLAC__byte)a_word;
  94478. }
  94479. }
  94480. else if(channels == 1) {
  94481. for(sample = 0; sample < samples; sample++) {
  94482. a_word = signal[0][sample];
  94483. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94484. *buf_++ = (FLAC__byte)a_word;
  94485. }
  94486. }
  94487. else {
  94488. for(sample = 0; sample < samples; sample++) {
  94489. for(channel = 0; channel < channels; channel++) {
  94490. a_word = signal[channel][sample];
  94491. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94492. *buf_++ = (FLAC__byte)a_word;
  94493. }
  94494. }
  94495. }
  94496. }
  94497. else if(bytes_per_sample == 3) {
  94498. if(channels == 2) {
  94499. for(sample = 0; sample < samples; sample++) {
  94500. a_word = signal[0][sample];
  94501. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94502. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94503. *buf_++ = (FLAC__byte)a_word;
  94504. a_word = signal[1][sample];
  94505. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94506. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94507. *buf_++ = (FLAC__byte)a_word;
  94508. }
  94509. }
  94510. else if(channels == 1) {
  94511. for(sample = 0; sample < samples; sample++) {
  94512. a_word = signal[0][sample];
  94513. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94514. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94515. *buf_++ = (FLAC__byte)a_word;
  94516. }
  94517. }
  94518. else {
  94519. for(sample = 0; sample < samples; sample++) {
  94520. for(channel = 0; channel < channels; channel++) {
  94521. a_word = signal[channel][sample];
  94522. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94523. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94524. *buf_++ = (FLAC__byte)a_word;
  94525. }
  94526. }
  94527. }
  94528. }
  94529. else if(bytes_per_sample == 1) {
  94530. if(channels == 2) {
  94531. for(sample = 0; sample < samples; sample++) {
  94532. a_word = signal[0][sample];
  94533. *buf_++ = (FLAC__byte)a_word;
  94534. a_word = signal[1][sample];
  94535. *buf_++ = (FLAC__byte)a_word;
  94536. }
  94537. }
  94538. else if(channels == 1) {
  94539. for(sample = 0; sample < samples; sample++) {
  94540. a_word = signal[0][sample];
  94541. *buf_++ = (FLAC__byte)a_word;
  94542. }
  94543. }
  94544. else {
  94545. for(sample = 0; sample < samples; sample++) {
  94546. for(channel = 0; channel < channels; channel++) {
  94547. a_word = signal[channel][sample];
  94548. *buf_++ = (FLAC__byte)a_word;
  94549. }
  94550. }
  94551. }
  94552. }
  94553. else { /* bytes_per_sample == 4, maybe optimize more later */
  94554. for(sample = 0; sample < samples; sample++) {
  94555. for(channel = 0; channel < channels; channel++) {
  94556. a_word = signal[channel][sample];
  94557. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94558. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94559. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94560. *buf_++ = (FLAC__byte)a_word;
  94561. }
  94562. }
  94563. }
  94564. }
  94565. /*
  94566. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  94567. */
  94568. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94569. {
  94570. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  94571. /* overflow check */
  94572. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  94573. return false;
  94574. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  94575. return false;
  94576. if(ctx->capacity < bytes_needed) {
  94577. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  94578. if(0 == tmp) {
  94579. free(ctx->internal_buf);
  94580. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  94581. return false;
  94582. }
  94583. ctx->internal_buf = tmp;
  94584. ctx->capacity = bytes_needed;
  94585. }
  94586. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  94587. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  94588. return true;
  94589. }
  94590. #endif
  94591. /********* End of inlined file: md5.c *********/
  94592. /********* Start of inlined file: memory.c *********/
  94593. /********* Start of inlined file: juce_FlacHeader.h *********/
  94594. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94595. // tasks..
  94596. #define VERSION "1.2.1"
  94597. #define FLAC__NO_DLL 1
  94598. #if JUCE_MSVC
  94599. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94600. #endif
  94601. #if JUCE_MAC
  94602. #define FLAC__SYS_DARWIN 1
  94603. #endif
  94604. /********* End of inlined file: juce_FlacHeader.h *********/
  94605. #if JUCE_USE_FLAC
  94606. #if HAVE_CONFIG_H
  94607. # include <config.h>
  94608. #endif
  94609. /********* Start of inlined file: memory.h *********/
  94610. #ifndef FLAC__PRIVATE__MEMORY_H
  94611. #define FLAC__PRIVATE__MEMORY_H
  94612. #ifdef HAVE_CONFIG_H
  94613. #include <config.h>
  94614. #endif
  94615. #include <stdlib.h> /* for size_t */
  94616. /* Returns the unaligned address returned by malloc.
  94617. * Use free() on this address to deallocate.
  94618. */
  94619. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  94620. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  94621. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  94622. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  94623. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  94624. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94625. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  94626. #endif
  94627. #endif
  94628. /********* End of inlined file: memory.h *********/
  94629. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  94630. {
  94631. void *x;
  94632. FLAC__ASSERT(0 != aligned_address);
  94633. #ifdef FLAC__ALIGN_MALLOC_DATA
  94634. /* align on 32-byte (256-bit) boundary */
  94635. x = safe_malloc_add_2op_(bytes, /*+*/31);
  94636. #ifdef SIZEOF_VOIDP
  94637. #if SIZEOF_VOIDP == 4
  94638. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  94639. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94640. #elif SIZEOF_VOIDP == 8
  94641. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94642. #else
  94643. # error Unsupported sizeof(void*)
  94644. #endif
  94645. #else
  94646. /* there's got to be a better way to do this right for all archs */
  94647. if(sizeof(void*) == sizeof(unsigned))
  94648. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94649. else if(sizeof(void*) == sizeof(FLAC__uint64))
  94650. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94651. else
  94652. return 0;
  94653. #endif
  94654. #else
  94655. x = safe_malloc_(bytes);
  94656. *aligned_address = x;
  94657. #endif
  94658. return x;
  94659. }
  94660. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  94661. {
  94662. FLAC__int32 *pu; /* unaligned pointer */
  94663. union { /* union needed to comply with C99 pointer aliasing rules */
  94664. FLAC__int32 *pa; /* aligned pointer */
  94665. void *pv; /* aligned pointer alias */
  94666. } u;
  94667. FLAC__ASSERT(elements > 0);
  94668. FLAC__ASSERT(0 != unaligned_pointer);
  94669. FLAC__ASSERT(0 != aligned_pointer);
  94670. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94671. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94672. return false;
  94673. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  94674. if(0 == pu) {
  94675. return false;
  94676. }
  94677. else {
  94678. if(*unaligned_pointer != 0)
  94679. free(*unaligned_pointer);
  94680. *unaligned_pointer = pu;
  94681. *aligned_pointer = u.pa;
  94682. return true;
  94683. }
  94684. }
  94685. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  94686. {
  94687. FLAC__uint32 *pu; /* unaligned pointer */
  94688. union { /* union needed to comply with C99 pointer aliasing rules */
  94689. FLAC__uint32 *pa; /* aligned pointer */
  94690. void *pv; /* aligned pointer alias */
  94691. } u;
  94692. FLAC__ASSERT(elements > 0);
  94693. FLAC__ASSERT(0 != unaligned_pointer);
  94694. FLAC__ASSERT(0 != aligned_pointer);
  94695. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94696. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94697. return false;
  94698. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94699. if(0 == pu) {
  94700. return false;
  94701. }
  94702. else {
  94703. if(*unaligned_pointer != 0)
  94704. free(*unaligned_pointer);
  94705. *unaligned_pointer = pu;
  94706. *aligned_pointer = u.pa;
  94707. return true;
  94708. }
  94709. }
  94710. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  94711. {
  94712. FLAC__uint64 *pu; /* unaligned pointer */
  94713. union { /* union needed to comply with C99 pointer aliasing rules */
  94714. FLAC__uint64 *pa; /* aligned pointer */
  94715. void *pv; /* aligned pointer alias */
  94716. } u;
  94717. FLAC__ASSERT(elements > 0);
  94718. FLAC__ASSERT(0 != unaligned_pointer);
  94719. FLAC__ASSERT(0 != aligned_pointer);
  94720. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94721. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94722. return false;
  94723. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94724. if(0 == pu) {
  94725. return false;
  94726. }
  94727. else {
  94728. if(*unaligned_pointer != 0)
  94729. free(*unaligned_pointer);
  94730. *unaligned_pointer = pu;
  94731. *aligned_pointer = u.pa;
  94732. return true;
  94733. }
  94734. }
  94735. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  94736. {
  94737. unsigned *pu; /* unaligned pointer */
  94738. union { /* union needed to comply with C99 pointer aliasing rules */
  94739. unsigned *pa; /* aligned pointer */
  94740. void *pv; /* aligned pointer alias */
  94741. } u;
  94742. FLAC__ASSERT(elements > 0);
  94743. FLAC__ASSERT(0 != unaligned_pointer);
  94744. FLAC__ASSERT(0 != aligned_pointer);
  94745. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94746. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94747. return false;
  94748. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94749. if(0 == pu) {
  94750. return false;
  94751. }
  94752. else {
  94753. if(*unaligned_pointer != 0)
  94754. free(*unaligned_pointer);
  94755. *unaligned_pointer = pu;
  94756. *aligned_pointer = u.pa;
  94757. return true;
  94758. }
  94759. }
  94760. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94761. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  94762. {
  94763. FLAC__real *pu; /* unaligned pointer */
  94764. union { /* union needed to comply with C99 pointer aliasing rules */
  94765. FLAC__real *pa; /* aligned pointer */
  94766. void *pv; /* aligned pointer alias */
  94767. } u;
  94768. FLAC__ASSERT(elements > 0);
  94769. FLAC__ASSERT(0 != unaligned_pointer);
  94770. FLAC__ASSERT(0 != aligned_pointer);
  94771. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94772. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94773. return false;
  94774. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94775. if(0 == pu) {
  94776. return false;
  94777. }
  94778. else {
  94779. if(*unaligned_pointer != 0)
  94780. free(*unaligned_pointer);
  94781. *unaligned_pointer = pu;
  94782. *aligned_pointer = u.pa;
  94783. return true;
  94784. }
  94785. }
  94786. #endif
  94787. #endif
  94788. /********* End of inlined file: memory.c *********/
  94789. /********* Start of inlined file: stream_decoder.c *********/
  94790. /********* Start of inlined file: juce_FlacHeader.h *********/
  94791. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94792. // tasks..
  94793. #define VERSION "1.2.1"
  94794. #define FLAC__NO_DLL 1
  94795. #if JUCE_MSVC
  94796. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94797. #endif
  94798. #if JUCE_MAC
  94799. #define FLAC__SYS_DARWIN 1
  94800. #endif
  94801. /********* End of inlined file: juce_FlacHeader.h *********/
  94802. #if JUCE_USE_FLAC
  94803. #if HAVE_CONFIG_H
  94804. # include <config.h>
  94805. #endif
  94806. #if defined _MSC_VER || defined __MINGW32__
  94807. #include <io.h> /* for _setmode() */
  94808. #include <fcntl.h> /* for _O_BINARY */
  94809. #endif
  94810. #if defined __CYGWIN__ || defined __EMX__
  94811. #include <io.h> /* for setmode(), O_BINARY */
  94812. #include <fcntl.h> /* for _O_BINARY */
  94813. #endif
  94814. #include <stdio.h>
  94815. #include <stdlib.h> /* for malloc() */
  94816. #include <string.h> /* for memset/memcpy() */
  94817. #include <sys/stat.h> /* for stat() */
  94818. #include <sys/types.h> /* for off_t */
  94819. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  94820. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  94821. #define fseeko fseek
  94822. #define ftello ftell
  94823. #endif
  94824. #endif
  94825. /********* Start of inlined file: stream_decoder.h *********/
  94826. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  94827. #define FLAC__PROTECTED__STREAM_DECODER_H
  94828. #if FLAC__HAS_OGG
  94829. #include "include/private/ogg_decoder_aspect.h"
  94830. #endif
  94831. typedef struct FLAC__StreamDecoderProtected {
  94832. FLAC__StreamDecoderState state;
  94833. unsigned channels;
  94834. FLAC__ChannelAssignment channel_assignment;
  94835. unsigned bits_per_sample;
  94836. unsigned sample_rate; /* in Hz */
  94837. unsigned blocksize; /* in samples (per channel) */
  94838. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  94839. #if FLAC__HAS_OGG
  94840. FLAC__OggDecoderAspect ogg_decoder_aspect;
  94841. #endif
  94842. } FLAC__StreamDecoderProtected;
  94843. /*
  94844. * return the number of input bytes consumed
  94845. */
  94846. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  94847. #endif
  94848. /********* End of inlined file: stream_decoder.h *********/
  94849. #ifdef max
  94850. #undef max
  94851. #endif
  94852. #define max(a,b) ((a)>(b)?(a):(b))
  94853. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94854. #ifdef _MSC_VER
  94855. #define FLAC__U64L(x) x
  94856. #else
  94857. #define FLAC__U64L(x) x##LLU
  94858. #endif
  94859. /* technically this should be in an "export.c" but this is convenient enough */
  94860. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  94861. #if FLAC__HAS_OGG
  94862. 1
  94863. #else
  94864. 0
  94865. #endif
  94866. ;
  94867. /***********************************************************************
  94868. *
  94869. * Private static data
  94870. *
  94871. ***********************************************************************/
  94872. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  94873. /***********************************************************************
  94874. *
  94875. * Private class method prototypes
  94876. *
  94877. ***********************************************************************/
  94878. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  94879. static FILE *get_binary_stdin_(void);
  94880. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  94881. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  94882. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  94883. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  94884. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94885. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94886. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  94887. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  94888. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  94889. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  94890. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  94891. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  94892. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  94893. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94894. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94895. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94896. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94897. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94898. 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);
  94899. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  94900. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  94901. #if FLAC__HAS_OGG
  94902. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  94903. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94904. #endif
  94905. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  94906. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  94907. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94908. #if FLAC__HAS_OGG
  94909. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94910. #endif
  94911. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94912. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  94913. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  94914. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  94915. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  94916. /***********************************************************************
  94917. *
  94918. * Private class data
  94919. *
  94920. ***********************************************************************/
  94921. typedef struct FLAC__StreamDecoderPrivate {
  94922. #if FLAC__HAS_OGG
  94923. FLAC__bool is_ogg;
  94924. #endif
  94925. FLAC__StreamDecoderReadCallback read_callback;
  94926. FLAC__StreamDecoderSeekCallback seek_callback;
  94927. FLAC__StreamDecoderTellCallback tell_callback;
  94928. FLAC__StreamDecoderLengthCallback length_callback;
  94929. FLAC__StreamDecoderEofCallback eof_callback;
  94930. FLAC__StreamDecoderWriteCallback write_callback;
  94931. FLAC__StreamDecoderMetadataCallback metadata_callback;
  94932. FLAC__StreamDecoderErrorCallback error_callback;
  94933. /* generic 32-bit datapath: */
  94934. 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[]);
  94935. /* generic 64-bit datapath: */
  94936. 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[]);
  94937. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  94938. 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[]);
  94939. /* 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: */
  94940. 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[]);
  94941. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  94942. void *client_data;
  94943. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  94944. FLAC__BitReader *input;
  94945. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  94946. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  94947. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  94948. unsigned output_capacity, output_channels;
  94949. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  94950. FLAC__uint64 samples_decoded;
  94951. FLAC__bool has_stream_info, has_seek_table;
  94952. FLAC__StreamMetadata stream_info;
  94953. FLAC__StreamMetadata seek_table;
  94954. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  94955. FLAC__byte *metadata_filter_ids;
  94956. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  94957. FLAC__Frame frame;
  94958. FLAC__bool cached; /* true if there is a byte in lookahead */
  94959. FLAC__CPUInfo cpuinfo;
  94960. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  94961. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  94962. /* unaligned (original) pointers to allocated data */
  94963. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  94964. 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 */
  94965. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  94966. FLAC__bool is_seeking;
  94967. FLAC__MD5Context md5context;
  94968. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  94969. /* (the rest of these are only used for seeking) */
  94970. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  94971. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  94972. FLAC__uint64 target_sample;
  94973. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  94974. #if FLAC__HAS_OGG
  94975. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  94976. #endif
  94977. } FLAC__StreamDecoderPrivate;
  94978. /***********************************************************************
  94979. *
  94980. * Public static class data
  94981. *
  94982. ***********************************************************************/
  94983. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  94984. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  94985. "FLAC__STREAM_DECODER_READ_METADATA",
  94986. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  94987. "FLAC__STREAM_DECODER_READ_FRAME",
  94988. "FLAC__STREAM_DECODER_END_OF_STREAM",
  94989. "FLAC__STREAM_DECODER_OGG_ERROR",
  94990. "FLAC__STREAM_DECODER_SEEK_ERROR",
  94991. "FLAC__STREAM_DECODER_ABORTED",
  94992. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  94993. "FLAC__STREAM_DECODER_UNINITIALIZED"
  94994. };
  94995. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  94996. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  94997. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  94998. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  94999. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  95000. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  95001. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  95002. };
  95003. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  95004. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  95005. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  95006. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  95007. };
  95008. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  95009. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  95010. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  95011. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  95012. };
  95013. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  95014. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  95015. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  95016. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  95017. };
  95018. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  95019. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  95020. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  95021. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  95022. };
  95023. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  95024. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  95025. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  95026. };
  95027. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  95028. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  95029. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  95030. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  95031. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  95032. };
  95033. /***********************************************************************
  95034. *
  95035. * Class constructor/destructor
  95036. *
  95037. ***********************************************************************/
  95038. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  95039. {
  95040. FLAC__StreamDecoder *decoder;
  95041. unsigned i;
  95042. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  95043. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  95044. if(decoder == 0) {
  95045. return 0;
  95046. }
  95047. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  95048. if(decoder->protected_ == 0) {
  95049. free(decoder);
  95050. return 0;
  95051. }
  95052. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  95053. if(decoder->private_ == 0) {
  95054. free(decoder->protected_);
  95055. free(decoder);
  95056. return 0;
  95057. }
  95058. decoder->private_->input = FLAC__bitreader_new();
  95059. if(decoder->private_->input == 0) {
  95060. free(decoder->private_);
  95061. free(decoder->protected_);
  95062. free(decoder);
  95063. return 0;
  95064. }
  95065. decoder->private_->metadata_filter_ids_capacity = 16;
  95066. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  95067. FLAC__bitreader_delete(decoder->private_->input);
  95068. free(decoder->private_);
  95069. free(decoder->protected_);
  95070. free(decoder);
  95071. return 0;
  95072. }
  95073. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95074. decoder->private_->output[i] = 0;
  95075. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95076. }
  95077. decoder->private_->output_capacity = 0;
  95078. decoder->private_->output_channels = 0;
  95079. decoder->private_->has_seek_table = false;
  95080. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95081. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  95082. decoder->private_->file = 0;
  95083. set_defaults_dec(decoder);
  95084. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95085. return decoder;
  95086. }
  95087. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  95088. {
  95089. unsigned i;
  95090. FLAC__ASSERT(0 != decoder);
  95091. FLAC__ASSERT(0 != decoder->protected_);
  95092. FLAC__ASSERT(0 != decoder->private_);
  95093. FLAC__ASSERT(0 != decoder->private_->input);
  95094. (void)FLAC__stream_decoder_finish(decoder);
  95095. if(0 != decoder->private_->metadata_filter_ids)
  95096. free(decoder->private_->metadata_filter_ids);
  95097. FLAC__bitreader_delete(decoder->private_->input);
  95098. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95099. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  95100. free(decoder->private_);
  95101. free(decoder->protected_);
  95102. free(decoder);
  95103. }
  95104. /***********************************************************************
  95105. *
  95106. * Public class methods
  95107. *
  95108. ***********************************************************************/
  95109. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  95110. FLAC__StreamDecoder *decoder,
  95111. FLAC__StreamDecoderReadCallback read_callback,
  95112. FLAC__StreamDecoderSeekCallback seek_callback,
  95113. FLAC__StreamDecoderTellCallback tell_callback,
  95114. FLAC__StreamDecoderLengthCallback length_callback,
  95115. FLAC__StreamDecoderEofCallback eof_callback,
  95116. FLAC__StreamDecoderWriteCallback write_callback,
  95117. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95118. FLAC__StreamDecoderErrorCallback error_callback,
  95119. void *client_data,
  95120. FLAC__bool is_ogg
  95121. )
  95122. {
  95123. FLAC__ASSERT(0 != decoder);
  95124. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95125. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  95126. #if !FLAC__HAS_OGG
  95127. if(is_ogg)
  95128. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  95129. #endif
  95130. if(
  95131. 0 == read_callback ||
  95132. 0 == write_callback ||
  95133. 0 == error_callback ||
  95134. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  95135. )
  95136. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  95137. #if FLAC__HAS_OGG
  95138. decoder->private_->is_ogg = is_ogg;
  95139. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  95140. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  95141. #endif
  95142. /*
  95143. * get the CPU info and set the function pointers
  95144. */
  95145. FLAC__cpu_info(&decoder->private_->cpuinfo);
  95146. /* first default to the non-asm routines */
  95147. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  95148. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  95149. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  95150. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  95151. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  95152. /* now override with asm where appropriate */
  95153. #ifndef FLAC__NO_ASM
  95154. if(decoder->private_->cpuinfo.use_asm) {
  95155. #ifdef FLAC__CPU_IA32
  95156. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  95157. #ifdef FLAC__HAS_NASM
  95158. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  95159. if(decoder->private_->cpuinfo.data.ia32.bswap)
  95160. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  95161. #endif
  95162. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  95163. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95164. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95165. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95166. }
  95167. else {
  95168. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95169. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  95170. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  95171. }
  95172. #endif
  95173. #elif defined FLAC__CPU_PPC
  95174. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  95175. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  95176. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  95177. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  95178. }
  95179. #endif
  95180. }
  95181. #endif
  95182. /* from here on, errors are fatal */
  95183. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  95184. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95185. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95186. }
  95187. decoder->private_->read_callback = read_callback;
  95188. decoder->private_->seek_callback = seek_callback;
  95189. decoder->private_->tell_callback = tell_callback;
  95190. decoder->private_->length_callback = length_callback;
  95191. decoder->private_->eof_callback = eof_callback;
  95192. decoder->private_->write_callback = write_callback;
  95193. decoder->private_->metadata_callback = metadata_callback;
  95194. decoder->private_->error_callback = error_callback;
  95195. decoder->private_->client_data = client_data;
  95196. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95197. decoder->private_->samples_decoded = 0;
  95198. decoder->private_->has_stream_info = false;
  95199. decoder->private_->cached = false;
  95200. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95201. decoder->private_->is_seeking = false;
  95202. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  95203. if(!FLAC__stream_decoder_reset(decoder)) {
  95204. /* above call sets the state for us */
  95205. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95206. }
  95207. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  95208. }
  95209. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  95210. FLAC__StreamDecoder *decoder,
  95211. FLAC__StreamDecoderReadCallback read_callback,
  95212. FLAC__StreamDecoderSeekCallback seek_callback,
  95213. FLAC__StreamDecoderTellCallback tell_callback,
  95214. FLAC__StreamDecoderLengthCallback length_callback,
  95215. FLAC__StreamDecoderEofCallback eof_callback,
  95216. FLAC__StreamDecoderWriteCallback write_callback,
  95217. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95218. FLAC__StreamDecoderErrorCallback error_callback,
  95219. void *client_data
  95220. )
  95221. {
  95222. return init_stream_internal_dec(
  95223. decoder,
  95224. read_callback,
  95225. seek_callback,
  95226. tell_callback,
  95227. length_callback,
  95228. eof_callback,
  95229. write_callback,
  95230. metadata_callback,
  95231. error_callback,
  95232. client_data,
  95233. /*is_ogg=*/false
  95234. );
  95235. }
  95236. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  95237. FLAC__StreamDecoder *decoder,
  95238. FLAC__StreamDecoderReadCallback read_callback,
  95239. FLAC__StreamDecoderSeekCallback seek_callback,
  95240. FLAC__StreamDecoderTellCallback tell_callback,
  95241. FLAC__StreamDecoderLengthCallback length_callback,
  95242. FLAC__StreamDecoderEofCallback eof_callback,
  95243. FLAC__StreamDecoderWriteCallback write_callback,
  95244. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95245. FLAC__StreamDecoderErrorCallback error_callback,
  95246. void *client_data
  95247. )
  95248. {
  95249. return init_stream_internal_dec(
  95250. decoder,
  95251. read_callback,
  95252. seek_callback,
  95253. tell_callback,
  95254. length_callback,
  95255. eof_callback,
  95256. write_callback,
  95257. metadata_callback,
  95258. error_callback,
  95259. client_data,
  95260. /*is_ogg=*/true
  95261. );
  95262. }
  95263. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  95264. FLAC__StreamDecoder *decoder,
  95265. FILE *file,
  95266. FLAC__StreamDecoderWriteCallback write_callback,
  95267. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95268. FLAC__StreamDecoderErrorCallback error_callback,
  95269. void *client_data,
  95270. FLAC__bool is_ogg
  95271. )
  95272. {
  95273. FLAC__ASSERT(0 != decoder);
  95274. FLAC__ASSERT(0 != file);
  95275. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95276. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95277. if(0 == write_callback || 0 == error_callback)
  95278. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95279. /*
  95280. * To make sure that our file does not go unclosed after an error, we
  95281. * must assign the FILE pointer before any further error can occur in
  95282. * this routine.
  95283. */
  95284. if(file == stdin)
  95285. file = get_binary_stdin_(); /* just to be safe */
  95286. decoder->private_->file = file;
  95287. return init_stream_internal_dec(
  95288. decoder,
  95289. file_read_callback_dec,
  95290. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  95291. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  95292. decoder->private_->file == stdin? 0: file_length_callback_,
  95293. file_eof_callback_,
  95294. write_callback,
  95295. metadata_callback,
  95296. error_callback,
  95297. client_data,
  95298. is_ogg
  95299. );
  95300. }
  95301. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  95302. FLAC__StreamDecoder *decoder,
  95303. FILE *file,
  95304. FLAC__StreamDecoderWriteCallback write_callback,
  95305. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95306. FLAC__StreamDecoderErrorCallback error_callback,
  95307. void *client_data
  95308. )
  95309. {
  95310. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95311. }
  95312. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  95313. FLAC__StreamDecoder *decoder,
  95314. FILE *file,
  95315. FLAC__StreamDecoderWriteCallback write_callback,
  95316. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95317. FLAC__StreamDecoderErrorCallback error_callback,
  95318. void *client_data
  95319. )
  95320. {
  95321. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95322. }
  95323. static FLAC__StreamDecoderInitStatus init_file_internal_(
  95324. FLAC__StreamDecoder *decoder,
  95325. const char *filename,
  95326. FLAC__StreamDecoderWriteCallback write_callback,
  95327. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95328. FLAC__StreamDecoderErrorCallback error_callback,
  95329. void *client_data,
  95330. FLAC__bool is_ogg
  95331. )
  95332. {
  95333. FILE *file;
  95334. FLAC__ASSERT(0 != decoder);
  95335. /*
  95336. * To make sure that our file does not go unclosed after an error, we
  95337. * have to do the same entrance checks here that are later performed
  95338. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  95339. */
  95340. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95341. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95342. if(0 == write_callback || 0 == error_callback)
  95343. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95344. file = filename? fopen(filename, "rb") : stdin;
  95345. if(0 == file)
  95346. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  95347. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  95348. }
  95349. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  95350. FLAC__StreamDecoder *decoder,
  95351. const char *filename,
  95352. FLAC__StreamDecoderWriteCallback write_callback,
  95353. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95354. FLAC__StreamDecoderErrorCallback error_callback,
  95355. void *client_data
  95356. )
  95357. {
  95358. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95359. }
  95360. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  95361. FLAC__StreamDecoder *decoder,
  95362. const char *filename,
  95363. FLAC__StreamDecoderWriteCallback write_callback,
  95364. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95365. FLAC__StreamDecoderErrorCallback error_callback,
  95366. void *client_data
  95367. )
  95368. {
  95369. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95370. }
  95371. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  95372. {
  95373. FLAC__bool md5_failed = false;
  95374. unsigned i;
  95375. FLAC__ASSERT(0 != decoder);
  95376. FLAC__ASSERT(0 != decoder->private_);
  95377. FLAC__ASSERT(0 != decoder->protected_);
  95378. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  95379. return true;
  95380. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  95381. * always call FLAC__MD5Final()
  95382. */
  95383. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  95384. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95385. free(decoder->private_->seek_table.data.seek_table.points);
  95386. decoder->private_->seek_table.data.seek_table.points = 0;
  95387. decoder->private_->has_seek_table = false;
  95388. }
  95389. FLAC__bitreader_free(decoder->private_->input);
  95390. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95391. /* WATCHOUT:
  95392. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95393. * output arrays have a buffer of up to 3 zeroes in front
  95394. * (at negative indices) for alignment purposes; we use 4
  95395. * to keep the data well-aligned.
  95396. */
  95397. if(0 != decoder->private_->output[i]) {
  95398. free(decoder->private_->output[i]-4);
  95399. decoder->private_->output[i] = 0;
  95400. }
  95401. if(0 != decoder->private_->residual_unaligned[i]) {
  95402. free(decoder->private_->residual_unaligned[i]);
  95403. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95404. }
  95405. }
  95406. decoder->private_->output_capacity = 0;
  95407. decoder->private_->output_channels = 0;
  95408. #if FLAC__HAS_OGG
  95409. if(decoder->private_->is_ogg)
  95410. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  95411. #endif
  95412. if(0 != decoder->private_->file) {
  95413. if(decoder->private_->file != stdin)
  95414. fclose(decoder->private_->file);
  95415. decoder->private_->file = 0;
  95416. }
  95417. if(decoder->private_->do_md5_checking) {
  95418. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  95419. md5_failed = true;
  95420. }
  95421. decoder->private_->is_seeking = false;
  95422. set_defaults_dec(decoder);
  95423. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95424. return !md5_failed;
  95425. }
  95426. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  95427. {
  95428. FLAC__ASSERT(0 != decoder);
  95429. FLAC__ASSERT(0 != decoder->private_);
  95430. FLAC__ASSERT(0 != decoder->protected_);
  95431. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95432. return false;
  95433. #if FLAC__HAS_OGG
  95434. /* can't check decoder->private_->is_ogg since that's not set until init time */
  95435. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  95436. return true;
  95437. #else
  95438. (void)value;
  95439. return false;
  95440. #endif
  95441. }
  95442. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  95443. {
  95444. FLAC__ASSERT(0 != decoder);
  95445. FLAC__ASSERT(0 != decoder->protected_);
  95446. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95447. return false;
  95448. decoder->protected_->md5_checking = value;
  95449. return true;
  95450. }
  95451. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95452. {
  95453. FLAC__ASSERT(0 != decoder);
  95454. FLAC__ASSERT(0 != decoder->private_);
  95455. FLAC__ASSERT(0 != decoder->protected_);
  95456. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95457. /* double protection */
  95458. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95459. return false;
  95460. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95461. return false;
  95462. decoder->private_->metadata_filter[type] = true;
  95463. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95464. decoder->private_->metadata_filter_ids_count = 0;
  95465. return true;
  95466. }
  95467. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95468. {
  95469. FLAC__ASSERT(0 != decoder);
  95470. FLAC__ASSERT(0 != decoder->private_);
  95471. FLAC__ASSERT(0 != decoder->protected_);
  95472. FLAC__ASSERT(0 != id);
  95473. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95474. return false;
  95475. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95476. return true;
  95477. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95478. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95479. 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))) {
  95480. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95481. return false;
  95482. }
  95483. decoder->private_->metadata_filter_ids_capacity *= 2;
  95484. }
  95485. 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));
  95486. decoder->private_->metadata_filter_ids_count++;
  95487. return true;
  95488. }
  95489. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  95490. {
  95491. unsigned i;
  95492. FLAC__ASSERT(0 != decoder);
  95493. FLAC__ASSERT(0 != decoder->private_);
  95494. FLAC__ASSERT(0 != decoder->protected_);
  95495. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95496. return false;
  95497. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  95498. decoder->private_->metadata_filter[i] = true;
  95499. decoder->private_->metadata_filter_ids_count = 0;
  95500. return true;
  95501. }
  95502. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95503. {
  95504. FLAC__ASSERT(0 != decoder);
  95505. FLAC__ASSERT(0 != decoder->private_);
  95506. FLAC__ASSERT(0 != decoder->protected_);
  95507. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95508. /* double protection */
  95509. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95510. return false;
  95511. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95512. return false;
  95513. decoder->private_->metadata_filter[type] = false;
  95514. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95515. decoder->private_->metadata_filter_ids_count = 0;
  95516. return true;
  95517. }
  95518. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95519. {
  95520. FLAC__ASSERT(0 != decoder);
  95521. FLAC__ASSERT(0 != decoder->private_);
  95522. FLAC__ASSERT(0 != decoder->protected_);
  95523. FLAC__ASSERT(0 != id);
  95524. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95525. return false;
  95526. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95527. return true;
  95528. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95529. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95530. 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))) {
  95531. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95532. return false;
  95533. }
  95534. decoder->private_->metadata_filter_ids_capacity *= 2;
  95535. }
  95536. 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));
  95537. decoder->private_->metadata_filter_ids_count++;
  95538. return true;
  95539. }
  95540. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  95541. {
  95542. FLAC__ASSERT(0 != decoder);
  95543. FLAC__ASSERT(0 != decoder->private_);
  95544. FLAC__ASSERT(0 != decoder->protected_);
  95545. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95546. return false;
  95547. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95548. decoder->private_->metadata_filter_ids_count = 0;
  95549. return true;
  95550. }
  95551. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  95552. {
  95553. FLAC__ASSERT(0 != decoder);
  95554. FLAC__ASSERT(0 != decoder->protected_);
  95555. return decoder->protected_->state;
  95556. }
  95557. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  95558. {
  95559. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  95560. }
  95561. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  95562. {
  95563. FLAC__ASSERT(0 != decoder);
  95564. FLAC__ASSERT(0 != decoder->protected_);
  95565. return decoder->protected_->md5_checking;
  95566. }
  95567. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  95568. {
  95569. FLAC__ASSERT(0 != decoder);
  95570. FLAC__ASSERT(0 != decoder->protected_);
  95571. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  95572. }
  95573. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  95574. {
  95575. FLAC__ASSERT(0 != decoder);
  95576. FLAC__ASSERT(0 != decoder->protected_);
  95577. return decoder->protected_->channels;
  95578. }
  95579. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  95580. {
  95581. FLAC__ASSERT(0 != decoder);
  95582. FLAC__ASSERT(0 != decoder->protected_);
  95583. return decoder->protected_->channel_assignment;
  95584. }
  95585. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  95586. {
  95587. FLAC__ASSERT(0 != decoder);
  95588. FLAC__ASSERT(0 != decoder->protected_);
  95589. return decoder->protected_->bits_per_sample;
  95590. }
  95591. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  95592. {
  95593. FLAC__ASSERT(0 != decoder);
  95594. FLAC__ASSERT(0 != decoder->protected_);
  95595. return decoder->protected_->sample_rate;
  95596. }
  95597. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  95598. {
  95599. FLAC__ASSERT(0 != decoder);
  95600. FLAC__ASSERT(0 != decoder->protected_);
  95601. return decoder->protected_->blocksize;
  95602. }
  95603. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  95604. {
  95605. FLAC__ASSERT(0 != decoder);
  95606. FLAC__ASSERT(0 != decoder->private_);
  95607. FLAC__ASSERT(0 != position);
  95608. #if FLAC__HAS_OGG
  95609. if(decoder->private_->is_ogg)
  95610. return false;
  95611. #endif
  95612. if(0 == decoder->private_->tell_callback)
  95613. return false;
  95614. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  95615. return false;
  95616. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  95617. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  95618. return false;
  95619. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  95620. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  95621. return true;
  95622. }
  95623. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  95624. {
  95625. FLAC__ASSERT(0 != decoder);
  95626. FLAC__ASSERT(0 != decoder->private_);
  95627. FLAC__ASSERT(0 != decoder->protected_);
  95628. decoder->private_->samples_decoded = 0;
  95629. decoder->private_->do_md5_checking = false;
  95630. #if FLAC__HAS_OGG
  95631. if(decoder->private_->is_ogg)
  95632. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  95633. #endif
  95634. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  95635. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95636. return false;
  95637. }
  95638. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95639. return true;
  95640. }
  95641. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  95642. {
  95643. FLAC__ASSERT(0 != decoder);
  95644. FLAC__ASSERT(0 != decoder->private_);
  95645. FLAC__ASSERT(0 != decoder->protected_);
  95646. if(!FLAC__stream_decoder_flush(decoder)) {
  95647. /* above call sets the state for us */
  95648. return false;
  95649. }
  95650. #if FLAC__HAS_OGG
  95651. /*@@@ could go in !internal_reset_hack block below */
  95652. if(decoder->private_->is_ogg)
  95653. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  95654. #endif
  95655. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  95656. * (internal_reset_hack) don't try to rewind since we are already at
  95657. * the beginning of the stream and don't want to fail if the input is
  95658. * not seekable.
  95659. */
  95660. if(!decoder->private_->internal_reset_hack) {
  95661. if(decoder->private_->file == stdin)
  95662. return false; /* can't rewind stdin, reset fails */
  95663. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  95664. return false; /* seekable and seek fails, reset fails */
  95665. }
  95666. else
  95667. decoder->private_->internal_reset_hack = false;
  95668. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  95669. decoder->private_->has_stream_info = false;
  95670. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95671. free(decoder->private_->seek_table.data.seek_table.points);
  95672. decoder->private_->seek_table.data.seek_table.points = 0;
  95673. decoder->private_->has_seek_table = false;
  95674. }
  95675. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95676. /*
  95677. * This goes in reset() and not flush() because according to the spec, a
  95678. * fixed-blocksize stream must stay that way through the whole stream.
  95679. */
  95680. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95681. /* We initialize the FLAC__MD5Context even though we may never use it. This
  95682. * is because md5 checking may be turned on to start and then turned off if
  95683. * a seek occurs. So we init the context here and finalize it in
  95684. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  95685. * properly.
  95686. */
  95687. FLAC__MD5Init(&decoder->private_->md5context);
  95688. decoder->private_->first_frame_offset = 0;
  95689. decoder->private_->unparseable_frame_count = 0;
  95690. return true;
  95691. }
  95692. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  95693. {
  95694. FLAC__bool got_a_frame;
  95695. FLAC__ASSERT(0 != decoder);
  95696. FLAC__ASSERT(0 != decoder->protected_);
  95697. while(1) {
  95698. switch(decoder->protected_->state) {
  95699. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95700. if(!find_metadata_(decoder))
  95701. return false; /* above function sets the status for us */
  95702. break;
  95703. case FLAC__STREAM_DECODER_READ_METADATA:
  95704. if(!read_metadata_(decoder))
  95705. return false; /* above function sets the status for us */
  95706. else
  95707. return true;
  95708. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95709. if(!frame_sync_(decoder))
  95710. return true; /* above function sets the status for us */
  95711. break;
  95712. case FLAC__STREAM_DECODER_READ_FRAME:
  95713. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  95714. return false; /* above function sets the status for us */
  95715. if(got_a_frame)
  95716. return true; /* above function sets the status for us */
  95717. break;
  95718. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95719. case FLAC__STREAM_DECODER_ABORTED:
  95720. return true;
  95721. default:
  95722. FLAC__ASSERT(0);
  95723. return false;
  95724. }
  95725. }
  95726. }
  95727. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  95728. {
  95729. FLAC__ASSERT(0 != decoder);
  95730. FLAC__ASSERT(0 != decoder->protected_);
  95731. while(1) {
  95732. switch(decoder->protected_->state) {
  95733. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95734. if(!find_metadata_(decoder))
  95735. return false; /* above function sets the status for us */
  95736. break;
  95737. case FLAC__STREAM_DECODER_READ_METADATA:
  95738. if(!read_metadata_(decoder))
  95739. return false; /* above function sets the status for us */
  95740. break;
  95741. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95742. case FLAC__STREAM_DECODER_READ_FRAME:
  95743. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95744. case FLAC__STREAM_DECODER_ABORTED:
  95745. return true;
  95746. default:
  95747. FLAC__ASSERT(0);
  95748. return false;
  95749. }
  95750. }
  95751. }
  95752. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  95753. {
  95754. FLAC__bool dummy;
  95755. FLAC__ASSERT(0 != decoder);
  95756. FLAC__ASSERT(0 != decoder->protected_);
  95757. while(1) {
  95758. switch(decoder->protected_->state) {
  95759. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95760. if(!find_metadata_(decoder))
  95761. return false; /* above function sets the status for us */
  95762. break;
  95763. case FLAC__STREAM_DECODER_READ_METADATA:
  95764. if(!read_metadata_(decoder))
  95765. return false; /* above function sets the status for us */
  95766. break;
  95767. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95768. if(!frame_sync_(decoder))
  95769. return true; /* above function sets the status for us */
  95770. break;
  95771. case FLAC__STREAM_DECODER_READ_FRAME:
  95772. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  95773. return false; /* above function sets the status for us */
  95774. break;
  95775. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95776. case FLAC__STREAM_DECODER_ABORTED:
  95777. return true;
  95778. default:
  95779. FLAC__ASSERT(0);
  95780. return false;
  95781. }
  95782. }
  95783. }
  95784. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  95785. {
  95786. FLAC__bool got_a_frame;
  95787. FLAC__ASSERT(0 != decoder);
  95788. FLAC__ASSERT(0 != decoder->protected_);
  95789. while(1) {
  95790. switch(decoder->protected_->state) {
  95791. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95792. case FLAC__STREAM_DECODER_READ_METADATA:
  95793. return false; /* above function sets the status for us */
  95794. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95795. if(!frame_sync_(decoder))
  95796. return true; /* above function sets the status for us */
  95797. break;
  95798. case FLAC__STREAM_DECODER_READ_FRAME:
  95799. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  95800. return false; /* above function sets the status for us */
  95801. if(got_a_frame)
  95802. return true; /* above function sets the status for us */
  95803. break;
  95804. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95805. case FLAC__STREAM_DECODER_ABORTED:
  95806. return true;
  95807. default:
  95808. FLAC__ASSERT(0);
  95809. return false;
  95810. }
  95811. }
  95812. }
  95813. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  95814. {
  95815. FLAC__uint64 length;
  95816. FLAC__ASSERT(0 != decoder);
  95817. if(
  95818. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  95819. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  95820. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  95821. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  95822. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  95823. )
  95824. return false;
  95825. if(0 == decoder->private_->seek_callback)
  95826. return false;
  95827. FLAC__ASSERT(decoder->private_->seek_callback);
  95828. FLAC__ASSERT(decoder->private_->tell_callback);
  95829. FLAC__ASSERT(decoder->private_->length_callback);
  95830. FLAC__ASSERT(decoder->private_->eof_callback);
  95831. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  95832. return false;
  95833. decoder->private_->is_seeking = true;
  95834. /* turn off md5 checking if a seek is attempted */
  95835. decoder->private_->do_md5_checking = false;
  95836. /* 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) */
  95837. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  95838. decoder->private_->is_seeking = false;
  95839. return false;
  95840. }
  95841. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  95842. if(
  95843. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  95844. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  95845. ) {
  95846. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  95847. /* above call sets the state for us */
  95848. decoder->private_->is_seeking = false;
  95849. return false;
  95850. }
  95851. /* check this again in case we didn't know total_samples the first time */
  95852. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  95853. decoder->private_->is_seeking = false;
  95854. return false;
  95855. }
  95856. }
  95857. {
  95858. const FLAC__bool ok =
  95859. #if FLAC__HAS_OGG
  95860. decoder->private_->is_ogg?
  95861. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  95862. #endif
  95863. seek_to_absolute_sample_(decoder, length, sample)
  95864. ;
  95865. decoder->private_->is_seeking = false;
  95866. return ok;
  95867. }
  95868. }
  95869. /***********************************************************************
  95870. *
  95871. * Protected class methods
  95872. *
  95873. ***********************************************************************/
  95874. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  95875. {
  95876. FLAC__ASSERT(0 != decoder);
  95877. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95878. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  95879. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  95880. }
  95881. /***********************************************************************
  95882. *
  95883. * Private class methods
  95884. *
  95885. ***********************************************************************/
  95886. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  95887. {
  95888. #if FLAC__HAS_OGG
  95889. decoder->private_->is_ogg = false;
  95890. #endif
  95891. decoder->private_->read_callback = 0;
  95892. decoder->private_->seek_callback = 0;
  95893. decoder->private_->tell_callback = 0;
  95894. decoder->private_->length_callback = 0;
  95895. decoder->private_->eof_callback = 0;
  95896. decoder->private_->write_callback = 0;
  95897. decoder->private_->metadata_callback = 0;
  95898. decoder->private_->error_callback = 0;
  95899. decoder->private_->client_data = 0;
  95900. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95901. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  95902. decoder->private_->metadata_filter_ids_count = 0;
  95903. decoder->protected_->md5_checking = false;
  95904. #if FLAC__HAS_OGG
  95905. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  95906. #endif
  95907. }
  95908. /*
  95909. * This will forcibly set stdin to binary mode (for OSes that require it)
  95910. */
  95911. FILE *get_binary_stdin_(void)
  95912. {
  95913. /* if something breaks here it is probably due to the presence or
  95914. * absence of an underscore before the identifiers 'setmode',
  95915. * 'fileno', and/or 'O_BINARY'; check your system header files.
  95916. */
  95917. #if defined _MSC_VER || defined __MINGW32__
  95918. _setmode(_fileno(stdin), _O_BINARY);
  95919. #elif defined __CYGWIN__
  95920. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  95921. setmode(_fileno(stdin), _O_BINARY);
  95922. #elif defined __EMX__
  95923. setmode(fileno(stdin), O_BINARY);
  95924. #endif
  95925. return stdin;
  95926. }
  95927. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  95928. {
  95929. unsigned i;
  95930. FLAC__int32 *tmp;
  95931. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  95932. return true;
  95933. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  95934. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95935. if(0 != decoder->private_->output[i]) {
  95936. free(decoder->private_->output[i]-4);
  95937. decoder->private_->output[i] = 0;
  95938. }
  95939. if(0 != decoder->private_->residual_unaligned[i]) {
  95940. free(decoder->private_->residual_unaligned[i]);
  95941. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95942. }
  95943. }
  95944. for(i = 0; i < channels; i++) {
  95945. /* WATCHOUT:
  95946. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95947. * output arrays have a buffer of up to 3 zeroes in front
  95948. * (at negative indices) for alignment purposes; we use 4
  95949. * to keep the data well-aligned.
  95950. */
  95951. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  95952. if(tmp == 0) {
  95953. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95954. return false;
  95955. }
  95956. memset(tmp, 0, sizeof(FLAC__int32)*4);
  95957. decoder->private_->output[i] = tmp + 4;
  95958. /* WATCHOUT:
  95959. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  95960. */
  95961. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  95962. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95963. return false;
  95964. }
  95965. }
  95966. decoder->private_->output_capacity = size;
  95967. decoder->private_->output_channels = channels;
  95968. return true;
  95969. }
  95970. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  95971. {
  95972. size_t i;
  95973. FLAC__ASSERT(0 != decoder);
  95974. FLAC__ASSERT(0 != decoder->private_);
  95975. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  95976. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  95977. return true;
  95978. return false;
  95979. }
  95980. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  95981. {
  95982. FLAC__uint32 x;
  95983. unsigned i, id_;
  95984. FLAC__bool first = true;
  95985. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95986. for(i = id_ = 0; i < 4; ) {
  95987. if(decoder->private_->cached) {
  95988. x = (FLAC__uint32)decoder->private_->lookahead;
  95989. decoder->private_->cached = false;
  95990. }
  95991. else {
  95992. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95993. return false; /* read_callback_ sets the state for us */
  95994. }
  95995. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  95996. first = true;
  95997. i++;
  95998. id_ = 0;
  95999. continue;
  96000. }
  96001. if(x == ID3V2_TAG_[id_]) {
  96002. id_++;
  96003. i = 0;
  96004. if(id_ == 3) {
  96005. if(!skip_id3v2_tag_(decoder))
  96006. return false; /* skip_id3v2_tag_ sets the state for us */
  96007. }
  96008. continue;
  96009. }
  96010. id_ = 0;
  96011. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96012. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96013. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96014. return false; /* read_callback_ sets the state for us */
  96015. /* 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 */
  96016. /* else we have to check if the second byte is the end of a sync code */
  96017. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96018. decoder->private_->lookahead = (FLAC__byte)x;
  96019. decoder->private_->cached = true;
  96020. }
  96021. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96022. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96023. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96024. return true;
  96025. }
  96026. }
  96027. i = 0;
  96028. if(first) {
  96029. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96030. first = false;
  96031. }
  96032. }
  96033. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  96034. return true;
  96035. }
  96036. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  96037. {
  96038. FLAC__bool is_last;
  96039. FLAC__uint32 i, x, type, length;
  96040. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96041. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  96042. return false; /* read_callback_ sets the state for us */
  96043. is_last = x? true : false;
  96044. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  96045. return false; /* read_callback_ sets the state for us */
  96046. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  96047. return false; /* read_callback_ sets the state for us */
  96048. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  96049. if(!read_metadata_streaminfo_(decoder, is_last, length))
  96050. return false;
  96051. decoder->private_->has_stream_info = true;
  96052. 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))
  96053. decoder->private_->do_md5_checking = false;
  96054. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  96055. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  96056. }
  96057. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96058. if(!read_metadata_seektable_(decoder, is_last, length))
  96059. return false;
  96060. decoder->private_->has_seek_table = true;
  96061. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  96062. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  96063. }
  96064. else {
  96065. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  96066. unsigned real_length = length;
  96067. FLAC__StreamMetadata block;
  96068. block.is_last = is_last;
  96069. block.type = (FLAC__MetadataType)type;
  96070. block.length = length;
  96071. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  96072. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  96073. return false; /* read_callback_ sets the state for us */
  96074. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  96075. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  96076. return false;
  96077. }
  96078. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  96079. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  96080. skip_it = !skip_it;
  96081. }
  96082. if(skip_it) {
  96083. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96084. return false; /* read_callback_ sets the state for us */
  96085. }
  96086. else {
  96087. switch(type) {
  96088. case FLAC__METADATA_TYPE_PADDING:
  96089. /* skip the padding bytes */
  96090. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96091. return false; /* read_callback_ sets the state for us */
  96092. break;
  96093. case FLAC__METADATA_TYPE_APPLICATION:
  96094. /* remember, we read the ID already */
  96095. if(real_length > 0) {
  96096. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  96097. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96098. return false;
  96099. }
  96100. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  96101. return false; /* read_callback_ sets the state for us */
  96102. }
  96103. else
  96104. block.data.application.data = 0;
  96105. break;
  96106. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96107. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  96108. return false;
  96109. break;
  96110. case FLAC__METADATA_TYPE_CUESHEET:
  96111. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  96112. return false;
  96113. break;
  96114. case FLAC__METADATA_TYPE_PICTURE:
  96115. if(!read_metadata_picture_(decoder, &block.data.picture))
  96116. return false;
  96117. break;
  96118. case FLAC__METADATA_TYPE_STREAMINFO:
  96119. case FLAC__METADATA_TYPE_SEEKTABLE:
  96120. FLAC__ASSERT(0);
  96121. break;
  96122. default:
  96123. if(real_length > 0) {
  96124. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  96125. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96126. return false;
  96127. }
  96128. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  96129. return false; /* read_callback_ sets the state for us */
  96130. }
  96131. else
  96132. block.data.unknown.data = 0;
  96133. break;
  96134. }
  96135. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  96136. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  96137. /* now we have to free any malloc()ed data in the block */
  96138. switch(type) {
  96139. case FLAC__METADATA_TYPE_PADDING:
  96140. break;
  96141. case FLAC__METADATA_TYPE_APPLICATION:
  96142. if(0 != block.data.application.data)
  96143. free(block.data.application.data);
  96144. break;
  96145. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96146. if(0 != block.data.vorbis_comment.vendor_string.entry)
  96147. free(block.data.vorbis_comment.vendor_string.entry);
  96148. if(block.data.vorbis_comment.num_comments > 0)
  96149. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  96150. if(0 != block.data.vorbis_comment.comments[i].entry)
  96151. free(block.data.vorbis_comment.comments[i].entry);
  96152. if(0 != block.data.vorbis_comment.comments)
  96153. free(block.data.vorbis_comment.comments);
  96154. break;
  96155. case FLAC__METADATA_TYPE_CUESHEET:
  96156. if(block.data.cue_sheet.num_tracks > 0)
  96157. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  96158. if(0 != block.data.cue_sheet.tracks[i].indices)
  96159. free(block.data.cue_sheet.tracks[i].indices);
  96160. if(0 != block.data.cue_sheet.tracks)
  96161. free(block.data.cue_sheet.tracks);
  96162. break;
  96163. case FLAC__METADATA_TYPE_PICTURE:
  96164. if(0 != block.data.picture.mime_type)
  96165. free(block.data.picture.mime_type);
  96166. if(0 != block.data.picture.description)
  96167. free(block.data.picture.description);
  96168. if(0 != block.data.picture.data)
  96169. free(block.data.picture.data);
  96170. break;
  96171. case FLAC__METADATA_TYPE_STREAMINFO:
  96172. case FLAC__METADATA_TYPE_SEEKTABLE:
  96173. FLAC__ASSERT(0);
  96174. default:
  96175. if(0 != block.data.unknown.data)
  96176. free(block.data.unknown.data);
  96177. break;
  96178. }
  96179. }
  96180. }
  96181. if(is_last) {
  96182. /* if this fails, it's OK, it's just a hint for the seek routine */
  96183. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  96184. decoder->private_->first_frame_offset = 0;
  96185. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96186. }
  96187. return true;
  96188. }
  96189. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96190. {
  96191. FLAC__uint32 x;
  96192. unsigned bits, used_bits = 0;
  96193. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96194. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  96195. decoder->private_->stream_info.is_last = is_last;
  96196. decoder->private_->stream_info.length = length;
  96197. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  96198. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  96199. return false; /* read_callback_ sets the state for us */
  96200. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  96201. used_bits += bits;
  96202. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  96203. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  96204. return false; /* read_callback_ sets the state for us */
  96205. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  96206. used_bits += bits;
  96207. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  96208. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  96209. return false; /* read_callback_ sets the state for us */
  96210. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  96211. used_bits += bits;
  96212. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  96213. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  96214. return false; /* read_callback_ sets the state for us */
  96215. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  96216. used_bits += bits;
  96217. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  96218. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  96219. return false; /* read_callback_ sets the state for us */
  96220. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  96221. used_bits += bits;
  96222. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  96223. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  96224. return false; /* read_callback_ sets the state for us */
  96225. decoder->private_->stream_info.data.stream_info.channels = x+1;
  96226. used_bits += bits;
  96227. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  96228. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  96229. return false; /* read_callback_ sets the state for us */
  96230. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  96231. used_bits += bits;
  96232. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  96233. 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))
  96234. return false; /* read_callback_ sets the state for us */
  96235. used_bits += bits;
  96236. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  96237. return false; /* read_callback_ sets the state for us */
  96238. used_bits += 16*8;
  96239. /* skip the rest of the block */
  96240. FLAC__ASSERT(used_bits % 8 == 0);
  96241. length -= (used_bits / 8);
  96242. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96243. return false; /* read_callback_ sets the state for us */
  96244. return true;
  96245. }
  96246. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96247. {
  96248. FLAC__uint32 i, x;
  96249. FLAC__uint64 xx;
  96250. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96251. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  96252. decoder->private_->seek_table.is_last = is_last;
  96253. decoder->private_->seek_table.length = length;
  96254. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  96255. /* use realloc since we may pass through here several times (e.g. after seeking) */
  96256. 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)))) {
  96257. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96258. return false;
  96259. }
  96260. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  96261. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  96262. return false; /* read_callback_ sets the state for us */
  96263. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  96264. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  96265. return false; /* read_callback_ sets the state for us */
  96266. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  96267. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  96268. return false; /* read_callback_ sets the state for us */
  96269. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  96270. }
  96271. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  96272. /* if there is a partial point left, skip over it */
  96273. if(length > 0) {
  96274. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  96275. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96276. return false; /* read_callback_ sets the state for us */
  96277. }
  96278. return true;
  96279. }
  96280. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  96281. {
  96282. FLAC__uint32 i;
  96283. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96284. /* read vendor string */
  96285. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96286. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  96287. return false; /* read_callback_ sets the state for us */
  96288. if(obj->vendor_string.length > 0) {
  96289. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  96290. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96291. return false;
  96292. }
  96293. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  96294. return false; /* read_callback_ sets the state for us */
  96295. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  96296. }
  96297. else
  96298. obj->vendor_string.entry = 0;
  96299. /* read num comments */
  96300. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  96301. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  96302. return false; /* read_callback_ sets the state for us */
  96303. /* read comments */
  96304. if(obj->num_comments > 0) {
  96305. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  96306. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96307. return false;
  96308. }
  96309. for(i = 0; i < obj->num_comments; i++) {
  96310. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96311. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  96312. return false; /* read_callback_ sets the state for us */
  96313. if(obj->comments[i].length > 0) {
  96314. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  96315. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96316. return false;
  96317. }
  96318. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  96319. return false; /* read_callback_ sets the state for us */
  96320. obj->comments[i].entry[obj->comments[i].length] = '\0';
  96321. }
  96322. else
  96323. obj->comments[i].entry = 0;
  96324. }
  96325. }
  96326. else {
  96327. obj->comments = 0;
  96328. }
  96329. return true;
  96330. }
  96331. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  96332. {
  96333. FLAC__uint32 i, j, x;
  96334. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96335. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  96336. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  96337. 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))
  96338. return false; /* read_callback_ sets the state for us */
  96339. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  96340. return false; /* read_callback_ sets the state for us */
  96341. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  96342. return false; /* read_callback_ sets the state for us */
  96343. obj->is_cd = x? true : false;
  96344. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  96345. return false; /* read_callback_ sets the state for us */
  96346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  96347. return false; /* read_callback_ sets the state for us */
  96348. obj->num_tracks = x;
  96349. if(obj->num_tracks > 0) {
  96350. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  96351. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96352. return false;
  96353. }
  96354. for(i = 0; i < obj->num_tracks; i++) {
  96355. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  96356. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  96357. return false; /* read_callback_ sets the state for us */
  96358. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  96359. return false; /* read_callback_ sets the state for us */
  96360. track->number = (FLAC__byte)x;
  96361. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  96362. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  96363. return false; /* read_callback_ sets the state for us */
  96364. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  96365. return false; /* read_callback_ sets the state for us */
  96366. track->type = x;
  96367. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  96368. return false; /* read_callback_ sets the state for us */
  96369. track->pre_emphasis = x;
  96370. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  96371. return false; /* read_callback_ sets the state for us */
  96372. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  96373. return false; /* read_callback_ sets the state for us */
  96374. track->num_indices = (FLAC__byte)x;
  96375. if(track->num_indices > 0) {
  96376. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  96377. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96378. return false;
  96379. }
  96380. for(j = 0; j < track->num_indices; j++) {
  96381. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  96382. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  96383. return false; /* read_callback_ sets the state for us */
  96384. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  96385. return false; /* read_callback_ sets the state for us */
  96386. index->number = (FLAC__byte)x;
  96387. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  96388. return false; /* read_callback_ sets the state for us */
  96389. }
  96390. }
  96391. }
  96392. }
  96393. return true;
  96394. }
  96395. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  96396. {
  96397. FLAC__uint32 x;
  96398. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96399. /* read type */
  96400. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  96401. return false; /* read_callback_ sets the state for us */
  96402. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  96403. /* read MIME type */
  96404. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  96405. return false; /* read_callback_ sets the state for us */
  96406. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  96407. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96408. return false;
  96409. }
  96410. if(x > 0) {
  96411. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  96412. return false; /* read_callback_ sets the state for us */
  96413. }
  96414. obj->mime_type[x] = '\0';
  96415. /* read description */
  96416. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  96417. return false; /* read_callback_ sets the state for us */
  96418. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  96419. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96420. return false;
  96421. }
  96422. if(x > 0) {
  96423. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  96424. return false; /* read_callback_ sets the state for us */
  96425. }
  96426. obj->description[x] = '\0';
  96427. /* read width */
  96428. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  96429. return false; /* read_callback_ sets the state for us */
  96430. /* read height */
  96431. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  96432. return false; /* read_callback_ sets the state for us */
  96433. /* read depth */
  96434. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  96435. return false; /* read_callback_ sets the state for us */
  96436. /* read colors */
  96437. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  96438. return false; /* read_callback_ sets the state for us */
  96439. /* read data */
  96440. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  96441. return false; /* read_callback_ sets the state for us */
  96442. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  96443. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96444. return false;
  96445. }
  96446. if(obj->data_length > 0) {
  96447. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  96448. return false; /* read_callback_ sets the state for us */
  96449. }
  96450. return true;
  96451. }
  96452. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  96453. {
  96454. FLAC__uint32 x;
  96455. unsigned i, skip;
  96456. /* skip the version and flags bytes */
  96457. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  96458. return false; /* read_callback_ sets the state for us */
  96459. /* get the size (in bytes) to skip */
  96460. skip = 0;
  96461. for(i = 0; i < 4; i++) {
  96462. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96463. return false; /* read_callback_ sets the state for us */
  96464. skip <<= 7;
  96465. skip |= (x & 0x7f);
  96466. }
  96467. /* skip the rest of the tag */
  96468. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  96469. return false; /* read_callback_ sets the state for us */
  96470. return true;
  96471. }
  96472. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  96473. {
  96474. FLAC__uint32 x;
  96475. FLAC__bool first = true;
  96476. /* If we know the total number of samples in the stream, stop if we've read that many. */
  96477. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  96478. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  96479. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  96480. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96481. return true;
  96482. }
  96483. }
  96484. /* make sure we're byte aligned */
  96485. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  96486. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  96487. return false; /* read_callback_ sets the state for us */
  96488. }
  96489. while(1) {
  96490. if(decoder->private_->cached) {
  96491. x = (FLAC__uint32)decoder->private_->lookahead;
  96492. decoder->private_->cached = false;
  96493. }
  96494. else {
  96495. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96496. return false; /* read_callback_ sets the state for us */
  96497. }
  96498. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96499. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96500. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96501. return false; /* read_callback_ sets the state for us */
  96502. /* 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 */
  96503. /* else we have to check if the second byte is the end of a sync code */
  96504. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96505. decoder->private_->lookahead = (FLAC__byte)x;
  96506. decoder->private_->cached = true;
  96507. }
  96508. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96509. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96510. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96511. return true;
  96512. }
  96513. }
  96514. if(first) {
  96515. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96516. first = false;
  96517. }
  96518. }
  96519. return true;
  96520. }
  96521. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  96522. {
  96523. unsigned channel;
  96524. unsigned i;
  96525. FLAC__int32 mid, side;
  96526. unsigned frame_crc; /* the one we calculate from the input stream */
  96527. FLAC__uint32 x;
  96528. *got_a_frame = false;
  96529. /* init the CRC */
  96530. frame_crc = 0;
  96531. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  96532. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  96533. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  96534. if(!read_frame_header_(decoder))
  96535. return false;
  96536. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  96537. return true;
  96538. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  96539. return false;
  96540. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96541. /*
  96542. * first figure the correct bits-per-sample of the subframe
  96543. */
  96544. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  96545. switch(decoder->private_->frame.header.channel_assignment) {
  96546. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96547. /* no adjustment needed */
  96548. break;
  96549. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96550. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96551. if(channel == 1)
  96552. bps++;
  96553. break;
  96554. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96555. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96556. if(channel == 0)
  96557. bps++;
  96558. break;
  96559. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96560. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96561. if(channel == 1)
  96562. bps++;
  96563. break;
  96564. default:
  96565. FLAC__ASSERT(0);
  96566. }
  96567. /*
  96568. * now read it
  96569. */
  96570. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  96571. return false;
  96572. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96573. return true;
  96574. }
  96575. if(!read_zero_padding_(decoder))
  96576. return false;
  96577. 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) */
  96578. return true;
  96579. /*
  96580. * Read the frame CRC-16 from the footer and check
  96581. */
  96582. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  96583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  96584. return false; /* read_callback_ sets the state for us */
  96585. if(frame_crc == x) {
  96586. if(do_full_decode) {
  96587. /* Undo any special channel coding */
  96588. switch(decoder->private_->frame.header.channel_assignment) {
  96589. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96590. /* do nothing */
  96591. break;
  96592. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96593. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96594. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96595. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  96596. break;
  96597. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96598. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96599. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96600. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  96601. break;
  96602. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96603. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96604. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96605. #if 1
  96606. mid = decoder->private_->output[0][i];
  96607. side = decoder->private_->output[1][i];
  96608. mid <<= 1;
  96609. mid |= (side & 1); /* i.e. if 'side' is odd... */
  96610. decoder->private_->output[0][i] = (mid + side) >> 1;
  96611. decoder->private_->output[1][i] = (mid - side) >> 1;
  96612. #else
  96613. /* OPT: without 'side' temp variable */
  96614. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  96615. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  96616. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  96617. #endif
  96618. }
  96619. break;
  96620. default:
  96621. FLAC__ASSERT(0);
  96622. break;
  96623. }
  96624. }
  96625. }
  96626. else {
  96627. /* Bad frame, emit error and zero the output signal */
  96628. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  96629. if(do_full_decode) {
  96630. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96631. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  96632. }
  96633. }
  96634. }
  96635. *got_a_frame = true;
  96636. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  96637. if(decoder->private_->next_fixed_block_size)
  96638. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  96639. /* put the latest values into the public section of the decoder instance */
  96640. decoder->protected_->channels = decoder->private_->frame.header.channels;
  96641. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  96642. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  96643. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  96644. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  96645. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96646. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  96647. /* write it */
  96648. if(do_full_decode) {
  96649. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  96650. return false;
  96651. }
  96652. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96653. return true;
  96654. }
  96655. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  96656. {
  96657. FLAC__uint32 x;
  96658. FLAC__uint64 xx;
  96659. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  96660. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  96661. unsigned raw_header_len;
  96662. FLAC__bool is_unparseable = false;
  96663. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96664. /* init the raw header with the saved bits from synchronization */
  96665. raw_header[0] = decoder->private_->header_warmup[0];
  96666. raw_header[1] = decoder->private_->header_warmup[1];
  96667. raw_header_len = 2;
  96668. /* check to make sure that reserved bit is 0 */
  96669. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  96670. is_unparseable = true;
  96671. /*
  96672. * Note that along the way as we read the header, we look for a sync
  96673. * code inside. If we find one it would indicate that our original
  96674. * sync was bad since there cannot be a sync code in a valid header.
  96675. *
  96676. * Three kinds of things can go wrong when reading the frame header:
  96677. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  96678. * If we don't find a sync code, it can end up looking like we read
  96679. * a valid but unparseable header, until getting to the frame header
  96680. * CRC. Even then we could get a false positive on the CRC.
  96681. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  96682. * future encoder).
  96683. * 3) We may be on a damaged frame which appears valid but unparseable.
  96684. *
  96685. * For all these reasons, we try and read a complete frame header as
  96686. * long as it seems valid, even if unparseable, up until the frame
  96687. * header CRC.
  96688. */
  96689. /*
  96690. * read in the raw header as bytes so we can CRC it, and parse it on the way
  96691. */
  96692. for(i = 0; i < 2; i++) {
  96693. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96694. return false; /* read_callback_ sets the state for us */
  96695. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96696. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  96697. decoder->private_->lookahead = (FLAC__byte)x;
  96698. decoder->private_->cached = true;
  96699. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96700. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96701. return true;
  96702. }
  96703. raw_header[raw_header_len++] = (FLAC__byte)x;
  96704. }
  96705. switch(x = raw_header[2] >> 4) {
  96706. case 0:
  96707. is_unparseable = true;
  96708. break;
  96709. case 1:
  96710. decoder->private_->frame.header.blocksize = 192;
  96711. break;
  96712. case 2:
  96713. case 3:
  96714. case 4:
  96715. case 5:
  96716. decoder->private_->frame.header.blocksize = 576 << (x-2);
  96717. break;
  96718. case 6:
  96719. case 7:
  96720. blocksize_hint = x;
  96721. break;
  96722. case 8:
  96723. case 9:
  96724. case 10:
  96725. case 11:
  96726. case 12:
  96727. case 13:
  96728. case 14:
  96729. case 15:
  96730. decoder->private_->frame.header.blocksize = 256 << (x-8);
  96731. break;
  96732. default:
  96733. FLAC__ASSERT(0);
  96734. break;
  96735. }
  96736. switch(x = raw_header[2] & 0x0f) {
  96737. case 0:
  96738. if(decoder->private_->has_stream_info)
  96739. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  96740. else
  96741. is_unparseable = true;
  96742. break;
  96743. case 1:
  96744. decoder->private_->frame.header.sample_rate = 88200;
  96745. break;
  96746. case 2:
  96747. decoder->private_->frame.header.sample_rate = 176400;
  96748. break;
  96749. case 3:
  96750. decoder->private_->frame.header.sample_rate = 192000;
  96751. break;
  96752. case 4:
  96753. decoder->private_->frame.header.sample_rate = 8000;
  96754. break;
  96755. case 5:
  96756. decoder->private_->frame.header.sample_rate = 16000;
  96757. break;
  96758. case 6:
  96759. decoder->private_->frame.header.sample_rate = 22050;
  96760. break;
  96761. case 7:
  96762. decoder->private_->frame.header.sample_rate = 24000;
  96763. break;
  96764. case 8:
  96765. decoder->private_->frame.header.sample_rate = 32000;
  96766. break;
  96767. case 9:
  96768. decoder->private_->frame.header.sample_rate = 44100;
  96769. break;
  96770. case 10:
  96771. decoder->private_->frame.header.sample_rate = 48000;
  96772. break;
  96773. case 11:
  96774. decoder->private_->frame.header.sample_rate = 96000;
  96775. break;
  96776. case 12:
  96777. case 13:
  96778. case 14:
  96779. sample_rate_hint = x;
  96780. break;
  96781. case 15:
  96782. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96783. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96784. return true;
  96785. default:
  96786. FLAC__ASSERT(0);
  96787. }
  96788. x = (unsigned)(raw_header[3] >> 4);
  96789. if(x & 8) {
  96790. decoder->private_->frame.header.channels = 2;
  96791. switch(x & 7) {
  96792. case 0:
  96793. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  96794. break;
  96795. case 1:
  96796. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  96797. break;
  96798. case 2:
  96799. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  96800. break;
  96801. default:
  96802. is_unparseable = true;
  96803. break;
  96804. }
  96805. }
  96806. else {
  96807. decoder->private_->frame.header.channels = (unsigned)x + 1;
  96808. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  96809. }
  96810. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  96811. case 0:
  96812. if(decoder->private_->has_stream_info)
  96813. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  96814. else
  96815. is_unparseable = true;
  96816. break;
  96817. case 1:
  96818. decoder->private_->frame.header.bits_per_sample = 8;
  96819. break;
  96820. case 2:
  96821. decoder->private_->frame.header.bits_per_sample = 12;
  96822. break;
  96823. case 4:
  96824. decoder->private_->frame.header.bits_per_sample = 16;
  96825. break;
  96826. case 5:
  96827. decoder->private_->frame.header.bits_per_sample = 20;
  96828. break;
  96829. case 6:
  96830. decoder->private_->frame.header.bits_per_sample = 24;
  96831. break;
  96832. case 3:
  96833. case 7:
  96834. is_unparseable = true;
  96835. break;
  96836. default:
  96837. FLAC__ASSERT(0);
  96838. break;
  96839. }
  96840. /* check to make sure that reserved bit is 0 */
  96841. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  96842. is_unparseable = true;
  96843. /* read the frame's starting sample number (or frame number as the case may be) */
  96844. if(
  96845. raw_header[1] & 0x01 ||
  96846. /*@@@ 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 */
  96847. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  96848. ) { /* variable blocksize */
  96849. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  96850. return false; /* read_callback_ sets the state for us */
  96851. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  96852. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96853. decoder->private_->cached = true;
  96854. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96855. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96856. return true;
  96857. }
  96858. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96859. decoder->private_->frame.header.number.sample_number = xx;
  96860. }
  96861. else { /* fixed blocksize */
  96862. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  96863. return false; /* read_callback_ sets the state for us */
  96864. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  96865. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96866. decoder->private_->cached = true;
  96867. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96868. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96869. return true;
  96870. }
  96871. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  96872. decoder->private_->frame.header.number.frame_number = x;
  96873. }
  96874. if(blocksize_hint) {
  96875. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96876. return false; /* read_callback_ sets the state for us */
  96877. raw_header[raw_header_len++] = (FLAC__byte)x;
  96878. if(blocksize_hint == 7) {
  96879. FLAC__uint32 _x;
  96880. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96881. return false; /* read_callback_ sets the state for us */
  96882. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96883. x = (x << 8) | _x;
  96884. }
  96885. decoder->private_->frame.header.blocksize = x+1;
  96886. }
  96887. if(sample_rate_hint) {
  96888. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96889. return false; /* read_callback_ sets the state for us */
  96890. raw_header[raw_header_len++] = (FLAC__byte)x;
  96891. if(sample_rate_hint != 12) {
  96892. FLAC__uint32 _x;
  96893. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96894. return false; /* read_callback_ sets the state for us */
  96895. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96896. x = (x << 8) | _x;
  96897. }
  96898. if(sample_rate_hint == 12)
  96899. decoder->private_->frame.header.sample_rate = x*1000;
  96900. else if(sample_rate_hint == 13)
  96901. decoder->private_->frame.header.sample_rate = x;
  96902. else
  96903. decoder->private_->frame.header.sample_rate = x*10;
  96904. }
  96905. /* read the CRC-8 byte */
  96906. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96907. return false; /* read_callback_ sets the state for us */
  96908. crc8 = (FLAC__byte)x;
  96909. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  96910. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96911. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96912. return true;
  96913. }
  96914. /* calculate the sample number from the frame number if needed */
  96915. decoder->private_->next_fixed_block_size = 0;
  96916. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  96917. x = decoder->private_->frame.header.number.frame_number;
  96918. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96919. if(decoder->private_->fixed_block_size)
  96920. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  96921. else if(decoder->private_->has_stream_info) {
  96922. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  96923. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  96924. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96925. }
  96926. else
  96927. is_unparseable = true;
  96928. }
  96929. else if(x == 0) {
  96930. decoder->private_->frame.header.number.sample_number = 0;
  96931. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  96932. }
  96933. else {
  96934. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  96935. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  96936. }
  96937. }
  96938. if(is_unparseable) {
  96939. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96940. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96941. return true;
  96942. }
  96943. return true;
  96944. }
  96945. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96946. {
  96947. FLAC__uint32 x;
  96948. FLAC__bool wasted_bits;
  96949. unsigned i;
  96950. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  96951. return false; /* read_callback_ sets the state for us */
  96952. wasted_bits = (x & 1);
  96953. x &= 0xfe;
  96954. if(wasted_bits) {
  96955. unsigned u;
  96956. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  96957. return false; /* read_callback_ sets the state for us */
  96958. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  96959. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  96960. }
  96961. else
  96962. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  96963. /*
  96964. * Lots of magic numbers here
  96965. */
  96966. if(x & 0x80) {
  96967. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96968. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96969. return true;
  96970. }
  96971. else if(x == 0) {
  96972. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  96973. return false;
  96974. }
  96975. else if(x == 2) {
  96976. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  96977. return false;
  96978. }
  96979. else if(x < 16) {
  96980. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96981. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96982. return true;
  96983. }
  96984. else if(x <= 24) {
  96985. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  96986. return false;
  96987. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96988. return true;
  96989. }
  96990. else if(x < 64) {
  96991. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96992. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96993. return true;
  96994. }
  96995. else {
  96996. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  96997. return false;
  96998. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96999. return true;
  97000. }
  97001. if(wasted_bits && do_full_decode) {
  97002. x = decoder->private_->frame.subframes[channel].wasted_bits;
  97003. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97004. decoder->private_->output[channel][i] <<= x;
  97005. }
  97006. return true;
  97007. }
  97008. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97009. {
  97010. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  97011. FLAC__int32 x;
  97012. unsigned i;
  97013. FLAC__int32 *output = decoder->private_->output[channel];
  97014. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  97015. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97016. return false; /* read_callback_ sets the state for us */
  97017. subframe->value = x;
  97018. /* decode the subframe */
  97019. if(do_full_decode) {
  97020. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97021. output[i] = x;
  97022. }
  97023. return true;
  97024. }
  97025. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97026. {
  97027. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  97028. FLAC__int32 i32;
  97029. FLAC__uint32 u32;
  97030. unsigned u;
  97031. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  97032. subframe->residual = decoder->private_->residual[channel];
  97033. subframe->order = order;
  97034. /* read warm-up samples */
  97035. for(u = 0; u < order; u++) {
  97036. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97037. return false; /* read_callback_ sets the state for us */
  97038. subframe->warmup[u] = i32;
  97039. }
  97040. /* read entropy coding method info */
  97041. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97042. return false; /* read_callback_ sets the state for us */
  97043. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97044. switch(subframe->entropy_coding_method.type) {
  97045. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97046. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97047. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97048. return false; /* read_callback_ sets the state for us */
  97049. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97050. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97051. break;
  97052. default:
  97053. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97054. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97055. return true;
  97056. }
  97057. /* read residual */
  97058. switch(subframe->entropy_coding_method.type) {
  97059. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97060. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97061. 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))
  97062. return false;
  97063. break;
  97064. default:
  97065. FLAC__ASSERT(0);
  97066. }
  97067. /* decode the subframe */
  97068. if(do_full_decode) {
  97069. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97070. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  97071. }
  97072. return true;
  97073. }
  97074. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97075. {
  97076. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  97077. FLAC__int32 i32;
  97078. FLAC__uint32 u32;
  97079. unsigned u;
  97080. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  97081. subframe->residual = decoder->private_->residual[channel];
  97082. subframe->order = order;
  97083. /* read warm-up samples */
  97084. for(u = 0; u < order; u++) {
  97085. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97086. return false; /* read_callback_ sets the state for us */
  97087. subframe->warmup[u] = i32;
  97088. }
  97089. /* read qlp coeff precision */
  97090. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  97091. return false; /* read_callback_ sets the state for us */
  97092. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  97093. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97094. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97095. return true;
  97096. }
  97097. subframe->qlp_coeff_precision = u32+1;
  97098. /* read qlp shift */
  97099. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  97100. return false; /* read_callback_ sets the state for us */
  97101. subframe->quantization_level = i32;
  97102. /* read quantized lp coefficiencts */
  97103. for(u = 0; u < order; u++) {
  97104. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  97105. return false; /* read_callback_ sets the state for us */
  97106. subframe->qlp_coeff[u] = i32;
  97107. }
  97108. /* read entropy coding method info */
  97109. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97110. return false; /* read_callback_ sets the state for us */
  97111. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97112. switch(subframe->entropy_coding_method.type) {
  97113. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97114. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97115. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97116. return false; /* read_callback_ sets the state for us */
  97117. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97118. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97119. break;
  97120. default:
  97121. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97122. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97123. return true;
  97124. }
  97125. /* read residual */
  97126. switch(subframe->entropy_coding_method.type) {
  97127. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97128. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97129. 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))
  97130. return false;
  97131. break;
  97132. default:
  97133. FLAC__ASSERT(0);
  97134. }
  97135. /* decode the subframe */
  97136. if(do_full_decode) {
  97137. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97138. /*@@@@@@ technically not pessimistic enough, should be more like
  97139. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  97140. */
  97141. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  97142. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  97143. if(order <= 8)
  97144. 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);
  97145. else
  97146. 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);
  97147. }
  97148. else
  97149. 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);
  97150. else
  97151. 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);
  97152. }
  97153. return true;
  97154. }
  97155. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97156. {
  97157. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  97158. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  97159. unsigned i;
  97160. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  97161. subframe->data = residual;
  97162. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97163. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97164. return false; /* read_callback_ sets the state for us */
  97165. residual[i] = x;
  97166. }
  97167. /* decode the subframe */
  97168. if(do_full_decode)
  97169. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97170. return true;
  97171. }
  97172. 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)
  97173. {
  97174. FLAC__uint32 rice_parameter;
  97175. int i;
  97176. unsigned partition, sample, u;
  97177. const unsigned partitions = 1u << partition_order;
  97178. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  97179. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  97180. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  97181. /* sanity checks */
  97182. if(partition_order == 0) {
  97183. if(decoder->private_->frame.header.blocksize < predictor_order) {
  97184. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97185. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97186. return true;
  97187. }
  97188. }
  97189. else {
  97190. if(partition_samples < predictor_order) {
  97191. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97192. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97193. return true;
  97194. }
  97195. }
  97196. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  97197. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97198. return false;
  97199. }
  97200. sample = 0;
  97201. for(partition = 0; partition < partitions; partition++) {
  97202. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  97203. return false; /* read_callback_ sets the state for us */
  97204. partitioned_rice_contents->parameters[partition] = rice_parameter;
  97205. if(rice_parameter < pesc) {
  97206. partitioned_rice_contents->raw_bits[partition] = 0;
  97207. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  97208. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  97209. return false; /* read_callback_ sets the state for us */
  97210. sample += u;
  97211. }
  97212. else {
  97213. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  97214. return false; /* read_callback_ sets the state for us */
  97215. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  97216. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  97217. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  97218. return false; /* read_callback_ sets the state for us */
  97219. residual[sample] = i;
  97220. }
  97221. }
  97222. }
  97223. return true;
  97224. }
  97225. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  97226. {
  97227. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97228. FLAC__uint32 zero = 0;
  97229. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97230. return false; /* read_callback_ sets the state for us */
  97231. if(zero != 0) {
  97232. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97233. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97234. }
  97235. }
  97236. return true;
  97237. }
  97238. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  97239. {
  97240. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  97241. if(
  97242. #if FLAC__HAS_OGG
  97243. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97244. !decoder->private_->is_ogg &&
  97245. #endif
  97246. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97247. ) {
  97248. *bytes = 0;
  97249. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97250. return false;
  97251. }
  97252. else if(*bytes > 0) {
  97253. /* While seeking, it is possible for our seek to land in the
  97254. * middle of audio data that looks exactly like a frame header
  97255. * from a future version of an encoder. When that happens, our
  97256. * error callback will get an
  97257. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  97258. * unparseable_frame_count. But there is a remote possibility
  97259. * that it is properly synced at such a "future-codec frame",
  97260. * so to make sure, we wait to see many "unparseable" errors in
  97261. * a row before bailing out.
  97262. */
  97263. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  97264. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97265. return false;
  97266. }
  97267. else {
  97268. const FLAC__StreamDecoderReadStatus status =
  97269. #if FLAC__HAS_OGG
  97270. decoder->private_->is_ogg?
  97271. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  97272. #endif
  97273. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  97274. ;
  97275. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  97276. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97277. return false;
  97278. }
  97279. else if(*bytes == 0) {
  97280. if(
  97281. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  97282. (
  97283. #if FLAC__HAS_OGG
  97284. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97285. !decoder->private_->is_ogg &&
  97286. #endif
  97287. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97288. )
  97289. ) {
  97290. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97291. return false;
  97292. }
  97293. else
  97294. return true;
  97295. }
  97296. else
  97297. return true;
  97298. }
  97299. }
  97300. else {
  97301. /* abort to avoid a deadlock */
  97302. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97303. return false;
  97304. }
  97305. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  97306. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  97307. * and at the same time hit the end of the stream (for example, seeking
  97308. * to a point that is after the beginning of the last Ogg page). There
  97309. * is no way to report an Ogg sync loss through the callbacks (see note
  97310. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  97311. * So to keep the decoder from stopping at this point we gate the call
  97312. * to the eof_callback and let the Ogg decoder aspect set the
  97313. * end-of-stream state when it is needed.
  97314. */
  97315. }
  97316. #if FLAC__HAS_OGG
  97317. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  97318. {
  97319. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  97320. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  97321. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97322. /* we don't really have a way to handle lost sync via read
  97323. * callback so we'll let it pass and let the underlying
  97324. * FLAC decoder catch the error
  97325. */
  97326. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  97327. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97328. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  97329. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97330. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  97331. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  97332. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  97333. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  97334. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  97335. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97336. default:
  97337. FLAC__ASSERT(0);
  97338. /* double protection */
  97339. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97340. }
  97341. }
  97342. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97343. {
  97344. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  97345. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  97346. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  97347. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  97348. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  97349. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  97350. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  97351. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97352. default:
  97353. /* double protection: */
  97354. FLAC__ASSERT(0);
  97355. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97356. }
  97357. }
  97358. #endif
  97359. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  97360. {
  97361. if(decoder->private_->is_seeking) {
  97362. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  97363. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  97364. FLAC__uint64 target_sample = decoder->private_->target_sample;
  97365. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97366. #if FLAC__HAS_OGG
  97367. decoder->private_->got_a_frame = true;
  97368. #endif
  97369. decoder->private_->last_frame = *frame; /* save the frame */
  97370. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  97371. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  97372. /* kick out of seek mode */
  97373. decoder->private_->is_seeking = false;
  97374. /* shift out the samples before target_sample */
  97375. if(delta > 0) {
  97376. unsigned channel;
  97377. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  97378. for(channel = 0; channel < frame->header.channels; channel++)
  97379. newbuffer[channel] = buffer[channel] + delta;
  97380. decoder->private_->last_frame.header.blocksize -= delta;
  97381. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  97382. /* write the relevant samples */
  97383. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  97384. }
  97385. else {
  97386. /* write the relevant samples */
  97387. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97388. }
  97389. }
  97390. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  97391. }
  97392. /*
  97393. * If we never got STREAMINFO, turn off MD5 checking to save
  97394. * cycles since we don't have a sum to compare to anyway
  97395. */
  97396. if(!decoder->private_->has_stream_info)
  97397. decoder->private_->do_md5_checking = false;
  97398. if(decoder->private_->do_md5_checking) {
  97399. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  97400. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  97401. }
  97402. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97403. }
  97404. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  97405. {
  97406. if(!decoder->private_->is_seeking)
  97407. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  97408. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  97409. decoder->private_->unparseable_frame_count++;
  97410. }
  97411. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97412. {
  97413. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  97414. FLAC__int64 pos = -1;
  97415. int i;
  97416. unsigned approx_bytes_per_frame;
  97417. FLAC__bool first_seek = true;
  97418. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  97419. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  97420. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  97421. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  97422. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  97423. /* take these from the current frame in case they've changed mid-stream */
  97424. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  97425. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  97426. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  97427. /* use values from stream info if we didn't decode a frame */
  97428. if(channels == 0)
  97429. channels = decoder->private_->stream_info.data.stream_info.channels;
  97430. if(bps == 0)
  97431. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  97432. /* we are just guessing here */
  97433. if(max_framesize > 0)
  97434. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  97435. /*
  97436. * Check if it's a known fixed-blocksize stream. Note that though
  97437. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  97438. * never get a STREAMINFO block when decoding so the value of
  97439. * min_blocksize might be zero.
  97440. */
  97441. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  97442. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  97443. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  97444. }
  97445. else
  97446. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  97447. /*
  97448. * First, we set an upper and lower bound on where in the
  97449. * stream we will search. For now we assume the worst case
  97450. * scenario, which is our best guess at the beginning of
  97451. * the first frame and end of the stream.
  97452. */
  97453. lower_bound = first_frame_offset;
  97454. lower_bound_sample = 0;
  97455. upper_bound = stream_length;
  97456. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  97457. /*
  97458. * Now we refine the bounds if we have a seektable with
  97459. * suitable points. Note that according to the spec they
  97460. * must be ordered by ascending sample number.
  97461. *
  97462. * Note: to protect against invalid seek tables we will ignore points
  97463. * that have frame_samples==0 or sample_number>=total_samples
  97464. */
  97465. if(seek_table) {
  97466. FLAC__uint64 new_lower_bound = lower_bound;
  97467. FLAC__uint64 new_upper_bound = upper_bound;
  97468. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  97469. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  97470. /* find the closest seek point <= target_sample, if it exists */
  97471. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  97472. if(
  97473. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97474. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97475. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97476. seek_table->points[i].sample_number <= target_sample
  97477. )
  97478. break;
  97479. }
  97480. if(i >= 0) { /* i.e. we found a suitable seek point... */
  97481. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97482. new_lower_bound_sample = seek_table->points[i].sample_number;
  97483. }
  97484. /* find the closest seek point > target_sample, if it exists */
  97485. for(i = 0; i < (int)seek_table->num_points; i++) {
  97486. if(
  97487. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97488. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97489. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97490. seek_table->points[i].sample_number > target_sample
  97491. )
  97492. break;
  97493. }
  97494. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  97495. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97496. new_upper_bound_sample = seek_table->points[i].sample_number;
  97497. }
  97498. /* final protection against unsorted seek tables; keep original values if bogus */
  97499. if(new_upper_bound >= new_lower_bound) {
  97500. lower_bound = new_lower_bound;
  97501. upper_bound = new_upper_bound;
  97502. lower_bound_sample = new_lower_bound_sample;
  97503. upper_bound_sample = new_upper_bound_sample;
  97504. }
  97505. }
  97506. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  97507. /* there are 2 insidious ways that the following equality occurs, which
  97508. * we need to fix:
  97509. * 1) total_samples is 0 (unknown) and target_sample is 0
  97510. * 2) total_samples is 0 (unknown) and target_sample happens to be
  97511. * exactly equal to the last seek point in the seek table; this
  97512. * means there is no seek point above it, and upper_bound_samples
  97513. * remains equal to the estimate (of target_samples) we made above
  97514. * in either case it does not hurt to move upper_bound_sample up by 1
  97515. */
  97516. if(upper_bound_sample == lower_bound_sample)
  97517. upper_bound_sample++;
  97518. decoder->private_->target_sample = target_sample;
  97519. while(1) {
  97520. /* check if the bounds are still ok */
  97521. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  97522. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97523. return false;
  97524. }
  97525. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97526. #if defined _MSC_VER || defined __MINGW32__
  97527. /* with VC++ you have to spoon feed it the casting */
  97528. 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;
  97529. #else
  97530. 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;
  97531. #endif
  97532. #else
  97533. /* a little less accurate: */
  97534. if(upper_bound - lower_bound < 0xffffffff)
  97535. 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;
  97536. else /* @@@ WATCHOUT, ~2TB limit */
  97537. 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;
  97538. #endif
  97539. if(pos >= (FLAC__int64)upper_bound)
  97540. pos = (FLAC__int64)upper_bound - 1;
  97541. if(pos < (FLAC__int64)lower_bound)
  97542. pos = (FLAC__int64)lower_bound;
  97543. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97544. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97545. return false;
  97546. }
  97547. if(!FLAC__stream_decoder_flush(decoder)) {
  97548. /* above call sets the state for us */
  97549. return false;
  97550. }
  97551. /* Now we need to get a frame. First we need to reset our
  97552. * unparseable_frame_count; if we get too many unparseable
  97553. * frames in a row, the read callback will return
  97554. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  97555. * FLAC__stream_decoder_process_single() to return false.
  97556. */
  97557. decoder->private_->unparseable_frame_count = 0;
  97558. if(!FLAC__stream_decoder_process_single(decoder)) {
  97559. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97560. return false;
  97561. }
  97562. /* our write callback will change the state when it gets to the target frame */
  97563. /* 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 */
  97564. #if 0
  97565. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  97566. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  97567. break;
  97568. #endif
  97569. if(!decoder->private_->is_seeking)
  97570. break;
  97571. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97572. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97573. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  97574. if (pos == (FLAC__int64)lower_bound) {
  97575. /* can't move back any more than the first frame, something is fatally wrong */
  97576. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97577. return false;
  97578. }
  97579. /* our last move backwards wasn't big enough, try again */
  97580. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  97581. continue;
  97582. }
  97583. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  97584. first_seek = false;
  97585. /* make sure we are not seeking in corrupted stream */
  97586. if (this_frame_sample < lower_bound_sample) {
  97587. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97588. return false;
  97589. }
  97590. /* we need to narrow the search */
  97591. if(target_sample < this_frame_sample) {
  97592. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97593. /*@@@@@@ what will decode position be if at end of stream? */
  97594. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  97595. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97596. return false;
  97597. }
  97598. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  97599. }
  97600. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  97601. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97602. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  97603. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97604. return false;
  97605. }
  97606. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  97607. }
  97608. }
  97609. return true;
  97610. }
  97611. #if FLAC__HAS_OGG
  97612. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97613. {
  97614. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  97615. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  97616. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  97617. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  97618. FLAC__bool did_a_seek;
  97619. unsigned iteration = 0;
  97620. /* In the first iterations, we will calculate the target byte position
  97621. * by the distance from the target sample to left_sample and
  97622. * right_sample (let's call it "proportional search"). After that, we
  97623. * will switch to binary search.
  97624. */
  97625. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  97626. /* We will switch to a linear search once our current sample is less
  97627. * than this number of samples ahead of the target sample
  97628. */
  97629. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  97630. /* If the total number of samples is unknown, use a large value, and
  97631. * force binary search immediately.
  97632. */
  97633. if(right_sample == 0) {
  97634. right_sample = (FLAC__uint64)(-1);
  97635. BINARY_SEARCH_AFTER_ITERATION = 0;
  97636. }
  97637. decoder->private_->target_sample = target_sample;
  97638. for( ; ; iteration++) {
  97639. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  97640. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  97641. pos = (right_pos + left_pos) / 2;
  97642. }
  97643. else {
  97644. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97645. #if defined _MSC_VER || defined __MINGW32__
  97646. /* with MSVC you have to spoon feed it the casting */
  97647. 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));
  97648. #else
  97649. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  97650. #endif
  97651. #else
  97652. /* a little less accurate: */
  97653. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  97654. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  97655. else /* @@@ WATCHOUT, ~2TB limit */
  97656. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  97657. #endif
  97658. /* @@@ TODO: might want to limit pos to some distance
  97659. * before EOF, to make sure we land before the last frame,
  97660. * thereby getting a this_frame_sample and so having a better
  97661. * estimate.
  97662. */
  97663. }
  97664. /* physical seek */
  97665. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97666. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97667. return false;
  97668. }
  97669. if(!FLAC__stream_decoder_flush(decoder)) {
  97670. /* above call sets the state for us */
  97671. return false;
  97672. }
  97673. did_a_seek = true;
  97674. }
  97675. else
  97676. did_a_seek = false;
  97677. decoder->private_->got_a_frame = false;
  97678. if(!FLAC__stream_decoder_process_single(decoder)) {
  97679. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97680. return false;
  97681. }
  97682. if(!decoder->private_->got_a_frame) {
  97683. if(did_a_seek) {
  97684. /* this can happen if we seek to a point after the last frame; we drop
  97685. * to binary search right away in this case to avoid any wasted
  97686. * iterations of proportional search.
  97687. */
  97688. right_pos = pos;
  97689. BINARY_SEARCH_AFTER_ITERATION = 0;
  97690. }
  97691. else {
  97692. /* this can probably only happen if total_samples is unknown and the
  97693. * target_sample is past the end of the stream
  97694. */
  97695. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97696. return false;
  97697. }
  97698. }
  97699. /* our write callback will change the state when it gets to the target frame */
  97700. else if(!decoder->private_->is_seeking) {
  97701. break;
  97702. }
  97703. else {
  97704. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97705. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97706. if (did_a_seek) {
  97707. if (this_frame_sample <= target_sample) {
  97708. /* The 'equal' case should not happen, since
  97709. * FLAC__stream_decoder_process_single()
  97710. * should recognize that it has hit the
  97711. * target sample and we would exit through
  97712. * the 'break' above.
  97713. */
  97714. FLAC__ASSERT(this_frame_sample != target_sample);
  97715. left_sample = this_frame_sample;
  97716. /* sanity check to avoid infinite loop */
  97717. if (left_pos == pos) {
  97718. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97719. return false;
  97720. }
  97721. left_pos = pos;
  97722. }
  97723. else if(this_frame_sample > target_sample) {
  97724. right_sample = this_frame_sample;
  97725. /* sanity check to avoid infinite loop */
  97726. if (right_pos == pos) {
  97727. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97728. return false;
  97729. }
  97730. right_pos = pos;
  97731. }
  97732. }
  97733. }
  97734. }
  97735. return true;
  97736. }
  97737. #endif
  97738. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97739. {
  97740. (void)client_data;
  97741. if(*bytes > 0) {
  97742. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  97743. if(ferror(decoder->private_->file))
  97744. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97745. else if(*bytes == 0)
  97746. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97747. else
  97748. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97749. }
  97750. else
  97751. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  97752. }
  97753. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  97754. {
  97755. (void)client_data;
  97756. if(decoder->private_->file == stdin)
  97757. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  97758. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  97759. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  97760. else
  97761. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  97762. }
  97763. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  97764. {
  97765. off_t pos;
  97766. (void)client_data;
  97767. if(decoder->private_->file == stdin)
  97768. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  97769. else if((pos = ftello(decoder->private_->file)) < 0)
  97770. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  97771. else {
  97772. *absolute_byte_offset = (FLAC__uint64)pos;
  97773. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  97774. }
  97775. }
  97776. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  97777. {
  97778. struct stat filestats;
  97779. (void)client_data;
  97780. if(decoder->private_->file == stdin)
  97781. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  97782. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  97783. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  97784. else {
  97785. *stream_length = (FLAC__uint64)filestats.st_size;
  97786. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  97787. }
  97788. }
  97789. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  97790. {
  97791. (void)client_data;
  97792. return feof(decoder->private_->file)? true : false;
  97793. }
  97794. #endif
  97795. /********* End of inlined file: stream_decoder.c *********/
  97796. /********* Start of inlined file: stream_encoder.c *********/
  97797. /********* Start of inlined file: juce_FlacHeader.h *********/
  97798. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97799. // tasks..
  97800. #define VERSION "1.2.1"
  97801. #define FLAC__NO_DLL 1
  97802. #if JUCE_MSVC
  97803. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97804. #endif
  97805. #if JUCE_MAC
  97806. #define FLAC__SYS_DARWIN 1
  97807. #endif
  97808. /********* End of inlined file: juce_FlacHeader.h *********/
  97809. #if JUCE_USE_FLAC
  97810. #if HAVE_CONFIG_H
  97811. # include <config.h>
  97812. #endif
  97813. #if defined _MSC_VER || defined __MINGW32__
  97814. #include <io.h> /* for _setmode() */
  97815. #include <fcntl.h> /* for _O_BINARY */
  97816. #endif
  97817. #if defined __CYGWIN__ || defined __EMX__
  97818. #include <io.h> /* for setmode(), O_BINARY */
  97819. #include <fcntl.h> /* for _O_BINARY */
  97820. #endif
  97821. #include <limits.h>
  97822. #include <stdio.h>
  97823. #include <stdlib.h> /* for malloc() */
  97824. #include <string.h> /* for memcpy() */
  97825. #include <sys/types.h> /* for off_t */
  97826. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  97827. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  97828. #define fseeko fseek
  97829. #define ftello ftell
  97830. #endif
  97831. #endif
  97832. /********* Start of inlined file: stream_encoder.h *********/
  97833. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  97834. #define FLAC__PROTECTED__STREAM_ENCODER_H
  97835. #if FLAC__HAS_OGG
  97836. #include "private/ogg_encoder_aspect.h"
  97837. #endif
  97838. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97839. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  97840. typedef enum {
  97841. FLAC__APODIZATION_BARTLETT,
  97842. FLAC__APODIZATION_BARTLETT_HANN,
  97843. FLAC__APODIZATION_BLACKMAN,
  97844. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  97845. FLAC__APODIZATION_CONNES,
  97846. FLAC__APODIZATION_FLATTOP,
  97847. FLAC__APODIZATION_GAUSS,
  97848. FLAC__APODIZATION_HAMMING,
  97849. FLAC__APODIZATION_HANN,
  97850. FLAC__APODIZATION_KAISER_BESSEL,
  97851. FLAC__APODIZATION_NUTTALL,
  97852. FLAC__APODIZATION_RECTANGLE,
  97853. FLAC__APODIZATION_TRIANGLE,
  97854. FLAC__APODIZATION_TUKEY,
  97855. FLAC__APODIZATION_WELCH
  97856. } FLAC__ApodizationFunction;
  97857. typedef struct {
  97858. FLAC__ApodizationFunction type;
  97859. union {
  97860. struct {
  97861. FLAC__real stddev;
  97862. } gauss;
  97863. struct {
  97864. FLAC__real p;
  97865. } tukey;
  97866. } parameters;
  97867. } FLAC__ApodizationSpecification;
  97868. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97869. typedef struct FLAC__StreamEncoderProtected {
  97870. FLAC__StreamEncoderState state;
  97871. FLAC__bool verify;
  97872. FLAC__bool streamable_subset;
  97873. FLAC__bool do_md5;
  97874. FLAC__bool do_mid_side_stereo;
  97875. FLAC__bool loose_mid_side_stereo;
  97876. unsigned channels;
  97877. unsigned bits_per_sample;
  97878. unsigned sample_rate;
  97879. unsigned blocksize;
  97880. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97881. unsigned num_apodizations;
  97882. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  97883. #endif
  97884. unsigned max_lpc_order;
  97885. unsigned qlp_coeff_precision;
  97886. FLAC__bool do_qlp_coeff_prec_search;
  97887. FLAC__bool do_exhaustive_model_search;
  97888. FLAC__bool do_escape_coding;
  97889. unsigned min_residual_partition_order;
  97890. unsigned max_residual_partition_order;
  97891. unsigned rice_parameter_search_dist;
  97892. FLAC__uint64 total_samples_estimate;
  97893. FLAC__StreamMetadata **metadata;
  97894. unsigned num_metadata_blocks;
  97895. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  97896. #if FLAC__HAS_OGG
  97897. FLAC__OggEncoderAspect ogg_encoder_aspect;
  97898. #endif
  97899. } FLAC__StreamEncoderProtected;
  97900. #endif
  97901. /********* End of inlined file: stream_encoder.h *********/
  97902. #if FLAC__HAS_OGG
  97903. #include "include/private/ogg_helper.h"
  97904. #include "include/private/ogg_mapping.h"
  97905. #endif
  97906. /********* Start of inlined file: stream_encoder_framing.h *********/
  97907. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97908. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97909. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  97910. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  97911. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97912. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97913. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97914. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97915. #endif
  97916. /********* End of inlined file: stream_encoder_framing.h *********/
  97917. /********* Start of inlined file: window.h *********/
  97918. #ifndef FLAC__PRIVATE__WINDOW_H
  97919. #define FLAC__PRIVATE__WINDOW_H
  97920. #ifdef HAVE_CONFIG_H
  97921. #include <config.h>
  97922. #endif
  97923. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97924. /*
  97925. * FLAC__window_*()
  97926. * --------------------------------------------------------------------
  97927. * Calculates window coefficients according to different apodization
  97928. * functions.
  97929. *
  97930. * OUT window[0,L-1]
  97931. * IN L (number of points in window)
  97932. */
  97933. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  97934. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  97935. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  97936. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  97937. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  97938. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  97939. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  97940. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  97941. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  97942. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  97943. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  97944. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  97945. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  97946. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  97947. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  97948. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97949. #endif
  97950. /********* End of inlined file: window.h *********/
  97951. #ifndef FLaC__INLINE
  97952. #define FLaC__INLINE
  97953. #endif
  97954. #ifdef min
  97955. #undef min
  97956. #endif
  97957. #define min(x,y) ((x)<(y)?(x):(y))
  97958. #ifdef max
  97959. #undef max
  97960. #endif
  97961. #define max(x,y) ((x)>(y)?(x):(y))
  97962. /* Exact Rice codeword length calculation is off by default. The simple
  97963. * (and fast) estimation (of how many bits a residual value will be
  97964. * encoded with) in this encoder is very good, almost always yielding
  97965. * compression within 0.1% of exact calculation.
  97966. */
  97967. #undef EXACT_RICE_BITS_CALCULATION
  97968. /* Rice parameter searching is off by default. The simple (and fast)
  97969. * parameter estimation in this encoder is very good, almost always
  97970. * yielding compression within 0.1% of the optimal parameters.
  97971. */
  97972. #undef ENABLE_RICE_PARAMETER_SEARCH
  97973. typedef struct {
  97974. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  97975. unsigned size; /* of each data[] in samples */
  97976. unsigned tail;
  97977. } verify_input_fifo;
  97978. typedef struct {
  97979. const FLAC__byte *data;
  97980. unsigned capacity;
  97981. unsigned bytes;
  97982. } verify_output;
  97983. typedef enum {
  97984. ENCODER_IN_MAGIC = 0,
  97985. ENCODER_IN_METADATA = 1,
  97986. ENCODER_IN_AUDIO = 2
  97987. } EncoderStateHint;
  97988. static struct CompressionLevels {
  97989. FLAC__bool do_mid_side_stereo;
  97990. FLAC__bool loose_mid_side_stereo;
  97991. unsigned max_lpc_order;
  97992. unsigned qlp_coeff_precision;
  97993. FLAC__bool do_qlp_coeff_prec_search;
  97994. FLAC__bool do_escape_coding;
  97995. FLAC__bool do_exhaustive_model_search;
  97996. unsigned min_residual_partition_order;
  97997. unsigned max_residual_partition_order;
  97998. unsigned rice_parameter_search_dist;
  97999. } compression_levels_[] = {
  98000. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  98001. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  98002. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  98003. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  98004. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  98005. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  98006. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  98007. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  98008. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  98009. };
  98010. /***********************************************************************
  98011. *
  98012. * Private class method prototypes
  98013. *
  98014. ***********************************************************************/
  98015. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  98016. static void free_(FLAC__StreamEncoder *encoder);
  98017. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  98018. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  98019. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  98020. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  98021. #if FLAC__HAS_OGG
  98022. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  98023. #endif
  98024. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  98025. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  98026. static FLAC__bool process_subframe_(
  98027. FLAC__StreamEncoder *encoder,
  98028. unsigned min_partition_order,
  98029. unsigned max_partition_order,
  98030. const FLAC__FrameHeader *frame_header,
  98031. unsigned subframe_bps,
  98032. const FLAC__int32 integer_signal[],
  98033. FLAC__Subframe *subframe[2],
  98034. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  98035. FLAC__int32 *residual[2],
  98036. unsigned *best_subframe,
  98037. unsigned *best_bits
  98038. );
  98039. static FLAC__bool add_subframe_(
  98040. FLAC__StreamEncoder *encoder,
  98041. unsigned blocksize,
  98042. unsigned subframe_bps,
  98043. const FLAC__Subframe *subframe,
  98044. FLAC__BitWriter *frame
  98045. );
  98046. static unsigned evaluate_constant_subframe_(
  98047. FLAC__StreamEncoder *encoder,
  98048. const FLAC__int32 signal,
  98049. unsigned blocksize,
  98050. unsigned subframe_bps,
  98051. FLAC__Subframe *subframe
  98052. );
  98053. static unsigned evaluate_fixed_subframe_(
  98054. FLAC__StreamEncoder *encoder,
  98055. const FLAC__int32 signal[],
  98056. FLAC__int32 residual[],
  98057. FLAC__uint64 abs_residual_partition_sums[],
  98058. unsigned raw_bits_per_partition[],
  98059. unsigned blocksize,
  98060. unsigned subframe_bps,
  98061. unsigned order,
  98062. unsigned rice_parameter,
  98063. unsigned rice_parameter_limit,
  98064. unsigned min_partition_order,
  98065. unsigned max_partition_order,
  98066. FLAC__bool do_escape_coding,
  98067. unsigned rice_parameter_search_dist,
  98068. FLAC__Subframe *subframe,
  98069. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98070. );
  98071. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98072. static unsigned evaluate_lpc_subframe_(
  98073. FLAC__StreamEncoder *encoder,
  98074. const FLAC__int32 signal[],
  98075. FLAC__int32 residual[],
  98076. FLAC__uint64 abs_residual_partition_sums[],
  98077. unsigned raw_bits_per_partition[],
  98078. const FLAC__real lp_coeff[],
  98079. unsigned blocksize,
  98080. unsigned subframe_bps,
  98081. unsigned order,
  98082. unsigned qlp_coeff_precision,
  98083. unsigned rice_parameter,
  98084. unsigned rice_parameter_limit,
  98085. unsigned min_partition_order,
  98086. unsigned max_partition_order,
  98087. FLAC__bool do_escape_coding,
  98088. unsigned rice_parameter_search_dist,
  98089. FLAC__Subframe *subframe,
  98090. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98091. );
  98092. #endif
  98093. static unsigned evaluate_verbatim_subframe_(
  98094. FLAC__StreamEncoder *encoder,
  98095. const FLAC__int32 signal[],
  98096. unsigned blocksize,
  98097. unsigned subframe_bps,
  98098. FLAC__Subframe *subframe
  98099. );
  98100. static unsigned find_best_partition_order_(
  98101. struct FLAC__StreamEncoderPrivate *private_,
  98102. const FLAC__int32 residual[],
  98103. FLAC__uint64 abs_residual_partition_sums[],
  98104. unsigned raw_bits_per_partition[],
  98105. unsigned residual_samples,
  98106. unsigned predictor_order,
  98107. unsigned rice_parameter,
  98108. unsigned rice_parameter_limit,
  98109. unsigned min_partition_order,
  98110. unsigned max_partition_order,
  98111. unsigned bps,
  98112. FLAC__bool do_escape_coding,
  98113. unsigned rice_parameter_search_dist,
  98114. FLAC__EntropyCodingMethod *best_ecm
  98115. );
  98116. static void precompute_partition_info_sums_(
  98117. const FLAC__int32 residual[],
  98118. FLAC__uint64 abs_residual_partition_sums[],
  98119. unsigned residual_samples,
  98120. unsigned predictor_order,
  98121. unsigned min_partition_order,
  98122. unsigned max_partition_order,
  98123. unsigned bps
  98124. );
  98125. static void precompute_partition_info_escapes_(
  98126. const FLAC__int32 residual[],
  98127. unsigned raw_bits_per_partition[],
  98128. unsigned residual_samples,
  98129. unsigned predictor_order,
  98130. unsigned min_partition_order,
  98131. unsigned max_partition_order
  98132. );
  98133. static FLAC__bool set_partitioned_rice_(
  98134. #ifdef EXACT_RICE_BITS_CALCULATION
  98135. const FLAC__int32 residual[],
  98136. #endif
  98137. const FLAC__uint64 abs_residual_partition_sums[],
  98138. const unsigned raw_bits_per_partition[],
  98139. const unsigned residual_samples,
  98140. const unsigned predictor_order,
  98141. const unsigned suggested_rice_parameter,
  98142. const unsigned rice_parameter_limit,
  98143. const unsigned rice_parameter_search_dist,
  98144. const unsigned partition_order,
  98145. const FLAC__bool search_for_escapes,
  98146. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  98147. unsigned *bits
  98148. );
  98149. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  98150. /* verify-related routines: */
  98151. static void append_to_verify_fifo_(
  98152. verify_input_fifo *fifo,
  98153. const FLAC__int32 * const input[],
  98154. unsigned input_offset,
  98155. unsigned channels,
  98156. unsigned wide_samples
  98157. );
  98158. static void append_to_verify_fifo_interleaved_(
  98159. verify_input_fifo *fifo,
  98160. const FLAC__int32 input[],
  98161. unsigned input_offset,
  98162. unsigned channels,
  98163. unsigned wide_samples
  98164. );
  98165. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98166. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  98167. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  98168. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  98169. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98170. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98171. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98172. 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);
  98173. static FILE *get_binary_stdout_(void);
  98174. /***********************************************************************
  98175. *
  98176. * Private class data
  98177. *
  98178. ***********************************************************************/
  98179. typedef struct FLAC__StreamEncoderPrivate {
  98180. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  98181. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  98182. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  98183. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98184. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  98185. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  98186. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  98187. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  98188. #endif
  98189. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  98190. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  98191. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  98192. FLAC__int32 *residual_workspace_mid_side[2][2];
  98193. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  98194. FLAC__Subframe subframe_workspace_mid_side[2][2];
  98195. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98196. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  98197. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  98198. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  98199. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98200. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  98201. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  98202. unsigned best_subframe_mid_side[2];
  98203. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  98204. unsigned best_subframe_bits_mid_side[2];
  98205. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  98206. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  98207. FLAC__BitWriter *frame; /* the current frame being worked on */
  98208. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  98209. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  98210. FLAC__ChannelAssignment last_channel_assignment;
  98211. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  98212. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  98213. unsigned current_sample_number;
  98214. unsigned current_frame_number;
  98215. FLAC__MD5Context md5context;
  98216. FLAC__CPUInfo cpuinfo;
  98217. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98218. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98219. #else
  98220. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98221. #endif
  98222. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98223. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  98224. 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[]);
  98225. 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[]);
  98226. 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[]);
  98227. #endif
  98228. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  98229. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  98230. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  98231. FLAC__bool disable_constant_subframes;
  98232. FLAC__bool disable_fixed_subframes;
  98233. FLAC__bool disable_verbatim_subframes;
  98234. #if FLAC__HAS_OGG
  98235. FLAC__bool is_ogg;
  98236. #endif
  98237. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  98238. FLAC__StreamEncoderSeekCallback seek_callback;
  98239. FLAC__StreamEncoderTellCallback tell_callback;
  98240. FLAC__StreamEncoderWriteCallback write_callback;
  98241. FLAC__StreamEncoderMetadataCallback metadata_callback;
  98242. FLAC__StreamEncoderProgressCallback progress_callback;
  98243. void *client_data;
  98244. unsigned first_seekpoint_to_check;
  98245. FILE *file; /* only used when encoding to a file */
  98246. FLAC__uint64 bytes_written;
  98247. FLAC__uint64 samples_written;
  98248. unsigned frames_written;
  98249. unsigned total_frames_estimate;
  98250. /* unaligned (original) pointers to allocated data */
  98251. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  98252. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  98253. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98254. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  98255. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  98256. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  98257. FLAC__real *windowed_signal_unaligned;
  98258. #endif
  98259. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  98260. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  98261. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  98262. unsigned *raw_bits_per_partition_unaligned;
  98263. /*
  98264. * These fields have been moved here from private function local
  98265. * declarations merely to save stack space during encoding.
  98266. */
  98267. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98268. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  98269. #endif
  98270. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  98271. /*
  98272. * The data for the verify section
  98273. */
  98274. struct {
  98275. FLAC__StreamDecoder *decoder;
  98276. EncoderStateHint state_hint;
  98277. FLAC__bool needs_magic_hack;
  98278. verify_input_fifo input_fifo;
  98279. verify_output output;
  98280. struct {
  98281. FLAC__uint64 absolute_sample;
  98282. unsigned frame_number;
  98283. unsigned channel;
  98284. unsigned sample;
  98285. FLAC__int32 expected;
  98286. FLAC__int32 got;
  98287. } error_stats;
  98288. } verify;
  98289. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  98290. } FLAC__StreamEncoderPrivate;
  98291. /***********************************************************************
  98292. *
  98293. * Public static class data
  98294. *
  98295. ***********************************************************************/
  98296. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  98297. "FLAC__STREAM_ENCODER_OK",
  98298. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  98299. "FLAC__STREAM_ENCODER_OGG_ERROR",
  98300. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  98301. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  98302. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  98303. "FLAC__STREAM_ENCODER_IO_ERROR",
  98304. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  98305. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  98306. };
  98307. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  98308. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  98309. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  98310. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98311. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  98312. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  98313. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  98314. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  98315. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  98316. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  98317. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  98318. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  98319. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  98320. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  98321. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  98322. };
  98323. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  98324. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  98325. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  98326. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  98327. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  98328. };
  98329. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  98330. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  98331. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  98332. };
  98333. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  98334. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  98335. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  98336. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  98337. };
  98338. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  98339. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  98340. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  98341. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  98342. };
  98343. /* Number of samples that will be overread to watch for end of stream. By
  98344. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  98345. * always try to read blocksize+1 samples before encoding a block, so that
  98346. * even if the stream has a total sample count that is an integral multiple
  98347. * of the blocksize, we will still notice when we are encoding the last
  98348. * block. This is needed, for example, to correctly set the end-of-stream
  98349. * marker in Ogg FLAC.
  98350. *
  98351. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  98352. * not really any reason to change it.
  98353. */
  98354. static const unsigned OVERREAD_ = 1;
  98355. /***********************************************************************
  98356. *
  98357. * Class constructor/destructor
  98358. *
  98359. */
  98360. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  98361. {
  98362. FLAC__StreamEncoder *encoder;
  98363. unsigned i;
  98364. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98365. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  98366. if(encoder == 0) {
  98367. return 0;
  98368. }
  98369. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  98370. if(encoder->protected_ == 0) {
  98371. free(encoder);
  98372. return 0;
  98373. }
  98374. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  98375. if(encoder->private_ == 0) {
  98376. free(encoder->protected_);
  98377. free(encoder);
  98378. return 0;
  98379. }
  98380. encoder->private_->frame = FLAC__bitwriter_new();
  98381. if(encoder->private_->frame == 0) {
  98382. free(encoder->private_);
  98383. free(encoder->protected_);
  98384. free(encoder);
  98385. return 0;
  98386. }
  98387. encoder->private_->file = 0;
  98388. set_defaults_enc(encoder);
  98389. encoder->private_->is_being_deleted = false;
  98390. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98391. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  98392. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  98393. }
  98394. for(i = 0; i < 2; i++) {
  98395. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  98396. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  98397. }
  98398. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98399. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  98400. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  98401. }
  98402. for(i = 0; i < 2; i++) {
  98403. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  98404. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  98405. }
  98406. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98407. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98408. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  98409. }
  98410. for(i = 0; i < 2; i++) {
  98411. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98412. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  98413. }
  98414. for(i = 0; i < 2; i++)
  98415. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  98416. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98417. return encoder;
  98418. }
  98419. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  98420. {
  98421. unsigned i;
  98422. FLAC__ASSERT(0 != encoder);
  98423. FLAC__ASSERT(0 != encoder->protected_);
  98424. FLAC__ASSERT(0 != encoder->private_);
  98425. FLAC__ASSERT(0 != encoder->private_->frame);
  98426. encoder->private_->is_being_deleted = true;
  98427. (void)FLAC__stream_encoder_finish(encoder);
  98428. if(0 != encoder->private_->verify.decoder)
  98429. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  98430. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98431. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98432. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  98433. }
  98434. for(i = 0; i < 2; i++) {
  98435. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98436. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  98437. }
  98438. for(i = 0; i < 2; i++)
  98439. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  98440. FLAC__bitwriter_delete(encoder->private_->frame);
  98441. free(encoder->private_);
  98442. free(encoder->protected_);
  98443. free(encoder);
  98444. }
  98445. /***********************************************************************
  98446. *
  98447. * Public class methods
  98448. *
  98449. ***********************************************************************/
  98450. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  98451. FLAC__StreamEncoder *encoder,
  98452. FLAC__StreamEncoderReadCallback read_callback,
  98453. FLAC__StreamEncoderWriteCallback write_callback,
  98454. FLAC__StreamEncoderSeekCallback seek_callback,
  98455. FLAC__StreamEncoderTellCallback tell_callback,
  98456. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98457. void *client_data,
  98458. FLAC__bool is_ogg
  98459. )
  98460. {
  98461. unsigned i;
  98462. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  98463. FLAC__ASSERT(0 != encoder);
  98464. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98465. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98466. #if !FLAC__HAS_OGG
  98467. if(is_ogg)
  98468. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98469. #endif
  98470. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  98471. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  98472. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  98473. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  98474. if(encoder->protected_->channels != 2) {
  98475. encoder->protected_->do_mid_side_stereo = false;
  98476. encoder->protected_->loose_mid_side_stereo = false;
  98477. }
  98478. else if(!encoder->protected_->do_mid_side_stereo)
  98479. encoder->protected_->loose_mid_side_stereo = false;
  98480. if(encoder->protected_->bits_per_sample >= 32)
  98481. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  98482. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  98483. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  98484. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  98485. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  98486. if(encoder->protected_->blocksize == 0) {
  98487. if(encoder->protected_->max_lpc_order == 0)
  98488. encoder->protected_->blocksize = 1152;
  98489. else
  98490. encoder->protected_->blocksize = 4096;
  98491. }
  98492. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  98493. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  98494. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  98495. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  98496. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  98497. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  98498. if(encoder->protected_->qlp_coeff_precision == 0) {
  98499. if(encoder->protected_->bits_per_sample < 16) {
  98500. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  98501. /* @@@ until then we'll make a guess */
  98502. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  98503. }
  98504. else if(encoder->protected_->bits_per_sample == 16) {
  98505. if(encoder->protected_->blocksize <= 192)
  98506. encoder->protected_->qlp_coeff_precision = 7;
  98507. else if(encoder->protected_->blocksize <= 384)
  98508. encoder->protected_->qlp_coeff_precision = 8;
  98509. else if(encoder->protected_->blocksize <= 576)
  98510. encoder->protected_->qlp_coeff_precision = 9;
  98511. else if(encoder->protected_->blocksize <= 1152)
  98512. encoder->protected_->qlp_coeff_precision = 10;
  98513. else if(encoder->protected_->blocksize <= 2304)
  98514. encoder->protected_->qlp_coeff_precision = 11;
  98515. else if(encoder->protected_->blocksize <= 4608)
  98516. encoder->protected_->qlp_coeff_precision = 12;
  98517. else
  98518. encoder->protected_->qlp_coeff_precision = 13;
  98519. }
  98520. else {
  98521. if(encoder->protected_->blocksize <= 384)
  98522. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  98523. else if(encoder->protected_->blocksize <= 1152)
  98524. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  98525. else
  98526. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  98527. }
  98528. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  98529. }
  98530. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  98531. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  98532. if(encoder->protected_->streamable_subset) {
  98533. if(
  98534. encoder->protected_->blocksize != 192 &&
  98535. encoder->protected_->blocksize != 576 &&
  98536. encoder->protected_->blocksize != 1152 &&
  98537. encoder->protected_->blocksize != 2304 &&
  98538. encoder->protected_->blocksize != 4608 &&
  98539. encoder->protected_->blocksize != 256 &&
  98540. encoder->protected_->blocksize != 512 &&
  98541. encoder->protected_->blocksize != 1024 &&
  98542. encoder->protected_->blocksize != 2048 &&
  98543. encoder->protected_->blocksize != 4096 &&
  98544. encoder->protected_->blocksize != 8192 &&
  98545. encoder->protected_->blocksize != 16384
  98546. )
  98547. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98548. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  98549. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98550. if(
  98551. encoder->protected_->bits_per_sample != 8 &&
  98552. encoder->protected_->bits_per_sample != 12 &&
  98553. encoder->protected_->bits_per_sample != 16 &&
  98554. encoder->protected_->bits_per_sample != 20 &&
  98555. encoder->protected_->bits_per_sample != 24
  98556. )
  98557. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98558. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  98559. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98560. if(
  98561. encoder->protected_->sample_rate <= 48000 &&
  98562. (
  98563. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  98564. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  98565. )
  98566. ) {
  98567. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98568. }
  98569. }
  98570. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98571. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  98572. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  98573. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  98574. #if FLAC__HAS_OGG
  98575. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  98576. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  98577. unsigned i;
  98578. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  98579. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98580. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  98581. for( ; i > 0; i--)
  98582. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  98583. encoder->protected_->metadata[0] = vc;
  98584. break;
  98585. }
  98586. }
  98587. }
  98588. #endif
  98589. /* keep track of any SEEKTABLE block */
  98590. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  98591. unsigned i;
  98592. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98593. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98594. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  98595. break; /* take only the first one */
  98596. }
  98597. }
  98598. }
  98599. /* validate metadata */
  98600. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  98601. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98602. metadata_has_seektable = false;
  98603. metadata_has_vorbis_comment = false;
  98604. metadata_picture_has_type1 = false;
  98605. metadata_picture_has_type2 = false;
  98606. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98607. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  98608. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  98609. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98610. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98611. if(metadata_has_seektable) /* only one is allowed */
  98612. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98613. metadata_has_seektable = true;
  98614. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  98615. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98616. }
  98617. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98618. if(metadata_has_vorbis_comment) /* only one is allowed */
  98619. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98620. metadata_has_vorbis_comment = true;
  98621. }
  98622. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  98623. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  98624. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98625. }
  98626. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  98627. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  98628. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98629. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  98630. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  98631. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98632. metadata_picture_has_type1 = true;
  98633. /* standard icon must be 32x32 pixel PNG */
  98634. if(
  98635. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  98636. (
  98637. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  98638. m->data.picture.width != 32 ||
  98639. m->data.picture.height != 32
  98640. )
  98641. )
  98642. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98643. }
  98644. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  98645. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  98646. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98647. metadata_picture_has_type2 = true;
  98648. }
  98649. }
  98650. }
  98651. encoder->private_->input_capacity = 0;
  98652. for(i = 0; i < encoder->protected_->channels; i++) {
  98653. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  98654. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98655. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  98656. #endif
  98657. }
  98658. for(i = 0; i < 2; i++) {
  98659. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  98660. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98661. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  98662. #endif
  98663. }
  98664. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98665. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  98666. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  98667. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  98668. #endif
  98669. for(i = 0; i < encoder->protected_->channels; i++) {
  98670. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  98671. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  98672. encoder->private_->best_subframe[i] = 0;
  98673. }
  98674. for(i = 0; i < 2; i++) {
  98675. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  98676. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  98677. encoder->private_->best_subframe_mid_side[i] = 0;
  98678. }
  98679. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  98680. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  98681. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98682. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  98683. #else
  98684. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  98685. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  98686. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  98687. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  98688. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  98689. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  98690. 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);
  98691. #endif
  98692. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  98693. encoder->private_->loose_mid_side_stereo_frames = 1;
  98694. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  98695. encoder->private_->current_sample_number = 0;
  98696. encoder->private_->current_frame_number = 0;
  98697. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  98698. 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? */
  98699. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  98700. /*
  98701. * get the CPU info and set the function pointers
  98702. */
  98703. FLAC__cpu_info(&encoder->private_->cpuinfo);
  98704. /* first default to the non-asm routines */
  98705. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98706. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  98707. #endif
  98708. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  98709. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98710. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98711. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  98712. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98713. #endif
  98714. /* now override with asm where appropriate */
  98715. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98716. # ifndef FLAC__NO_ASM
  98717. if(encoder->private_->cpuinfo.use_asm) {
  98718. # ifdef FLAC__CPU_IA32
  98719. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98720. # ifdef FLAC__HAS_NASM
  98721. if(encoder->private_->cpuinfo.data.ia32.sse) {
  98722. if(encoder->protected_->max_lpc_order < 4)
  98723. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  98724. else if(encoder->protected_->max_lpc_order < 8)
  98725. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  98726. else if(encoder->protected_->max_lpc_order < 12)
  98727. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  98728. else
  98729. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98730. }
  98731. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  98732. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  98733. else
  98734. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98735. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  98736. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98737. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  98738. }
  98739. else {
  98740. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98741. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98742. }
  98743. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  98744. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  98745. # endif /* FLAC__HAS_NASM */
  98746. # endif /* FLAC__CPU_IA32 */
  98747. }
  98748. # endif /* !FLAC__NO_ASM */
  98749. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  98750. /* finally override based on wide-ness if necessary */
  98751. if(encoder->private_->use_wide_by_block) {
  98752. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  98753. }
  98754. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  98755. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  98756. #if FLAC__HAS_OGG
  98757. encoder->private_->is_ogg = is_ogg;
  98758. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  98759. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98760. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98761. }
  98762. #endif
  98763. encoder->private_->read_callback = read_callback;
  98764. encoder->private_->write_callback = write_callback;
  98765. encoder->private_->seek_callback = seek_callback;
  98766. encoder->private_->tell_callback = tell_callback;
  98767. encoder->private_->metadata_callback = metadata_callback;
  98768. encoder->private_->client_data = client_data;
  98769. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  98770. /* the above function sets the state for us in case of an error */
  98771. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98772. }
  98773. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  98774. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98775. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98776. }
  98777. /*
  98778. * Set up the verify stuff if necessary
  98779. */
  98780. if(encoder->protected_->verify) {
  98781. /*
  98782. * First, set up the fifo which will hold the
  98783. * original signal to compare against
  98784. */
  98785. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  98786. for(i = 0; i < encoder->protected_->channels; i++) {
  98787. 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))) {
  98788. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98789. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98790. }
  98791. }
  98792. encoder->private_->verify.input_fifo.tail = 0;
  98793. /*
  98794. * Now set up a stream decoder for verification
  98795. */
  98796. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  98797. if(0 == encoder->private_->verify.decoder) {
  98798. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98799. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98800. }
  98801. 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) {
  98802. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98803. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98804. }
  98805. }
  98806. encoder->private_->verify.error_stats.absolute_sample = 0;
  98807. encoder->private_->verify.error_stats.frame_number = 0;
  98808. encoder->private_->verify.error_stats.channel = 0;
  98809. encoder->private_->verify.error_stats.sample = 0;
  98810. encoder->private_->verify.error_stats.expected = 0;
  98811. encoder->private_->verify.error_stats.got = 0;
  98812. /*
  98813. * These must be done before we write any metadata, because that
  98814. * calls the write_callback, which uses these values.
  98815. */
  98816. encoder->private_->first_seekpoint_to_check = 0;
  98817. encoder->private_->samples_written = 0;
  98818. encoder->protected_->streaminfo_offset = 0;
  98819. encoder->protected_->seektable_offset = 0;
  98820. encoder->protected_->audio_offset = 0;
  98821. /*
  98822. * write the stream header
  98823. */
  98824. if(encoder->protected_->verify)
  98825. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  98826. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  98827. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98828. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98829. }
  98830. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98831. /* the above function sets the state for us in case of an error */
  98832. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98833. }
  98834. /*
  98835. * write the STREAMINFO metadata block
  98836. */
  98837. if(encoder->protected_->verify)
  98838. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  98839. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  98840. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  98841. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  98842. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  98843. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  98844. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  98845. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  98846. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  98847. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  98848. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  98849. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  98850. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  98851. if(encoder->protected_->do_md5)
  98852. FLAC__MD5Init(&encoder->private_->md5context);
  98853. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  98854. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98855. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98856. }
  98857. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98858. /* the above function sets the state for us in case of an error */
  98859. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98860. }
  98861. /*
  98862. * Now that the STREAMINFO block is written, we can init this to an
  98863. * absurdly-high value...
  98864. */
  98865. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  98866. /* ... and clear this to 0 */
  98867. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  98868. /*
  98869. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  98870. * if not, we will write an empty one (FLAC__add_metadata_block()
  98871. * automatically supplies the vendor string).
  98872. *
  98873. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  98874. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  98875. * true it will have already insured that the metadata list is properly
  98876. * ordered.)
  98877. */
  98878. if(!metadata_has_vorbis_comment) {
  98879. FLAC__StreamMetadata vorbis_comment;
  98880. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  98881. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  98882. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  98883. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  98884. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  98885. vorbis_comment.data.vorbis_comment.num_comments = 0;
  98886. vorbis_comment.data.vorbis_comment.comments = 0;
  98887. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  98888. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98889. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98890. }
  98891. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98892. /* the above function sets the state for us in case of an error */
  98893. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98894. }
  98895. }
  98896. /*
  98897. * write the user's metadata blocks
  98898. */
  98899. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98900. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  98901. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  98902. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98903. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98904. }
  98905. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98906. /* the above function sets the state for us in case of an error */
  98907. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98908. }
  98909. }
  98910. /* now that all the metadata is written, we save the stream offset */
  98911. 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 */
  98912. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98913. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98914. }
  98915. if(encoder->protected_->verify)
  98916. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  98917. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  98918. }
  98919. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  98920. FLAC__StreamEncoder *encoder,
  98921. FLAC__StreamEncoderWriteCallback write_callback,
  98922. FLAC__StreamEncoderSeekCallback seek_callback,
  98923. FLAC__StreamEncoderTellCallback tell_callback,
  98924. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98925. void *client_data
  98926. )
  98927. {
  98928. return init_stream_internal_enc(
  98929. encoder,
  98930. /*read_callback=*/0,
  98931. write_callback,
  98932. seek_callback,
  98933. tell_callback,
  98934. metadata_callback,
  98935. client_data,
  98936. /*is_ogg=*/false
  98937. );
  98938. }
  98939. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  98940. FLAC__StreamEncoder *encoder,
  98941. FLAC__StreamEncoderReadCallback read_callback,
  98942. FLAC__StreamEncoderWriteCallback write_callback,
  98943. FLAC__StreamEncoderSeekCallback seek_callback,
  98944. FLAC__StreamEncoderTellCallback tell_callback,
  98945. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98946. void *client_data
  98947. )
  98948. {
  98949. return init_stream_internal_enc(
  98950. encoder,
  98951. read_callback,
  98952. write_callback,
  98953. seek_callback,
  98954. tell_callback,
  98955. metadata_callback,
  98956. client_data,
  98957. /*is_ogg=*/true
  98958. );
  98959. }
  98960. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  98961. FLAC__StreamEncoder *encoder,
  98962. FILE *file,
  98963. FLAC__StreamEncoderProgressCallback progress_callback,
  98964. void *client_data,
  98965. FLAC__bool is_ogg
  98966. )
  98967. {
  98968. FLAC__StreamEncoderInitStatus init_status;
  98969. FLAC__ASSERT(0 != encoder);
  98970. FLAC__ASSERT(0 != file);
  98971. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98972. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98973. /* double protection */
  98974. if(file == 0) {
  98975. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98976. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98977. }
  98978. /*
  98979. * To make sure that our file does not go unclosed after an error, we
  98980. * must assign the FILE pointer before any further error can occur in
  98981. * this routine.
  98982. */
  98983. if(file == stdout)
  98984. file = get_binary_stdout_(); /* just to be safe */
  98985. encoder->private_->file = file;
  98986. encoder->private_->progress_callback = progress_callback;
  98987. encoder->private_->bytes_written = 0;
  98988. encoder->private_->samples_written = 0;
  98989. encoder->private_->frames_written = 0;
  98990. init_status = init_stream_internal_enc(
  98991. encoder,
  98992. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  98993. file_write_callback_,
  98994. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  98995. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  98996. /*metadata_callback=*/0,
  98997. client_data,
  98998. is_ogg
  98999. );
  99000. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  99001. /* the above function sets the state for us in case of an error */
  99002. return init_status;
  99003. }
  99004. {
  99005. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99006. FLAC__ASSERT(blocksize != 0);
  99007. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  99008. }
  99009. return init_status;
  99010. }
  99011. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  99012. FLAC__StreamEncoder *encoder,
  99013. FILE *file,
  99014. FLAC__StreamEncoderProgressCallback progress_callback,
  99015. void *client_data
  99016. )
  99017. {
  99018. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  99019. }
  99020. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  99021. FLAC__StreamEncoder *encoder,
  99022. FILE *file,
  99023. FLAC__StreamEncoderProgressCallback progress_callback,
  99024. void *client_data
  99025. )
  99026. {
  99027. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  99028. }
  99029. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  99030. FLAC__StreamEncoder *encoder,
  99031. const char *filename,
  99032. FLAC__StreamEncoderProgressCallback progress_callback,
  99033. void *client_data,
  99034. FLAC__bool is_ogg
  99035. )
  99036. {
  99037. FILE *file;
  99038. FLAC__ASSERT(0 != encoder);
  99039. /*
  99040. * To make sure that our file does not go unclosed after an error, we
  99041. * have to do the same entrance checks here that are later performed
  99042. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  99043. */
  99044. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99045. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99046. file = filename? fopen(filename, "w+b") : stdout;
  99047. if(file == 0) {
  99048. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99049. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99050. }
  99051. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  99052. }
  99053. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  99054. FLAC__StreamEncoder *encoder,
  99055. const char *filename,
  99056. FLAC__StreamEncoderProgressCallback progress_callback,
  99057. void *client_data
  99058. )
  99059. {
  99060. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  99061. }
  99062. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  99063. FLAC__StreamEncoder *encoder,
  99064. const char *filename,
  99065. FLAC__StreamEncoderProgressCallback progress_callback,
  99066. void *client_data
  99067. )
  99068. {
  99069. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  99070. }
  99071. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  99072. {
  99073. FLAC__bool error = false;
  99074. FLAC__ASSERT(0 != encoder);
  99075. FLAC__ASSERT(0 != encoder->private_);
  99076. FLAC__ASSERT(0 != encoder->protected_);
  99077. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  99078. return true;
  99079. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  99080. if(encoder->private_->current_sample_number != 0) {
  99081. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  99082. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  99083. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  99084. error = true;
  99085. }
  99086. }
  99087. if(encoder->protected_->do_md5)
  99088. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  99089. if(!encoder->private_->is_being_deleted) {
  99090. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  99091. if(encoder->private_->seek_callback) {
  99092. #if FLAC__HAS_OGG
  99093. if(encoder->private_->is_ogg)
  99094. update_ogg_metadata_(encoder);
  99095. else
  99096. #endif
  99097. update_metadata_(encoder);
  99098. /* check if an error occurred while updating metadata */
  99099. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  99100. error = true;
  99101. }
  99102. if(encoder->private_->metadata_callback)
  99103. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  99104. }
  99105. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  99106. if(!error)
  99107. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  99108. error = true;
  99109. }
  99110. }
  99111. if(0 != encoder->private_->file) {
  99112. if(encoder->private_->file != stdout)
  99113. fclose(encoder->private_->file);
  99114. encoder->private_->file = 0;
  99115. }
  99116. #if FLAC__HAS_OGG
  99117. if(encoder->private_->is_ogg)
  99118. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  99119. #endif
  99120. free_(encoder);
  99121. set_defaults_enc(encoder);
  99122. if(!error)
  99123. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99124. return !error;
  99125. }
  99126. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  99127. {
  99128. FLAC__ASSERT(0 != encoder);
  99129. FLAC__ASSERT(0 != encoder->private_);
  99130. FLAC__ASSERT(0 != encoder->protected_);
  99131. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99132. return false;
  99133. #if FLAC__HAS_OGG
  99134. /* can't check encoder->private_->is_ogg since that's not set until init time */
  99135. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  99136. return true;
  99137. #else
  99138. (void)value;
  99139. return false;
  99140. #endif
  99141. }
  99142. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool 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. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99150. encoder->protected_->verify = value;
  99151. #endif
  99152. return true;
  99153. }
  99154. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99155. {
  99156. FLAC__ASSERT(0 != encoder);
  99157. FLAC__ASSERT(0 != encoder->private_);
  99158. FLAC__ASSERT(0 != encoder->protected_);
  99159. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99160. return false;
  99161. encoder->protected_->streamable_subset = value;
  99162. return true;
  99163. }
  99164. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99165. {
  99166. FLAC__ASSERT(0 != encoder);
  99167. FLAC__ASSERT(0 != encoder->private_);
  99168. FLAC__ASSERT(0 != encoder->protected_);
  99169. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99170. return false;
  99171. encoder->protected_->do_md5 = value;
  99172. return true;
  99173. }
  99174. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  99175. {
  99176. FLAC__ASSERT(0 != encoder);
  99177. FLAC__ASSERT(0 != encoder->private_);
  99178. FLAC__ASSERT(0 != encoder->protected_);
  99179. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99180. return false;
  99181. encoder->protected_->channels = value;
  99182. return true;
  99183. }
  99184. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  99185. {
  99186. FLAC__ASSERT(0 != encoder);
  99187. FLAC__ASSERT(0 != encoder->private_);
  99188. FLAC__ASSERT(0 != encoder->protected_);
  99189. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99190. return false;
  99191. encoder->protected_->bits_per_sample = value;
  99192. return true;
  99193. }
  99194. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  99195. {
  99196. FLAC__ASSERT(0 != encoder);
  99197. FLAC__ASSERT(0 != encoder->private_);
  99198. FLAC__ASSERT(0 != encoder->protected_);
  99199. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99200. return false;
  99201. encoder->protected_->sample_rate = value;
  99202. return true;
  99203. }
  99204. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  99205. {
  99206. FLAC__bool ok = true;
  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. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  99213. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  99214. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  99215. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  99216. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99217. #if 0
  99218. /* was: */
  99219. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  99220. /* but it's too hard to specify the string in a locale-specific way */
  99221. #else
  99222. encoder->protected_->num_apodizations = 1;
  99223. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99224. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99225. #endif
  99226. #endif
  99227. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  99228. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  99229. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  99230. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  99231. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  99232. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  99233. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  99234. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  99235. return ok;
  99236. }
  99237. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  99238. {
  99239. FLAC__ASSERT(0 != encoder);
  99240. FLAC__ASSERT(0 != encoder->private_);
  99241. FLAC__ASSERT(0 != encoder->protected_);
  99242. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99243. return false;
  99244. encoder->protected_->blocksize = value;
  99245. return true;
  99246. }
  99247. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99248. {
  99249. FLAC__ASSERT(0 != encoder);
  99250. FLAC__ASSERT(0 != encoder->private_);
  99251. FLAC__ASSERT(0 != encoder->protected_);
  99252. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99253. return false;
  99254. encoder->protected_->do_mid_side_stereo = value;
  99255. return true;
  99256. }
  99257. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99258. {
  99259. FLAC__ASSERT(0 != encoder);
  99260. FLAC__ASSERT(0 != encoder->private_);
  99261. FLAC__ASSERT(0 != encoder->protected_);
  99262. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99263. return false;
  99264. encoder->protected_->loose_mid_side_stereo = value;
  99265. return true;
  99266. }
  99267. /*@@@@add to tests*/
  99268. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  99269. {
  99270. FLAC__ASSERT(0 != encoder);
  99271. FLAC__ASSERT(0 != encoder->private_);
  99272. FLAC__ASSERT(0 != encoder->protected_);
  99273. FLAC__ASSERT(0 != specification);
  99274. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99275. return false;
  99276. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  99277. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  99278. #else
  99279. encoder->protected_->num_apodizations = 0;
  99280. while(1) {
  99281. const char *s = strchr(specification, ';');
  99282. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  99283. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  99284. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  99285. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  99286. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  99287. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  99288. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  99289. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  99290. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  99291. else if(n==6 && 0 == strncmp("connes" , specification, n))
  99292. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  99293. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  99294. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  99295. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  99296. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  99297. if (stddev > 0.0 && stddev <= 0.5) {
  99298. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  99299. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  99300. }
  99301. }
  99302. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  99303. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  99304. else if(n==4 && 0 == strncmp("hann" , specification, n))
  99305. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  99306. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  99307. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  99308. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  99309. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  99310. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  99311. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  99312. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  99313. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  99314. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  99315. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  99316. if (p >= 0.0 && p <= 1.0) {
  99317. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  99318. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  99319. }
  99320. }
  99321. else if(n==5 && 0 == strncmp("welch" , specification, n))
  99322. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  99323. if (encoder->protected_->num_apodizations == 32)
  99324. break;
  99325. if (s)
  99326. specification = s+1;
  99327. else
  99328. break;
  99329. }
  99330. if(encoder->protected_->num_apodizations == 0) {
  99331. encoder->protected_->num_apodizations = 1;
  99332. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99333. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99334. }
  99335. #endif
  99336. return true;
  99337. }
  99338. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  99339. {
  99340. FLAC__ASSERT(0 != encoder);
  99341. FLAC__ASSERT(0 != encoder->private_);
  99342. FLAC__ASSERT(0 != encoder->protected_);
  99343. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99344. return false;
  99345. encoder->protected_->max_lpc_order = value;
  99346. return true;
  99347. }
  99348. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  99349. {
  99350. FLAC__ASSERT(0 != encoder);
  99351. FLAC__ASSERT(0 != encoder->private_);
  99352. FLAC__ASSERT(0 != encoder->protected_);
  99353. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99354. return false;
  99355. encoder->protected_->qlp_coeff_precision = value;
  99356. return true;
  99357. }
  99358. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99359. {
  99360. FLAC__ASSERT(0 != encoder);
  99361. FLAC__ASSERT(0 != encoder->private_);
  99362. FLAC__ASSERT(0 != encoder->protected_);
  99363. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99364. return false;
  99365. encoder->protected_->do_qlp_coeff_prec_search = value;
  99366. return true;
  99367. }
  99368. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99369. {
  99370. FLAC__ASSERT(0 != encoder);
  99371. FLAC__ASSERT(0 != encoder->private_);
  99372. FLAC__ASSERT(0 != encoder->protected_);
  99373. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99374. return false;
  99375. #if 0
  99376. /*@@@ deprecated: */
  99377. encoder->protected_->do_escape_coding = value;
  99378. #else
  99379. (void)value;
  99380. #endif
  99381. return true;
  99382. }
  99383. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99384. {
  99385. FLAC__ASSERT(0 != encoder);
  99386. FLAC__ASSERT(0 != encoder->private_);
  99387. FLAC__ASSERT(0 != encoder->protected_);
  99388. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99389. return false;
  99390. encoder->protected_->do_exhaustive_model_search = value;
  99391. return true;
  99392. }
  99393. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99394. {
  99395. FLAC__ASSERT(0 != encoder);
  99396. FLAC__ASSERT(0 != encoder->private_);
  99397. FLAC__ASSERT(0 != encoder->protected_);
  99398. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99399. return false;
  99400. encoder->protected_->min_residual_partition_order = value;
  99401. return true;
  99402. }
  99403. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99404. {
  99405. FLAC__ASSERT(0 != encoder);
  99406. FLAC__ASSERT(0 != encoder->private_);
  99407. FLAC__ASSERT(0 != encoder->protected_);
  99408. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99409. return false;
  99410. encoder->protected_->max_residual_partition_order = value;
  99411. return true;
  99412. }
  99413. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  99414. {
  99415. FLAC__ASSERT(0 != encoder);
  99416. FLAC__ASSERT(0 != encoder->private_);
  99417. FLAC__ASSERT(0 != encoder->protected_);
  99418. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99419. return false;
  99420. #if 0
  99421. /*@@@ deprecated: */
  99422. encoder->protected_->rice_parameter_search_dist = value;
  99423. #else
  99424. (void)value;
  99425. #endif
  99426. return true;
  99427. }
  99428. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  99429. {
  99430. FLAC__ASSERT(0 != encoder);
  99431. FLAC__ASSERT(0 != encoder->private_);
  99432. FLAC__ASSERT(0 != encoder->protected_);
  99433. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99434. return false;
  99435. encoder->protected_->total_samples_estimate = value;
  99436. return true;
  99437. }
  99438. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  99439. {
  99440. FLAC__ASSERT(0 != encoder);
  99441. FLAC__ASSERT(0 != encoder->private_);
  99442. FLAC__ASSERT(0 != encoder->protected_);
  99443. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99444. return false;
  99445. if(0 == metadata)
  99446. num_blocks = 0;
  99447. if(0 == num_blocks)
  99448. metadata = 0;
  99449. /* realloc() does not do exactly what we want so... */
  99450. if(encoder->protected_->metadata) {
  99451. free(encoder->protected_->metadata);
  99452. encoder->protected_->metadata = 0;
  99453. encoder->protected_->num_metadata_blocks = 0;
  99454. }
  99455. if(num_blocks) {
  99456. FLAC__StreamMetadata **m;
  99457. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  99458. return false;
  99459. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  99460. encoder->protected_->metadata = m;
  99461. encoder->protected_->num_metadata_blocks = num_blocks;
  99462. }
  99463. #if FLAC__HAS_OGG
  99464. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  99465. return false;
  99466. #endif
  99467. return true;
  99468. }
  99469. /*
  99470. * These three functions are not static, but not publically exposed in
  99471. * include/FLAC/ either. They are used by the test suite.
  99472. */
  99473. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99474. {
  99475. FLAC__ASSERT(0 != encoder);
  99476. FLAC__ASSERT(0 != encoder->private_);
  99477. FLAC__ASSERT(0 != encoder->protected_);
  99478. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99479. return false;
  99480. encoder->private_->disable_constant_subframes = value;
  99481. return true;
  99482. }
  99483. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99484. {
  99485. FLAC__ASSERT(0 != encoder);
  99486. FLAC__ASSERT(0 != encoder->private_);
  99487. FLAC__ASSERT(0 != encoder->protected_);
  99488. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99489. return false;
  99490. encoder->private_->disable_fixed_subframes = value;
  99491. return true;
  99492. }
  99493. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99494. {
  99495. FLAC__ASSERT(0 != encoder);
  99496. FLAC__ASSERT(0 != encoder->private_);
  99497. FLAC__ASSERT(0 != encoder->protected_);
  99498. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99499. return false;
  99500. encoder->private_->disable_verbatim_subframes = value;
  99501. return true;
  99502. }
  99503. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  99504. {
  99505. FLAC__ASSERT(0 != encoder);
  99506. FLAC__ASSERT(0 != encoder->private_);
  99507. FLAC__ASSERT(0 != encoder->protected_);
  99508. return encoder->protected_->state;
  99509. }
  99510. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  99511. {
  99512. FLAC__ASSERT(0 != encoder);
  99513. FLAC__ASSERT(0 != encoder->private_);
  99514. FLAC__ASSERT(0 != encoder->protected_);
  99515. if(encoder->protected_->verify)
  99516. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  99517. else
  99518. return FLAC__STREAM_DECODER_UNINITIALIZED;
  99519. }
  99520. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  99521. {
  99522. FLAC__ASSERT(0 != encoder);
  99523. FLAC__ASSERT(0 != encoder->private_);
  99524. FLAC__ASSERT(0 != encoder->protected_);
  99525. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  99526. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  99527. else
  99528. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  99529. }
  99530. 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)
  99531. {
  99532. FLAC__ASSERT(0 != encoder);
  99533. FLAC__ASSERT(0 != encoder->private_);
  99534. FLAC__ASSERT(0 != encoder->protected_);
  99535. if(0 != absolute_sample)
  99536. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  99537. if(0 != frame_number)
  99538. *frame_number = encoder->private_->verify.error_stats.frame_number;
  99539. if(0 != channel)
  99540. *channel = encoder->private_->verify.error_stats.channel;
  99541. if(0 != sample)
  99542. *sample = encoder->private_->verify.error_stats.sample;
  99543. if(0 != expected)
  99544. *expected = encoder->private_->verify.error_stats.expected;
  99545. if(0 != got)
  99546. *got = encoder->private_->verify.error_stats.got;
  99547. }
  99548. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(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_->verify;
  99554. }
  99555. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(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_->streamable_subset;
  99561. }
  99562. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(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_->do_md5;
  99568. }
  99569. FLAC_API unsigned FLAC__stream_encoder_get_channels(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_->channels;
  99575. }
  99576. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(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_->bits_per_sample;
  99582. }
  99583. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(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_->sample_rate;
  99589. }
  99590. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(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_->blocksize;
  99596. }
  99597. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(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_mid_side_stereo;
  99603. }
  99604. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(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_->loose_mid_side_stereo;
  99610. }
  99611. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_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_lpc_order;
  99617. }
  99618. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(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_->qlp_coeff_precision;
  99624. }
  99625. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(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_->do_qlp_coeff_prec_search;
  99631. }
  99632. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  99633. {
  99634. FLAC__ASSERT(0 != encoder);
  99635. FLAC__ASSERT(0 != encoder->private_);
  99636. FLAC__ASSERT(0 != encoder->protected_);
  99637. return encoder->protected_->do_escape_coding;
  99638. }
  99639. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  99640. {
  99641. FLAC__ASSERT(0 != encoder);
  99642. FLAC__ASSERT(0 != encoder->private_);
  99643. FLAC__ASSERT(0 != encoder->protected_);
  99644. return encoder->protected_->do_exhaustive_model_search;
  99645. }
  99646. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99647. {
  99648. FLAC__ASSERT(0 != encoder);
  99649. FLAC__ASSERT(0 != encoder->private_);
  99650. FLAC__ASSERT(0 != encoder->protected_);
  99651. return encoder->protected_->min_residual_partition_order;
  99652. }
  99653. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99654. {
  99655. FLAC__ASSERT(0 != encoder);
  99656. FLAC__ASSERT(0 != encoder->private_);
  99657. FLAC__ASSERT(0 != encoder->protected_);
  99658. return encoder->protected_->max_residual_partition_order;
  99659. }
  99660. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  99661. {
  99662. FLAC__ASSERT(0 != encoder);
  99663. FLAC__ASSERT(0 != encoder->private_);
  99664. FLAC__ASSERT(0 != encoder->protected_);
  99665. return encoder->protected_->rice_parameter_search_dist;
  99666. }
  99667. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  99668. {
  99669. FLAC__ASSERT(0 != encoder);
  99670. FLAC__ASSERT(0 != encoder->private_);
  99671. FLAC__ASSERT(0 != encoder->protected_);
  99672. return encoder->protected_->total_samples_estimate;
  99673. }
  99674. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  99675. {
  99676. unsigned i, j = 0, channel;
  99677. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99678. FLAC__ASSERT(0 != encoder);
  99679. FLAC__ASSERT(0 != encoder->private_);
  99680. FLAC__ASSERT(0 != encoder->protected_);
  99681. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99682. do {
  99683. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  99684. if(encoder->protected_->verify)
  99685. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  99686. for(channel = 0; channel < channels; channel++)
  99687. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  99688. if(encoder->protected_->do_mid_side_stereo) {
  99689. FLAC__ASSERT(channels == 2);
  99690. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99691. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99692. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  99693. 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' ! */
  99694. }
  99695. }
  99696. else
  99697. j += n;
  99698. encoder->private_->current_sample_number += n;
  99699. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99700. if(encoder->private_->current_sample_number > blocksize) {
  99701. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  99702. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99703. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99704. return false;
  99705. /* move unprocessed overread samples to beginnings of arrays */
  99706. for(channel = 0; channel < channels; channel++)
  99707. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99708. if(encoder->protected_->do_mid_side_stereo) {
  99709. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99710. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99711. }
  99712. encoder->private_->current_sample_number = 1;
  99713. }
  99714. } while(j < samples);
  99715. return true;
  99716. }
  99717. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  99718. {
  99719. unsigned i, j, k, channel;
  99720. FLAC__int32 x, mid, side;
  99721. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99722. FLAC__ASSERT(0 != encoder);
  99723. FLAC__ASSERT(0 != encoder->private_);
  99724. FLAC__ASSERT(0 != encoder->protected_);
  99725. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99726. j = k = 0;
  99727. /*
  99728. * we have several flavors of the same basic loop, optimized for
  99729. * different conditions:
  99730. */
  99731. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  99732. /*
  99733. * stereo coding: unroll channel loop
  99734. */
  99735. do {
  99736. if(encoder->protected_->verify)
  99737. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99738. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99739. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99740. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  99741. x = buffer[k++];
  99742. encoder->private_->integer_signal[1][i] = x;
  99743. mid += x;
  99744. side -= x;
  99745. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  99746. encoder->private_->integer_signal_mid_side[1][i] = side;
  99747. encoder->private_->integer_signal_mid_side[0][i] = mid;
  99748. }
  99749. encoder->private_->current_sample_number = i;
  99750. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99751. if(i > blocksize) {
  99752. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99753. return false;
  99754. /* move unprocessed overread samples to beginnings of arrays */
  99755. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99756. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99757. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  99758. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  99759. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99760. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99761. encoder->private_->current_sample_number = 1;
  99762. }
  99763. } while(j < samples);
  99764. }
  99765. else {
  99766. /*
  99767. * independent channel coding: buffer each channel in inner loop
  99768. */
  99769. do {
  99770. if(encoder->protected_->verify)
  99771. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99772. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99773. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99774. for(channel = 0; channel < channels; channel++)
  99775. encoder->private_->integer_signal[channel][i] = buffer[k++];
  99776. }
  99777. encoder->private_->current_sample_number = i;
  99778. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99779. if(i > blocksize) {
  99780. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99781. return false;
  99782. /* move unprocessed overread samples to beginnings of arrays */
  99783. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99784. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99785. for(channel = 0; channel < channels; channel++)
  99786. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99787. encoder->private_->current_sample_number = 1;
  99788. }
  99789. } while(j < samples);
  99790. }
  99791. return true;
  99792. }
  99793. /***********************************************************************
  99794. *
  99795. * Private class methods
  99796. *
  99797. ***********************************************************************/
  99798. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  99799. {
  99800. FLAC__ASSERT(0 != encoder);
  99801. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99802. encoder->protected_->verify = true;
  99803. #else
  99804. encoder->protected_->verify = false;
  99805. #endif
  99806. encoder->protected_->streamable_subset = true;
  99807. encoder->protected_->do_md5 = true;
  99808. encoder->protected_->do_mid_side_stereo = false;
  99809. encoder->protected_->loose_mid_side_stereo = false;
  99810. encoder->protected_->channels = 2;
  99811. encoder->protected_->bits_per_sample = 16;
  99812. encoder->protected_->sample_rate = 44100;
  99813. encoder->protected_->blocksize = 0;
  99814. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99815. encoder->protected_->num_apodizations = 1;
  99816. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99817. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99818. #endif
  99819. encoder->protected_->max_lpc_order = 0;
  99820. encoder->protected_->qlp_coeff_precision = 0;
  99821. encoder->protected_->do_qlp_coeff_prec_search = false;
  99822. encoder->protected_->do_exhaustive_model_search = false;
  99823. encoder->protected_->do_escape_coding = false;
  99824. encoder->protected_->min_residual_partition_order = 0;
  99825. encoder->protected_->max_residual_partition_order = 0;
  99826. encoder->protected_->rice_parameter_search_dist = 0;
  99827. encoder->protected_->total_samples_estimate = 0;
  99828. encoder->protected_->metadata = 0;
  99829. encoder->protected_->num_metadata_blocks = 0;
  99830. encoder->private_->seek_table = 0;
  99831. encoder->private_->disable_constant_subframes = false;
  99832. encoder->private_->disable_fixed_subframes = false;
  99833. encoder->private_->disable_verbatim_subframes = false;
  99834. #if FLAC__HAS_OGG
  99835. encoder->private_->is_ogg = false;
  99836. #endif
  99837. encoder->private_->read_callback = 0;
  99838. encoder->private_->write_callback = 0;
  99839. encoder->private_->seek_callback = 0;
  99840. encoder->private_->tell_callback = 0;
  99841. encoder->private_->metadata_callback = 0;
  99842. encoder->private_->progress_callback = 0;
  99843. encoder->private_->client_data = 0;
  99844. #if FLAC__HAS_OGG
  99845. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  99846. #endif
  99847. }
  99848. void free_(FLAC__StreamEncoder *encoder)
  99849. {
  99850. unsigned i, channel;
  99851. FLAC__ASSERT(0 != encoder);
  99852. if(encoder->protected_->metadata) {
  99853. free(encoder->protected_->metadata);
  99854. encoder->protected_->metadata = 0;
  99855. encoder->protected_->num_metadata_blocks = 0;
  99856. }
  99857. for(i = 0; i < encoder->protected_->channels; i++) {
  99858. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  99859. free(encoder->private_->integer_signal_unaligned[i]);
  99860. encoder->private_->integer_signal_unaligned[i] = 0;
  99861. }
  99862. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99863. if(0 != encoder->private_->real_signal_unaligned[i]) {
  99864. free(encoder->private_->real_signal_unaligned[i]);
  99865. encoder->private_->real_signal_unaligned[i] = 0;
  99866. }
  99867. #endif
  99868. }
  99869. for(i = 0; i < 2; i++) {
  99870. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  99871. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  99872. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  99873. }
  99874. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99875. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  99876. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  99877. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  99878. }
  99879. #endif
  99880. }
  99881. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99882. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  99883. if(0 != encoder->private_->window_unaligned[i]) {
  99884. free(encoder->private_->window_unaligned[i]);
  99885. encoder->private_->window_unaligned[i] = 0;
  99886. }
  99887. }
  99888. if(0 != encoder->private_->windowed_signal_unaligned) {
  99889. free(encoder->private_->windowed_signal_unaligned);
  99890. encoder->private_->windowed_signal_unaligned = 0;
  99891. }
  99892. #endif
  99893. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99894. for(i = 0; i < 2; i++) {
  99895. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  99896. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  99897. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  99898. }
  99899. }
  99900. }
  99901. for(channel = 0; channel < 2; channel++) {
  99902. for(i = 0; i < 2; i++) {
  99903. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  99904. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  99905. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  99906. }
  99907. }
  99908. }
  99909. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  99910. free(encoder->private_->abs_residual_partition_sums_unaligned);
  99911. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  99912. }
  99913. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  99914. free(encoder->private_->raw_bits_per_partition_unaligned);
  99915. encoder->private_->raw_bits_per_partition_unaligned = 0;
  99916. }
  99917. if(encoder->protected_->verify) {
  99918. for(i = 0; i < encoder->protected_->channels; i++) {
  99919. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  99920. free(encoder->private_->verify.input_fifo.data[i]);
  99921. encoder->private_->verify.input_fifo.data[i] = 0;
  99922. }
  99923. }
  99924. }
  99925. FLAC__bitwriter_free(encoder->private_->frame);
  99926. }
  99927. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  99928. {
  99929. FLAC__bool ok;
  99930. unsigned i, channel;
  99931. FLAC__ASSERT(new_blocksize > 0);
  99932. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99933. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  99934. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  99935. if(new_blocksize <= encoder->private_->input_capacity)
  99936. return true;
  99937. ok = true;
  99938. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  99939. * requires that the input arrays (in our case the integer signals)
  99940. * have a buffer of up to 3 zeroes in front (at negative indices) for
  99941. * alignment purposes; we use 4 in front to keep the data well-aligned.
  99942. */
  99943. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  99944. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  99945. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  99946. encoder->private_->integer_signal[i] += 4;
  99947. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99948. #if 0 /* @@@ currently unused */
  99949. if(encoder->protected_->max_lpc_order > 0)
  99950. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  99951. #endif
  99952. #endif
  99953. }
  99954. for(i = 0; ok && i < 2; i++) {
  99955. 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]);
  99956. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  99957. encoder->private_->integer_signal_mid_side[i] += 4;
  99958. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99959. #if 0 /* @@@ currently unused */
  99960. if(encoder->protected_->max_lpc_order > 0)
  99961. 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]);
  99962. #endif
  99963. #endif
  99964. }
  99965. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99966. if(ok && encoder->protected_->max_lpc_order > 0) {
  99967. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  99968. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  99969. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  99970. }
  99971. #endif
  99972. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  99973. for(i = 0; ok && i < 2; i++) {
  99974. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  99975. }
  99976. }
  99977. for(channel = 0; ok && channel < 2; channel++) {
  99978. for(i = 0; ok && i < 2; i++) {
  99979. 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]);
  99980. }
  99981. }
  99982. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  99983. /*@@@ 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) */
  99984. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  99985. if(encoder->protected_->do_escape_coding)
  99986. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  99987. /* now adjust the windows if the blocksize has changed */
  99988. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99989. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  99990. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  99991. switch(encoder->protected_->apodizations[i].type) {
  99992. case FLAC__APODIZATION_BARTLETT:
  99993. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  99994. break;
  99995. case FLAC__APODIZATION_BARTLETT_HANN:
  99996. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  99997. break;
  99998. case FLAC__APODIZATION_BLACKMAN:
  99999. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  100000. break;
  100001. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  100002. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  100003. break;
  100004. case FLAC__APODIZATION_CONNES:
  100005. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  100006. break;
  100007. case FLAC__APODIZATION_FLATTOP:
  100008. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  100009. break;
  100010. case FLAC__APODIZATION_GAUSS:
  100011. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  100012. break;
  100013. case FLAC__APODIZATION_HAMMING:
  100014. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  100015. break;
  100016. case FLAC__APODIZATION_HANN:
  100017. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100018. break;
  100019. case FLAC__APODIZATION_KAISER_BESSEL:
  100020. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  100021. break;
  100022. case FLAC__APODIZATION_NUTTALL:
  100023. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  100024. break;
  100025. case FLAC__APODIZATION_RECTANGLE:
  100026. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  100027. break;
  100028. case FLAC__APODIZATION_TRIANGLE:
  100029. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  100030. break;
  100031. case FLAC__APODIZATION_TUKEY:
  100032. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  100033. break;
  100034. case FLAC__APODIZATION_WELCH:
  100035. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  100036. break;
  100037. default:
  100038. FLAC__ASSERT(0);
  100039. /* double protection */
  100040. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100041. break;
  100042. }
  100043. }
  100044. }
  100045. #endif
  100046. if(ok)
  100047. encoder->private_->input_capacity = new_blocksize;
  100048. else
  100049. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100050. return ok;
  100051. }
  100052. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  100053. {
  100054. const FLAC__byte *buffer;
  100055. size_t bytes;
  100056. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100057. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  100058. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100059. return false;
  100060. }
  100061. if(encoder->protected_->verify) {
  100062. encoder->private_->verify.output.data = buffer;
  100063. encoder->private_->verify.output.bytes = bytes;
  100064. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  100065. encoder->private_->verify.needs_magic_hack = true;
  100066. }
  100067. else {
  100068. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  100069. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100070. FLAC__bitwriter_clear(encoder->private_->frame);
  100071. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  100072. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100073. return false;
  100074. }
  100075. }
  100076. }
  100077. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100078. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100079. FLAC__bitwriter_clear(encoder->private_->frame);
  100080. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100081. return false;
  100082. }
  100083. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100084. FLAC__bitwriter_clear(encoder->private_->frame);
  100085. if(samples > 0) {
  100086. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  100087. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  100088. }
  100089. return true;
  100090. }
  100091. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  100092. {
  100093. FLAC__StreamEncoderWriteStatus status;
  100094. FLAC__uint64 output_position = 0;
  100095. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  100096. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  100097. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100098. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100099. }
  100100. /*
  100101. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  100102. */
  100103. if(samples == 0) {
  100104. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  100105. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  100106. encoder->protected_->streaminfo_offset = output_position;
  100107. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  100108. encoder->protected_->seektable_offset = output_position;
  100109. }
  100110. /*
  100111. * Mark the current seek point if hit (if audio_offset == 0 that
  100112. * means we're still writing metadata and haven't hit the first
  100113. * frame yet)
  100114. */
  100115. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  100116. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  100117. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  100118. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  100119. FLAC__uint64 test_sample;
  100120. unsigned i;
  100121. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  100122. test_sample = encoder->private_->seek_table->points[i].sample_number;
  100123. if(test_sample > frame_last_sample) {
  100124. break;
  100125. }
  100126. else if(test_sample >= frame_first_sample) {
  100127. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  100128. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  100129. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  100130. encoder->private_->first_seekpoint_to_check++;
  100131. /* DO NOT: "break;" and here's why:
  100132. * The seektable template may contain more than one target
  100133. * sample for any given frame; we will keep looping, generating
  100134. * duplicate seekpoints for them, and we'll clean it up later,
  100135. * just before writing the seektable back to the metadata.
  100136. */
  100137. }
  100138. else {
  100139. encoder->private_->first_seekpoint_to_check++;
  100140. }
  100141. }
  100142. }
  100143. #if FLAC__HAS_OGG
  100144. if(encoder->private_->is_ogg) {
  100145. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  100146. &encoder->protected_->ogg_encoder_aspect,
  100147. buffer,
  100148. bytes,
  100149. samples,
  100150. encoder->private_->current_frame_number,
  100151. is_last_block,
  100152. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  100153. encoder,
  100154. encoder->private_->client_data
  100155. );
  100156. }
  100157. else
  100158. #endif
  100159. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  100160. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100161. encoder->private_->bytes_written += bytes;
  100162. encoder->private_->samples_written += samples;
  100163. /* we keep a high watermark on the number of frames written because
  100164. * when the encoder goes back to write metadata, 'current_frame'
  100165. * will drop back to 0.
  100166. */
  100167. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  100168. }
  100169. else
  100170. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100171. return status;
  100172. }
  100173. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100174. void update_metadata_(const FLAC__StreamEncoder *encoder)
  100175. {
  100176. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100177. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100178. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100179. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100180. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100181. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  100182. FLAC__StreamEncoderSeekStatus seek_status;
  100183. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100184. /* All this is based on intimate knowledge of the stream header
  100185. * layout, but a change to the header format that would break this
  100186. * would also break all streams encoded in the previous format.
  100187. */
  100188. /*
  100189. * Write MD5 signature
  100190. */
  100191. {
  100192. const unsigned md5_offset =
  100193. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100194. (
  100195. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100196. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100197. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100198. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100199. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100200. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100201. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100202. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100203. ) / 8;
  100204. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100205. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100206. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100207. return;
  100208. }
  100209. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100210. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100211. return;
  100212. }
  100213. }
  100214. /*
  100215. * Write total samples
  100216. */
  100217. {
  100218. const unsigned total_samples_byte_offset =
  100219. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100220. (
  100221. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100222. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100223. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100224. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100225. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100226. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100227. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100228. - 4
  100229. ) / 8;
  100230. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  100231. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100232. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100233. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100234. b[4] = (FLAC__byte)(samples & 0xFF);
  100235. 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) {
  100236. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100237. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100238. return;
  100239. }
  100240. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100241. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100242. return;
  100243. }
  100244. }
  100245. /*
  100246. * Write min/max framesize
  100247. */
  100248. {
  100249. const unsigned min_framesize_offset =
  100250. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100251. (
  100252. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100253. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100254. ) / 8;
  100255. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100256. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100257. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100258. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100259. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100260. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100261. 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) {
  100262. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100263. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100264. return;
  100265. }
  100266. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100267. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100268. return;
  100269. }
  100270. }
  100271. /*
  100272. * Write seektable
  100273. */
  100274. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100275. unsigned i;
  100276. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100277. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100278. 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) {
  100279. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100280. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100281. return;
  100282. }
  100283. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  100284. FLAC__uint64 xx;
  100285. unsigned x;
  100286. xx = encoder->private_->seek_table->points[i].sample_number;
  100287. b[7] = (FLAC__byte)xx; xx >>= 8;
  100288. b[6] = (FLAC__byte)xx; xx >>= 8;
  100289. b[5] = (FLAC__byte)xx; xx >>= 8;
  100290. b[4] = (FLAC__byte)xx; xx >>= 8;
  100291. b[3] = (FLAC__byte)xx; xx >>= 8;
  100292. b[2] = (FLAC__byte)xx; xx >>= 8;
  100293. b[1] = (FLAC__byte)xx; xx >>= 8;
  100294. b[0] = (FLAC__byte)xx; xx >>= 8;
  100295. xx = encoder->private_->seek_table->points[i].stream_offset;
  100296. b[15] = (FLAC__byte)xx; xx >>= 8;
  100297. b[14] = (FLAC__byte)xx; xx >>= 8;
  100298. b[13] = (FLAC__byte)xx; xx >>= 8;
  100299. b[12] = (FLAC__byte)xx; xx >>= 8;
  100300. b[11] = (FLAC__byte)xx; xx >>= 8;
  100301. b[10] = (FLAC__byte)xx; xx >>= 8;
  100302. b[9] = (FLAC__byte)xx; xx >>= 8;
  100303. b[8] = (FLAC__byte)xx; xx >>= 8;
  100304. x = encoder->private_->seek_table->points[i].frame_samples;
  100305. b[17] = (FLAC__byte)x; x >>= 8;
  100306. b[16] = (FLAC__byte)x; x >>= 8;
  100307. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100308. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100309. return;
  100310. }
  100311. }
  100312. }
  100313. }
  100314. #if FLAC__HAS_OGG
  100315. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100316. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  100317. {
  100318. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  100319. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  100320. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  100321. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  100322. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  100323. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  100324. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  100325. FLAC__STREAM_SYNC_LENGTH
  100326. ;
  100327. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100328. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100329. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100330. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100331. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100332. ogg_page page;
  100333. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100334. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  100335. /* Pre-check that client supports seeking, since we don't want the
  100336. * ogg_helper code to ever have to deal with this condition.
  100337. */
  100338. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  100339. return;
  100340. /* All this is based on intimate knowledge of the stream header
  100341. * layout, but a change to the header format that would break this
  100342. * would also break all streams encoded in the previous format.
  100343. */
  100344. /**
  100345. ** Write STREAMINFO stats
  100346. **/
  100347. simple_ogg_page__init(&page);
  100348. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100349. simple_ogg_page__clear(&page);
  100350. return; /* state already set */
  100351. }
  100352. /*
  100353. * Write MD5 signature
  100354. */
  100355. {
  100356. const unsigned md5_offset =
  100357. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100358. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100359. (
  100360. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100361. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100362. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100363. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100364. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100365. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100366. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100367. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100368. ) / 8;
  100369. if(md5_offset + 16 > (unsigned)page.body_len) {
  100370. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100371. simple_ogg_page__clear(&page);
  100372. return;
  100373. }
  100374. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  100375. }
  100376. /*
  100377. * Write total samples
  100378. */
  100379. {
  100380. const unsigned total_samples_byte_offset =
  100381. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100382. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100383. (
  100384. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100385. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100386. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100387. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100388. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100389. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100390. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100391. - 4
  100392. ) / 8;
  100393. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  100394. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100395. simple_ogg_page__clear(&page);
  100396. return;
  100397. }
  100398. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  100399. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  100400. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100401. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100402. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100403. b[4] = (FLAC__byte)(samples & 0xFF);
  100404. memcpy(page.body + total_samples_byte_offset, b, 5);
  100405. }
  100406. /*
  100407. * Write min/max framesize
  100408. */
  100409. {
  100410. const unsigned min_framesize_offset =
  100411. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100412. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100413. (
  100414. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100415. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100416. ) / 8;
  100417. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  100418. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100419. simple_ogg_page__clear(&page);
  100420. return;
  100421. }
  100422. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100423. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100424. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100425. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100426. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100427. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100428. memcpy(page.body + min_framesize_offset, b, 6);
  100429. }
  100430. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100431. simple_ogg_page__clear(&page);
  100432. return; /* state already set */
  100433. }
  100434. simple_ogg_page__clear(&page);
  100435. /*
  100436. * Write seektable
  100437. */
  100438. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100439. unsigned i;
  100440. FLAC__byte *p;
  100441. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100442. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100443. simple_ogg_page__init(&page);
  100444. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100445. simple_ogg_page__clear(&page);
  100446. return; /* state already set */
  100447. }
  100448. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  100449. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100450. simple_ogg_page__clear(&page);
  100451. return;
  100452. }
  100453. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  100454. FLAC__uint64 xx;
  100455. unsigned x;
  100456. xx = encoder->private_->seek_table->points[i].sample_number;
  100457. b[7] = (FLAC__byte)xx; xx >>= 8;
  100458. b[6] = (FLAC__byte)xx; xx >>= 8;
  100459. b[5] = (FLAC__byte)xx; xx >>= 8;
  100460. b[4] = (FLAC__byte)xx; xx >>= 8;
  100461. b[3] = (FLAC__byte)xx; xx >>= 8;
  100462. b[2] = (FLAC__byte)xx; xx >>= 8;
  100463. b[1] = (FLAC__byte)xx; xx >>= 8;
  100464. b[0] = (FLAC__byte)xx; xx >>= 8;
  100465. xx = encoder->private_->seek_table->points[i].stream_offset;
  100466. b[15] = (FLAC__byte)xx; xx >>= 8;
  100467. b[14] = (FLAC__byte)xx; xx >>= 8;
  100468. b[13] = (FLAC__byte)xx; xx >>= 8;
  100469. b[12] = (FLAC__byte)xx; xx >>= 8;
  100470. b[11] = (FLAC__byte)xx; xx >>= 8;
  100471. b[10] = (FLAC__byte)xx; xx >>= 8;
  100472. b[9] = (FLAC__byte)xx; xx >>= 8;
  100473. b[8] = (FLAC__byte)xx; xx >>= 8;
  100474. x = encoder->private_->seek_table->points[i].frame_samples;
  100475. b[17] = (FLAC__byte)x; x >>= 8;
  100476. b[16] = (FLAC__byte)x; x >>= 8;
  100477. memcpy(p, b, 18);
  100478. }
  100479. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100480. simple_ogg_page__clear(&page);
  100481. return; /* state already set */
  100482. }
  100483. simple_ogg_page__clear(&page);
  100484. }
  100485. }
  100486. #endif
  100487. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  100488. {
  100489. FLAC__uint16 crc;
  100490. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100491. /*
  100492. * Accumulate raw signal to the MD5 signature
  100493. */
  100494. 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)) {
  100495. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100496. return false;
  100497. }
  100498. /*
  100499. * Process the frame header and subframes into the frame bitbuffer
  100500. */
  100501. if(!process_subframes_(encoder, is_fractional_block)) {
  100502. /* the above function sets the state for us in case of an error */
  100503. return false;
  100504. }
  100505. /*
  100506. * Zero-pad the frame to a byte_boundary
  100507. */
  100508. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  100509. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100510. return false;
  100511. }
  100512. /*
  100513. * CRC-16 the whole thing
  100514. */
  100515. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100516. if(
  100517. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  100518. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  100519. ) {
  100520. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100521. return false;
  100522. }
  100523. /*
  100524. * Write it
  100525. */
  100526. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  100527. /* the above function sets the state for us in case of an error */
  100528. return false;
  100529. }
  100530. /*
  100531. * Get ready for the next frame
  100532. */
  100533. encoder->private_->current_sample_number = 0;
  100534. encoder->private_->current_frame_number++;
  100535. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  100536. return true;
  100537. }
  100538. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  100539. {
  100540. FLAC__FrameHeader frame_header;
  100541. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  100542. FLAC__bool do_independent, do_mid_side;
  100543. /*
  100544. * Calculate the min,max Rice partition orders
  100545. */
  100546. if(is_fractional_block) {
  100547. max_partition_order = 0;
  100548. }
  100549. else {
  100550. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  100551. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  100552. }
  100553. min_partition_order = min(min_partition_order, max_partition_order);
  100554. /*
  100555. * Setup the frame
  100556. */
  100557. frame_header.blocksize = encoder->protected_->blocksize;
  100558. frame_header.sample_rate = encoder->protected_->sample_rate;
  100559. frame_header.channels = encoder->protected_->channels;
  100560. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  100561. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  100562. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100563. frame_header.number.frame_number = encoder->private_->current_frame_number;
  100564. /*
  100565. * Figure out what channel assignments to try
  100566. */
  100567. if(encoder->protected_->do_mid_side_stereo) {
  100568. if(encoder->protected_->loose_mid_side_stereo) {
  100569. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  100570. do_independent = true;
  100571. do_mid_side = true;
  100572. }
  100573. else {
  100574. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  100575. do_mid_side = !do_independent;
  100576. }
  100577. }
  100578. else {
  100579. do_independent = true;
  100580. do_mid_side = true;
  100581. }
  100582. }
  100583. else {
  100584. do_independent = true;
  100585. do_mid_side = false;
  100586. }
  100587. FLAC__ASSERT(do_independent || do_mid_side);
  100588. /*
  100589. * Check for wasted bits; set effective bps for each subframe
  100590. */
  100591. if(do_independent) {
  100592. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100593. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  100594. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  100595. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  100596. }
  100597. }
  100598. if(do_mid_side) {
  100599. FLAC__ASSERT(encoder->protected_->channels == 2);
  100600. for(channel = 0; channel < 2; channel++) {
  100601. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  100602. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  100603. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  100604. }
  100605. }
  100606. /*
  100607. * First do a normal encoding pass of each independent channel
  100608. */
  100609. if(do_independent) {
  100610. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100611. if(!
  100612. process_subframe_(
  100613. encoder,
  100614. min_partition_order,
  100615. max_partition_order,
  100616. &frame_header,
  100617. encoder->private_->subframe_bps[channel],
  100618. encoder->private_->integer_signal[channel],
  100619. encoder->private_->subframe_workspace_ptr[channel],
  100620. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  100621. encoder->private_->residual_workspace[channel],
  100622. encoder->private_->best_subframe+channel,
  100623. encoder->private_->best_subframe_bits+channel
  100624. )
  100625. )
  100626. return false;
  100627. }
  100628. }
  100629. /*
  100630. * Now do mid and side channels if requested
  100631. */
  100632. if(do_mid_side) {
  100633. FLAC__ASSERT(encoder->protected_->channels == 2);
  100634. for(channel = 0; channel < 2; channel++) {
  100635. if(!
  100636. process_subframe_(
  100637. encoder,
  100638. min_partition_order,
  100639. max_partition_order,
  100640. &frame_header,
  100641. encoder->private_->subframe_bps_mid_side[channel],
  100642. encoder->private_->integer_signal_mid_side[channel],
  100643. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  100644. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  100645. encoder->private_->residual_workspace_mid_side[channel],
  100646. encoder->private_->best_subframe_mid_side+channel,
  100647. encoder->private_->best_subframe_bits_mid_side+channel
  100648. )
  100649. )
  100650. return false;
  100651. }
  100652. }
  100653. /*
  100654. * Compose the frame bitbuffer
  100655. */
  100656. if(do_mid_side) {
  100657. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  100658. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  100659. FLAC__ChannelAssignment channel_assignment;
  100660. FLAC__ASSERT(encoder->protected_->channels == 2);
  100661. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  100662. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  100663. }
  100664. else {
  100665. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  100666. unsigned min_bits;
  100667. int ca;
  100668. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  100669. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  100670. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  100671. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  100672. FLAC__ASSERT(do_independent && do_mid_side);
  100673. /* We have to figure out which channel assignent results in the smallest frame */
  100674. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  100675. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  100676. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  100677. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  100678. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100679. min_bits = bits[channel_assignment];
  100680. for(ca = 1; ca <= 3; ca++) {
  100681. if(bits[ca] < min_bits) {
  100682. min_bits = bits[ca];
  100683. channel_assignment = (FLAC__ChannelAssignment)ca;
  100684. }
  100685. }
  100686. }
  100687. frame_header.channel_assignment = channel_assignment;
  100688. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100689. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100690. return false;
  100691. }
  100692. switch(channel_assignment) {
  100693. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100694. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100695. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100696. break;
  100697. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100698. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100699. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100700. break;
  100701. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100702. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100703. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100704. break;
  100705. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100706. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  100707. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100708. break;
  100709. default:
  100710. FLAC__ASSERT(0);
  100711. }
  100712. switch(channel_assignment) {
  100713. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100714. left_bps = encoder->private_->subframe_bps [0];
  100715. right_bps = encoder->private_->subframe_bps [1];
  100716. break;
  100717. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100718. left_bps = encoder->private_->subframe_bps [0];
  100719. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100720. break;
  100721. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100722. left_bps = encoder->private_->subframe_bps_mid_side[1];
  100723. right_bps = encoder->private_->subframe_bps [1];
  100724. break;
  100725. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100726. left_bps = encoder->private_->subframe_bps_mid_side[0];
  100727. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100728. break;
  100729. default:
  100730. FLAC__ASSERT(0);
  100731. }
  100732. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  100733. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  100734. return false;
  100735. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  100736. return false;
  100737. }
  100738. else {
  100739. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100740. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100741. return false;
  100742. }
  100743. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100744. 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)) {
  100745. /* the above function sets the state for us in case of an error */
  100746. return false;
  100747. }
  100748. }
  100749. }
  100750. if(encoder->protected_->loose_mid_side_stereo) {
  100751. encoder->private_->loose_mid_side_stereo_frame_count++;
  100752. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  100753. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  100754. }
  100755. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  100756. return true;
  100757. }
  100758. FLAC__bool process_subframe_(
  100759. FLAC__StreamEncoder *encoder,
  100760. unsigned min_partition_order,
  100761. unsigned max_partition_order,
  100762. const FLAC__FrameHeader *frame_header,
  100763. unsigned subframe_bps,
  100764. const FLAC__int32 integer_signal[],
  100765. FLAC__Subframe *subframe[2],
  100766. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  100767. FLAC__int32 *residual[2],
  100768. unsigned *best_subframe,
  100769. unsigned *best_bits
  100770. )
  100771. {
  100772. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100773. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100774. #else
  100775. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100776. #endif
  100777. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100778. FLAC__double lpc_residual_bits_per_sample;
  100779. 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 */
  100780. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  100781. unsigned min_lpc_order, max_lpc_order, lpc_order;
  100782. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  100783. #endif
  100784. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  100785. unsigned rice_parameter;
  100786. unsigned _candidate_bits, _best_bits;
  100787. unsigned _best_subframe;
  100788. /* only use RICE2 partitions if stream bps > 16 */
  100789. 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;
  100790. FLAC__ASSERT(frame_header->blocksize > 0);
  100791. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  100792. _best_subframe = 0;
  100793. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  100794. _best_bits = UINT_MAX;
  100795. else
  100796. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100797. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  100798. unsigned signal_is_constant = false;
  100799. 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);
  100800. /* check for constant subframe */
  100801. if(
  100802. !encoder->private_->disable_constant_subframes &&
  100803. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100804. fixed_residual_bits_per_sample[1] == 0.0
  100805. #else
  100806. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  100807. #endif
  100808. ) {
  100809. /* the above means it's possible all samples are the same value; now double-check it: */
  100810. unsigned i;
  100811. signal_is_constant = true;
  100812. for(i = 1; i < frame_header->blocksize; i++) {
  100813. if(integer_signal[0] != integer_signal[i]) {
  100814. signal_is_constant = false;
  100815. break;
  100816. }
  100817. }
  100818. }
  100819. if(signal_is_constant) {
  100820. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  100821. if(_candidate_bits < _best_bits) {
  100822. _best_subframe = !_best_subframe;
  100823. _best_bits = _candidate_bits;
  100824. }
  100825. }
  100826. else {
  100827. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  100828. /* encode fixed */
  100829. if(encoder->protected_->do_exhaustive_model_search) {
  100830. min_fixed_order = 0;
  100831. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  100832. }
  100833. else {
  100834. min_fixed_order = max_fixed_order = guess_fixed_order;
  100835. }
  100836. if(max_fixed_order >= frame_header->blocksize)
  100837. max_fixed_order = frame_header->blocksize - 1;
  100838. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  100839. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100840. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  100841. continue; /* don't even try */
  100842. 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 */
  100843. #else
  100844. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  100845. continue; /* don't even try */
  100846. 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 */
  100847. #endif
  100848. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100849. if(rice_parameter >= rice_parameter_limit) {
  100850. #ifdef DEBUG_VERBOSE
  100851. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  100852. #endif
  100853. rice_parameter = rice_parameter_limit - 1;
  100854. }
  100855. _candidate_bits =
  100856. evaluate_fixed_subframe_(
  100857. encoder,
  100858. integer_signal,
  100859. residual[!_best_subframe],
  100860. encoder->private_->abs_residual_partition_sums,
  100861. encoder->private_->raw_bits_per_partition,
  100862. frame_header->blocksize,
  100863. subframe_bps,
  100864. fixed_order,
  100865. rice_parameter,
  100866. rice_parameter_limit,
  100867. min_partition_order,
  100868. max_partition_order,
  100869. encoder->protected_->do_escape_coding,
  100870. encoder->protected_->rice_parameter_search_dist,
  100871. subframe[!_best_subframe],
  100872. partitioned_rice_contents[!_best_subframe]
  100873. );
  100874. if(_candidate_bits < _best_bits) {
  100875. _best_subframe = !_best_subframe;
  100876. _best_bits = _candidate_bits;
  100877. }
  100878. }
  100879. }
  100880. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100881. /* encode lpc */
  100882. if(encoder->protected_->max_lpc_order > 0) {
  100883. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  100884. max_lpc_order = frame_header->blocksize-1;
  100885. else
  100886. max_lpc_order = encoder->protected_->max_lpc_order;
  100887. if(max_lpc_order > 0) {
  100888. unsigned a;
  100889. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  100890. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  100891. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  100892. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  100893. if(autoc[0] != 0.0) {
  100894. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  100895. if(encoder->protected_->do_exhaustive_model_search) {
  100896. min_lpc_order = 1;
  100897. }
  100898. else {
  100899. const unsigned guess_lpc_order =
  100900. FLAC__lpc_compute_best_order(
  100901. lpc_error,
  100902. max_lpc_order,
  100903. frame_header->blocksize,
  100904. subframe_bps + (
  100905. encoder->protected_->do_qlp_coeff_prec_search?
  100906. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  100907. encoder->protected_->qlp_coeff_precision
  100908. )
  100909. );
  100910. min_lpc_order = max_lpc_order = guess_lpc_order;
  100911. }
  100912. if(max_lpc_order >= frame_header->blocksize)
  100913. max_lpc_order = frame_header->blocksize - 1;
  100914. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  100915. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  100916. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  100917. continue; /* don't even try */
  100918. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  100919. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100920. if(rice_parameter >= rice_parameter_limit) {
  100921. #ifdef DEBUG_VERBOSE
  100922. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  100923. #endif
  100924. rice_parameter = rice_parameter_limit - 1;
  100925. }
  100926. if(encoder->protected_->do_qlp_coeff_prec_search) {
  100927. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  100928. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  100929. if(subframe_bps <= 17) {
  100930. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  100931. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  100932. }
  100933. else
  100934. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  100935. }
  100936. else {
  100937. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  100938. }
  100939. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  100940. _candidate_bits =
  100941. evaluate_lpc_subframe_(
  100942. encoder,
  100943. integer_signal,
  100944. residual[!_best_subframe],
  100945. encoder->private_->abs_residual_partition_sums,
  100946. encoder->private_->raw_bits_per_partition,
  100947. encoder->private_->lp_coeff[lpc_order-1],
  100948. frame_header->blocksize,
  100949. subframe_bps,
  100950. lpc_order,
  100951. qlp_coeff_precision,
  100952. rice_parameter,
  100953. rice_parameter_limit,
  100954. min_partition_order,
  100955. max_partition_order,
  100956. encoder->protected_->do_escape_coding,
  100957. encoder->protected_->rice_parameter_search_dist,
  100958. subframe[!_best_subframe],
  100959. partitioned_rice_contents[!_best_subframe]
  100960. );
  100961. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  100962. if(_candidate_bits < _best_bits) {
  100963. _best_subframe = !_best_subframe;
  100964. _best_bits = _candidate_bits;
  100965. }
  100966. }
  100967. }
  100968. }
  100969. }
  100970. }
  100971. }
  100972. }
  100973. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100974. }
  100975. }
  100976. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  100977. if(_best_bits == UINT_MAX) {
  100978. FLAC__ASSERT(_best_subframe == 0);
  100979. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100980. }
  100981. *best_subframe = _best_subframe;
  100982. *best_bits = _best_bits;
  100983. return true;
  100984. }
  100985. FLAC__bool add_subframe_(
  100986. FLAC__StreamEncoder *encoder,
  100987. unsigned blocksize,
  100988. unsigned subframe_bps,
  100989. const FLAC__Subframe *subframe,
  100990. FLAC__BitWriter *frame
  100991. )
  100992. {
  100993. switch(subframe->type) {
  100994. case FLAC__SUBFRAME_TYPE_CONSTANT:
  100995. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  100996. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100997. return false;
  100998. }
  100999. break;
  101000. case FLAC__SUBFRAME_TYPE_FIXED:
  101001. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  101002. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101003. return false;
  101004. }
  101005. break;
  101006. case FLAC__SUBFRAME_TYPE_LPC:
  101007. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  101008. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101009. return false;
  101010. }
  101011. break;
  101012. case FLAC__SUBFRAME_TYPE_VERBATIM:
  101013. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  101014. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101015. return false;
  101016. }
  101017. break;
  101018. default:
  101019. FLAC__ASSERT(0);
  101020. }
  101021. return true;
  101022. }
  101023. #define SPOTCHECK_ESTIMATE 0
  101024. #if SPOTCHECK_ESTIMATE
  101025. static void spotcheck_subframe_estimate_(
  101026. FLAC__StreamEncoder *encoder,
  101027. unsigned blocksize,
  101028. unsigned subframe_bps,
  101029. const FLAC__Subframe *subframe,
  101030. unsigned estimate
  101031. )
  101032. {
  101033. FLAC__bool ret;
  101034. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  101035. if(frame == 0) {
  101036. fprintf(stderr, "EST: can't allocate frame\n");
  101037. return;
  101038. }
  101039. if(!FLAC__bitwriter_init(frame)) {
  101040. fprintf(stderr, "EST: can't init frame\n");
  101041. return;
  101042. }
  101043. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  101044. FLAC__ASSERT(ret);
  101045. {
  101046. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  101047. if(estimate != actual)
  101048. 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);
  101049. }
  101050. FLAC__bitwriter_delete(frame);
  101051. }
  101052. #endif
  101053. unsigned evaluate_constant_subframe_(
  101054. FLAC__StreamEncoder *encoder,
  101055. const FLAC__int32 signal,
  101056. unsigned blocksize,
  101057. unsigned subframe_bps,
  101058. FLAC__Subframe *subframe
  101059. )
  101060. {
  101061. unsigned estimate;
  101062. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101063. subframe->data.constant.value = signal;
  101064. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  101065. #if SPOTCHECK_ESTIMATE
  101066. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101067. #else
  101068. (void)encoder, (void)blocksize;
  101069. #endif
  101070. return estimate;
  101071. }
  101072. unsigned evaluate_fixed_subframe_(
  101073. FLAC__StreamEncoder *encoder,
  101074. const FLAC__int32 signal[],
  101075. FLAC__int32 residual[],
  101076. FLAC__uint64 abs_residual_partition_sums[],
  101077. unsigned raw_bits_per_partition[],
  101078. unsigned blocksize,
  101079. unsigned subframe_bps,
  101080. unsigned order,
  101081. unsigned rice_parameter,
  101082. unsigned rice_parameter_limit,
  101083. unsigned min_partition_order,
  101084. unsigned max_partition_order,
  101085. FLAC__bool do_escape_coding,
  101086. unsigned rice_parameter_search_dist,
  101087. FLAC__Subframe *subframe,
  101088. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101089. )
  101090. {
  101091. unsigned i, residual_bits, estimate;
  101092. const unsigned residual_samples = blocksize - order;
  101093. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  101094. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  101095. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101096. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101097. subframe->data.fixed.residual = residual;
  101098. residual_bits =
  101099. find_best_partition_order_(
  101100. encoder->private_,
  101101. residual,
  101102. abs_residual_partition_sums,
  101103. raw_bits_per_partition,
  101104. residual_samples,
  101105. order,
  101106. rice_parameter,
  101107. rice_parameter_limit,
  101108. min_partition_order,
  101109. max_partition_order,
  101110. subframe_bps,
  101111. do_escape_coding,
  101112. rice_parameter_search_dist,
  101113. &subframe->data.fixed.entropy_coding_method
  101114. );
  101115. subframe->data.fixed.order = order;
  101116. for(i = 0; i < order; i++)
  101117. subframe->data.fixed.warmup[i] = signal[i];
  101118. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  101119. #if SPOTCHECK_ESTIMATE
  101120. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101121. #endif
  101122. return estimate;
  101123. }
  101124. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101125. unsigned evaluate_lpc_subframe_(
  101126. FLAC__StreamEncoder *encoder,
  101127. const FLAC__int32 signal[],
  101128. FLAC__int32 residual[],
  101129. FLAC__uint64 abs_residual_partition_sums[],
  101130. unsigned raw_bits_per_partition[],
  101131. const FLAC__real lp_coeff[],
  101132. unsigned blocksize,
  101133. unsigned subframe_bps,
  101134. unsigned order,
  101135. unsigned qlp_coeff_precision,
  101136. unsigned rice_parameter,
  101137. unsigned rice_parameter_limit,
  101138. unsigned min_partition_order,
  101139. unsigned max_partition_order,
  101140. FLAC__bool do_escape_coding,
  101141. unsigned rice_parameter_search_dist,
  101142. FLAC__Subframe *subframe,
  101143. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101144. )
  101145. {
  101146. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  101147. unsigned i, residual_bits, estimate;
  101148. int quantization, ret;
  101149. const unsigned residual_samples = blocksize - order;
  101150. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  101151. if(subframe_bps <= 16) {
  101152. FLAC__ASSERT(order > 0);
  101153. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  101154. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  101155. }
  101156. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  101157. if(ret != 0)
  101158. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  101159. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101160. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  101161. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101162. else
  101163. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101164. else
  101165. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101166. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  101167. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101168. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101169. subframe->data.lpc.residual = residual;
  101170. residual_bits =
  101171. find_best_partition_order_(
  101172. encoder->private_,
  101173. residual,
  101174. abs_residual_partition_sums,
  101175. raw_bits_per_partition,
  101176. residual_samples,
  101177. order,
  101178. rice_parameter,
  101179. rice_parameter_limit,
  101180. min_partition_order,
  101181. max_partition_order,
  101182. subframe_bps,
  101183. do_escape_coding,
  101184. rice_parameter_search_dist,
  101185. &subframe->data.lpc.entropy_coding_method
  101186. );
  101187. subframe->data.lpc.order = order;
  101188. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  101189. subframe->data.lpc.quantization_level = quantization;
  101190. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  101191. for(i = 0; i < order; i++)
  101192. subframe->data.lpc.warmup[i] = signal[i];
  101193. 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;
  101194. #if SPOTCHECK_ESTIMATE
  101195. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101196. #endif
  101197. return estimate;
  101198. }
  101199. #endif
  101200. unsigned evaluate_verbatim_subframe_(
  101201. FLAC__StreamEncoder *encoder,
  101202. const FLAC__int32 signal[],
  101203. unsigned blocksize,
  101204. unsigned subframe_bps,
  101205. FLAC__Subframe *subframe
  101206. )
  101207. {
  101208. unsigned estimate;
  101209. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101210. subframe->data.verbatim.data = signal;
  101211. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  101212. #if SPOTCHECK_ESTIMATE
  101213. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101214. #else
  101215. (void)encoder;
  101216. #endif
  101217. return estimate;
  101218. }
  101219. unsigned find_best_partition_order_(
  101220. FLAC__StreamEncoderPrivate *private_,
  101221. const FLAC__int32 residual[],
  101222. FLAC__uint64 abs_residual_partition_sums[],
  101223. unsigned raw_bits_per_partition[],
  101224. unsigned residual_samples,
  101225. unsigned predictor_order,
  101226. unsigned rice_parameter,
  101227. unsigned rice_parameter_limit,
  101228. unsigned min_partition_order,
  101229. unsigned max_partition_order,
  101230. unsigned bps,
  101231. FLAC__bool do_escape_coding,
  101232. unsigned rice_parameter_search_dist,
  101233. FLAC__EntropyCodingMethod *best_ecm
  101234. )
  101235. {
  101236. unsigned residual_bits, best_residual_bits = 0;
  101237. unsigned best_parameters_index = 0;
  101238. unsigned best_partition_order = 0;
  101239. const unsigned blocksize = residual_samples + predictor_order;
  101240. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  101241. min_partition_order = min(min_partition_order, max_partition_order);
  101242. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  101243. if(do_escape_coding)
  101244. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  101245. {
  101246. int partition_order;
  101247. unsigned sum;
  101248. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  101249. if(!
  101250. set_partitioned_rice_(
  101251. #ifdef EXACT_RICE_BITS_CALCULATION
  101252. residual,
  101253. #endif
  101254. abs_residual_partition_sums+sum,
  101255. raw_bits_per_partition+sum,
  101256. residual_samples,
  101257. predictor_order,
  101258. rice_parameter,
  101259. rice_parameter_limit,
  101260. rice_parameter_search_dist,
  101261. (unsigned)partition_order,
  101262. do_escape_coding,
  101263. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  101264. &residual_bits
  101265. )
  101266. )
  101267. {
  101268. FLAC__ASSERT(best_residual_bits != 0);
  101269. break;
  101270. }
  101271. sum += 1u << partition_order;
  101272. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  101273. best_residual_bits = residual_bits;
  101274. best_parameters_index = !best_parameters_index;
  101275. best_partition_order = partition_order;
  101276. }
  101277. }
  101278. }
  101279. best_ecm->data.partitioned_rice.order = best_partition_order;
  101280. {
  101281. /*
  101282. * We are allowed to de-const the pointer based on our special
  101283. * knowledge; it is const to the outside world.
  101284. */
  101285. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  101286. unsigned partition;
  101287. /* save best parameters and raw_bits */
  101288. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  101289. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  101290. if(do_escape_coding)
  101291. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  101292. /*
  101293. * Now need to check if the type should be changed to
  101294. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  101295. * size of the rice parameters.
  101296. */
  101297. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  101298. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  101299. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  101300. break;
  101301. }
  101302. }
  101303. }
  101304. return best_residual_bits;
  101305. }
  101306. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101307. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  101308. const FLAC__int32 residual[],
  101309. FLAC__uint64 abs_residual_partition_sums[],
  101310. unsigned blocksize,
  101311. unsigned predictor_order,
  101312. unsigned min_partition_order,
  101313. unsigned max_partition_order
  101314. );
  101315. #endif
  101316. void precompute_partition_info_sums_(
  101317. const FLAC__int32 residual[],
  101318. FLAC__uint64 abs_residual_partition_sums[],
  101319. unsigned residual_samples,
  101320. unsigned predictor_order,
  101321. unsigned min_partition_order,
  101322. unsigned max_partition_order,
  101323. unsigned bps
  101324. )
  101325. {
  101326. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  101327. unsigned partitions = 1u << max_partition_order;
  101328. FLAC__ASSERT(default_partition_samples > predictor_order);
  101329. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101330. /* slightly pessimistic but still catches all common cases */
  101331. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101332. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101333. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  101334. return;
  101335. }
  101336. #endif
  101337. /* first do max_partition_order */
  101338. {
  101339. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  101340. /* slightly pessimistic but still catches all common cases */
  101341. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101342. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101343. FLAC__uint32 abs_residual_partition_sum;
  101344. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101345. end += default_partition_samples;
  101346. abs_residual_partition_sum = 0;
  101347. for( ; residual_sample < end; residual_sample++)
  101348. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101349. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101350. }
  101351. }
  101352. else { /* have to pessimistically use 64 bits for accumulator */
  101353. FLAC__uint64 abs_residual_partition_sum;
  101354. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101355. end += default_partition_samples;
  101356. abs_residual_partition_sum = 0;
  101357. for( ; residual_sample < end; residual_sample++)
  101358. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101359. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101360. }
  101361. }
  101362. }
  101363. /* now merge partitions for lower orders */
  101364. {
  101365. unsigned from_partition = 0, to_partition = partitions;
  101366. int partition_order;
  101367. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  101368. unsigned i;
  101369. partitions >>= 1;
  101370. for(i = 0; i < partitions; i++) {
  101371. abs_residual_partition_sums[to_partition++] =
  101372. abs_residual_partition_sums[from_partition ] +
  101373. abs_residual_partition_sums[from_partition+1];
  101374. from_partition += 2;
  101375. }
  101376. }
  101377. }
  101378. }
  101379. void precompute_partition_info_escapes_(
  101380. const FLAC__int32 residual[],
  101381. unsigned raw_bits_per_partition[],
  101382. unsigned residual_samples,
  101383. unsigned predictor_order,
  101384. unsigned min_partition_order,
  101385. unsigned max_partition_order
  101386. )
  101387. {
  101388. int partition_order;
  101389. unsigned from_partition, to_partition = 0;
  101390. const unsigned blocksize = residual_samples + predictor_order;
  101391. /* first do max_partition_order */
  101392. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  101393. FLAC__int32 r;
  101394. FLAC__uint32 rmax;
  101395. unsigned partition, partition_sample, partition_samples, residual_sample;
  101396. const unsigned partitions = 1u << partition_order;
  101397. const unsigned default_partition_samples = blocksize >> partition_order;
  101398. FLAC__ASSERT(default_partition_samples > predictor_order);
  101399. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101400. partition_samples = default_partition_samples;
  101401. if(partition == 0)
  101402. partition_samples -= predictor_order;
  101403. rmax = 0;
  101404. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  101405. r = residual[residual_sample++];
  101406. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  101407. if(r < 0)
  101408. rmax |= ~r;
  101409. else
  101410. rmax |= r;
  101411. }
  101412. /* now we know all residual values are in the range [-rmax-1,rmax] */
  101413. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  101414. }
  101415. to_partition = partitions;
  101416. break; /*@@@ yuck, should remove the 'for' loop instead */
  101417. }
  101418. /* now merge partitions for lower orders */
  101419. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  101420. unsigned m;
  101421. unsigned i;
  101422. const unsigned partitions = 1u << partition_order;
  101423. for(i = 0; i < partitions; i++) {
  101424. m = raw_bits_per_partition[from_partition];
  101425. from_partition++;
  101426. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  101427. from_partition++;
  101428. to_partition++;
  101429. }
  101430. }
  101431. }
  101432. #ifdef EXACT_RICE_BITS_CALCULATION
  101433. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101434. const unsigned rice_parameter,
  101435. const unsigned partition_samples,
  101436. const FLAC__int32 *residual
  101437. )
  101438. {
  101439. unsigned i, partition_bits =
  101440. 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 */
  101441. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  101442. ;
  101443. for(i = 0; i < partition_samples; i++)
  101444. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  101445. return partition_bits;
  101446. }
  101447. #else
  101448. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101449. const unsigned rice_parameter,
  101450. const unsigned partition_samples,
  101451. const FLAC__uint64 abs_residual_partition_sum
  101452. )
  101453. {
  101454. return
  101455. 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 */
  101456. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  101457. (
  101458. rice_parameter?
  101459. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  101460. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  101461. )
  101462. - (partition_samples >> 1)
  101463. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  101464. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  101465. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  101466. * So the subtraction term tries to guess how many extra bits were contributed.
  101467. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  101468. */
  101469. ;
  101470. }
  101471. #endif
  101472. FLAC__bool set_partitioned_rice_(
  101473. #ifdef EXACT_RICE_BITS_CALCULATION
  101474. const FLAC__int32 residual[],
  101475. #endif
  101476. const FLAC__uint64 abs_residual_partition_sums[],
  101477. const unsigned raw_bits_per_partition[],
  101478. const unsigned residual_samples,
  101479. const unsigned predictor_order,
  101480. const unsigned suggested_rice_parameter,
  101481. const unsigned rice_parameter_limit,
  101482. const unsigned rice_parameter_search_dist,
  101483. const unsigned partition_order,
  101484. const FLAC__bool search_for_escapes,
  101485. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101486. unsigned *bits
  101487. )
  101488. {
  101489. unsigned rice_parameter, partition_bits;
  101490. unsigned best_partition_bits, best_rice_parameter = 0;
  101491. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  101492. unsigned *parameters, *raw_bits;
  101493. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101494. unsigned min_rice_parameter, max_rice_parameter;
  101495. #else
  101496. (void)rice_parameter_search_dist;
  101497. #endif
  101498. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101499. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101500. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  101501. parameters = partitioned_rice_contents->parameters;
  101502. raw_bits = partitioned_rice_contents->raw_bits;
  101503. if(partition_order == 0) {
  101504. best_partition_bits = (unsigned)(-1);
  101505. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101506. if(rice_parameter_search_dist) {
  101507. if(suggested_rice_parameter < rice_parameter_search_dist)
  101508. min_rice_parameter = 0;
  101509. else
  101510. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  101511. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  101512. if(max_rice_parameter >= rice_parameter_limit) {
  101513. #ifdef DEBUG_VERBOSE
  101514. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  101515. #endif
  101516. max_rice_parameter = rice_parameter_limit - 1;
  101517. }
  101518. }
  101519. else
  101520. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  101521. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101522. #else
  101523. rice_parameter = suggested_rice_parameter;
  101524. #endif
  101525. #ifdef EXACT_RICE_BITS_CALCULATION
  101526. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  101527. #else
  101528. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  101529. #endif
  101530. if(partition_bits < best_partition_bits) {
  101531. best_rice_parameter = rice_parameter;
  101532. best_partition_bits = partition_bits;
  101533. }
  101534. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101535. }
  101536. #endif
  101537. if(search_for_escapes) {
  101538. 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;
  101539. if(partition_bits <= best_partition_bits) {
  101540. raw_bits[0] = raw_bits_per_partition[0];
  101541. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101542. best_partition_bits = partition_bits;
  101543. }
  101544. else
  101545. raw_bits[0] = 0;
  101546. }
  101547. parameters[0] = best_rice_parameter;
  101548. bits_ += best_partition_bits;
  101549. }
  101550. else {
  101551. unsigned partition, residual_sample;
  101552. unsigned partition_samples;
  101553. FLAC__uint64 mean, k;
  101554. const unsigned partitions = 1u << partition_order;
  101555. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101556. partition_samples = (residual_samples+predictor_order) >> partition_order;
  101557. if(partition == 0) {
  101558. if(partition_samples <= predictor_order)
  101559. return false;
  101560. else
  101561. partition_samples -= predictor_order;
  101562. }
  101563. mean = abs_residual_partition_sums[partition];
  101564. /* we are basically calculating the size in bits of the
  101565. * average residual magnitude in the partition:
  101566. * rice_parameter = floor(log2(mean/partition_samples))
  101567. * 'mean' is not a good name for the variable, it is
  101568. * actually the sum of magnitudes of all residual values
  101569. * in the partition, so the actual mean is
  101570. * mean/partition_samples
  101571. */
  101572. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  101573. ;
  101574. if(rice_parameter >= rice_parameter_limit) {
  101575. #ifdef DEBUG_VERBOSE
  101576. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  101577. #endif
  101578. rice_parameter = rice_parameter_limit - 1;
  101579. }
  101580. best_partition_bits = (unsigned)(-1);
  101581. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101582. if(rice_parameter_search_dist) {
  101583. if(rice_parameter < rice_parameter_search_dist)
  101584. min_rice_parameter = 0;
  101585. else
  101586. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  101587. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  101588. if(max_rice_parameter >= rice_parameter_limit) {
  101589. #ifdef DEBUG_VERBOSE
  101590. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  101591. #endif
  101592. max_rice_parameter = rice_parameter_limit - 1;
  101593. }
  101594. }
  101595. else
  101596. min_rice_parameter = max_rice_parameter = rice_parameter;
  101597. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101598. #endif
  101599. #ifdef EXACT_RICE_BITS_CALCULATION
  101600. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  101601. #else
  101602. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  101603. #endif
  101604. if(partition_bits < best_partition_bits) {
  101605. best_rice_parameter = rice_parameter;
  101606. best_partition_bits = partition_bits;
  101607. }
  101608. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101609. }
  101610. #endif
  101611. if(search_for_escapes) {
  101612. 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;
  101613. if(partition_bits <= best_partition_bits) {
  101614. raw_bits[partition] = raw_bits_per_partition[partition];
  101615. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101616. best_partition_bits = partition_bits;
  101617. }
  101618. else
  101619. raw_bits[partition] = 0;
  101620. }
  101621. parameters[partition] = best_rice_parameter;
  101622. bits_ += best_partition_bits;
  101623. residual_sample += partition_samples;
  101624. }
  101625. }
  101626. *bits = bits_;
  101627. return true;
  101628. }
  101629. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  101630. {
  101631. unsigned i, shift;
  101632. FLAC__int32 x = 0;
  101633. for(i = 0; i < samples && !(x&1); i++)
  101634. x |= signal[i];
  101635. if(x == 0) {
  101636. shift = 0;
  101637. }
  101638. else {
  101639. for(shift = 0; !(x&1); shift++)
  101640. x >>= 1;
  101641. }
  101642. if(shift > 0) {
  101643. for(i = 0; i < samples; i++)
  101644. signal[i] >>= shift;
  101645. }
  101646. return shift;
  101647. }
  101648. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101649. {
  101650. unsigned channel;
  101651. for(channel = 0; channel < channels; channel++)
  101652. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  101653. fifo->tail += wide_samples;
  101654. FLAC__ASSERT(fifo->tail <= fifo->size);
  101655. }
  101656. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101657. {
  101658. unsigned channel;
  101659. unsigned sample, wide_sample;
  101660. unsigned tail = fifo->tail;
  101661. sample = input_offset * channels;
  101662. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  101663. for(channel = 0; channel < channels; channel++)
  101664. fifo->data[channel][tail] = input[sample++];
  101665. tail++;
  101666. }
  101667. fifo->tail = tail;
  101668. FLAC__ASSERT(fifo->tail <= fifo->size);
  101669. }
  101670. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101671. {
  101672. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101673. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  101674. (void)decoder;
  101675. if(encoder->private_->verify.needs_magic_hack) {
  101676. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  101677. *bytes = FLAC__STREAM_SYNC_LENGTH;
  101678. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  101679. encoder->private_->verify.needs_magic_hack = false;
  101680. }
  101681. else {
  101682. if(encoded_bytes == 0) {
  101683. /*
  101684. * If we get here, a FIFO underflow has occurred,
  101685. * which means there is a bug somewhere.
  101686. */
  101687. FLAC__ASSERT(0);
  101688. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101689. }
  101690. else if(encoded_bytes < *bytes)
  101691. *bytes = encoded_bytes;
  101692. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  101693. encoder->private_->verify.output.data += *bytes;
  101694. encoder->private_->verify.output.bytes -= *bytes;
  101695. }
  101696. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101697. }
  101698. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  101699. {
  101700. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  101701. unsigned channel;
  101702. const unsigned channels = frame->header.channels;
  101703. const unsigned blocksize = frame->header.blocksize;
  101704. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  101705. (void)decoder;
  101706. for(channel = 0; channel < channels; channel++) {
  101707. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  101708. unsigned i, sample = 0;
  101709. FLAC__int32 expect = 0, got = 0;
  101710. for(i = 0; i < blocksize; i++) {
  101711. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  101712. sample = i;
  101713. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  101714. got = (FLAC__int32)buffer[channel][i];
  101715. break;
  101716. }
  101717. }
  101718. FLAC__ASSERT(i < blocksize);
  101719. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101720. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  101721. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  101722. encoder->private_->verify.error_stats.channel = channel;
  101723. encoder->private_->verify.error_stats.sample = sample;
  101724. encoder->private_->verify.error_stats.expected = expect;
  101725. encoder->private_->verify.error_stats.got = got;
  101726. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  101727. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101728. }
  101729. }
  101730. /* dequeue the frame from the fifo */
  101731. encoder->private_->verify.input_fifo.tail -= blocksize;
  101732. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  101733. for(channel = 0; channel < channels; channel++)
  101734. 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]));
  101735. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101736. }
  101737. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  101738. {
  101739. (void)decoder, (void)metadata, (void)client_data;
  101740. }
  101741. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  101742. {
  101743. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101744. (void)decoder, (void)status;
  101745. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101746. }
  101747. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101748. {
  101749. (void)client_data;
  101750. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  101751. if (*bytes == 0) {
  101752. if (feof(encoder->private_->file))
  101753. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  101754. else if (ferror(encoder->private_->file))
  101755. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  101756. }
  101757. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  101758. }
  101759. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101760. {
  101761. (void)client_data;
  101762. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101763. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  101764. else
  101765. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  101766. }
  101767. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101768. {
  101769. off_t offset;
  101770. (void)client_data;
  101771. offset = ftello(encoder->private_->file);
  101772. if(offset < 0) {
  101773. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  101774. }
  101775. else {
  101776. *absolute_byte_offset = (FLAC__uint64)offset;
  101777. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  101778. }
  101779. }
  101780. #ifdef FLAC__VALGRIND_TESTING
  101781. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  101782. {
  101783. size_t ret = fwrite(ptr, size, nmemb, stream);
  101784. if(!ferror(stream))
  101785. fflush(stream);
  101786. return ret;
  101787. }
  101788. #else
  101789. #define local__fwrite fwrite
  101790. #endif
  101791. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  101792. {
  101793. (void)client_data, (void)current_frame;
  101794. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  101795. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  101796. #if FLAC__HAS_OGG
  101797. /* We would like to be able to use 'samples > 0' in the
  101798. * clause here but currently because of the nature of our
  101799. * Ogg writing implementation, 'samples' is always 0 (see
  101800. * ogg_encoder_aspect.c). The downside is extra progress
  101801. * callbacks.
  101802. */
  101803. encoder->private_->is_ogg? true :
  101804. #endif
  101805. samples > 0
  101806. );
  101807. if(call_it) {
  101808. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  101809. * because at this point in the callback chain, the stats
  101810. * have not been updated. Only after we return and control
  101811. * gets back to write_frame_() are the stats updated
  101812. */
  101813. 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);
  101814. }
  101815. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  101816. }
  101817. else
  101818. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101819. }
  101820. /*
  101821. * This will forcibly set stdout to binary mode (for OSes that require it)
  101822. */
  101823. FILE *get_binary_stdout_(void)
  101824. {
  101825. /* if something breaks here it is probably due to the presence or
  101826. * absence of an underscore before the identifiers 'setmode',
  101827. * 'fileno', and/or 'O_BINARY'; check your system header files.
  101828. */
  101829. #if defined _MSC_VER || defined __MINGW32__
  101830. _setmode(_fileno(stdout), _O_BINARY);
  101831. #elif defined __CYGWIN__
  101832. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  101833. setmode(_fileno(stdout), _O_BINARY);
  101834. #elif defined __EMX__
  101835. setmode(fileno(stdout), O_BINARY);
  101836. #endif
  101837. return stdout;
  101838. }
  101839. #endif
  101840. /********* End of inlined file: stream_encoder.c *********/
  101841. /********* Start of inlined file: stream_encoder_framing.c *********/
  101842. /********* Start of inlined file: juce_FlacHeader.h *********/
  101843. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101844. // tasks..
  101845. #define VERSION "1.2.1"
  101846. #define FLAC__NO_DLL 1
  101847. #if JUCE_MSVC
  101848. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101849. #endif
  101850. #if JUCE_MAC
  101851. #define FLAC__SYS_DARWIN 1
  101852. #endif
  101853. /********* End of inlined file: juce_FlacHeader.h *********/
  101854. #if JUCE_USE_FLAC
  101855. #if HAVE_CONFIG_H
  101856. # include <config.h>
  101857. #endif
  101858. #include <stdio.h>
  101859. #include <string.h> /* for strlen() */
  101860. #ifdef max
  101861. #undef max
  101862. #endif
  101863. #define max(x,y) ((x)>(y)?(x):(y))
  101864. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  101865. 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);
  101866. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  101867. {
  101868. unsigned i, j;
  101869. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  101870. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  101871. return false;
  101872. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  101873. return false;
  101874. /*
  101875. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  101876. */
  101877. i = metadata->length;
  101878. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101879. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  101880. i -= metadata->data.vorbis_comment.vendor_string.length;
  101881. i += vendor_string_length;
  101882. }
  101883. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  101884. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  101885. return false;
  101886. switch(metadata->type) {
  101887. case FLAC__METADATA_TYPE_STREAMINFO:
  101888. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  101889. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  101890. return false;
  101891. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  101892. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  101893. return false;
  101894. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  101895. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  101896. return false;
  101897. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  101898. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  101899. return false;
  101900. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  101901. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  101902. return false;
  101903. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  101904. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  101905. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  101906. return false;
  101907. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  101908. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101909. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  101910. return false;
  101911. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  101912. return false;
  101913. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  101914. return false;
  101915. break;
  101916. case FLAC__METADATA_TYPE_PADDING:
  101917. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  101918. return false;
  101919. break;
  101920. case FLAC__METADATA_TYPE_APPLICATION:
  101921. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  101922. return false;
  101923. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  101924. return false;
  101925. break;
  101926. case FLAC__METADATA_TYPE_SEEKTABLE:
  101927. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  101928. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  101929. return false;
  101930. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  101931. return false;
  101932. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  101933. return false;
  101934. }
  101935. break;
  101936. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  101937. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  101938. return false;
  101939. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  101940. return false;
  101941. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  101942. return false;
  101943. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  101944. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  101945. return false;
  101946. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  101947. return false;
  101948. }
  101949. break;
  101950. case FLAC__METADATA_TYPE_CUESHEET:
  101951. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  101952. 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))
  101953. return false;
  101954. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  101955. return false;
  101956. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  101957. return false;
  101958. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  101959. return false;
  101960. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  101961. return false;
  101962. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  101963. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  101964. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  101965. return false;
  101966. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  101967. return false;
  101968. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  101969. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  101970. return false;
  101971. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  101972. return false;
  101973. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  101974. return false;
  101975. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  101976. return false;
  101977. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  101978. return false;
  101979. for(j = 0; j < track->num_indices; j++) {
  101980. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  101981. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  101982. return false;
  101983. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  101984. return false;
  101985. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  101986. return false;
  101987. }
  101988. }
  101989. break;
  101990. case FLAC__METADATA_TYPE_PICTURE:
  101991. {
  101992. size_t len;
  101993. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  101994. return false;
  101995. len = strlen(metadata->data.picture.mime_type);
  101996. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  101997. return false;
  101998. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  101999. return false;
  102000. len = strlen((const char *)metadata->data.picture.description);
  102001. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  102002. return false;
  102003. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  102004. return false;
  102005. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  102006. return false;
  102007. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  102008. return false;
  102009. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  102010. return false;
  102011. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  102012. return false;
  102013. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  102014. return false;
  102015. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  102016. return false;
  102017. }
  102018. break;
  102019. default:
  102020. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  102021. return false;
  102022. break;
  102023. }
  102024. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102025. return true;
  102026. }
  102027. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  102028. {
  102029. unsigned u, blocksize_hint, sample_rate_hint;
  102030. FLAC__byte crc;
  102031. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102032. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  102033. return false;
  102034. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  102035. return false;
  102036. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  102037. return false;
  102038. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  102039. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  102040. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  102041. blocksize_hint = 0;
  102042. switch(header->blocksize) {
  102043. case 192: u = 1; break;
  102044. case 576: u = 2; break;
  102045. case 1152: u = 3; break;
  102046. case 2304: u = 4; break;
  102047. case 4608: u = 5; break;
  102048. case 256: u = 8; break;
  102049. case 512: u = 9; break;
  102050. case 1024: u = 10; break;
  102051. case 2048: u = 11; break;
  102052. case 4096: u = 12; break;
  102053. case 8192: u = 13; break;
  102054. case 16384: u = 14; break;
  102055. case 32768: u = 15; break;
  102056. default:
  102057. if(header->blocksize <= 0x100)
  102058. blocksize_hint = u = 6;
  102059. else
  102060. blocksize_hint = u = 7;
  102061. break;
  102062. }
  102063. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  102064. return false;
  102065. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  102066. sample_rate_hint = 0;
  102067. switch(header->sample_rate) {
  102068. case 88200: u = 1; break;
  102069. case 176400: u = 2; break;
  102070. case 192000: u = 3; break;
  102071. case 8000: u = 4; break;
  102072. case 16000: u = 5; break;
  102073. case 22050: u = 6; break;
  102074. case 24000: u = 7; break;
  102075. case 32000: u = 8; break;
  102076. case 44100: u = 9; break;
  102077. case 48000: u = 10; break;
  102078. case 96000: u = 11; break;
  102079. default:
  102080. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  102081. sample_rate_hint = u = 12;
  102082. else if(header->sample_rate % 10 == 0)
  102083. sample_rate_hint = u = 14;
  102084. else if(header->sample_rate <= 0xffff)
  102085. sample_rate_hint = u = 13;
  102086. else
  102087. u = 0;
  102088. break;
  102089. }
  102090. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  102091. return false;
  102092. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  102093. switch(header->channel_assignment) {
  102094. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  102095. u = header->channels - 1;
  102096. break;
  102097. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  102098. FLAC__ASSERT(header->channels == 2);
  102099. u = 8;
  102100. break;
  102101. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  102102. FLAC__ASSERT(header->channels == 2);
  102103. u = 9;
  102104. break;
  102105. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  102106. FLAC__ASSERT(header->channels == 2);
  102107. u = 10;
  102108. break;
  102109. default:
  102110. FLAC__ASSERT(0);
  102111. }
  102112. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  102113. return false;
  102114. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  102115. switch(header->bits_per_sample) {
  102116. case 8 : u = 1; break;
  102117. case 12: u = 2; break;
  102118. case 16: u = 4; break;
  102119. case 20: u = 5; break;
  102120. case 24: u = 6; break;
  102121. default: u = 0; break;
  102122. }
  102123. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  102124. return false;
  102125. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  102126. return false;
  102127. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  102128. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  102129. return false;
  102130. }
  102131. else {
  102132. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  102133. return false;
  102134. }
  102135. if(blocksize_hint)
  102136. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  102137. return false;
  102138. switch(sample_rate_hint) {
  102139. case 12:
  102140. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  102141. return false;
  102142. break;
  102143. case 13:
  102144. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  102145. return false;
  102146. break;
  102147. case 14:
  102148. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  102149. return false;
  102150. break;
  102151. }
  102152. /* write the CRC */
  102153. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  102154. return false;
  102155. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  102156. return false;
  102157. return true;
  102158. }
  102159. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102160. {
  102161. FLAC__bool ok;
  102162. ok =
  102163. 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) &&
  102164. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  102165. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  102166. ;
  102167. return ok;
  102168. }
  102169. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102170. {
  102171. unsigned i;
  102172. 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))
  102173. return false;
  102174. if(wasted_bits)
  102175. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102176. return false;
  102177. for(i = 0; i < subframe->order; i++)
  102178. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102179. return false;
  102180. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102181. return false;
  102182. switch(subframe->entropy_coding_method.type) {
  102183. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102184. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102185. if(!add_residual_partitioned_rice_(
  102186. bw,
  102187. subframe->residual,
  102188. residual_samples,
  102189. subframe->order,
  102190. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102191. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102192. subframe->entropy_coding_method.data.partitioned_rice.order,
  102193. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102194. ))
  102195. return false;
  102196. break;
  102197. default:
  102198. FLAC__ASSERT(0);
  102199. }
  102200. return true;
  102201. }
  102202. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102203. {
  102204. unsigned i;
  102205. 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))
  102206. return false;
  102207. if(wasted_bits)
  102208. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102209. return false;
  102210. for(i = 0; i < subframe->order; i++)
  102211. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102212. return false;
  102213. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  102214. return false;
  102215. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  102216. return false;
  102217. for(i = 0; i < subframe->order; i++)
  102218. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  102219. return false;
  102220. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102221. return false;
  102222. switch(subframe->entropy_coding_method.type) {
  102223. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102224. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102225. if(!add_residual_partitioned_rice_(
  102226. bw,
  102227. subframe->residual,
  102228. residual_samples,
  102229. subframe->order,
  102230. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102231. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102232. subframe->entropy_coding_method.data.partitioned_rice.order,
  102233. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102234. ))
  102235. return false;
  102236. break;
  102237. default:
  102238. FLAC__ASSERT(0);
  102239. }
  102240. return true;
  102241. }
  102242. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102243. {
  102244. unsigned i;
  102245. const FLAC__int32 *signal = subframe->data;
  102246. 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))
  102247. return false;
  102248. if(wasted_bits)
  102249. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102250. return false;
  102251. for(i = 0; i < samples; i++)
  102252. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  102253. return false;
  102254. return true;
  102255. }
  102256. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  102257. {
  102258. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  102259. return false;
  102260. switch(method->type) {
  102261. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102262. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102263. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102264. return false;
  102265. break;
  102266. default:
  102267. FLAC__ASSERT(0);
  102268. }
  102269. return true;
  102270. }
  102271. 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)
  102272. {
  102273. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  102274. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  102275. if(partition_order == 0) {
  102276. unsigned i;
  102277. if(raw_bits[0] == 0) {
  102278. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  102279. return false;
  102280. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  102281. return false;
  102282. }
  102283. else {
  102284. FLAC__ASSERT(rice_parameters[0] == 0);
  102285. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102286. return false;
  102287. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102288. return false;
  102289. for(i = 0; i < residual_samples; i++) {
  102290. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  102291. return false;
  102292. }
  102293. }
  102294. return true;
  102295. }
  102296. else {
  102297. unsigned i, j, k = 0, k_last = 0;
  102298. unsigned partition_samples;
  102299. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  102300. for(i = 0; i < (1u<<partition_order); i++) {
  102301. partition_samples = default_partition_samples;
  102302. if(i == 0)
  102303. partition_samples -= predictor_order;
  102304. k += partition_samples;
  102305. if(raw_bits[i] == 0) {
  102306. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  102307. return false;
  102308. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  102309. return false;
  102310. }
  102311. else {
  102312. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102313. return false;
  102314. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102315. return false;
  102316. for(j = k_last; j < k; j++) {
  102317. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  102318. return false;
  102319. }
  102320. }
  102321. k_last = k;
  102322. }
  102323. return true;
  102324. }
  102325. }
  102326. #endif
  102327. /********* End of inlined file: stream_encoder_framing.c *********/
  102328. /********* Start of inlined file: window_flac.c *********/
  102329. /********* Start of inlined file: juce_FlacHeader.h *********/
  102330. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102331. // tasks..
  102332. #define VERSION "1.2.1"
  102333. #define FLAC__NO_DLL 1
  102334. #if JUCE_MSVC
  102335. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102336. #endif
  102337. #if JUCE_MAC
  102338. #define FLAC__SYS_DARWIN 1
  102339. #endif
  102340. /********* End of inlined file: juce_FlacHeader.h *********/
  102341. #if JUCE_USE_FLAC
  102342. #if HAVE_CONFIG_H
  102343. # include <config.h>
  102344. #endif
  102345. #include <math.h>
  102346. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102347. #ifndef M_PI
  102348. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  102349. #define M_PI 3.14159265358979323846
  102350. #endif
  102351. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  102352. {
  102353. const FLAC__int32 N = L - 1;
  102354. FLAC__int32 n;
  102355. if (L & 1) {
  102356. for (n = 0; n <= N/2; n++)
  102357. window[n] = 2.0f * n / (float)N;
  102358. for (; n <= N; n++)
  102359. window[n] = 2.0f - 2.0f * n / (float)N;
  102360. }
  102361. else {
  102362. for (n = 0; n <= L/2-1; n++)
  102363. window[n] = 2.0f * n / (float)N;
  102364. for (; n <= N; n++)
  102365. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  102366. }
  102367. }
  102368. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  102369. {
  102370. const FLAC__int32 N = L - 1;
  102371. FLAC__int32 n;
  102372. for (n = 0; n < L; n++)
  102373. 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)));
  102374. }
  102375. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  102376. {
  102377. const FLAC__int32 N = L - 1;
  102378. FLAC__int32 n;
  102379. for (n = 0; n < L; n++)
  102380. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  102381. }
  102382. /* 4-term -92dB side-lobe */
  102383. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  102384. {
  102385. const FLAC__int32 N = L - 1;
  102386. FLAC__int32 n;
  102387. for (n = 0; n <= N; n++)
  102388. 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));
  102389. }
  102390. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  102391. {
  102392. const FLAC__int32 N = L - 1;
  102393. const double N2 = (double)N / 2.;
  102394. FLAC__int32 n;
  102395. for (n = 0; n <= N; n++) {
  102396. double k = ((double)n - N2) / N2;
  102397. k = 1.0f - k * k;
  102398. window[n] = (FLAC__real)(k * k);
  102399. }
  102400. }
  102401. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  102402. {
  102403. const FLAC__int32 N = L - 1;
  102404. FLAC__int32 n;
  102405. for (n = 0; n < L; n++)
  102406. 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));
  102407. }
  102408. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  102409. {
  102410. const FLAC__int32 N = L - 1;
  102411. const double N2 = (double)N / 2.;
  102412. FLAC__int32 n;
  102413. for (n = 0; n <= N; n++) {
  102414. const double k = ((double)n - N2) / (stddev * N2);
  102415. window[n] = (FLAC__real)exp(-0.5f * k * k);
  102416. }
  102417. }
  102418. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  102419. {
  102420. const FLAC__int32 N = L - 1;
  102421. FLAC__int32 n;
  102422. for (n = 0; n < L; n++)
  102423. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  102424. }
  102425. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  102426. {
  102427. const FLAC__int32 N = L - 1;
  102428. FLAC__int32 n;
  102429. for (n = 0; n < L; n++)
  102430. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  102431. }
  102432. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  102433. {
  102434. const FLAC__int32 N = L - 1;
  102435. FLAC__int32 n;
  102436. for (n = 0; n < L; n++)
  102437. 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));
  102438. }
  102439. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  102440. {
  102441. const FLAC__int32 N = L - 1;
  102442. FLAC__int32 n;
  102443. for (n = 0; n < L; n++)
  102444. 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));
  102445. }
  102446. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  102447. {
  102448. FLAC__int32 n;
  102449. for (n = 0; n < L; n++)
  102450. window[n] = 1.0f;
  102451. }
  102452. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  102453. {
  102454. FLAC__int32 n;
  102455. if (L & 1) {
  102456. for (n = 1; n <= L+1/2; n++)
  102457. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  102458. for (; n <= L; n++)
  102459. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  102460. }
  102461. else {
  102462. for (n = 1; n <= L/2; n++)
  102463. window[n-1] = 2.0f * n / (float)L;
  102464. for (; n <= L; n++)
  102465. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  102466. }
  102467. }
  102468. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  102469. {
  102470. if (p <= 0.0)
  102471. FLAC__window_rectangle(window, L);
  102472. else if (p >= 1.0)
  102473. FLAC__window_hann(window, L);
  102474. else {
  102475. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  102476. FLAC__int32 n;
  102477. /* start with rectangle... */
  102478. FLAC__window_rectangle(window, L);
  102479. /* ...replace ends with hann */
  102480. if (Np > 0) {
  102481. for (n = 0; n <= Np; n++) {
  102482. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  102483. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  102484. }
  102485. }
  102486. }
  102487. }
  102488. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  102489. {
  102490. const FLAC__int32 N = L - 1;
  102491. const double N2 = (double)N / 2.;
  102492. FLAC__int32 n;
  102493. for (n = 0; n <= N; n++) {
  102494. const double k = ((double)n - N2) / N2;
  102495. window[n] = (FLAC__real)(1.0f - k * k);
  102496. }
  102497. }
  102498. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102499. #endif
  102500. /********* End of inlined file: window_flac.c *********/
  102501. #else
  102502. #include <FLAC/all.h>
  102503. #endif
  102504. }
  102505. #ifdef _MSC_VER
  102506. #pragma warning (pop)
  102507. #endif
  102508. BEGIN_JUCE_NAMESPACE
  102509. using namespace FlacNamespace;
  102510. #define flacFormatName TRANS("FLAC file")
  102511. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  102512. class FlacReader : public AudioFormatReader
  102513. {
  102514. FLAC__StreamDecoder* decoder;
  102515. AudioSampleBuffer reservoir;
  102516. int reservoirStart, samplesInReservoir;
  102517. bool ok, scanningForLength;
  102518. public:
  102519. FlacReader (InputStream* const in)
  102520. : AudioFormatReader (in, flacFormatName),
  102521. reservoir (2, 0),
  102522. reservoirStart (0),
  102523. samplesInReservoir (0),
  102524. scanningForLength (false)
  102525. {
  102526. using namespace FlacNamespace;
  102527. lengthInSamples = 0;
  102528. decoder = FLAC__stream_decoder_new();
  102529. ok = FLAC__stream_decoder_init_stream (decoder,
  102530. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  102531. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  102532. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  102533. if (ok)
  102534. {
  102535. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102536. if (lengthInSamples == 0 && sampleRate > 0)
  102537. {
  102538. // the length hasn't been stored in the metadata, so we'll need to
  102539. // work it out the length the hard way, by scanning the whole file..
  102540. scanningForLength = true;
  102541. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  102542. scanningForLength = false;
  102543. const int64 tempLength = lengthInSamples;
  102544. FLAC__stream_decoder_reset (decoder);
  102545. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102546. lengthInSamples = tempLength;
  102547. }
  102548. }
  102549. }
  102550. ~FlacReader()
  102551. {
  102552. FLAC__stream_decoder_delete (decoder);
  102553. }
  102554. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  102555. {
  102556. sampleRate = info.sample_rate;
  102557. bitsPerSample = info.bits_per_sample;
  102558. lengthInSamples = (unsigned int) info.total_samples;
  102559. numChannels = info.channels;
  102560. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  102561. }
  102562. // returns the number of samples read
  102563. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  102564. int64 startSampleInFile, int numSamples)
  102565. {
  102566. using namespace FlacNamespace;
  102567. if (! ok)
  102568. return false;
  102569. while (numSamples > 0)
  102570. {
  102571. if (startSampleInFile >= reservoirStart
  102572. && startSampleInFile < reservoirStart + samplesInReservoir)
  102573. {
  102574. const int num = (int) jmin ((int64) numSamples,
  102575. reservoirStart + samplesInReservoir - startSampleInFile);
  102576. jassert (num > 0);
  102577. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  102578. if (destSamples[i] != 0)
  102579. memcpy (destSamples[i] + startOffsetInDestBuffer,
  102580. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  102581. sizeof (int) * num);
  102582. startOffsetInDestBuffer += num;
  102583. startSampleInFile += num;
  102584. numSamples -= num;
  102585. }
  102586. else
  102587. {
  102588. if (startSampleInFile >= (int) lengthInSamples)
  102589. {
  102590. samplesInReservoir = 0;
  102591. }
  102592. else if (startSampleInFile < reservoirStart
  102593. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  102594. {
  102595. // had some problems with flac crashing if the read pos is aligned more
  102596. // accurately than this. Probably fixed in newer versions of the library, though.
  102597. reservoirStart = (int) (startSampleInFile & ~511);
  102598. samplesInReservoir = 0;
  102599. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  102600. }
  102601. else
  102602. {
  102603. reservoirStart += samplesInReservoir;
  102604. samplesInReservoir = 0;
  102605. FLAC__stream_decoder_process_single (decoder);
  102606. }
  102607. if (samplesInReservoir == 0)
  102608. break;
  102609. }
  102610. }
  102611. if (numSamples > 0)
  102612. {
  102613. for (int i = numDestChannels; --i >= 0;)
  102614. if (destSamples[i] != 0)
  102615. zeromem (destSamples[i] + startOffsetInDestBuffer,
  102616. sizeof (int) * numSamples);
  102617. }
  102618. return true;
  102619. }
  102620. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  102621. {
  102622. if (scanningForLength)
  102623. {
  102624. lengthInSamples += numSamples;
  102625. }
  102626. else
  102627. {
  102628. if (numSamples > reservoir.getNumSamples())
  102629. reservoir.setSize (numChannels, numSamples, false, false, true);
  102630. const int bitsToShift = 32 - bitsPerSample;
  102631. for (int i = 0; i < (int) numChannels; ++i)
  102632. {
  102633. const FLAC__int32* src = buffer[i];
  102634. int n = i;
  102635. while (src == 0 && n > 0)
  102636. src = buffer [--n];
  102637. if (src != 0)
  102638. {
  102639. int* dest = (int*) reservoir.getSampleData(i);
  102640. for (int j = 0; j < numSamples; ++j)
  102641. dest[j] = src[j] << bitsToShift;
  102642. }
  102643. }
  102644. samplesInReservoir = numSamples;
  102645. }
  102646. }
  102647. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  102648. {
  102649. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  102650. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102651. }
  102652. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  102653. {
  102654. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  102655. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102656. }
  102657. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  102658. {
  102659. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  102660. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102661. }
  102662. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  102663. {
  102664. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  102665. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102666. }
  102667. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  102668. {
  102669. return ((const FlacReader*) client_data)->input->isExhausted();
  102670. }
  102671. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  102672. const FLAC__Frame* frame,
  102673. const FLAC__int32* const buffer[],
  102674. void* client_data)
  102675. {
  102676. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  102677. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102678. }
  102679. static void metadataCallback_ (const FLAC__StreamDecoder*,
  102680. const FLAC__StreamMetadata* metadata,
  102681. void* client_data)
  102682. {
  102683. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  102684. }
  102685. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  102686. {
  102687. }
  102688. juce_UseDebuggingNewOperator
  102689. };
  102690. class FlacWriter : public AudioFormatWriter
  102691. {
  102692. FLAC__StreamEncoder* encoder;
  102693. MemoryBlock temp;
  102694. public:
  102695. bool ok;
  102696. FlacWriter (OutputStream* const out,
  102697. const double sampleRate,
  102698. const int numChannels,
  102699. const int bitsPerSample_)
  102700. : AudioFormatWriter (out, flacFormatName,
  102701. sampleRate,
  102702. numChannels,
  102703. bitsPerSample_)
  102704. {
  102705. using namespace FlacNamespace;
  102706. encoder = FLAC__stream_encoder_new();
  102707. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  102708. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  102709. FLAC__stream_encoder_set_channels (encoder, numChannels);
  102710. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  102711. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  102712. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  102713. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  102714. ok = FLAC__stream_encoder_init_stream (encoder,
  102715. encodeWriteCallback, encodeSeekCallback,
  102716. encodeTellCallback, encodeMetadataCallback,
  102717. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102718. }
  102719. ~FlacWriter()
  102720. {
  102721. if (ok)
  102722. {
  102723. FLAC__stream_encoder_finish (encoder);
  102724. output->flush();
  102725. }
  102726. else
  102727. {
  102728. output = 0; // to stop the base class deleting this, as it needs to be returned
  102729. // to the caller of createWriter()
  102730. }
  102731. FLAC__stream_encoder_delete (encoder);
  102732. }
  102733. bool write (const int** samplesToWrite, int numSamples)
  102734. {
  102735. if (! ok)
  102736. return false;
  102737. int* buf[3];
  102738. const int bitsToShift = 32 - bitsPerSample;
  102739. if (bitsToShift > 0)
  102740. {
  102741. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  102742. temp.setSize (sizeof (int) * numSamples * numChannels);
  102743. buf[0] = (int*) temp.getData();
  102744. buf[1] = buf[0] + numSamples;
  102745. buf[2] = 0;
  102746. for (int i = numChannels; --i >= 0;)
  102747. {
  102748. if (samplesToWrite[i] != 0)
  102749. {
  102750. for (int j = 0; j < numSamples; ++j)
  102751. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  102752. }
  102753. }
  102754. samplesToWrite = (const int**) buf;
  102755. }
  102756. return FLAC__stream_encoder_process (encoder,
  102757. (const FLAC__int32**) samplesToWrite,
  102758. numSamples) != 0;
  102759. }
  102760. bool writeData (const void* const data, const int size) const
  102761. {
  102762. return output->write (data, size);
  102763. }
  102764. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  102765. {
  102766. b += bytes;
  102767. for (int i = 0; i < bytes; ++i)
  102768. {
  102769. *(--b) = (FLAC__byte) (val & 0xff);
  102770. val >>= 8;
  102771. }
  102772. }
  102773. void writeMetaData (const FLAC__StreamMetadata* metadata)
  102774. {
  102775. using namespace FlacNamespace;
  102776. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  102777. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  102778. const unsigned int channelsMinus1 = info.channels - 1;
  102779. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  102780. packUint32 (info.min_blocksize, buffer, 2);
  102781. packUint32 (info.max_blocksize, buffer + 2, 2);
  102782. packUint32 (info.min_framesize, buffer + 4, 3);
  102783. packUint32 (info.max_framesize, buffer + 7, 3);
  102784. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  102785. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  102786. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  102787. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  102788. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  102789. memcpy (buffer + 18, info.md5sum, 16);
  102790. const bool ok = output->setPosition (4);
  102791. (void) ok;
  102792. // if this fails, you've given it an output stream that can't seek! It needs
  102793. // to be able to seek back to write the header
  102794. jassert (ok);
  102795. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102796. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102797. }
  102798. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  102799. const FLAC__byte buffer[],
  102800. size_t bytes,
  102801. unsigned int /*samples*/,
  102802. unsigned int /*current_frame*/,
  102803. void* client_data)
  102804. {
  102805. using namespace FlacNamespace;
  102806. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  102807. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  102808. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102809. }
  102810. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  102811. {
  102812. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  102813. }
  102814. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  102815. {
  102816. if (client_data == 0)
  102817. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  102818. *absolute_byte_offset = (FLAC__uint64) ((FlacWriter*) client_data)->output->getPosition();
  102819. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  102820. }
  102821. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  102822. const FLAC__StreamMetadata* metadata,
  102823. void* client_data)
  102824. {
  102825. ((FlacWriter*) client_data)->writeMetaData (metadata);
  102826. }
  102827. juce_UseDebuggingNewOperator
  102828. };
  102829. FlacAudioFormat::FlacAudioFormat()
  102830. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  102831. {
  102832. }
  102833. FlacAudioFormat::~FlacAudioFormat()
  102834. {
  102835. }
  102836. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  102837. {
  102838. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  102839. return Array <int> (rates);
  102840. }
  102841. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  102842. {
  102843. const int depths[] = { 16, 24, 0 };
  102844. return Array <int> (depths);
  102845. }
  102846. bool FlacAudioFormat::canDoStereo()
  102847. {
  102848. return true;
  102849. }
  102850. bool FlacAudioFormat::canDoMono()
  102851. {
  102852. return true;
  102853. }
  102854. bool FlacAudioFormat::isCompressed()
  102855. {
  102856. return true;
  102857. }
  102858. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  102859. const bool deleteStreamIfOpeningFails)
  102860. {
  102861. FlacReader* r = new FlacReader (in);
  102862. if (r->sampleRate == 0)
  102863. {
  102864. if (! deleteStreamIfOpeningFails)
  102865. r->input = 0;
  102866. deleteAndZero (r);
  102867. }
  102868. return r;
  102869. }
  102870. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  102871. double sampleRate,
  102872. unsigned int numberOfChannels,
  102873. int bitsPerSample,
  102874. const StringPairArray& /*metadataValues*/,
  102875. int /*qualityOptionIndex*/)
  102876. {
  102877. if (getPossibleBitDepths().contains (bitsPerSample))
  102878. {
  102879. FlacWriter* w = new FlacWriter (out,
  102880. sampleRate,
  102881. numberOfChannels,
  102882. bitsPerSample);
  102883. if (! w->ok)
  102884. deleteAndZero (w);
  102885. return w;
  102886. }
  102887. return 0;
  102888. }
  102889. END_JUCE_NAMESPACE
  102890. #endif
  102891. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  102892. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  102893. #if JUCE_USE_OGGVORBIS
  102894. #if JUCE_MAC
  102895. #define __MACOSX__ 1
  102896. #endif
  102897. namespace OggVorbisNamespace
  102898. {
  102899. #if JUCE_INCLUDE_OGGVORBIS_CODE
  102900. /********* Start of inlined file: vorbisenc.h *********/
  102901. #ifndef _OV_ENC_H_
  102902. #define _OV_ENC_H_
  102903. #ifdef __cplusplus
  102904. extern "C"
  102905. {
  102906. #endif /* __cplusplus */
  102907. /********* Start of inlined file: codec.h *********/
  102908. #ifndef _vorbis_codec_h_
  102909. #define _vorbis_codec_h_
  102910. #ifdef __cplusplus
  102911. extern "C"
  102912. {
  102913. #endif /* __cplusplus */
  102914. /********* Start of inlined file: ogg.h *********/
  102915. #ifndef _OGG_H
  102916. #define _OGG_H
  102917. #ifdef __cplusplus
  102918. extern "C" {
  102919. #endif
  102920. /********* Start of inlined file: os_types.h *********/
  102921. #ifndef _OS_TYPES_H
  102922. #define _OS_TYPES_H
  102923. /* make it easy on the folks that want to compile the libs with a
  102924. different malloc than stdlib */
  102925. #define _ogg_malloc malloc
  102926. #define _ogg_calloc calloc
  102927. #define _ogg_realloc realloc
  102928. #define _ogg_free free
  102929. #if defined(_WIN32)
  102930. # if defined(__CYGWIN__)
  102931. # include <_G_config.h>
  102932. typedef _G_int64_t ogg_int64_t;
  102933. typedef _G_int32_t ogg_int32_t;
  102934. typedef _G_uint32_t ogg_uint32_t;
  102935. typedef _G_int16_t ogg_int16_t;
  102936. typedef _G_uint16_t ogg_uint16_t;
  102937. # elif defined(__MINGW32__)
  102938. typedef short ogg_int16_t;
  102939. typedef unsigned short ogg_uint16_t;
  102940. typedef int ogg_int32_t;
  102941. typedef unsigned int ogg_uint32_t;
  102942. typedef long long ogg_int64_t;
  102943. typedef unsigned long long ogg_uint64_t;
  102944. # elif defined(__MWERKS__)
  102945. typedef long long ogg_int64_t;
  102946. typedef int ogg_int32_t;
  102947. typedef unsigned int ogg_uint32_t;
  102948. typedef short ogg_int16_t;
  102949. typedef unsigned short ogg_uint16_t;
  102950. # else
  102951. /* MSVC/Borland */
  102952. typedef __int64 ogg_int64_t;
  102953. typedef __int32 ogg_int32_t;
  102954. typedef unsigned __int32 ogg_uint32_t;
  102955. typedef __int16 ogg_int16_t;
  102956. typedef unsigned __int16 ogg_uint16_t;
  102957. # endif
  102958. #elif defined(__MACOS__)
  102959. # include <sys/types.h>
  102960. typedef SInt16 ogg_int16_t;
  102961. typedef UInt16 ogg_uint16_t;
  102962. typedef SInt32 ogg_int32_t;
  102963. typedef UInt32 ogg_uint32_t;
  102964. typedef SInt64 ogg_int64_t;
  102965. #elif defined(__MACOSX__) /* MacOS X Framework build */
  102966. # include <sys/types.h>
  102967. typedef int16_t ogg_int16_t;
  102968. typedef u_int16_t ogg_uint16_t;
  102969. typedef int32_t ogg_int32_t;
  102970. typedef u_int32_t ogg_uint32_t;
  102971. typedef int64_t ogg_int64_t;
  102972. #elif defined(__BEOS__)
  102973. /* Be */
  102974. # include <inttypes.h>
  102975. typedef int16_t ogg_int16_t;
  102976. typedef u_int16_t ogg_uint16_t;
  102977. typedef int32_t ogg_int32_t;
  102978. typedef u_int32_t ogg_uint32_t;
  102979. typedef int64_t ogg_int64_t;
  102980. #elif defined (__EMX__)
  102981. /* OS/2 GCC */
  102982. typedef short ogg_int16_t;
  102983. typedef unsigned short ogg_uint16_t;
  102984. typedef int ogg_int32_t;
  102985. typedef unsigned int ogg_uint32_t;
  102986. typedef long long ogg_int64_t;
  102987. #elif defined (DJGPP)
  102988. /* DJGPP */
  102989. typedef short ogg_int16_t;
  102990. typedef int ogg_int32_t;
  102991. typedef unsigned int ogg_uint32_t;
  102992. typedef long long ogg_int64_t;
  102993. #elif defined(R5900)
  102994. /* PS2 EE */
  102995. typedef long ogg_int64_t;
  102996. typedef int ogg_int32_t;
  102997. typedef unsigned ogg_uint32_t;
  102998. typedef short ogg_int16_t;
  102999. #elif defined(__SYMBIAN32__)
  103000. /* Symbian GCC */
  103001. typedef signed short ogg_int16_t;
  103002. typedef unsigned short ogg_uint16_t;
  103003. typedef signed int ogg_int32_t;
  103004. typedef unsigned int ogg_uint32_t;
  103005. typedef long long int ogg_int64_t;
  103006. #else
  103007. # include <sys/types.h>
  103008. /********* Start of inlined file: config_types.h *********/
  103009. #ifndef __CONFIG_TYPES_H__
  103010. #define __CONFIG_TYPES_H__
  103011. typedef int16_t ogg_int16_t;
  103012. typedef unsigned short ogg_uint16_t;
  103013. typedef int32_t ogg_int32_t;
  103014. typedef unsigned int ogg_uint32_t;
  103015. typedef int64_t ogg_int64_t;
  103016. #endif
  103017. /********* End of inlined file: config_types.h *********/
  103018. #endif
  103019. #endif /* _OS_TYPES_H */
  103020. /********* End of inlined file: os_types.h *********/
  103021. typedef struct {
  103022. long endbyte;
  103023. int endbit;
  103024. unsigned char *buffer;
  103025. unsigned char *ptr;
  103026. long storage;
  103027. } oggpack_buffer;
  103028. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  103029. typedef struct {
  103030. unsigned char *header;
  103031. long header_len;
  103032. unsigned char *body;
  103033. long body_len;
  103034. } ogg_page;
  103035. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  103036. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  103037. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  103038. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  103039. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  103040. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  103041. }
  103042. /* ogg_stream_state contains the current encode/decode state of a logical
  103043. Ogg bitstream **********************************************************/
  103044. typedef struct {
  103045. unsigned char *body_data; /* bytes from packet bodies */
  103046. long body_storage; /* storage elements allocated */
  103047. long body_fill; /* elements stored; fill mark */
  103048. long body_returned; /* elements of fill returned */
  103049. int *lacing_vals; /* The values that will go to the segment table */
  103050. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  103051. this way, but it is simple coupled to the
  103052. lacing fifo */
  103053. long lacing_storage;
  103054. long lacing_fill;
  103055. long lacing_packet;
  103056. long lacing_returned;
  103057. unsigned char header[282]; /* working space for header encode */
  103058. int header_fill;
  103059. int e_o_s; /* set when we have buffered the last packet in the
  103060. logical bitstream */
  103061. int b_o_s; /* set after we've written the initial page
  103062. of a logical bitstream */
  103063. long serialno;
  103064. long pageno;
  103065. ogg_int64_t packetno; /* sequence number for decode; the framing
  103066. knows where there's a hole in the data,
  103067. but we need coupling so that the codec
  103068. (which is in a seperate abstraction
  103069. layer) also knows about the gap */
  103070. ogg_int64_t granulepos;
  103071. } ogg_stream_state;
  103072. /* ogg_packet is used to encapsulate the data and metadata belonging
  103073. to a single raw Ogg/Vorbis packet *************************************/
  103074. typedef struct {
  103075. unsigned char *packet;
  103076. long bytes;
  103077. long b_o_s;
  103078. long e_o_s;
  103079. ogg_int64_t granulepos;
  103080. ogg_int64_t packetno; /* sequence number for decode; the framing
  103081. knows where there's a hole in the data,
  103082. but we need coupling so that the codec
  103083. (which is in a seperate abstraction
  103084. layer) also knows about the gap */
  103085. } ogg_packet;
  103086. typedef struct {
  103087. unsigned char *data;
  103088. int storage;
  103089. int fill;
  103090. int returned;
  103091. int unsynced;
  103092. int headerbytes;
  103093. int bodybytes;
  103094. } ogg_sync_state;
  103095. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  103096. extern void oggpack_writeinit(oggpack_buffer *b);
  103097. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  103098. extern void oggpack_writealign(oggpack_buffer *b);
  103099. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  103100. extern void oggpack_reset(oggpack_buffer *b);
  103101. extern void oggpack_writeclear(oggpack_buffer *b);
  103102. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103103. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  103104. extern long oggpack_look(oggpack_buffer *b,int bits);
  103105. extern long oggpack_look1(oggpack_buffer *b);
  103106. extern void oggpack_adv(oggpack_buffer *b,int bits);
  103107. extern void oggpack_adv1(oggpack_buffer *b);
  103108. extern long oggpack_read(oggpack_buffer *b,int bits);
  103109. extern long oggpack_read1(oggpack_buffer *b);
  103110. extern long oggpack_bytes(oggpack_buffer *b);
  103111. extern long oggpack_bits(oggpack_buffer *b);
  103112. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  103113. extern void oggpackB_writeinit(oggpack_buffer *b);
  103114. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  103115. extern void oggpackB_writealign(oggpack_buffer *b);
  103116. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  103117. extern void oggpackB_reset(oggpack_buffer *b);
  103118. extern void oggpackB_writeclear(oggpack_buffer *b);
  103119. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  103120. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  103121. extern long oggpackB_look(oggpack_buffer *b,int bits);
  103122. extern long oggpackB_look1(oggpack_buffer *b);
  103123. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  103124. extern void oggpackB_adv1(oggpack_buffer *b);
  103125. extern long oggpackB_read(oggpack_buffer *b,int bits);
  103126. extern long oggpackB_read1(oggpack_buffer *b);
  103127. extern long oggpackB_bytes(oggpack_buffer *b);
  103128. extern long oggpackB_bits(oggpack_buffer *b);
  103129. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  103130. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  103131. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  103132. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  103133. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  103134. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  103135. extern int ogg_sync_init(ogg_sync_state *oy);
  103136. extern int ogg_sync_clear(ogg_sync_state *oy);
  103137. extern int ogg_sync_reset(ogg_sync_state *oy);
  103138. extern int ogg_sync_destroy(ogg_sync_state *oy);
  103139. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  103140. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  103141. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  103142. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  103143. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  103144. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  103145. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  103146. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  103147. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  103148. extern int ogg_stream_clear(ogg_stream_state *os);
  103149. extern int ogg_stream_reset(ogg_stream_state *os);
  103150. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  103151. extern int ogg_stream_destroy(ogg_stream_state *os);
  103152. extern int ogg_stream_eos(ogg_stream_state *os);
  103153. extern void ogg_page_checksum_set(ogg_page *og);
  103154. extern int ogg_page_version(ogg_page *og);
  103155. extern int ogg_page_continued(ogg_page *og);
  103156. extern int ogg_page_bos(ogg_page *og);
  103157. extern int ogg_page_eos(ogg_page *og);
  103158. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  103159. extern int ogg_page_serialno(ogg_page *og);
  103160. extern long ogg_page_pageno(ogg_page *og);
  103161. extern int ogg_page_packets(ogg_page *og);
  103162. extern void ogg_packet_clear(ogg_packet *op);
  103163. #ifdef __cplusplus
  103164. }
  103165. #endif
  103166. #endif /* _OGG_H */
  103167. /********* End of inlined file: ogg.h *********/
  103168. typedef struct vorbis_info{
  103169. int version;
  103170. int channels;
  103171. long rate;
  103172. /* The below bitrate declarations are *hints*.
  103173. Combinations of the three values carry the following implications:
  103174. all three set to the same value:
  103175. implies a fixed rate bitstream
  103176. only nominal set:
  103177. implies a VBR stream that averages the nominal bitrate. No hard
  103178. upper/lower limit
  103179. upper and or lower set:
  103180. implies a VBR bitstream that obeys the bitrate limits. nominal
  103181. may also be set to give a nominal rate.
  103182. none set:
  103183. the coder does not care to speculate.
  103184. */
  103185. long bitrate_upper;
  103186. long bitrate_nominal;
  103187. long bitrate_lower;
  103188. long bitrate_window;
  103189. void *codec_setup;
  103190. } vorbis_info;
  103191. /* vorbis_dsp_state buffers the current vorbis audio
  103192. analysis/synthesis state. The DSP state belongs to a specific
  103193. logical bitstream ****************************************************/
  103194. typedef struct vorbis_dsp_state{
  103195. int analysisp;
  103196. vorbis_info *vi;
  103197. float **pcm;
  103198. float **pcmret;
  103199. int pcm_storage;
  103200. int pcm_current;
  103201. int pcm_returned;
  103202. int preextrapolate;
  103203. int eofflag;
  103204. long lW;
  103205. long W;
  103206. long nW;
  103207. long centerW;
  103208. ogg_int64_t granulepos;
  103209. ogg_int64_t sequence;
  103210. ogg_int64_t glue_bits;
  103211. ogg_int64_t time_bits;
  103212. ogg_int64_t floor_bits;
  103213. ogg_int64_t res_bits;
  103214. void *backend_state;
  103215. } vorbis_dsp_state;
  103216. typedef struct vorbis_block{
  103217. /* necessary stream state for linking to the framing abstraction */
  103218. float **pcm; /* this is a pointer into local storage */
  103219. oggpack_buffer opb;
  103220. long lW;
  103221. long W;
  103222. long nW;
  103223. int pcmend;
  103224. int mode;
  103225. int eofflag;
  103226. ogg_int64_t granulepos;
  103227. ogg_int64_t sequence;
  103228. vorbis_dsp_state *vd; /* For read-only access of configuration */
  103229. /* local storage to avoid remallocing; it's up to the mapping to
  103230. structure it */
  103231. void *localstore;
  103232. long localtop;
  103233. long localalloc;
  103234. long totaluse;
  103235. struct alloc_chain *reap;
  103236. /* bitmetrics for the frame */
  103237. long glue_bits;
  103238. long time_bits;
  103239. long floor_bits;
  103240. long res_bits;
  103241. void *internal;
  103242. } vorbis_block;
  103243. /* vorbis_block is a single block of data to be processed as part of
  103244. the analysis/synthesis stream; it belongs to a specific logical
  103245. bitstream, but is independant from other vorbis_blocks belonging to
  103246. that logical bitstream. *************************************************/
  103247. struct alloc_chain{
  103248. void *ptr;
  103249. struct alloc_chain *next;
  103250. };
  103251. /* vorbis_info contains all the setup information specific to the
  103252. specific compression/decompression mode in progress (eg,
  103253. psychoacoustic settings, channel setup, options, codebook
  103254. etc). vorbis_info and substructures are in backends.h.
  103255. *********************************************************************/
  103256. /* the comments are not part of vorbis_info so that vorbis_info can be
  103257. static storage */
  103258. typedef struct vorbis_comment{
  103259. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  103260. whatever vendor is set to in encode */
  103261. char **user_comments;
  103262. int *comment_lengths;
  103263. int comments;
  103264. char *vendor;
  103265. } vorbis_comment;
  103266. /* libvorbis encodes in two abstraction layers; first we perform DSP
  103267. and produce a packet (see docs/analysis.txt). The packet is then
  103268. coded into a framed OggSquish bitstream by the second layer (see
  103269. docs/framing.txt). Decode is the reverse process; we sync/frame
  103270. the bitstream and extract individual packets, then decode the
  103271. packet back into PCM audio.
  103272. The extra framing/packetizing is used in streaming formats, such as
  103273. files. Over the net (such as with UDP), the framing and
  103274. packetization aren't necessary as they're provided by the transport
  103275. and the streaming layer is not used */
  103276. /* Vorbis PRIMITIVES: general ***************************************/
  103277. extern void vorbis_info_init(vorbis_info *vi);
  103278. extern void vorbis_info_clear(vorbis_info *vi);
  103279. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  103280. extern void vorbis_comment_init(vorbis_comment *vc);
  103281. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  103282. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  103283. const char *tag, char *contents);
  103284. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  103285. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  103286. extern void vorbis_comment_clear(vorbis_comment *vc);
  103287. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  103288. extern int vorbis_block_clear(vorbis_block *vb);
  103289. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  103290. extern double vorbis_granule_time(vorbis_dsp_state *v,
  103291. ogg_int64_t granulepos);
  103292. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  103293. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103294. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  103295. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  103296. vorbis_comment *vc,
  103297. ogg_packet *op,
  103298. ogg_packet *op_comm,
  103299. ogg_packet *op_code);
  103300. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  103301. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  103302. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  103303. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  103304. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  103305. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  103306. ogg_packet *op);
  103307. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  103308. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  103309. ogg_packet *op);
  103310. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103311. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  103312. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  103313. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  103314. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  103315. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  103316. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  103317. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  103318. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  103319. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  103320. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  103321. /* Vorbis ERRORS and return codes ***********************************/
  103322. #define OV_FALSE -1
  103323. #define OV_EOF -2
  103324. #define OV_HOLE -3
  103325. #define OV_EREAD -128
  103326. #define OV_EFAULT -129
  103327. #define OV_EIMPL -130
  103328. #define OV_EINVAL -131
  103329. #define OV_ENOTVORBIS -132
  103330. #define OV_EBADHEADER -133
  103331. #define OV_EVERSION -134
  103332. #define OV_ENOTAUDIO -135
  103333. #define OV_EBADPACKET -136
  103334. #define OV_EBADLINK -137
  103335. #define OV_ENOSEEK -138
  103336. #ifdef __cplusplus
  103337. }
  103338. #endif /* __cplusplus */
  103339. #endif
  103340. /********* End of inlined file: codec.h *********/
  103341. extern int vorbis_encode_init(vorbis_info *vi,
  103342. long channels,
  103343. long rate,
  103344. long max_bitrate,
  103345. long nominal_bitrate,
  103346. long min_bitrate);
  103347. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  103348. long channels,
  103349. long rate,
  103350. long max_bitrate,
  103351. long nominal_bitrate,
  103352. long min_bitrate);
  103353. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  103354. long channels,
  103355. long rate,
  103356. float quality /* quality level from 0. (lo) to 1. (hi) */
  103357. );
  103358. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  103359. long channels,
  103360. long rate,
  103361. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  103362. );
  103363. extern int vorbis_encode_setup_init(vorbis_info *vi);
  103364. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  103365. /* deprecated rate management supported only for compatability */
  103366. #define OV_ECTL_RATEMANAGE_GET 0x10
  103367. #define OV_ECTL_RATEMANAGE_SET 0x11
  103368. #define OV_ECTL_RATEMANAGE_AVG 0x12
  103369. #define OV_ECTL_RATEMANAGE_HARD 0x13
  103370. struct ovectl_ratemanage_arg {
  103371. int management_active;
  103372. long bitrate_hard_min;
  103373. long bitrate_hard_max;
  103374. double bitrate_hard_window;
  103375. long bitrate_av_lo;
  103376. long bitrate_av_hi;
  103377. double bitrate_av_window;
  103378. double bitrate_av_window_center;
  103379. };
  103380. /* new rate setup */
  103381. #define OV_ECTL_RATEMANAGE2_GET 0x14
  103382. #define OV_ECTL_RATEMANAGE2_SET 0x15
  103383. struct ovectl_ratemanage2_arg {
  103384. int management_active;
  103385. long bitrate_limit_min_kbps;
  103386. long bitrate_limit_max_kbps;
  103387. long bitrate_limit_reservoir_bits;
  103388. double bitrate_limit_reservoir_bias;
  103389. long bitrate_average_kbps;
  103390. double bitrate_average_damping;
  103391. };
  103392. #define OV_ECTL_LOWPASS_GET 0x20
  103393. #define OV_ECTL_LOWPASS_SET 0x21
  103394. #define OV_ECTL_IBLOCK_GET 0x30
  103395. #define OV_ECTL_IBLOCK_SET 0x31
  103396. #ifdef __cplusplus
  103397. }
  103398. #endif /* __cplusplus */
  103399. #endif
  103400. /********* End of inlined file: vorbisenc.h *********/
  103401. /********* Start of inlined file: vorbisfile.h *********/
  103402. #ifndef _OV_FILE_H_
  103403. #define _OV_FILE_H_
  103404. #ifdef __cplusplus
  103405. extern "C"
  103406. {
  103407. #endif /* __cplusplus */
  103408. #include <stdio.h>
  103409. /* The function prototypes for the callbacks are basically the same as for
  103410. * the stdio functions fread, fseek, fclose, ftell.
  103411. * The one difference is that the FILE * arguments have been replaced with
  103412. * a void * - this is to be used as a pointer to whatever internal data these
  103413. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  103414. *
  103415. * If you use other functions, check the docs for these functions and return
  103416. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  103417. * unseekable
  103418. */
  103419. typedef struct {
  103420. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  103421. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  103422. int (*close_func) (void *datasource);
  103423. long (*tell_func) (void *datasource);
  103424. } ov_callbacks;
  103425. #define NOTOPEN 0
  103426. #define PARTOPEN 1
  103427. #define OPENED 2
  103428. #define STREAMSET 3
  103429. #define INITSET 4
  103430. typedef struct OggVorbis_File {
  103431. void *datasource; /* Pointer to a FILE *, etc. */
  103432. int seekable;
  103433. ogg_int64_t offset;
  103434. ogg_int64_t end;
  103435. ogg_sync_state oy;
  103436. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  103437. stream appears */
  103438. int links;
  103439. ogg_int64_t *offsets;
  103440. ogg_int64_t *dataoffsets;
  103441. long *serialnos;
  103442. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  103443. compatability; x2 size, stores both
  103444. beginning and end values */
  103445. vorbis_info *vi;
  103446. vorbis_comment *vc;
  103447. /* Decoding working state local storage */
  103448. ogg_int64_t pcm_offset;
  103449. int ready_state;
  103450. long current_serialno;
  103451. int current_link;
  103452. double bittrack;
  103453. double samptrack;
  103454. ogg_stream_state os; /* take physical pages, weld into a logical
  103455. stream of packets */
  103456. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  103457. vorbis_block vb; /* local working space for packet->PCM decode */
  103458. ov_callbacks callbacks;
  103459. } OggVorbis_File;
  103460. extern int ov_clear(OggVorbis_File *vf);
  103461. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103462. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  103463. char *initial, long ibytes, ov_callbacks callbacks);
  103464. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103465. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  103466. char *initial, long ibytes, ov_callbacks callbacks);
  103467. extern int ov_test_open(OggVorbis_File *vf);
  103468. extern long ov_bitrate(OggVorbis_File *vf,int i);
  103469. extern long ov_bitrate_instant(OggVorbis_File *vf);
  103470. extern long ov_streams(OggVorbis_File *vf);
  103471. extern long ov_seekable(OggVorbis_File *vf);
  103472. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  103473. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  103474. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  103475. extern double ov_time_total(OggVorbis_File *vf,int i);
  103476. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103477. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103478. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  103479. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  103480. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  103481. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103482. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103483. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103484. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  103485. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  103486. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  103487. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  103488. extern double ov_time_tell(OggVorbis_File *vf);
  103489. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  103490. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  103491. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  103492. int *bitstream);
  103493. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  103494. int bigendianp,int word,int sgned,int *bitstream);
  103495. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  103496. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  103497. extern int ov_halfrate_p(OggVorbis_File *vf);
  103498. #ifdef __cplusplus
  103499. }
  103500. #endif /* __cplusplus */
  103501. #endif
  103502. /********* End of inlined file: vorbisfile.h *********/
  103503. /********* Start of inlined file: bitwise.c *********/
  103504. /* We're 'LSb' endian; if we write a word but read individual bits,
  103505. then we'll read the lsb first */
  103506. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103507. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103508. // tasks..
  103509. #if JUCE_MSVC
  103510. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103511. #endif
  103512. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103513. #if JUCE_USE_OGGVORBIS
  103514. #include <string.h>
  103515. #include <stdlib.h>
  103516. #define BUFFER_INCREMENT 256
  103517. static const unsigned long mask[]=
  103518. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  103519. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  103520. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  103521. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  103522. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  103523. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  103524. 0x3fffffff,0x7fffffff,0xffffffff };
  103525. static const unsigned int mask8B[]=
  103526. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  103527. void oggpack_writeinit(oggpack_buffer *b){
  103528. memset(b,0,sizeof(*b));
  103529. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  103530. b->buffer[0]='\0';
  103531. b->storage=BUFFER_INCREMENT;
  103532. }
  103533. void oggpackB_writeinit(oggpack_buffer *b){
  103534. oggpack_writeinit(b);
  103535. }
  103536. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  103537. long bytes=bits>>3;
  103538. bits-=bytes*8;
  103539. b->ptr=b->buffer+bytes;
  103540. b->endbit=bits;
  103541. b->endbyte=bytes;
  103542. *b->ptr&=mask[bits];
  103543. }
  103544. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  103545. long bytes=bits>>3;
  103546. bits-=bytes*8;
  103547. b->ptr=b->buffer+bytes;
  103548. b->endbit=bits;
  103549. b->endbyte=bytes;
  103550. *b->ptr&=mask8B[bits];
  103551. }
  103552. /* Takes only up to 32 bits. */
  103553. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  103554. if(b->endbyte+4>=b->storage){
  103555. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103556. b->storage+=BUFFER_INCREMENT;
  103557. b->ptr=b->buffer+b->endbyte;
  103558. }
  103559. value&=mask[bits];
  103560. bits+=b->endbit;
  103561. b->ptr[0]|=value<<b->endbit;
  103562. if(bits>=8){
  103563. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  103564. if(bits>=16){
  103565. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  103566. if(bits>=24){
  103567. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  103568. if(bits>=32){
  103569. if(b->endbit)
  103570. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  103571. else
  103572. b->ptr[4]=0;
  103573. }
  103574. }
  103575. }
  103576. }
  103577. b->endbyte+=bits/8;
  103578. b->ptr+=bits/8;
  103579. b->endbit=bits&7;
  103580. }
  103581. /* Takes only up to 32 bits. */
  103582. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  103583. if(b->endbyte+4>=b->storage){
  103584. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103585. b->storage+=BUFFER_INCREMENT;
  103586. b->ptr=b->buffer+b->endbyte;
  103587. }
  103588. value=(value&mask[bits])<<(32-bits);
  103589. bits+=b->endbit;
  103590. b->ptr[0]|=value>>(24+b->endbit);
  103591. if(bits>=8){
  103592. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  103593. if(bits>=16){
  103594. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  103595. if(bits>=24){
  103596. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  103597. if(bits>=32){
  103598. if(b->endbit)
  103599. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  103600. else
  103601. b->ptr[4]=0;
  103602. }
  103603. }
  103604. }
  103605. }
  103606. b->endbyte+=bits/8;
  103607. b->ptr+=bits/8;
  103608. b->endbit=bits&7;
  103609. }
  103610. void oggpack_writealign(oggpack_buffer *b){
  103611. int bits=8-b->endbit;
  103612. if(bits<8)
  103613. oggpack_write(b,0,bits);
  103614. }
  103615. void oggpackB_writealign(oggpack_buffer *b){
  103616. int bits=8-b->endbit;
  103617. if(bits<8)
  103618. oggpackB_write(b,0,bits);
  103619. }
  103620. static void oggpack_writecopy_helper(oggpack_buffer *b,
  103621. void *source,
  103622. long bits,
  103623. void (*w)(oggpack_buffer *,
  103624. unsigned long,
  103625. int),
  103626. int msb){
  103627. unsigned char *ptr=(unsigned char *)source;
  103628. long bytes=bits/8;
  103629. bits-=bytes*8;
  103630. if(b->endbit){
  103631. int i;
  103632. /* unaligned copy. Do it the hard way. */
  103633. for(i=0;i<bytes;i++)
  103634. w(b,(unsigned long)(ptr[i]),8);
  103635. }else{
  103636. /* aligned block copy */
  103637. if(b->endbyte+bytes+1>=b->storage){
  103638. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  103639. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  103640. b->ptr=b->buffer+b->endbyte;
  103641. }
  103642. memmove(b->ptr,source,bytes);
  103643. b->ptr+=bytes;
  103644. b->endbyte+=bytes;
  103645. *b->ptr=0;
  103646. }
  103647. if(bits){
  103648. if(msb)
  103649. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  103650. else
  103651. w(b,(unsigned long)(ptr[bytes]),bits);
  103652. }
  103653. }
  103654. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  103655. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  103656. }
  103657. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  103658. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  103659. }
  103660. void oggpack_reset(oggpack_buffer *b){
  103661. b->ptr=b->buffer;
  103662. b->buffer[0]=0;
  103663. b->endbit=b->endbyte=0;
  103664. }
  103665. void oggpackB_reset(oggpack_buffer *b){
  103666. oggpack_reset(b);
  103667. }
  103668. void oggpack_writeclear(oggpack_buffer *b){
  103669. _ogg_free(b->buffer);
  103670. memset(b,0,sizeof(*b));
  103671. }
  103672. void oggpackB_writeclear(oggpack_buffer *b){
  103673. oggpack_writeclear(b);
  103674. }
  103675. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103676. memset(b,0,sizeof(*b));
  103677. b->buffer=b->ptr=buf;
  103678. b->storage=bytes;
  103679. }
  103680. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103681. oggpack_readinit(b,buf,bytes);
  103682. }
  103683. /* Read in bits without advancing the bitptr; bits <= 32 */
  103684. long oggpack_look(oggpack_buffer *b,int bits){
  103685. unsigned long ret;
  103686. unsigned long m=mask[bits];
  103687. bits+=b->endbit;
  103688. if(b->endbyte+4>=b->storage){
  103689. /* not the main path */
  103690. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103691. }
  103692. ret=b->ptr[0]>>b->endbit;
  103693. if(bits>8){
  103694. ret|=b->ptr[1]<<(8-b->endbit);
  103695. if(bits>16){
  103696. ret|=b->ptr[2]<<(16-b->endbit);
  103697. if(bits>24){
  103698. ret|=b->ptr[3]<<(24-b->endbit);
  103699. if(bits>32 && b->endbit)
  103700. ret|=b->ptr[4]<<(32-b->endbit);
  103701. }
  103702. }
  103703. }
  103704. return(m&ret);
  103705. }
  103706. /* Read in bits without advancing the bitptr; bits <= 32 */
  103707. long oggpackB_look(oggpack_buffer *b,int bits){
  103708. unsigned long ret;
  103709. int m=32-bits;
  103710. bits+=b->endbit;
  103711. if(b->endbyte+4>=b->storage){
  103712. /* not the main path */
  103713. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103714. }
  103715. ret=b->ptr[0]<<(24+b->endbit);
  103716. if(bits>8){
  103717. ret|=b->ptr[1]<<(16+b->endbit);
  103718. if(bits>16){
  103719. ret|=b->ptr[2]<<(8+b->endbit);
  103720. if(bits>24){
  103721. ret|=b->ptr[3]<<(b->endbit);
  103722. if(bits>32 && b->endbit)
  103723. ret|=b->ptr[4]>>(8-b->endbit);
  103724. }
  103725. }
  103726. }
  103727. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  103728. }
  103729. long oggpack_look1(oggpack_buffer *b){
  103730. if(b->endbyte>=b->storage)return(-1);
  103731. return((b->ptr[0]>>b->endbit)&1);
  103732. }
  103733. long oggpackB_look1(oggpack_buffer *b){
  103734. if(b->endbyte>=b->storage)return(-1);
  103735. return((b->ptr[0]>>(7-b->endbit))&1);
  103736. }
  103737. void oggpack_adv(oggpack_buffer *b,int bits){
  103738. bits+=b->endbit;
  103739. b->ptr+=bits/8;
  103740. b->endbyte+=bits/8;
  103741. b->endbit=bits&7;
  103742. }
  103743. void oggpackB_adv(oggpack_buffer *b,int bits){
  103744. oggpack_adv(b,bits);
  103745. }
  103746. void oggpack_adv1(oggpack_buffer *b){
  103747. if(++(b->endbit)>7){
  103748. b->endbit=0;
  103749. b->ptr++;
  103750. b->endbyte++;
  103751. }
  103752. }
  103753. void oggpackB_adv1(oggpack_buffer *b){
  103754. oggpack_adv1(b);
  103755. }
  103756. /* bits <= 32 */
  103757. long oggpack_read(oggpack_buffer *b,int bits){
  103758. long ret;
  103759. unsigned long m=mask[bits];
  103760. bits+=b->endbit;
  103761. if(b->endbyte+4>=b->storage){
  103762. /* not the main path */
  103763. ret=-1L;
  103764. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103765. }
  103766. ret=b->ptr[0]>>b->endbit;
  103767. if(bits>8){
  103768. ret|=b->ptr[1]<<(8-b->endbit);
  103769. if(bits>16){
  103770. ret|=b->ptr[2]<<(16-b->endbit);
  103771. if(bits>24){
  103772. ret|=b->ptr[3]<<(24-b->endbit);
  103773. if(bits>32 && b->endbit){
  103774. ret|=b->ptr[4]<<(32-b->endbit);
  103775. }
  103776. }
  103777. }
  103778. }
  103779. ret&=m;
  103780. overflow:
  103781. b->ptr+=bits/8;
  103782. b->endbyte+=bits/8;
  103783. b->endbit=bits&7;
  103784. return(ret);
  103785. }
  103786. /* bits <= 32 */
  103787. long oggpackB_read(oggpack_buffer *b,int bits){
  103788. long ret;
  103789. long m=32-bits;
  103790. bits+=b->endbit;
  103791. if(b->endbyte+4>=b->storage){
  103792. /* not the main path */
  103793. ret=-1L;
  103794. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103795. }
  103796. ret=b->ptr[0]<<(24+b->endbit);
  103797. if(bits>8){
  103798. ret|=b->ptr[1]<<(16+b->endbit);
  103799. if(bits>16){
  103800. ret|=b->ptr[2]<<(8+b->endbit);
  103801. if(bits>24){
  103802. ret|=b->ptr[3]<<(b->endbit);
  103803. if(bits>32 && b->endbit)
  103804. ret|=b->ptr[4]>>(8-b->endbit);
  103805. }
  103806. }
  103807. }
  103808. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  103809. overflow:
  103810. b->ptr+=bits/8;
  103811. b->endbyte+=bits/8;
  103812. b->endbit=bits&7;
  103813. return(ret);
  103814. }
  103815. long oggpack_read1(oggpack_buffer *b){
  103816. long ret;
  103817. if(b->endbyte>=b->storage){
  103818. /* not the main path */
  103819. ret=-1L;
  103820. goto overflow;
  103821. }
  103822. ret=(b->ptr[0]>>b->endbit)&1;
  103823. overflow:
  103824. b->endbit++;
  103825. if(b->endbit>7){
  103826. b->endbit=0;
  103827. b->ptr++;
  103828. b->endbyte++;
  103829. }
  103830. return(ret);
  103831. }
  103832. long oggpackB_read1(oggpack_buffer *b){
  103833. long ret;
  103834. if(b->endbyte>=b->storage){
  103835. /* not the main path */
  103836. ret=-1L;
  103837. goto overflow;
  103838. }
  103839. ret=(b->ptr[0]>>(7-b->endbit))&1;
  103840. overflow:
  103841. b->endbit++;
  103842. if(b->endbit>7){
  103843. b->endbit=0;
  103844. b->ptr++;
  103845. b->endbyte++;
  103846. }
  103847. return(ret);
  103848. }
  103849. long oggpack_bytes(oggpack_buffer *b){
  103850. return(b->endbyte+(b->endbit+7)/8);
  103851. }
  103852. long oggpack_bits(oggpack_buffer *b){
  103853. return(b->endbyte*8+b->endbit);
  103854. }
  103855. long oggpackB_bytes(oggpack_buffer *b){
  103856. return oggpack_bytes(b);
  103857. }
  103858. long oggpackB_bits(oggpack_buffer *b){
  103859. return oggpack_bits(b);
  103860. }
  103861. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  103862. return(b->buffer);
  103863. }
  103864. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  103865. return oggpack_get_buffer(b);
  103866. }
  103867. /* Self test of the bitwise routines; everything else is based on
  103868. them, so they damned well better be solid. */
  103869. #ifdef _V_SELFTEST
  103870. #include <stdio.h>
  103871. static int ilog(unsigned int v){
  103872. int ret=0;
  103873. while(v){
  103874. ret++;
  103875. v>>=1;
  103876. }
  103877. return(ret);
  103878. }
  103879. oggpack_buffer o;
  103880. oggpack_buffer r;
  103881. void report(char *in){
  103882. fprintf(stderr,"%s",in);
  103883. exit(1);
  103884. }
  103885. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103886. long bytes,i;
  103887. unsigned char *buffer;
  103888. oggpack_reset(&o);
  103889. for(i=0;i<vals;i++)
  103890. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  103891. buffer=oggpack_get_buffer(&o);
  103892. bytes=oggpack_bytes(&o);
  103893. if(bytes!=compsize)report("wrong number of bytes!\n");
  103894. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103895. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103896. report("wrote incorrect value!\n");
  103897. }
  103898. oggpack_readinit(&r,buffer,bytes);
  103899. for(i=0;i<vals;i++){
  103900. int tbit=bits?bits:ilog(b[i]);
  103901. if(oggpack_look(&r,tbit)==-1)
  103902. report("out of data!\n");
  103903. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  103904. report("looked at incorrect value!\n");
  103905. if(tbit==1)
  103906. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  103907. report("looked at single bit incorrect value!\n");
  103908. if(tbit==1){
  103909. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  103910. report("read incorrect single bit value!\n");
  103911. }else{
  103912. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  103913. report("read incorrect value!\n");
  103914. }
  103915. }
  103916. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103917. }
  103918. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103919. long bytes,i;
  103920. unsigned char *buffer;
  103921. oggpackB_reset(&o);
  103922. for(i=0;i<vals;i++)
  103923. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  103924. buffer=oggpackB_get_buffer(&o);
  103925. bytes=oggpackB_bytes(&o);
  103926. if(bytes!=compsize)report("wrong number of bytes!\n");
  103927. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103928. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103929. report("wrote incorrect value!\n");
  103930. }
  103931. oggpackB_readinit(&r,buffer,bytes);
  103932. for(i=0;i<vals;i++){
  103933. int tbit=bits?bits:ilog(b[i]);
  103934. if(oggpackB_look(&r,tbit)==-1)
  103935. report("out of data!\n");
  103936. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  103937. report("looked at incorrect value!\n");
  103938. if(tbit==1)
  103939. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  103940. report("looked at single bit incorrect value!\n");
  103941. if(tbit==1){
  103942. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  103943. report("read incorrect single bit value!\n");
  103944. }else{
  103945. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  103946. report("read incorrect value!\n");
  103947. }
  103948. }
  103949. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103950. }
  103951. int main(void){
  103952. unsigned char *buffer;
  103953. long bytes,i;
  103954. static unsigned long testbuffer1[]=
  103955. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  103956. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  103957. int test1size=43;
  103958. static unsigned long testbuffer2[]=
  103959. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  103960. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  103961. 85525151,0,12321,1,349528352};
  103962. int test2size=21;
  103963. static unsigned long testbuffer3[]=
  103964. {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,
  103965. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  103966. int test3size=56;
  103967. static unsigned long large[]=
  103968. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  103969. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  103970. 85525151,0,12321,1,2146528352};
  103971. int onesize=33;
  103972. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  103973. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  103974. 223,4};
  103975. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  103976. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  103977. 245,251,128};
  103978. int twosize=6;
  103979. static int two[6]={61,255,255,251,231,29};
  103980. static int twoB[6]={247,63,255,253,249,120};
  103981. int threesize=54;
  103982. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  103983. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  103984. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  103985. 100,52,4,14,18,86,77,1};
  103986. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  103987. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  103988. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  103989. 200,20,254,4,58,106,176,144,0};
  103990. int foursize=38;
  103991. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  103992. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  103993. 28,2,133,0,1};
  103994. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  103995. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  103996. 129,10,4,32};
  103997. int fivesize=45;
  103998. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  103999. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  104000. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  104001. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  104002. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  104003. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  104004. int sixsize=7;
  104005. static int six[7]={17,177,170,242,169,19,148};
  104006. static int sixB[7]={136,141,85,79,149,200,41};
  104007. /* Test read/write together */
  104008. /* Later we test against pregenerated bitstreams */
  104009. oggpack_writeinit(&o);
  104010. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  104011. cliptest(testbuffer1,test1size,0,one,onesize);
  104012. fprintf(stderr,"ok.");
  104013. fprintf(stderr,"\nNull bit call (LSb): ");
  104014. cliptest(testbuffer3,test3size,0,two,twosize);
  104015. fprintf(stderr,"ok.");
  104016. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  104017. cliptest(testbuffer2,test2size,0,three,threesize);
  104018. fprintf(stderr,"ok.");
  104019. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  104020. oggpack_reset(&o);
  104021. for(i=0;i<test2size;i++)
  104022. oggpack_write(&o,large[i],32);
  104023. buffer=oggpack_get_buffer(&o);
  104024. bytes=oggpack_bytes(&o);
  104025. oggpack_readinit(&r,buffer,bytes);
  104026. for(i=0;i<test2size;i++){
  104027. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  104028. if(oggpack_look(&r,32)!=large[i]){
  104029. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  104030. oggpack_look(&r,32),large[i]);
  104031. report("read incorrect value!\n");
  104032. }
  104033. oggpack_adv(&r,32);
  104034. }
  104035. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104036. fprintf(stderr,"ok.");
  104037. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  104038. cliptest(testbuffer1,test1size,7,four,foursize);
  104039. fprintf(stderr,"ok.");
  104040. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  104041. cliptest(testbuffer2,test2size,17,five,fivesize);
  104042. fprintf(stderr,"ok.");
  104043. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  104044. cliptest(testbuffer3,test3size,1,six,sixsize);
  104045. fprintf(stderr,"ok.");
  104046. fprintf(stderr,"\nTesting read past end (LSb): ");
  104047. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104048. for(i=0;i<64;i++){
  104049. if(oggpack_read(&r,1)!=0){
  104050. fprintf(stderr,"failed; got -1 prematurely.\n");
  104051. exit(1);
  104052. }
  104053. }
  104054. if(oggpack_look(&r,1)!=-1 ||
  104055. oggpack_read(&r,1)!=-1){
  104056. fprintf(stderr,"failed; read past end without -1.\n");
  104057. exit(1);
  104058. }
  104059. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104060. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  104061. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104062. exit(1);
  104063. }
  104064. if(oggpack_look(&r,18)!=0 ||
  104065. oggpack_look(&r,18)!=0){
  104066. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104067. exit(1);
  104068. }
  104069. if(oggpack_look(&r,19)!=-1 ||
  104070. oggpack_look(&r,19)!=-1){
  104071. fprintf(stderr,"failed; read past end without -1.\n");
  104072. exit(1);
  104073. }
  104074. if(oggpack_look(&r,32)!=-1 ||
  104075. oggpack_look(&r,32)!=-1){
  104076. fprintf(stderr,"failed; read past end without -1.\n");
  104077. exit(1);
  104078. }
  104079. oggpack_writeclear(&o);
  104080. fprintf(stderr,"ok.\n");
  104081. /********** lazy, cut-n-paste retest with MSb packing ***********/
  104082. /* Test read/write together */
  104083. /* Later we test against pregenerated bitstreams */
  104084. oggpackB_writeinit(&o);
  104085. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  104086. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  104087. fprintf(stderr,"ok.");
  104088. fprintf(stderr,"\nNull bit call (MSb): ");
  104089. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  104090. fprintf(stderr,"ok.");
  104091. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  104092. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  104093. fprintf(stderr,"ok.");
  104094. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  104095. oggpackB_reset(&o);
  104096. for(i=0;i<test2size;i++)
  104097. oggpackB_write(&o,large[i],32);
  104098. buffer=oggpackB_get_buffer(&o);
  104099. bytes=oggpackB_bytes(&o);
  104100. oggpackB_readinit(&r,buffer,bytes);
  104101. for(i=0;i<test2size;i++){
  104102. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  104103. if(oggpackB_look(&r,32)!=large[i]){
  104104. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  104105. oggpackB_look(&r,32),large[i]);
  104106. report("read incorrect value!\n");
  104107. }
  104108. oggpackB_adv(&r,32);
  104109. }
  104110. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  104111. fprintf(stderr,"ok.");
  104112. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  104113. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  104114. fprintf(stderr,"ok.");
  104115. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  104116. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  104117. fprintf(stderr,"ok.");
  104118. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  104119. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  104120. fprintf(stderr,"ok.");
  104121. fprintf(stderr,"\nTesting read past end (MSb): ");
  104122. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104123. for(i=0;i<64;i++){
  104124. if(oggpackB_read(&r,1)!=0){
  104125. fprintf(stderr,"failed; got -1 prematurely.\n");
  104126. exit(1);
  104127. }
  104128. }
  104129. if(oggpackB_look(&r,1)!=-1 ||
  104130. oggpackB_read(&r,1)!=-1){
  104131. fprintf(stderr,"failed; read past end without -1.\n");
  104132. exit(1);
  104133. }
  104134. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  104135. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  104136. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  104137. exit(1);
  104138. }
  104139. if(oggpackB_look(&r,18)!=0 ||
  104140. oggpackB_look(&r,18)!=0){
  104141. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  104142. exit(1);
  104143. }
  104144. if(oggpackB_look(&r,19)!=-1 ||
  104145. oggpackB_look(&r,19)!=-1){
  104146. fprintf(stderr,"failed; read past end without -1.\n");
  104147. exit(1);
  104148. }
  104149. if(oggpackB_look(&r,32)!=-1 ||
  104150. oggpackB_look(&r,32)!=-1){
  104151. fprintf(stderr,"failed; read past end without -1.\n");
  104152. exit(1);
  104153. }
  104154. oggpackB_writeclear(&o);
  104155. fprintf(stderr,"ok.\n\n");
  104156. return(0);
  104157. }
  104158. #endif /* _V_SELFTEST */
  104159. #undef BUFFER_INCREMENT
  104160. #endif
  104161. /********* End of inlined file: bitwise.c *********/
  104162. /********* Start of inlined file: framing.c *********/
  104163. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104164. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104165. // tasks..
  104166. #if JUCE_MSVC
  104167. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104168. #endif
  104169. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104170. #if JUCE_USE_OGGVORBIS
  104171. #include <stdlib.h>
  104172. #include <string.h>
  104173. /* A complete description of Ogg framing exists in docs/framing.html */
  104174. int ogg_page_version(ogg_page *og){
  104175. return((int)(og->header[4]));
  104176. }
  104177. int ogg_page_continued(ogg_page *og){
  104178. return((int)(og->header[5]&0x01));
  104179. }
  104180. int ogg_page_bos(ogg_page *og){
  104181. return((int)(og->header[5]&0x02));
  104182. }
  104183. int ogg_page_eos(ogg_page *og){
  104184. return((int)(og->header[5]&0x04));
  104185. }
  104186. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  104187. unsigned char *page=og->header;
  104188. ogg_int64_t granulepos=page[13]&(0xff);
  104189. granulepos= (granulepos<<8)|(page[12]&0xff);
  104190. granulepos= (granulepos<<8)|(page[11]&0xff);
  104191. granulepos= (granulepos<<8)|(page[10]&0xff);
  104192. granulepos= (granulepos<<8)|(page[9]&0xff);
  104193. granulepos= (granulepos<<8)|(page[8]&0xff);
  104194. granulepos= (granulepos<<8)|(page[7]&0xff);
  104195. granulepos= (granulepos<<8)|(page[6]&0xff);
  104196. return(granulepos);
  104197. }
  104198. int ogg_page_serialno(ogg_page *og){
  104199. return(og->header[14] |
  104200. (og->header[15]<<8) |
  104201. (og->header[16]<<16) |
  104202. (og->header[17]<<24));
  104203. }
  104204. long ogg_page_pageno(ogg_page *og){
  104205. return(og->header[18] |
  104206. (og->header[19]<<8) |
  104207. (og->header[20]<<16) |
  104208. (og->header[21]<<24));
  104209. }
  104210. /* returns the number of packets that are completed on this page (if
  104211. the leading packet is begun on a previous page, but ends on this
  104212. page, it's counted */
  104213. /* NOTE:
  104214. If a page consists of a packet begun on a previous page, and a new
  104215. packet begun (but not completed) on this page, the return will be:
  104216. ogg_page_packets(page) ==1,
  104217. ogg_page_continued(page) !=0
  104218. If a page happens to be a single packet that was begun on a
  104219. previous page, and spans to the next page (in the case of a three or
  104220. more page packet), the return will be:
  104221. ogg_page_packets(page) ==0,
  104222. ogg_page_continued(page) !=0
  104223. */
  104224. int ogg_page_packets(ogg_page *og){
  104225. int i,n=og->header[26],count=0;
  104226. for(i=0;i<n;i++)
  104227. if(og->header[27+i]<255)count++;
  104228. return(count);
  104229. }
  104230. #if 0
  104231. /* helper to initialize lookup for direct-table CRC (illustrative; we
  104232. use the static init below) */
  104233. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  104234. int i;
  104235. unsigned long r;
  104236. r = index << 24;
  104237. for (i=0; i<8; i++)
  104238. if (r & 0x80000000UL)
  104239. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  104240. polynomial, although we use an
  104241. unreflected alg and an init/final
  104242. of 0, not 0xffffffff */
  104243. else
  104244. r<<=1;
  104245. return (r & 0xffffffffUL);
  104246. }
  104247. #endif
  104248. static const ogg_uint32_t crc_lookup[256]={
  104249. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  104250. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  104251. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  104252. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  104253. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  104254. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  104255. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  104256. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  104257. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  104258. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  104259. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  104260. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  104261. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  104262. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  104263. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  104264. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  104265. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  104266. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  104267. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  104268. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  104269. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  104270. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  104271. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  104272. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  104273. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  104274. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  104275. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  104276. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  104277. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  104278. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  104279. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  104280. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  104281. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  104282. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  104283. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  104284. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  104285. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  104286. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  104287. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  104288. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  104289. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  104290. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  104291. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  104292. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  104293. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  104294. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  104295. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  104296. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  104297. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  104298. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  104299. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  104300. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  104301. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  104302. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  104303. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  104304. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  104305. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  104306. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  104307. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  104308. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  104309. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  104310. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  104311. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  104312. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  104313. /* init the encode/decode logical stream state */
  104314. int ogg_stream_init(ogg_stream_state *os,int serialno){
  104315. if(os){
  104316. memset(os,0,sizeof(*os));
  104317. os->body_storage=16*1024;
  104318. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  104319. os->lacing_storage=1024;
  104320. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  104321. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  104322. os->serialno=serialno;
  104323. return(0);
  104324. }
  104325. return(-1);
  104326. }
  104327. /* _clear does not free os, only the non-flat storage within */
  104328. int ogg_stream_clear(ogg_stream_state *os){
  104329. if(os){
  104330. if(os->body_data)_ogg_free(os->body_data);
  104331. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  104332. if(os->granule_vals)_ogg_free(os->granule_vals);
  104333. memset(os,0,sizeof(*os));
  104334. }
  104335. return(0);
  104336. }
  104337. int ogg_stream_destroy(ogg_stream_state *os){
  104338. if(os){
  104339. ogg_stream_clear(os);
  104340. _ogg_free(os);
  104341. }
  104342. return(0);
  104343. }
  104344. /* Helpers for ogg_stream_encode; this keeps the structure and
  104345. what's happening fairly clear */
  104346. static void _os_body_expand(ogg_stream_state *os,int needed){
  104347. if(os->body_storage<=os->body_fill+needed){
  104348. os->body_storage+=(needed+1024);
  104349. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  104350. }
  104351. }
  104352. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  104353. if(os->lacing_storage<=os->lacing_fill+needed){
  104354. os->lacing_storage+=(needed+32);
  104355. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  104356. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  104357. }
  104358. }
  104359. /* checksum the page */
  104360. /* Direct table CRC; note that this will be faster in the future if we
  104361. perform the checksum silmultaneously with other copies */
  104362. void ogg_page_checksum_set(ogg_page *og){
  104363. if(og){
  104364. ogg_uint32_t crc_reg=0;
  104365. int i;
  104366. /* safety; needed for API behavior, but not framing code */
  104367. og->header[22]=0;
  104368. og->header[23]=0;
  104369. og->header[24]=0;
  104370. og->header[25]=0;
  104371. for(i=0;i<og->header_len;i++)
  104372. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  104373. for(i=0;i<og->body_len;i++)
  104374. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  104375. og->header[22]=(unsigned char)(crc_reg&0xff);
  104376. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  104377. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  104378. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  104379. }
  104380. }
  104381. /* submit data to the internal buffer of the framing engine */
  104382. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  104383. int lacing_vals=op->bytes/255+1,i;
  104384. if(os->body_returned){
  104385. /* advance packet data according to the body_returned pointer. We
  104386. had to keep it around to return a pointer into the buffer last
  104387. call */
  104388. os->body_fill-=os->body_returned;
  104389. if(os->body_fill)
  104390. memmove(os->body_data,os->body_data+os->body_returned,
  104391. os->body_fill);
  104392. os->body_returned=0;
  104393. }
  104394. /* make sure we have the buffer storage */
  104395. _os_body_expand(os,op->bytes);
  104396. _os_lacing_expand(os,lacing_vals);
  104397. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  104398. the liability of overly clean abstraction for the time being. It
  104399. will actually be fairly easy to eliminate the extra copy in the
  104400. future */
  104401. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  104402. os->body_fill+=op->bytes;
  104403. /* Store lacing vals for this packet */
  104404. for(i=0;i<lacing_vals-1;i++){
  104405. os->lacing_vals[os->lacing_fill+i]=255;
  104406. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  104407. }
  104408. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  104409. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  104410. /* flag the first segment as the beginning of the packet */
  104411. os->lacing_vals[os->lacing_fill]|= 0x100;
  104412. os->lacing_fill+=lacing_vals;
  104413. /* for the sake of completeness */
  104414. os->packetno++;
  104415. if(op->e_o_s)os->e_o_s=1;
  104416. return(0);
  104417. }
  104418. /* This will flush remaining packets into a page (returning nonzero),
  104419. even if there is not enough data to trigger a flush normally
  104420. (undersized page). If there are no packets or partial packets to
  104421. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  104422. try to flush a normal sized page like ogg_stream_pageout; a call to
  104423. ogg_stream_flush does not guarantee that all packets have flushed.
  104424. Only a return value of 0 from ogg_stream_flush indicates all packet
  104425. data is flushed into pages.
  104426. since ogg_stream_flush will flush the last page in a stream even if
  104427. it's undersized, you almost certainly want to use ogg_stream_pageout
  104428. (and *not* ogg_stream_flush) unless you specifically need to flush
  104429. an page regardless of size in the middle of a stream. */
  104430. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  104431. int i;
  104432. int vals=0;
  104433. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  104434. int bytes=0;
  104435. long acc=0;
  104436. ogg_int64_t granule_pos=-1;
  104437. if(maxvals==0)return(0);
  104438. /* construct a page */
  104439. /* decide how many segments to include */
  104440. /* If this is the initial header case, the first page must only include
  104441. the initial header packet */
  104442. if(os->b_o_s==0){ /* 'initial header page' case */
  104443. granule_pos=0;
  104444. for(vals=0;vals<maxvals;vals++){
  104445. if((os->lacing_vals[vals]&0x0ff)<255){
  104446. vals++;
  104447. break;
  104448. }
  104449. }
  104450. }else{
  104451. for(vals=0;vals<maxvals;vals++){
  104452. if(acc>4096)break;
  104453. acc+=os->lacing_vals[vals]&0x0ff;
  104454. if((os->lacing_vals[vals]&0xff)<255)
  104455. granule_pos=os->granule_vals[vals];
  104456. }
  104457. }
  104458. /* construct the header in temp storage */
  104459. memcpy(os->header,"OggS",4);
  104460. /* stream structure version */
  104461. os->header[4]=0x00;
  104462. /* continued packet flag? */
  104463. os->header[5]=0x00;
  104464. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  104465. /* first page flag? */
  104466. if(os->b_o_s==0)os->header[5]|=0x02;
  104467. /* last page flag? */
  104468. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  104469. os->b_o_s=1;
  104470. /* 64 bits of PCM position */
  104471. for(i=6;i<14;i++){
  104472. os->header[i]=(unsigned char)(granule_pos&0xff);
  104473. granule_pos>>=8;
  104474. }
  104475. /* 32 bits of stream serial number */
  104476. {
  104477. long serialno=os->serialno;
  104478. for(i=14;i<18;i++){
  104479. os->header[i]=(unsigned char)(serialno&0xff);
  104480. serialno>>=8;
  104481. }
  104482. }
  104483. /* 32 bits of page counter (we have both counter and page header
  104484. because this val can roll over) */
  104485. if(os->pageno==-1)os->pageno=0; /* because someone called
  104486. stream_reset; this would be a
  104487. strange thing to do in an
  104488. encode stream, but it has
  104489. plausible uses */
  104490. {
  104491. long pageno=os->pageno++;
  104492. for(i=18;i<22;i++){
  104493. os->header[i]=(unsigned char)(pageno&0xff);
  104494. pageno>>=8;
  104495. }
  104496. }
  104497. /* zero for computation; filled in later */
  104498. os->header[22]=0;
  104499. os->header[23]=0;
  104500. os->header[24]=0;
  104501. os->header[25]=0;
  104502. /* segment table */
  104503. os->header[26]=(unsigned char)(vals&0xff);
  104504. for(i=0;i<vals;i++)
  104505. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  104506. /* set pointers in the ogg_page struct */
  104507. og->header=os->header;
  104508. og->header_len=os->header_fill=vals+27;
  104509. og->body=os->body_data+os->body_returned;
  104510. og->body_len=bytes;
  104511. /* advance the lacing data and set the body_returned pointer */
  104512. os->lacing_fill-=vals;
  104513. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  104514. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  104515. os->body_returned+=bytes;
  104516. /* calculate the checksum */
  104517. ogg_page_checksum_set(og);
  104518. /* done */
  104519. return(1);
  104520. }
  104521. /* This constructs pages from buffered packet segments. The pointers
  104522. returned are to static buffers; do not free. The returned buffers are
  104523. good only until the next call (using the same ogg_stream_state) */
  104524. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  104525. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  104526. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  104527. os->lacing_fill>=255 || /* 'segment table full' case */
  104528. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  104529. return(ogg_stream_flush(os,og));
  104530. }
  104531. /* not enough data to construct a page and not end of stream */
  104532. return(0);
  104533. }
  104534. int ogg_stream_eos(ogg_stream_state *os){
  104535. return os->e_o_s;
  104536. }
  104537. /* DECODING PRIMITIVES: packet streaming layer **********************/
  104538. /* This has two layers to place more of the multi-serialno and paging
  104539. control in the application's hands. First, we expose a data buffer
  104540. using ogg_sync_buffer(). The app either copies into the
  104541. buffer, or passes it directly to read(), etc. We then call
  104542. ogg_sync_wrote() to tell how many bytes we just added.
  104543. Pages are returned (pointers into the buffer in ogg_sync_state)
  104544. by ogg_sync_pageout(). The page is then submitted to
  104545. ogg_stream_pagein() along with the appropriate
  104546. ogg_stream_state* (ie, matching serialno). We then get raw
  104547. packets out calling ogg_stream_packetout() with a
  104548. ogg_stream_state. */
  104549. /* initialize the struct to a known state */
  104550. int ogg_sync_init(ogg_sync_state *oy){
  104551. if(oy){
  104552. memset(oy,0,sizeof(*oy));
  104553. }
  104554. return(0);
  104555. }
  104556. /* clear non-flat storage within */
  104557. int ogg_sync_clear(ogg_sync_state *oy){
  104558. if(oy){
  104559. if(oy->data)_ogg_free(oy->data);
  104560. ogg_sync_init(oy);
  104561. }
  104562. return(0);
  104563. }
  104564. int ogg_sync_destroy(ogg_sync_state *oy){
  104565. if(oy){
  104566. ogg_sync_clear(oy);
  104567. _ogg_free(oy);
  104568. }
  104569. return(0);
  104570. }
  104571. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  104572. /* first, clear out any space that has been previously returned */
  104573. if(oy->returned){
  104574. oy->fill-=oy->returned;
  104575. if(oy->fill>0)
  104576. memmove(oy->data,oy->data+oy->returned,oy->fill);
  104577. oy->returned=0;
  104578. }
  104579. if(size>oy->storage-oy->fill){
  104580. /* We need to extend the internal buffer */
  104581. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  104582. if(oy->data)
  104583. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  104584. else
  104585. oy->data=(unsigned char*) _ogg_malloc(newsize);
  104586. oy->storage=newsize;
  104587. }
  104588. /* expose a segment at least as large as requested at the fill mark */
  104589. return((char *)oy->data+oy->fill);
  104590. }
  104591. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  104592. if(oy->fill+bytes>oy->storage)return(-1);
  104593. oy->fill+=bytes;
  104594. return(0);
  104595. }
  104596. /* sync the stream. This is meant to be useful for finding page
  104597. boundaries.
  104598. return values for this:
  104599. -n) skipped n bytes
  104600. 0) page not ready; more data (no bytes skipped)
  104601. n) page synced at current location; page length n bytes
  104602. */
  104603. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  104604. unsigned char *page=oy->data+oy->returned;
  104605. unsigned char *next;
  104606. long bytes=oy->fill-oy->returned;
  104607. if(oy->headerbytes==0){
  104608. int headerbytes,i;
  104609. if(bytes<27)return(0); /* not enough for a header */
  104610. /* verify capture pattern */
  104611. if(memcmp(page,"OggS",4))goto sync_fail;
  104612. headerbytes=page[26]+27;
  104613. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  104614. /* count up body length in the segment table */
  104615. for(i=0;i<page[26];i++)
  104616. oy->bodybytes+=page[27+i];
  104617. oy->headerbytes=headerbytes;
  104618. }
  104619. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  104620. /* The whole test page is buffered. Verify the checksum */
  104621. {
  104622. /* Grab the checksum bytes, set the header field to zero */
  104623. char chksum[4];
  104624. ogg_page log;
  104625. memcpy(chksum,page+22,4);
  104626. memset(page+22,0,4);
  104627. /* set up a temp page struct and recompute the checksum */
  104628. log.header=page;
  104629. log.header_len=oy->headerbytes;
  104630. log.body=page+oy->headerbytes;
  104631. log.body_len=oy->bodybytes;
  104632. ogg_page_checksum_set(&log);
  104633. /* Compare */
  104634. if(memcmp(chksum,page+22,4)){
  104635. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  104636. at all) */
  104637. /* replace the computed checksum with the one actually read in */
  104638. memcpy(page+22,chksum,4);
  104639. /* Bad checksum. Lose sync */
  104640. goto sync_fail;
  104641. }
  104642. }
  104643. /* yes, have a whole page all ready to go */
  104644. {
  104645. unsigned char *page=oy->data+oy->returned;
  104646. long bytes;
  104647. if(og){
  104648. og->header=page;
  104649. og->header_len=oy->headerbytes;
  104650. og->body=page+oy->headerbytes;
  104651. og->body_len=oy->bodybytes;
  104652. }
  104653. oy->unsynced=0;
  104654. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  104655. oy->headerbytes=0;
  104656. oy->bodybytes=0;
  104657. return(bytes);
  104658. }
  104659. sync_fail:
  104660. oy->headerbytes=0;
  104661. oy->bodybytes=0;
  104662. /* search for possible capture */
  104663. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  104664. if(!next)
  104665. next=oy->data+oy->fill;
  104666. oy->returned=next-oy->data;
  104667. return(-(next-page));
  104668. }
  104669. /* sync the stream and get a page. Keep trying until we find a page.
  104670. Supress 'sync errors' after reporting the first.
  104671. return values:
  104672. -1) recapture (hole in data)
  104673. 0) need more data
  104674. 1) page returned
  104675. Returns pointers into buffered data; invalidated by next call to
  104676. _stream, _clear, _init, or _buffer */
  104677. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  104678. /* all we need to do is verify a page at the head of the stream
  104679. buffer. If it doesn't verify, we look for the next potential
  104680. frame */
  104681. for(;;){
  104682. long ret=ogg_sync_pageseek(oy,og);
  104683. if(ret>0){
  104684. /* have a page */
  104685. return(1);
  104686. }
  104687. if(ret==0){
  104688. /* need more data */
  104689. return(0);
  104690. }
  104691. /* head did not start a synced page... skipped some bytes */
  104692. if(!oy->unsynced){
  104693. oy->unsynced=1;
  104694. return(-1);
  104695. }
  104696. /* loop. keep looking */
  104697. }
  104698. }
  104699. /* add the incoming page to the stream state; we decompose the page
  104700. into packet segments here as well. */
  104701. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  104702. unsigned char *header=og->header;
  104703. unsigned char *body=og->body;
  104704. long bodysize=og->body_len;
  104705. int segptr=0;
  104706. int version=ogg_page_version(og);
  104707. int continued=ogg_page_continued(og);
  104708. int bos=ogg_page_bos(og);
  104709. int eos=ogg_page_eos(og);
  104710. ogg_int64_t granulepos=ogg_page_granulepos(og);
  104711. int serialno=ogg_page_serialno(og);
  104712. long pageno=ogg_page_pageno(og);
  104713. int segments=header[26];
  104714. /* clean up 'returned data' */
  104715. {
  104716. long lr=os->lacing_returned;
  104717. long br=os->body_returned;
  104718. /* body data */
  104719. if(br){
  104720. os->body_fill-=br;
  104721. if(os->body_fill)
  104722. memmove(os->body_data,os->body_data+br,os->body_fill);
  104723. os->body_returned=0;
  104724. }
  104725. if(lr){
  104726. /* segment table */
  104727. if(os->lacing_fill-lr){
  104728. memmove(os->lacing_vals,os->lacing_vals+lr,
  104729. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  104730. memmove(os->granule_vals,os->granule_vals+lr,
  104731. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  104732. }
  104733. os->lacing_fill-=lr;
  104734. os->lacing_packet-=lr;
  104735. os->lacing_returned=0;
  104736. }
  104737. }
  104738. /* check the serial number */
  104739. if(serialno!=os->serialno)return(-1);
  104740. if(version>0)return(-1);
  104741. _os_lacing_expand(os,segments+1);
  104742. /* are we in sequence? */
  104743. if(pageno!=os->pageno){
  104744. int i;
  104745. /* unroll previous partial packet (if any) */
  104746. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  104747. os->body_fill-=os->lacing_vals[i]&0xff;
  104748. os->lacing_fill=os->lacing_packet;
  104749. /* make a note of dropped data in segment table */
  104750. if(os->pageno!=-1){
  104751. os->lacing_vals[os->lacing_fill++]=0x400;
  104752. os->lacing_packet++;
  104753. }
  104754. }
  104755. /* are we a 'continued packet' page? If so, we may need to skip
  104756. some segments */
  104757. if(continued){
  104758. if(os->lacing_fill<1 ||
  104759. os->lacing_vals[os->lacing_fill-1]==0x400){
  104760. bos=0;
  104761. for(;segptr<segments;segptr++){
  104762. int val=header[27+segptr];
  104763. body+=val;
  104764. bodysize-=val;
  104765. if(val<255){
  104766. segptr++;
  104767. break;
  104768. }
  104769. }
  104770. }
  104771. }
  104772. if(bodysize){
  104773. _os_body_expand(os,bodysize);
  104774. memcpy(os->body_data+os->body_fill,body,bodysize);
  104775. os->body_fill+=bodysize;
  104776. }
  104777. {
  104778. int saved=-1;
  104779. while(segptr<segments){
  104780. int val=header[27+segptr];
  104781. os->lacing_vals[os->lacing_fill]=val;
  104782. os->granule_vals[os->lacing_fill]=-1;
  104783. if(bos){
  104784. os->lacing_vals[os->lacing_fill]|=0x100;
  104785. bos=0;
  104786. }
  104787. if(val<255)saved=os->lacing_fill;
  104788. os->lacing_fill++;
  104789. segptr++;
  104790. if(val<255)os->lacing_packet=os->lacing_fill;
  104791. }
  104792. /* set the granulepos on the last granuleval of the last full packet */
  104793. if(saved!=-1){
  104794. os->granule_vals[saved]=granulepos;
  104795. }
  104796. }
  104797. if(eos){
  104798. os->e_o_s=1;
  104799. if(os->lacing_fill>0)
  104800. os->lacing_vals[os->lacing_fill-1]|=0x200;
  104801. }
  104802. os->pageno=pageno+1;
  104803. return(0);
  104804. }
  104805. /* clear things to an initial state. Good to call, eg, before seeking */
  104806. int ogg_sync_reset(ogg_sync_state *oy){
  104807. oy->fill=0;
  104808. oy->returned=0;
  104809. oy->unsynced=0;
  104810. oy->headerbytes=0;
  104811. oy->bodybytes=0;
  104812. return(0);
  104813. }
  104814. int ogg_stream_reset(ogg_stream_state *os){
  104815. os->body_fill=0;
  104816. os->body_returned=0;
  104817. os->lacing_fill=0;
  104818. os->lacing_packet=0;
  104819. os->lacing_returned=0;
  104820. os->header_fill=0;
  104821. os->e_o_s=0;
  104822. os->b_o_s=0;
  104823. os->pageno=-1;
  104824. os->packetno=0;
  104825. os->granulepos=0;
  104826. return(0);
  104827. }
  104828. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  104829. ogg_stream_reset(os);
  104830. os->serialno=serialno;
  104831. return(0);
  104832. }
  104833. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  104834. /* The last part of decode. We have the stream broken into packet
  104835. segments. Now we need to group them into packets (or return the
  104836. out of sync markers) */
  104837. int ptr=os->lacing_returned;
  104838. if(os->lacing_packet<=ptr)return(0);
  104839. if(os->lacing_vals[ptr]&0x400){
  104840. /* we need to tell the codec there's a gap; it might need to
  104841. handle previous packet dependencies. */
  104842. os->lacing_returned++;
  104843. os->packetno++;
  104844. return(-1);
  104845. }
  104846. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  104847. to ask if there's a whole packet
  104848. waiting */
  104849. /* Gather the whole packet. We'll have no holes or a partial packet */
  104850. {
  104851. int size=os->lacing_vals[ptr]&0xff;
  104852. int bytes=size;
  104853. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  104854. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  104855. while(size==255){
  104856. int val=os->lacing_vals[++ptr];
  104857. size=val&0xff;
  104858. if(val&0x200)eos=0x200;
  104859. bytes+=size;
  104860. }
  104861. if(op){
  104862. op->e_o_s=eos;
  104863. op->b_o_s=bos;
  104864. op->packet=os->body_data+os->body_returned;
  104865. op->packetno=os->packetno;
  104866. op->granulepos=os->granule_vals[ptr];
  104867. op->bytes=bytes;
  104868. }
  104869. if(adv){
  104870. os->body_returned+=bytes;
  104871. os->lacing_returned=ptr+1;
  104872. os->packetno++;
  104873. }
  104874. }
  104875. return(1);
  104876. }
  104877. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  104878. return _packetout(os,op,1);
  104879. }
  104880. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  104881. return _packetout(os,op,0);
  104882. }
  104883. void ogg_packet_clear(ogg_packet *op) {
  104884. _ogg_free(op->packet);
  104885. memset(op, 0, sizeof(*op));
  104886. }
  104887. #ifdef _V_SELFTEST
  104888. #include <stdio.h>
  104889. ogg_stream_state os_en, os_de;
  104890. ogg_sync_state oy;
  104891. void checkpacket(ogg_packet *op,int len, int no, int pos){
  104892. long j;
  104893. static int sequence=0;
  104894. static int lastno=0;
  104895. if(op->bytes!=len){
  104896. fprintf(stderr,"incorrect packet length!\n");
  104897. exit(1);
  104898. }
  104899. if(op->granulepos!=pos){
  104900. fprintf(stderr,"incorrect packet position!\n");
  104901. exit(1);
  104902. }
  104903. /* packet number just follows sequence/gap; adjust the input number
  104904. for that */
  104905. if(no==0){
  104906. sequence=0;
  104907. }else{
  104908. sequence++;
  104909. if(no>lastno+1)
  104910. sequence++;
  104911. }
  104912. lastno=no;
  104913. if(op->packetno!=sequence){
  104914. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  104915. (long)(op->packetno),sequence);
  104916. exit(1);
  104917. }
  104918. /* Test data */
  104919. for(j=0;j<op->bytes;j++)
  104920. if(op->packet[j]!=((j+no)&0xff)){
  104921. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  104922. j,op->packet[j],(j+no)&0xff);
  104923. exit(1);
  104924. }
  104925. }
  104926. void check_page(unsigned char *data,const int *header,ogg_page *og){
  104927. long j;
  104928. /* Test data */
  104929. for(j=0;j<og->body_len;j++)
  104930. if(og->body[j]!=data[j]){
  104931. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  104932. j,data[j],og->body[j]);
  104933. exit(1);
  104934. }
  104935. /* Test header */
  104936. for(j=0;j<og->header_len;j++){
  104937. if(og->header[j]!=header[j]){
  104938. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  104939. for(j=0;j<header[26]+27;j++)
  104940. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  104941. fprintf(stderr,"\n");
  104942. exit(1);
  104943. }
  104944. }
  104945. if(og->header_len!=header[26]+27){
  104946. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  104947. og->header_len,header[26]+27);
  104948. exit(1);
  104949. }
  104950. }
  104951. void print_header(ogg_page *og){
  104952. int j;
  104953. fprintf(stderr,"\nHEADER:\n");
  104954. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  104955. og->header[0],og->header[1],og->header[2],og->header[3],
  104956. (int)og->header[4],(int)og->header[5]);
  104957. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  104958. (og->header[9]<<24)|(og->header[8]<<16)|
  104959. (og->header[7]<<8)|og->header[6],
  104960. (og->header[17]<<24)|(og->header[16]<<16)|
  104961. (og->header[15]<<8)|og->header[14],
  104962. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  104963. (og->header[19]<<8)|og->header[18]);
  104964. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  104965. (int)og->header[22],(int)og->header[23],
  104966. (int)og->header[24],(int)og->header[25],
  104967. (int)og->header[26]);
  104968. for(j=27;j<og->header_len;j++)
  104969. fprintf(stderr,"%d ",(int)og->header[j]);
  104970. fprintf(stderr,")\n\n");
  104971. }
  104972. void copy_page(ogg_page *og){
  104973. unsigned char *temp=_ogg_malloc(og->header_len);
  104974. memcpy(temp,og->header,og->header_len);
  104975. og->header=temp;
  104976. temp=_ogg_malloc(og->body_len);
  104977. memcpy(temp,og->body,og->body_len);
  104978. og->body=temp;
  104979. }
  104980. void free_page(ogg_page *og){
  104981. _ogg_free (og->header);
  104982. _ogg_free (og->body);
  104983. }
  104984. void error(void){
  104985. fprintf(stderr,"error!\n");
  104986. exit(1);
  104987. }
  104988. /* 17 only */
  104989. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  104990. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104991. 0x01,0x02,0x03,0x04,0,0,0,0,
  104992. 0x15,0xed,0xec,0x91,
  104993. 1,
  104994. 17};
  104995. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104996. const int head1_1[] = {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. 0x59,0x10,0x6c,0x2c,
  105000. 1,
  105001. 17};
  105002. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105003. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  105004. 0x01,0x02,0x03,0x04,1,0,0,0,
  105005. 0x89,0x33,0x85,0xce,
  105006. 13,
  105007. 254,255,0,255,1,255,245,255,255,0,
  105008. 255,255,90};
  105009. /* nil packets; beginning,middle,end */
  105010. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105011. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105012. 0x01,0x02,0x03,0x04,0,0,0,0,
  105013. 0xff,0x7b,0x23,0x17,
  105014. 1,
  105015. 0};
  105016. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105017. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  105018. 0x01,0x02,0x03,0x04,1,0,0,0,
  105019. 0x5c,0x3f,0x66,0xcb,
  105020. 17,
  105021. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  105022. 255,255,90,0};
  105023. /* large initial packet */
  105024. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105025. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105026. 0x01,0x02,0x03,0x04,0,0,0,0,
  105027. 0x01,0x27,0x31,0xaa,
  105028. 18,
  105029. 255,255,255,255,255,255,255,255,
  105030. 255,255,255,255,255,255,255,255,255,10};
  105031. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105032. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  105033. 0x01,0x02,0x03,0x04,1,0,0,0,
  105034. 0x7f,0x4e,0x8a,0xd2,
  105035. 4,
  105036. 255,4,255,0};
  105037. /* continuing packet test */
  105038. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105039. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105040. 0x01,0x02,0x03,0x04,0,0,0,0,
  105041. 0xff,0x7b,0x23,0x17,
  105042. 1,
  105043. 0};
  105044. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105045. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105046. 0x01,0x02,0x03,0x04,1,0,0,0,
  105047. 0x54,0x05,0x51,0xc8,
  105048. 17,
  105049. 255,255,255,255,255,255,255,255,
  105050. 255,255,255,255,255,255,255,255,255};
  105051. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105052. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  105053. 0x01,0x02,0x03,0x04,2,0,0,0,
  105054. 0xc8,0xc3,0xcb,0xed,
  105055. 5,
  105056. 10,255,4,255,0};
  105057. /* page with the 255 segment limit */
  105058. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105059. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105060. 0x01,0x02,0x03,0x04,0,0,0,0,
  105061. 0xff,0x7b,0x23,0x17,
  105062. 1,
  105063. 0};
  105064. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105065. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  105066. 0x01,0x02,0x03,0x04,1,0,0,0,
  105067. 0xed,0x2a,0x2e,0xa7,
  105068. 255,
  105069. 10,10,10,10,10,10,10,10,
  105070. 10,10,10,10,10,10,10,10,
  105071. 10,10,10,10,10,10,10,10,
  105072. 10,10,10,10,10,10,10,10,
  105073. 10,10,10,10,10,10,10,10,
  105074. 10,10,10,10,10,10,10,10,
  105075. 10,10,10,10,10,10,10,10,
  105076. 10,10,10,10,10,10,10,10,
  105077. 10,10,10,10,10,10,10,10,
  105078. 10,10,10,10,10,10,10,10,
  105079. 10,10,10,10,10,10,10,10,
  105080. 10,10,10,10,10,10,10,10,
  105081. 10,10,10,10,10,10,10,10,
  105082. 10,10,10,10,10,10,10,10,
  105083. 10,10,10,10,10,10,10,10,
  105084. 10,10,10,10,10,10,10,10,
  105085. 10,10,10,10,10,10,10,10,
  105086. 10,10,10,10,10,10,10,10,
  105087. 10,10,10,10,10,10,10,10,
  105088. 10,10,10,10,10,10,10,10,
  105089. 10,10,10,10,10,10,10,10,
  105090. 10,10,10,10,10,10,10,10,
  105091. 10,10,10,10,10,10,10,10,
  105092. 10,10,10,10,10,10,10,10,
  105093. 10,10,10,10,10,10,10,10,
  105094. 10,10,10,10,10,10,10,10,
  105095. 10,10,10,10,10,10,10,10,
  105096. 10,10,10,10,10,10,10,10,
  105097. 10,10,10,10,10,10,10,10,
  105098. 10,10,10,10,10,10,10,10,
  105099. 10,10,10,10,10,10,10,10,
  105100. 10,10,10,10,10,10,10};
  105101. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  105102. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  105103. 0x01,0x02,0x03,0x04,2,0,0,0,
  105104. 0x6c,0x3b,0x82,0x3d,
  105105. 1,
  105106. 50};
  105107. /* packet that overspans over an entire page */
  105108. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105109. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105110. 0x01,0x02,0x03,0x04,0,0,0,0,
  105111. 0xff,0x7b,0x23,0x17,
  105112. 1,
  105113. 0};
  105114. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105115. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105116. 0x01,0x02,0x03,0x04,1,0,0,0,
  105117. 0x3c,0xd9,0x4d,0x3f,
  105118. 17,
  105119. 100,255,255,255,255,255,255,255,255,
  105120. 255,255,255,255,255,255,255,255};
  105121. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  105122. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  105123. 0x01,0x02,0x03,0x04,2,0,0,0,
  105124. 0x01,0xd2,0xe5,0xe5,
  105125. 17,
  105126. 255,255,255,255,255,255,255,255,
  105127. 255,255,255,255,255,255,255,255,255};
  105128. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105129. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  105130. 0x01,0x02,0x03,0x04,3,0,0,0,
  105131. 0xef,0xdd,0x88,0xde,
  105132. 7,
  105133. 255,255,75,255,4,255,0};
  105134. /* packet that overspans over an entire page */
  105135. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  105136. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  105137. 0x01,0x02,0x03,0x04,0,0,0,0,
  105138. 0xff,0x7b,0x23,0x17,
  105139. 1,
  105140. 0};
  105141. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  105142. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  105143. 0x01,0x02,0x03,0x04,1,0,0,0,
  105144. 0x3c,0xd9,0x4d,0x3f,
  105145. 17,
  105146. 100,255,255,255,255,255,255,255,255,
  105147. 255,255,255,255,255,255,255,255};
  105148. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  105149. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  105150. 0x01,0x02,0x03,0x04,2,0,0,0,
  105151. 0xd4,0xe0,0x60,0xe5,
  105152. 1,0};
  105153. void test_pack(const int *pl, const int **headers, int byteskip,
  105154. int pageskip, int packetskip){
  105155. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  105156. long inptr=0;
  105157. long outptr=0;
  105158. long deptr=0;
  105159. long depacket=0;
  105160. long granule_pos=7,pageno=0;
  105161. int i,j,packets,pageout=pageskip;
  105162. int eosflag=0;
  105163. int bosflag=0;
  105164. int byteskipcount=0;
  105165. ogg_stream_reset(&os_en);
  105166. ogg_stream_reset(&os_de);
  105167. ogg_sync_reset(&oy);
  105168. for(packets=0;packets<packetskip;packets++)
  105169. depacket+=pl[packets];
  105170. for(packets=0;;packets++)if(pl[packets]==-1)break;
  105171. for(i=0;i<packets;i++){
  105172. /* construct a test packet */
  105173. ogg_packet op;
  105174. int len=pl[i];
  105175. op.packet=data+inptr;
  105176. op.bytes=len;
  105177. op.e_o_s=(pl[i+1]<0?1:0);
  105178. op.granulepos=granule_pos;
  105179. granule_pos+=1024;
  105180. for(j=0;j<len;j++)data[inptr++]=i+j;
  105181. /* submit the test packet */
  105182. ogg_stream_packetin(&os_en,&op);
  105183. /* retrieve any finished pages */
  105184. {
  105185. ogg_page og;
  105186. while(ogg_stream_pageout(&os_en,&og)){
  105187. /* We have a page. Check it carefully */
  105188. fprintf(stderr,"%ld, ",pageno);
  105189. if(headers[pageno]==NULL){
  105190. fprintf(stderr,"coded too many pages!\n");
  105191. exit(1);
  105192. }
  105193. check_page(data+outptr,headers[pageno],&og);
  105194. outptr+=og.body_len;
  105195. pageno++;
  105196. if(pageskip){
  105197. bosflag=1;
  105198. pageskip--;
  105199. deptr+=og.body_len;
  105200. }
  105201. /* have a complete page; submit it to sync/decode */
  105202. {
  105203. ogg_page og_de;
  105204. ogg_packet op_de,op_de2;
  105205. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  105206. char *next=buf;
  105207. byteskipcount+=og.header_len;
  105208. if(byteskipcount>byteskip){
  105209. memcpy(next,og.header,byteskipcount-byteskip);
  105210. next+=byteskipcount-byteskip;
  105211. byteskipcount=byteskip;
  105212. }
  105213. byteskipcount+=og.body_len;
  105214. if(byteskipcount>byteskip){
  105215. memcpy(next,og.body,byteskipcount-byteskip);
  105216. next+=byteskipcount-byteskip;
  105217. byteskipcount=byteskip;
  105218. }
  105219. ogg_sync_wrote(&oy,next-buf);
  105220. while(1){
  105221. int ret=ogg_sync_pageout(&oy,&og_de);
  105222. if(ret==0)break;
  105223. if(ret<0)continue;
  105224. /* got a page. Happy happy. Verify that it's good. */
  105225. fprintf(stderr,"(%ld), ",pageout);
  105226. check_page(data+deptr,headers[pageout],&og_de);
  105227. deptr+=og_de.body_len;
  105228. pageout++;
  105229. /* submit it to deconstitution */
  105230. ogg_stream_pagein(&os_de,&og_de);
  105231. /* packets out? */
  105232. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  105233. ogg_stream_packetpeek(&os_de,NULL);
  105234. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  105235. /* verify peek and out match */
  105236. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  105237. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  105238. depacket);
  105239. exit(1);
  105240. }
  105241. /* verify the packet! */
  105242. /* check data */
  105243. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  105244. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  105245. depacket);
  105246. exit(1);
  105247. }
  105248. /* check bos flag */
  105249. if(bosflag==0 && op_de.b_o_s==0){
  105250. fprintf(stderr,"b_o_s flag not set on packet!\n");
  105251. exit(1);
  105252. }
  105253. if(bosflag && op_de.b_o_s){
  105254. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  105255. exit(1);
  105256. }
  105257. bosflag=1;
  105258. depacket+=op_de.bytes;
  105259. /* check eos flag */
  105260. if(eosflag){
  105261. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  105262. exit(1);
  105263. }
  105264. if(op_de.e_o_s)eosflag=1;
  105265. /* check granulepos flag */
  105266. if(op_de.granulepos!=-1){
  105267. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  105268. }
  105269. }
  105270. }
  105271. }
  105272. }
  105273. }
  105274. }
  105275. _ogg_free(data);
  105276. if(headers[pageno]!=NULL){
  105277. fprintf(stderr,"did not write last page!\n");
  105278. exit(1);
  105279. }
  105280. if(headers[pageout]!=NULL){
  105281. fprintf(stderr,"did not decode last page!\n");
  105282. exit(1);
  105283. }
  105284. if(inptr!=outptr){
  105285. fprintf(stderr,"encoded page data incomplete!\n");
  105286. exit(1);
  105287. }
  105288. if(inptr!=deptr){
  105289. fprintf(stderr,"decoded page data incomplete!\n");
  105290. exit(1);
  105291. }
  105292. if(inptr!=depacket){
  105293. fprintf(stderr,"decoded packet data incomplete!\n");
  105294. exit(1);
  105295. }
  105296. if(!eosflag){
  105297. fprintf(stderr,"Never got a packet with EOS set!\n");
  105298. exit(1);
  105299. }
  105300. fprintf(stderr,"ok.\n");
  105301. }
  105302. int main(void){
  105303. ogg_stream_init(&os_en,0x04030201);
  105304. ogg_stream_init(&os_de,0x04030201);
  105305. ogg_sync_init(&oy);
  105306. /* Exercise each code path in the framing code. Also verify that
  105307. the checksums are working. */
  105308. {
  105309. /* 17 only */
  105310. const int packets[]={17, -1};
  105311. const int *headret[]={head1_0,NULL};
  105312. fprintf(stderr,"testing single page encoding... ");
  105313. test_pack(packets,headret,0,0,0);
  105314. }
  105315. {
  105316. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  105317. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  105318. const int *headret[]={head1_1,head2_1,NULL};
  105319. fprintf(stderr,"testing basic page encoding... ");
  105320. test_pack(packets,headret,0,0,0);
  105321. }
  105322. {
  105323. /* nil packets; beginning,middle,end */
  105324. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  105325. const int *headret[]={head1_2,head2_2,NULL};
  105326. fprintf(stderr,"testing basic nil packets... ");
  105327. test_pack(packets,headret,0,0,0);
  105328. }
  105329. {
  105330. /* large initial packet */
  105331. const int packets[]={4345,259,255,-1};
  105332. const int *headret[]={head1_3,head2_3,NULL};
  105333. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  105334. test_pack(packets,headret,0,0,0);
  105335. }
  105336. {
  105337. /* continuing packet test */
  105338. const int packets[]={0,4345,259,255,-1};
  105339. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  105340. fprintf(stderr,"testing single packet page span... ");
  105341. test_pack(packets,headret,0,0,0);
  105342. }
  105343. /* page with the 255 segment limit */
  105344. {
  105345. const int packets[]={0,10,10,10,10,10,10,10,10,
  105346. 10,10,10,10,10,10,10,10,
  105347. 10,10,10,10,10,10,10,10,
  105348. 10,10,10,10,10,10,10,10,
  105349. 10,10,10,10,10,10,10,10,
  105350. 10,10,10,10,10,10,10,10,
  105351. 10,10,10,10,10,10,10,10,
  105352. 10,10,10,10,10,10,10,10,
  105353. 10,10,10,10,10,10,10,10,
  105354. 10,10,10,10,10,10,10,10,
  105355. 10,10,10,10,10,10,10,10,
  105356. 10,10,10,10,10,10,10,10,
  105357. 10,10,10,10,10,10,10,10,
  105358. 10,10,10,10,10,10,10,10,
  105359. 10,10,10,10,10,10,10,10,
  105360. 10,10,10,10,10,10,10,10,
  105361. 10,10,10,10,10,10,10,10,
  105362. 10,10,10,10,10,10,10,10,
  105363. 10,10,10,10,10,10,10,10,
  105364. 10,10,10,10,10,10,10,10,
  105365. 10,10,10,10,10,10,10,10,
  105366. 10,10,10,10,10,10,10,10,
  105367. 10,10,10,10,10,10,10,10,
  105368. 10,10,10,10,10,10,10,10,
  105369. 10,10,10,10,10,10,10,10,
  105370. 10,10,10,10,10,10,10,10,
  105371. 10,10,10,10,10,10,10,10,
  105372. 10,10,10,10,10,10,10,10,
  105373. 10,10,10,10,10,10,10,10,
  105374. 10,10,10,10,10,10,10,10,
  105375. 10,10,10,10,10,10,10,10,
  105376. 10,10,10,10,10,10,10,50,-1};
  105377. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  105378. fprintf(stderr,"testing max packet segments... ");
  105379. test_pack(packets,headret,0,0,0);
  105380. }
  105381. {
  105382. /* packet that overspans over an entire page */
  105383. const int packets[]={0,100,9000,259,255,-1};
  105384. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105385. fprintf(stderr,"testing very large packets... ");
  105386. test_pack(packets,headret,0,0,0);
  105387. }
  105388. {
  105389. /* test for the libogg 1.1.1 resync in large continuation bug
  105390. found by Josh Coalson) */
  105391. const int packets[]={0,100,9000,259,255,-1};
  105392. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105393. fprintf(stderr,"testing continuation resync in very large packets... ");
  105394. test_pack(packets,headret,100,2,3);
  105395. }
  105396. {
  105397. /* term only page. why not? */
  105398. const int packets[]={0,100,4080,-1};
  105399. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  105400. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  105401. test_pack(packets,headret,0,0,0);
  105402. }
  105403. {
  105404. /* build a bunch of pages for testing */
  105405. unsigned char *data=_ogg_malloc(1024*1024);
  105406. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  105407. int inptr=0,i,j;
  105408. ogg_page og[5];
  105409. ogg_stream_reset(&os_en);
  105410. for(i=0;pl[i]!=-1;i++){
  105411. ogg_packet op;
  105412. int len=pl[i];
  105413. op.packet=data+inptr;
  105414. op.bytes=len;
  105415. op.e_o_s=(pl[i+1]<0?1:0);
  105416. op.granulepos=(i+1)*1000;
  105417. for(j=0;j<len;j++)data[inptr++]=i+j;
  105418. ogg_stream_packetin(&os_en,&op);
  105419. }
  105420. _ogg_free(data);
  105421. /* retrieve finished pages */
  105422. for(i=0;i<5;i++){
  105423. if(ogg_stream_pageout(&os_en,&og[i])==0){
  105424. fprintf(stderr,"Too few pages output building sync tests!\n");
  105425. exit(1);
  105426. }
  105427. copy_page(&og[i]);
  105428. }
  105429. /* Test lost pages on pagein/packetout: no rollback */
  105430. {
  105431. ogg_page temp;
  105432. ogg_packet test;
  105433. fprintf(stderr,"Testing loss of pages... ");
  105434. ogg_sync_reset(&oy);
  105435. ogg_stream_reset(&os_de);
  105436. for(i=0;i<5;i++){
  105437. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105438. og[i].header_len);
  105439. ogg_sync_wrote(&oy,og[i].header_len);
  105440. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105441. ogg_sync_wrote(&oy,og[i].body_len);
  105442. }
  105443. ogg_sync_pageout(&oy,&temp);
  105444. ogg_stream_pagein(&os_de,&temp);
  105445. ogg_sync_pageout(&oy,&temp);
  105446. ogg_stream_pagein(&os_de,&temp);
  105447. ogg_sync_pageout(&oy,&temp);
  105448. /* skip */
  105449. ogg_sync_pageout(&oy,&temp);
  105450. ogg_stream_pagein(&os_de,&temp);
  105451. /* do we get the expected results/packets? */
  105452. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105453. checkpacket(&test,0,0,0);
  105454. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105455. checkpacket(&test,100,1,-1);
  105456. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105457. checkpacket(&test,4079,2,3000);
  105458. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105459. fprintf(stderr,"Error: loss of page did not return error\n");
  105460. exit(1);
  105461. }
  105462. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105463. checkpacket(&test,76,5,-1);
  105464. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105465. checkpacket(&test,34,6,-1);
  105466. fprintf(stderr,"ok.\n");
  105467. }
  105468. /* Test lost pages on pagein/packetout: rollback with continuation */
  105469. {
  105470. ogg_page temp;
  105471. ogg_packet test;
  105472. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  105473. ogg_sync_reset(&oy);
  105474. ogg_stream_reset(&os_de);
  105475. for(i=0;i<5;i++){
  105476. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105477. og[i].header_len);
  105478. ogg_sync_wrote(&oy,og[i].header_len);
  105479. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105480. ogg_sync_wrote(&oy,og[i].body_len);
  105481. }
  105482. ogg_sync_pageout(&oy,&temp);
  105483. ogg_stream_pagein(&os_de,&temp);
  105484. ogg_sync_pageout(&oy,&temp);
  105485. ogg_stream_pagein(&os_de,&temp);
  105486. ogg_sync_pageout(&oy,&temp);
  105487. ogg_stream_pagein(&os_de,&temp);
  105488. ogg_sync_pageout(&oy,&temp);
  105489. /* skip */
  105490. ogg_sync_pageout(&oy,&temp);
  105491. ogg_stream_pagein(&os_de,&temp);
  105492. /* do we get the expected results/packets? */
  105493. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105494. checkpacket(&test,0,0,0);
  105495. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105496. checkpacket(&test,100,1,-1);
  105497. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105498. checkpacket(&test,4079,2,3000);
  105499. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105500. checkpacket(&test,2956,3,4000);
  105501. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105502. fprintf(stderr,"Error: loss of page did not return error\n");
  105503. exit(1);
  105504. }
  105505. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105506. checkpacket(&test,300,13,14000);
  105507. fprintf(stderr,"ok.\n");
  105508. }
  105509. /* the rest only test sync */
  105510. {
  105511. ogg_page og_de;
  105512. /* Test fractional page inputs: incomplete capture */
  105513. fprintf(stderr,"Testing sync on partial inputs... ");
  105514. ogg_sync_reset(&oy);
  105515. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105516. 3);
  105517. ogg_sync_wrote(&oy,3);
  105518. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105519. /* Test fractional page inputs: incomplete fixed header */
  105520. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  105521. 20);
  105522. ogg_sync_wrote(&oy,20);
  105523. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105524. /* Test fractional page inputs: incomplete header */
  105525. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  105526. 5);
  105527. ogg_sync_wrote(&oy,5);
  105528. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105529. /* Test fractional page inputs: incomplete body */
  105530. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  105531. og[1].header_len-28);
  105532. ogg_sync_wrote(&oy,og[1].header_len-28);
  105533. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105534. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  105535. ogg_sync_wrote(&oy,1000);
  105536. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105537. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  105538. og[1].body_len-1000);
  105539. ogg_sync_wrote(&oy,og[1].body_len-1000);
  105540. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105541. fprintf(stderr,"ok.\n");
  105542. }
  105543. /* Test fractional page inputs: page + incomplete capture */
  105544. {
  105545. ogg_page og_de;
  105546. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  105547. ogg_sync_reset(&oy);
  105548. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105549. og[1].header_len);
  105550. ogg_sync_wrote(&oy,og[1].header_len);
  105551. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105552. og[1].body_len);
  105553. ogg_sync_wrote(&oy,og[1].body_len);
  105554. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105555. 20);
  105556. ogg_sync_wrote(&oy,20);
  105557. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105558. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105559. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  105560. og[1].header_len-20);
  105561. ogg_sync_wrote(&oy,og[1].header_len-20);
  105562. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105563. og[1].body_len);
  105564. ogg_sync_wrote(&oy,og[1].body_len);
  105565. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105566. fprintf(stderr,"ok.\n");
  105567. }
  105568. /* Test recapture: garbage + page */
  105569. {
  105570. ogg_page og_de;
  105571. fprintf(stderr,"Testing search for capture... ");
  105572. ogg_sync_reset(&oy);
  105573. /* 'garbage' */
  105574. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105575. og[1].body_len);
  105576. ogg_sync_wrote(&oy,og[1].body_len);
  105577. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105578. og[1].header_len);
  105579. ogg_sync_wrote(&oy,og[1].header_len);
  105580. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105581. og[1].body_len);
  105582. ogg_sync_wrote(&oy,og[1].body_len);
  105583. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105584. 20);
  105585. ogg_sync_wrote(&oy,20);
  105586. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105587. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105588. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105589. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  105590. og[2].header_len-20);
  105591. ogg_sync_wrote(&oy,og[2].header_len-20);
  105592. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105593. og[2].body_len);
  105594. ogg_sync_wrote(&oy,og[2].body_len);
  105595. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105596. fprintf(stderr,"ok.\n");
  105597. }
  105598. /* Test recapture: page + garbage + page */
  105599. {
  105600. ogg_page og_de;
  105601. fprintf(stderr,"Testing recapture... ");
  105602. ogg_sync_reset(&oy);
  105603. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105604. og[1].header_len);
  105605. ogg_sync_wrote(&oy,og[1].header_len);
  105606. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105607. og[1].body_len);
  105608. ogg_sync_wrote(&oy,og[1].body_len);
  105609. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105610. og[2].header_len);
  105611. ogg_sync_wrote(&oy,og[2].header_len);
  105612. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105613. og[2].header_len);
  105614. ogg_sync_wrote(&oy,og[2].header_len);
  105615. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105616. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105617. og[2].body_len-5);
  105618. ogg_sync_wrote(&oy,og[2].body_len-5);
  105619. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  105620. og[3].header_len);
  105621. ogg_sync_wrote(&oy,og[3].header_len);
  105622. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  105623. og[3].body_len);
  105624. ogg_sync_wrote(&oy,og[3].body_len);
  105625. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105626. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105627. fprintf(stderr,"ok.\n");
  105628. }
  105629. /* Free page data that was previously copied */
  105630. {
  105631. for(i=0;i<5;i++){
  105632. free_page(&og[i]);
  105633. }
  105634. }
  105635. }
  105636. return(0);
  105637. }
  105638. #endif
  105639. #endif
  105640. /********* End of inlined file: framing.c *********/
  105641. /********* Start of inlined file: analysis.c *********/
  105642. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105643. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105644. // tasks..
  105645. #if JUCE_MSVC
  105646. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105647. #endif
  105648. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105649. #if JUCE_USE_OGGVORBIS
  105650. #include <stdio.h>
  105651. #include <string.h>
  105652. #include <math.h>
  105653. /********* Start of inlined file: codec_internal.h *********/
  105654. #ifndef _V_CODECI_H_
  105655. #define _V_CODECI_H_
  105656. /********* Start of inlined file: envelope.h *********/
  105657. #ifndef _V_ENVELOPE_
  105658. #define _V_ENVELOPE_
  105659. /********* Start of inlined file: mdct.h *********/
  105660. #ifndef _OGG_mdct_H_
  105661. #define _OGG_mdct_H_
  105662. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  105663. #ifdef MDCT_INTEGERIZED
  105664. #define DATA_TYPE int
  105665. #define REG_TYPE register int
  105666. #define TRIGBITS 14
  105667. #define cPI3_8 6270
  105668. #define cPI2_8 11585
  105669. #define cPI1_8 15137
  105670. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  105671. #define MULT_NORM(x) ((x)>>TRIGBITS)
  105672. #define HALVE(x) ((x)>>1)
  105673. #else
  105674. #define DATA_TYPE float
  105675. #define REG_TYPE float
  105676. #define cPI3_8 .38268343236508977175F
  105677. #define cPI2_8 .70710678118654752441F
  105678. #define cPI1_8 .92387953251128675613F
  105679. #define FLOAT_CONV(x) (x)
  105680. #define MULT_NORM(x) (x)
  105681. #define HALVE(x) ((x)*.5f)
  105682. #endif
  105683. typedef struct {
  105684. int n;
  105685. int log2n;
  105686. DATA_TYPE *trig;
  105687. int *bitrev;
  105688. DATA_TYPE scale;
  105689. } mdct_lookup;
  105690. extern void mdct_init(mdct_lookup *lookup,int n);
  105691. extern void mdct_clear(mdct_lookup *l);
  105692. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105693. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105694. #endif
  105695. /********* End of inlined file: mdct.h *********/
  105696. #define VE_PRE 16
  105697. #define VE_WIN 4
  105698. #define VE_POST 2
  105699. #define VE_AMP (VE_PRE+VE_POST-1)
  105700. #define VE_BANDS 7
  105701. #define VE_NEARDC 15
  105702. #define VE_MINSTRETCH 2 /* a bit less than short block */
  105703. #define VE_MAXSTRETCH 12 /* one-third full block */
  105704. typedef struct {
  105705. float ampbuf[VE_AMP];
  105706. int ampptr;
  105707. float nearDC[VE_NEARDC];
  105708. float nearDC_acc;
  105709. float nearDC_partialacc;
  105710. int nearptr;
  105711. } envelope_filter_state;
  105712. typedef struct {
  105713. int begin;
  105714. int end;
  105715. float *window;
  105716. float total;
  105717. } envelope_band;
  105718. typedef struct {
  105719. int ch;
  105720. int winlength;
  105721. int searchstep;
  105722. float minenergy;
  105723. mdct_lookup mdct;
  105724. float *mdct_win;
  105725. envelope_band band[VE_BANDS];
  105726. envelope_filter_state *filter;
  105727. int stretch;
  105728. int *mark;
  105729. long storage;
  105730. long current;
  105731. long curmark;
  105732. long cursor;
  105733. } envelope_lookup;
  105734. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  105735. extern void _ve_envelope_clear(envelope_lookup *e);
  105736. extern long _ve_envelope_search(vorbis_dsp_state *v);
  105737. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  105738. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  105739. #endif
  105740. /********* End of inlined file: envelope.h *********/
  105741. /********* Start of inlined file: codebook.h *********/
  105742. #ifndef _V_CODEBOOK_H_
  105743. #define _V_CODEBOOK_H_
  105744. /* This structure encapsulates huffman and VQ style encoding books; it
  105745. doesn't do anything specific to either.
  105746. valuelist/quantlist are nonNULL (and q_* significant) only if
  105747. there's entry->value mapping to be done.
  105748. If encode-side mapping must be done (and thus the entry needs to be
  105749. hunted), the auxiliary encode pointer will point to a decision
  105750. tree. This is true of both VQ and huffman, but is mostly useful
  105751. with VQ.
  105752. */
  105753. typedef struct static_codebook{
  105754. long dim; /* codebook dimensions (elements per vector) */
  105755. long entries; /* codebook entries */
  105756. long *lengthlist; /* codeword lengths in bits */
  105757. /* mapping ***************************************************************/
  105758. int maptype; /* 0=none
  105759. 1=implicitly populated values from map column
  105760. 2=listed arbitrary values */
  105761. /* The below does a linear, single monotonic sequence mapping. */
  105762. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  105763. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  105764. int q_quant; /* bits: 0 < quant <= 16 */
  105765. int q_sequencep; /* bitflag */
  105766. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  105767. map == 2: list of dim*entries quantized entry vals
  105768. */
  105769. /* encode helpers ********************************************************/
  105770. struct encode_aux_nearestmatch *nearest_tree;
  105771. struct encode_aux_threshmatch *thresh_tree;
  105772. struct encode_aux_pigeonhole *pigeon_tree;
  105773. int allocedp;
  105774. } static_codebook;
  105775. /* this structures an arbitrary trained book to quickly find the
  105776. nearest cell match */
  105777. typedef struct encode_aux_nearestmatch{
  105778. /* pre-calculated partitioning tree */
  105779. long *ptr0;
  105780. long *ptr1;
  105781. long *p; /* decision points (each is an entry) */
  105782. long *q; /* decision points (each is an entry) */
  105783. long aux; /* number of tree entries */
  105784. long alloc;
  105785. } encode_aux_nearestmatch;
  105786. /* assumes a maptype of 1; encode side only, so that's OK */
  105787. typedef struct encode_aux_threshmatch{
  105788. float *quantthresh;
  105789. long *quantmap;
  105790. int quantvals;
  105791. int threshvals;
  105792. } encode_aux_threshmatch;
  105793. typedef struct encode_aux_pigeonhole{
  105794. float min;
  105795. float del;
  105796. int mapentries;
  105797. int quantvals;
  105798. long *pigeonmap;
  105799. long fittotal;
  105800. long *fitlist;
  105801. long *fitmap;
  105802. long *fitlength;
  105803. } encode_aux_pigeonhole;
  105804. typedef struct codebook{
  105805. long dim; /* codebook dimensions (elements per vector) */
  105806. long entries; /* codebook entries */
  105807. long used_entries; /* populated codebook entries */
  105808. const static_codebook *c;
  105809. /* for encode, the below are entry-ordered, fully populated */
  105810. /* for decode, the below are ordered by bitreversed codeword and only
  105811. used entries are populated */
  105812. float *valuelist; /* list of dim*entries actual entry values */
  105813. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  105814. int *dec_index; /* only used if sparseness collapsed */
  105815. char *dec_codelengths;
  105816. ogg_uint32_t *dec_firsttable;
  105817. int dec_firsttablen;
  105818. int dec_maxlength;
  105819. } codebook;
  105820. extern void vorbis_staticbook_clear(static_codebook *b);
  105821. extern void vorbis_staticbook_destroy(static_codebook *b);
  105822. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  105823. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  105824. extern void vorbis_book_clear(codebook *b);
  105825. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  105826. extern float *_book_logdist(const static_codebook *b,float *vals);
  105827. extern float _float32_unpack(long val);
  105828. extern long _float32_pack(float val);
  105829. extern int _best(codebook *book, float *a, int step);
  105830. extern int _ilog(unsigned int v);
  105831. extern long _book_maptype1_quantvals(const static_codebook *b);
  105832. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  105833. extern long vorbis_book_codeword(codebook *book,int entry);
  105834. extern long vorbis_book_codelen(codebook *book,int entry);
  105835. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  105836. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  105837. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  105838. extern int vorbis_book_errorv(codebook *book, float *a);
  105839. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  105840. oggpack_buffer *b);
  105841. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  105842. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  105843. oggpack_buffer *b,int n);
  105844. extern long vorbis_book_decodev_set(codebook *book, float *a,
  105845. oggpack_buffer *b,int n);
  105846. extern long vorbis_book_decodev_add(codebook *book, float *a,
  105847. oggpack_buffer *b,int n);
  105848. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  105849. long off,int ch,
  105850. oggpack_buffer *b,int n);
  105851. #endif
  105852. /********* End of inlined file: codebook.h *********/
  105853. #define BLOCKTYPE_IMPULSE 0
  105854. #define BLOCKTYPE_PADDING 1
  105855. #define BLOCKTYPE_TRANSITION 0
  105856. #define BLOCKTYPE_LONG 1
  105857. #define PACKETBLOBS 15
  105858. typedef struct vorbis_block_internal{
  105859. float **pcmdelay; /* this is a pointer into local storage */
  105860. float ampmax;
  105861. int blocktype;
  105862. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  105863. blob [PACKETBLOBS/2] points to
  105864. the oggpack_buffer in the
  105865. main vorbis_block */
  105866. } vorbis_block_internal;
  105867. typedef void vorbis_look_floor;
  105868. typedef void vorbis_look_residue;
  105869. typedef void vorbis_look_transform;
  105870. /* mode ************************************************************/
  105871. typedef struct {
  105872. int blockflag;
  105873. int windowtype;
  105874. int transformtype;
  105875. int mapping;
  105876. } vorbis_info_mode;
  105877. typedef void vorbis_info_floor;
  105878. typedef void vorbis_info_residue;
  105879. typedef void vorbis_info_mapping;
  105880. /********* Start of inlined file: psy.h *********/
  105881. #ifndef _V_PSY_H_
  105882. #define _V_PSY_H_
  105883. /********* Start of inlined file: smallft.h *********/
  105884. #ifndef _V_SMFT_H_
  105885. #define _V_SMFT_H_
  105886. typedef struct {
  105887. int n;
  105888. float *trigcache;
  105889. int *splitcache;
  105890. } drft_lookup;
  105891. extern void drft_forward(drft_lookup *l,float *data);
  105892. extern void drft_backward(drft_lookup *l,float *data);
  105893. extern void drft_init(drft_lookup *l,int n);
  105894. extern void drft_clear(drft_lookup *l);
  105895. #endif
  105896. /********* End of inlined file: smallft.h *********/
  105897. /********* Start of inlined file: backends.h *********/
  105898. /* this is exposed up here because we need it for static modes.
  105899. Lookups for each backend aren't exposed because there's no reason
  105900. to do so */
  105901. #ifndef _vorbis_backend_h_
  105902. #define _vorbis_backend_h_
  105903. /* this would all be simpler/shorter with templates, but.... */
  105904. /* Floor backend generic *****************************************/
  105905. typedef struct{
  105906. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  105907. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  105908. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  105909. void (*free_info) (vorbis_info_floor *);
  105910. void (*free_look) (vorbis_look_floor *);
  105911. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  105912. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  105913. void *buffer,float *);
  105914. } vorbis_func_floor;
  105915. typedef struct{
  105916. int order;
  105917. long rate;
  105918. long barkmap;
  105919. int ampbits;
  105920. int ampdB;
  105921. int numbooks; /* <= 16 */
  105922. int books[16];
  105923. float lessthan; /* encode-only config setting hacks for libvorbis */
  105924. float greaterthan; /* encode-only config setting hacks for libvorbis */
  105925. } vorbis_info_floor0;
  105926. #define VIF_POSIT 63
  105927. #define VIF_CLASS 16
  105928. #define VIF_PARTS 31
  105929. typedef struct{
  105930. int partitions; /* 0 to 31 */
  105931. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  105932. int class_dim[VIF_CLASS]; /* 1 to 8 */
  105933. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  105934. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  105935. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  105936. int mult; /* 1 2 3 or 4 */
  105937. int postlist[VIF_POSIT+2]; /* first two implicit */
  105938. /* encode side analysis parameters */
  105939. float maxover;
  105940. float maxunder;
  105941. float maxerr;
  105942. float twofitweight;
  105943. float twofitatten;
  105944. int n;
  105945. } vorbis_info_floor1;
  105946. /* Residue backend generic *****************************************/
  105947. typedef struct{
  105948. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  105949. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  105950. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  105951. vorbis_info_residue *);
  105952. void (*free_info) (vorbis_info_residue *);
  105953. void (*free_look) (vorbis_look_residue *);
  105954. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  105955. float **,int *,int);
  105956. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  105957. vorbis_look_residue *,
  105958. float **,float **,int *,int,long **);
  105959. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  105960. float **,int *,int);
  105961. } vorbis_func_residue;
  105962. typedef struct vorbis_info_residue0{
  105963. /* block-partitioned VQ coded straight residue */
  105964. long begin;
  105965. long end;
  105966. /* first stage (lossless partitioning) */
  105967. int grouping; /* group n vectors per partition */
  105968. int partitions; /* possible codebooks for a partition */
  105969. int groupbook; /* huffbook for partitioning */
  105970. int secondstages[64]; /* expanded out to pointers in lookup */
  105971. int booklist[256]; /* list of second stage books */
  105972. float classmetric1[64];
  105973. float classmetric2[64];
  105974. } vorbis_info_residue0;
  105975. /* Mapping backend generic *****************************************/
  105976. typedef struct{
  105977. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  105978. oggpack_buffer *);
  105979. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  105980. void (*free_info) (vorbis_info_mapping *);
  105981. int (*forward) (struct vorbis_block *vb);
  105982. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  105983. } vorbis_func_mapping;
  105984. typedef struct vorbis_info_mapping0{
  105985. int submaps; /* <= 16 */
  105986. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  105987. int floorsubmap[16]; /* [mux] submap to floors */
  105988. int residuesubmap[16]; /* [mux] submap to residue */
  105989. int coupling_steps;
  105990. int coupling_mag[256];
  105991. int coupling_ang[256];
  105992. } vorbis_info_mapping0;
  105993. #endif
  105994. /********* End of inlined file: backends.h *********/
  105995. #ifndef EHMER_MAX
  105996. #define EHMER_MAX 56
  105997. #endif
  105998. /* psychoacoustic setup ********************************************/
  105999. #define P_BANDS 17 /* 62Hz to 16kHz */
  106000. #define P_LEVELS 8 /* 30dB to 100dB */
  106001. #define P_LEVEL_0 30. /* 30 dB */
  106002. #define P_NOISECURVES 3
  106003. #define NOISE_COMPAND_LEVELS 40
  106004. typedef struct vorbis_info_psy{
  106005. int blockflag;
  106006. float ath_adjatt;
  106007. float ath_maxatt;
  106008. float tone_masteratt[P_NOISECURVES];
  106009. float tone_centerboost;
  106010. float tone_decay;
  106011. float tone_abs_limit;
  106012. float toneatt[P_BANDS];
  106013. int noisemaskp;
  106014. float noisemaxsupp;
  106015. float noisewindowlo;
  106016. float noisewindowhi;
  106017. int noisewindowlomin;
  106018. int noisewindowhimin;
  106019. int noisewindowfixed;
  106020. float noiseoff[P_NOISECURVES][P_BANDS];
  106021. float noisecompand[NOISE_COMPAND_LEVELS];
  106022. float max_curve_dB;
  106023. int normal_channel_p;
  106024. int normal_point_p;
  106025. int normal_start;
  106026. int normal_partition;
  106027. double normal_thresh;
  106028. } vorbis_info_psy;
  106029. typedef struct{
  106030. int eighth_octave_lines;
  106031. /* for block long/short tuning; encode only */
  106032. float preecho_thresh[VE_BANDS];
  106033. float postecho_thresh[VE_BANDS];
  106034. float stretch_penalty;
  106035. float preecho_minenergy;
  106036. float ampmax_att_per_sec;
  106037. /* channel coupling config */
  106038. int coupling_pkHz[PACKETBLOBS];
  106039. int coupling_pointlimit[2][PACKETBLOBS];
  106040. int coupling_prepointamp[PACKETBLOBS];
  106041. int coupling_postpointamp[PACKETBLOBS];
  106042. int sliding_lowpass[2][PACKETBLOBS];
  106043. } vorbis_info_psy_global;
  106044. typedef struct {
  106045. float ampmax;
  106046. int channels;
  106047. vorbis_info_psy_global *gi;
  106048. int coupling_pointlimit[2][P_NOISECURVES];
  106049. } vorbis_look_psy_global;
  106050. typedef struct {
  106051. int n;
  106052. struct vorbis_info_psy *vi;
  106053. float ***tonecurves;
  106054. float **noiseoffset;
  106055. float *ath;
  106056. long *octave; /* in n.ocshift format */
  106057. long *bark;
  106058. long firstoc;
  106059. long shiftoc;
  106060. int eighth_octave_lines; /* power of two, please */
  106061. int total_octave_lines;
  106062. long rate; /* cache it */
  106063. float m_val; /* Masking compensation value */
  106064. } vorbis_look_psy;
  106065. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  106066. vorbis_info_psy_global *gi,int n,long rate);
  106067. extern void _vp_psy_clear(vorbis_look_psy *p);
  106068. extern void *_vi_psy_dup(void *source);
  106069. extern void _vi_psy_free(vorbis_info_psy *i);
  106070. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  106071. extern void _vp_remove_floor(vorbis_look_psy *p,
  106072. float *mdct,
  106073. int *icodedflr,
  106074. float *residue,
  106075. int sliding_lowpass);
  106076. extern void _vp_noisemask(vorbis_look_psy *p,
  106077. float *logmdct,
  106078. float *logmask);
  106079. extern void _vp_tonemask(vorbis_look_psy *p,
  106080. float *logfft,
  106081. float *logmask,
  106082. float global_specmax,
  106083. float local_specmax);
  106084. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  106085. float *noise,
  106086. float *tone,
  106087. int offset_select,
  106088. float *logmask,
  106089. float *mdct,
  106090. float *logmdct);
  106091. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  106092. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  106093. vorbis_info_psy_global *g,
  106094. vorbis_look_psy *p,
  106095. vorbis_info_mapping0 *vi,
  106096. float **mdct);
  106097. extern void _vp_couple(int blobno,
  106098. vorbis_info_psy_global *g,
  106099. vorbis_look_psy *p,
  106100. vorbis_info_mapping0 *vi,
  106101. float **res,
  106102. float **mag_memo,
  106103. int **mag_sort,
  106104. int **ifloor,
  106105. int *nonzero,
  106106. int sliding_lowpass);
  106107. extern void _vp_noise_normalize(vorbis_look_psy *p,
  106108. float *in,float *out,int *sortedindex);
  106109. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  106110. float *magnitudes,int *sortedindex);
  106111. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  106112. vorbis_look_psy *p,
  106113. vorbis_info_mapping0 *vi,
  106114. float **mags);
  106115. extern void hf_reduction(vorbis_info_psy_global *g,
  106116. vorbis_look_psy *p,
  106117. vorbis_info_mapping0 *vi,
  106118. float **mdct);
  106119. #endif
  106120. /********* End of inlined file: psy.h *********/
  106121. /********* Start of inlined file: bitrate.h *********/
  106122. #ifndef _V_BITRATE_H_
  106123. #define _V_BITRATE_H_
  106124. /********* Start of inlined file: os.h *********/
  106125. #ifndef _OS_H
  106126. #define _OS_H
  106127. /********************************************************************
  106128. * *
  106129. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  106130. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  106131. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  106132. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  106133. * *
  106134. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  106135. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  106136. * *
  106137. ********************************************************************
  106138. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  106139. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  106140. ********************************************************************/
  106141. #ifdef HAVE_CONFIG_H
  106142. #include "config.h"
  106143. #endif
  106144. #include <math.h>
  106145. /********* Start of inlined file: misc.h *********/
  106146. #ifndef _V_RANDOM_H_
  106147. #define _V_RANDOM_H_
  106148. extern int analysis_noisy;
  106149. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  106150. extern void _vorbis_block_ripcord(vorbis_block *vb);
  106151. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106152. ogg_int64_t off);
  106153. #ifdef DEBUG_MALLOC
  106154. #define _VDBG_GRAPHFILE "malloc.m"
  106155. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  106156. extern void _VDBG_free(void *ptr,char *file,long line);
  106157. #ifndef MISC_C
  106158. #undef _ogg_malloc
  106159. #undef _ogg_calloc
  106160. #undef _ogg_realloc
  106161. #undef _ogg_free
  106162. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  106163. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  106164. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  106165. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  106166. #endif
  106167. #endif
  106168. #endif
  106169. /********* End of inlined file: misc.h *********/
  106170. #ifndef _V_IFDEFJAIL_H_
  106171. # define _V_IFDEFJAIL_H_
  106172. # ifdef __GNUC__
  106173. # define STIN static __inline__
  106174. # elif _WIN32
  106175. # define STIN static __inline
  106176. # else
  106177. # define STIN static
  106178. # endif
  106179. #ifdef DJGPP
  106180. # define rint(x) (floor((x)+0.5f))
  106181. #endif
  106182. #ifndef M_PI
  106183. # define M_PI (3.1415926536f)
  106184. #endif
  106185. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  106186. # include <malloc.h>
  106187. # define rint(x) (floor((x)+0.5f))
  106188. # define NO_FLOAT_MATH_LIB
  106189. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  106190. #endif
  106191. #if defined(__SYMBIAN32__) && defined(__WINS__)
  106192. void *_alloca(size_t size);
  106193. # define alloca _alloca
  106194. #endif
  106195. #ifndef FAST_HYPOT
  106196. # define FAST_HYPOT hypot
  106197. #endif
  106198. #endif
  106199. #ifdef HAVE_ALLOCA_H
  106200. # include <alloca.h>
  106201. #endif
  106202. #ifdef USE_MEMORY_H
  106203. # include <memory.h>
  106204. #endif
  106205. #ifndef min
  106206. # define min(x,y) ((x)>(y)?(y):(x))
  106207. #endif
  106208. #ifndef max
  106209. # define max(x,y) ((x)<(y)?(y):(x))
  106210. #endif
  106211. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  106212. # define VORBIS_FPU_CONTROL
  106213. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  106214. Because of encapsulation constraints (GCC can't see inside the asm
  106215. block and so we end up doing stupid things like a store/load that
  106216. is collectively a noop), we do it this way */
  106217. /* we must set up the fpu before this works!! */
  106218. typedef ogg_int16_t vorbis_fpu_control;
  106219. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106220. ogg_int16_t ret;
  106221. ogg_int16_t temp;
  106222. __asm__ __volatile__("fnstcw %0\n\t"
  106223. "movw %0,%%dx\n\t"
  106224. "orw $62463,%%dx\n\t"
  106225. "movw %%dx,%1\n\t"
  106226. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  106227. *fpu=ret;
  106228. }
  106229. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106230. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  106231. }
  106232. /* assumes the FPU is in round mode! */
  106233. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  106234. we get extra fst/fld to
  106235. truncate precision */
  106236. int i;
  106237. __asm__("fistl %0": "=m"(i) : "t"(f));
  106238. return(i);
  106239. }
  106240. #endif
  106241. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  106242. # define VORBIS_FPU_CONTROL
  106243. typedef ogg_int16_t vorbis_fpu_control;
  106244. static __inline int vorbis_ftoi(double f){
  106245. int i;
  106246. __asm{
  106247. fld f
  106248. fistp i
  106249. }
  106250. return i;
  106251. }
  106252. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106253. }
  106254. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106255. }
  106256. #endif
  106257. #ifndef VORBIS_FPU_CONTROL
  106258. typedef int vorbis_fpu_control;
  106259. static int vorbis_ftoi(double f){
  106260. return (int)(f+.5);
  106261. }
  106262. /* We don't have special code for this compiler/arch, so do it the slow way */
  106263. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  106264. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  106265. #endif
  106266. #endif /* _OS_H */
  106267. /********* End of inlined file: os.h *********/
  106268. /* encode side bitrate tracking */
  106269. typedef struct bitrate_manager_state {
  106270. int managed;
  106271. long avg_reservoir;
  106272. long minmax_reservoir;
  106273. long avg_bitsper;
  106274. long min_bitsper;
  106275. long max_bitsper;
  106276. long short_per_long;
  106277. double avgfloat;
  106278. vorbis_block *vb;
  106279. int choice;
  106280. } bitrate_manager_state;
  106281. typedef struct bitrate_manager_info{
  106282. long avg_rate;
  106283. long min_rate;
  106284. long max_rate;
  106285. long reservoir_bits;
  106286. double reservoir_bias;
  106287. double slew_damp;
  106288. } bitrate_manager_info;
  106289. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  106290. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  106291. extern int vorbis_bitrate_managed(vorbis_block *vb);
  106292. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106293. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  106294. #endif
  106295. /********* End of inlined file: bitrate.h *********/
  106296. static int ilog(unsigned int v){
  106297. int ret=0;
  106298. while(v){
  106299. ret++;
  106300. v>>=1;
  106301. }
  106302. return(ret);
  106303. }
  106304. static int ilog2(unsigned int v){
  106305. int ret=0;
  106306. if(v)--v;
  106307. while(v){
  106308. ret++;
  106309. v>>=1;
  106310. }
  106311. return(ret);
  106312. }
  106313. typedef struct private_state {
  106314. /* local lookup storage */
  106315. envelope_lookup *ve; /* envelope lookup */
  106316. int window[2];
  106317. vorbis_look_transform **transform[2]; /* block, type */
  106318. drft_lookup fft_look[2];
  106319. int modebits;
  106320. vorbis_look_floor **flr;
  106321. vorbis_look_residue **residue;
  106322. vorbis_look_psy *psy;
  106323. vorbis_look_psy_global *psy_g_look;
  106324. /* local storage, only used on the encoding side. This way the
  106325. application does not need to worry about freeing some packets'
  106326. memory and not others'; packet storage is always tracked.
  106327. Cleared next call to a _dsp_ function */
  106328. unsigned char *header;
  106329. unsigned char *header1;
  106330. unsigned char *header2;
  106331. bitrate_manager_state bms;
  106332. ogg_int64_t sample_count;
  106333. } private_state;
  106334. /* codec_setup_info contains all the setup information specific to the
  106335. specific compression/decompression mode in progress (eg,
  106336. psychoacoustic settings, channel setup, options, codebook
  106337. etc).
  106338. *********************************************************************/
  106339. /********* Start of inlined file: highlevel.h *********/
  106340. typedef struct highlevel_byblocktype {
  106341. double tone_mask_setting;
  106342. double tone_peaklimit_setting;
  106343. double noise_bias_setting;
  106344. double noise_compand_setting;
  106345. } highlevel_byblocktype;
  106346. typedef struct highlevel_encode_setup {
  106347. void *setup;
  106348. int set_in_stone;
  106349. double base_setting;
  106350. double long_setting;
  106351. double short_setting;
  106352. double impulse_noisetune;
  106353. int managed;
  106354. long bitrate_min;
  106355. long bitrate_av;
  106356. double bitrate_av_damp;
  106357. long bitrate_max;
  106358. long bitrate_reservoir;
  106359. double bitrate_reservoir_bias;
  106360. int impulse_block_p;
  106361. int noise_normalize_p;
  106362. double stereo_point_setting;
  106363. double lowpass_kHz;
  106364. double ath_floating_dB;
  106365. double ath_absolute_dB;
  106366. double amplitude_track_dBpersec;
  106367. double trigger_setting;
  106368. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  106369. } highlevel_encode_setup;
  106370. /********* End of inlined file: highlevel.h *********/
  106371. typedef struct codec_setup_info {
  106372. /* Vorbis supports only short and long blocks, but allows the
  106373. encoder to choose the sizes */
  106374. long blocksizes[2];
  106375. /* modes are the primary means of supporting on-the-fly different
  106376. blocksizes, different channel mappings (LR or M/A),
  106377. different residue backends, etc. Each mode consists of a
  106378. blocksize flag and a mapping (along with the mapping setup */
  106379. int modes;
  106380. int maps;
  106381. int floors;
  106382. int residues;
  106383. int books;
  106384. int psys; /* encode only */
  106385. vorbis_info_mode *mode_param[64];
  106386. int map_type[64];
  106387. vorbis_info_mapping *map_param[64];
  106388. int floor_type[64];
  106389. vorbis_info_floor *floor_param[64];
  106390. int residue_type[64];
  106391. vorbis_info_residue *residue_param[64];
  106392. static_codebook *book_param[256];
  106393. codebook *fullbooks;
  106394. vorbis_info_psy *psy_param[4]; /* encode only */
  106395. vorbis_info_psy_global psy_g_param;
  106396. bitrate_manager_info bi;
  106397. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  106398. highly redundant structure, but
  106399. improves clarity of program flow. */
  106400. int halfrate_flag; /* painless downsample for decode */
  106401. } codec_setup_info;
  106402. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  106403. extern void _vp_global_free(vorbis_look_psy_global *look);
  106404. #endif
  106405. /********* End of inlined file: codec_internal.h *********/
  106406. /********* Start of inlined file: registry.h *********/
  106407. #ifndef _V_REG_H_
  106408. #define _V_REG_H_
  106409. #define VI_TRANSFORMB 1
  106410. #define VI_WINDOWB 1
  106411. #define VI_TIMEB 1
  106412. #define VI_FLOORB 2
  106413. #define VI_RESB 3
  106414. #define VI_MAPB 1
  106415. extern vorbis_func_floor *_floor_P[];
  106416. extern vorbis_func_residue *_residue_P[];
  106417. extern vorbis_func_mapping *_mapping_P[];
  106418. #endif
  106419. /********* End of inlined file: registry.h *********/
  106420. /********* Start of inlined file: scales.h *********/
  106421. #ifndef _V_SCALES_H_
  106422. #define _V_SCALES_H_
  106423. #include <math.h>
  106424. /* 20log10(x) */
  106425. #define VORBIS_IEEE_FLOAT32 1
  106426. #ifdef VORBIS_IEEE_FLOAT32
  106427. static float unitnorm(float x){
  106428. union {
  106429. ogg_uint32_t i;
  106430. float f;
  106431. } ix;
  106432. ix.f = x;
  106433. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  106434. return ix.f;
  106435. }
  106436. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  106437. static float todB(const float *x){
  106438. union {
  106439. ogg_uint32_t i;
  106440. float f;
  106441. } ix;
  106442. ix.f = *x;
  106443. ix.i = ix.i&0x7fffffff;
  106444. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  106445. }
  106446. #define todB_nn(x) todB(x)
  106447. #else
  106448. static float unitnorm(float x){
  106449. if(x<0)return(-1.f);
  106450. return(1.f);
  106451. }
  106452. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  106453. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  106454. #endif
  106455. #define fromdB(x) (exp((x)*.11512925f))
  106456. /* The bark scale equations are approximations, since the original
  106457. table was somewhat hand rolled. The below are chosen to have the
  106458. best possible fit to the rolled tables, thus their somewhat odd
  106459. appearance (these are more accurate and over a longer range than
  106460. the oft-quoted bark equations found in the texts I have). The
  106461. approximations are valid from 0 - 30kHz (nyquist) or so.
  106462. all f in Hz, z in Bark */
  106463. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  106464. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  106465. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  106466. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  106467. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  106468. 0.0 */
  106469. #define toOC(n) (log(n)*1.442695f-5.965784f)
  106470. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  106471. #endif
  106472. /********* End of inlined file: scales.h *********/
  106473. int analysis_noisy=1;
  106474. /* decides between modes, dispatches to the appropriate mapping. */
  106475. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  106476. int ret,i;
  106477. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106478. vb->glue_bits=0;
  106479. vb->time_bits=0;
  106480. vb->floor_bits=0;
  106481. vb->res_bits=0;
  106482. /* first things first. Make sure encode is ready */
  106483. for(i=0;i<PACKETBLOBS;i++)
  106484. oggpack_reset(vbi->packetblob[i]);
  106485. /* we only have one mapping type (0), and we let the mapping code
  106486. itself figure out what soft mode to use. This allows easier
  106487. bitrate management */
  106488. if((ret=_mapping_P[0]->forward(vb)))
  106489. return(ret);
  106490. if(op){
  106491. if(vorbis_bitrate_managed(vb))
  106492. /* The app is using a bitmanaged mode... but not using the
  106493. bitrate management interface. */
  106494. return(OV_EINVAL);
  106495. op->packet=oggpack_get_buffer(&vb->opb);
  106496. op->bytes=oggpack_bytes(&vb->opb);
  106497. op->b_o_s=0;
  106498. op->e_o_s=vb->eofflag;
  106499. op->granulepos=vb->granulepos;
  106500. op->packetno=vb->sequence; /* for sake of completeness */
  106501. }
  106502. return(0);
  106503. }
  106504. /* there was no great place to put this.... */
  106505. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  106506. int j;
  106507. FILE *of;
  106508. char buffer[80];
  106509. /* if(i==5870){*/
  106510. sprintf(buffer,"%s_%d.m",base,i);
  106511. of=fopen(buffer,"w");
  106512. if(!of)perror("failed to open data dump file");
  106513. for(j=0;j<n;j++){
  106514. if(bark){
  106515. float b=toBARK((4000.f*j/n)+.25);
  106516. fprintf(of,"%f ",b);
  106517. }else
  106518. if(off!=0)
  106519. fprintf(of,"%f ",(double)(j+off)/8000.);
  106520. else
  106521. fprintf(of,"%f ",(double)j);
  106522. if(dB){
  106523. float val;
  106524. if(v[j]==0.)
  106525. val=-140.;
  106526. else
  106527. val=todB(v+j);
  106528. fprintf(of,"%f\n",val);
  106529. }else{
  106530. fprintf(of,"%f\n",v[j]);
  106531. }
  106532. }
  106533. fclose(of);
  106534. /* } */
  106535. }
  106536. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106537. ogg_int64_t off){
  106538. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  106539. }
  106540. #endif
  106541. /********* End of inlined file: analysis.c *********/
  106542. /********* Start of inlined file: bitrate.c *********/
  106543. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106544. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106545. // tasks..
  106546. #if JUCE_MSVC
  106547. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106548. #endif
  106549. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106550. #if JUCE_USE_OGGVORBIS
  106551. #include <stdlib.h>
  106552. #include <string.h>
  106553. #include <math.h>
  106554. /* compute bitrate tracking setup */
  106555. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  106556. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106557. bitrate_manager_info *bi=&ci->bi;
  106558. memset(bm,0,sizeof(*bm));
  106559. if(bi && (bi->reservoir_bits>0)){
  106560. long ratesamples=vi->rate;
  106561. int halfsamples=ci->blocksizes[0]>>1;
  106562. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  106563. bm->managed=1;
  106564. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  106565. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  106566. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  106567. bm->avgfloat=PACKETBLOBS/2;
  106568. /* not a necessary fix, but one that leads to a more balanced
  106569. typical initialization */
  106570. {
  106571. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106572. bm->minmax_reservoir=desired_fill;
  106573. bm->avg_reservoir=desired_fill;
  106574. }
  106575. }
  106576. }
  106577. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  106578. memset(bm,0,sizeof(*bm));
  106579. return;
  106580. }
  106581. int vorbis_bitrate_managed(vorbis_block *vb){
  106582. vorbis_dsp_state *vd=vb->vd;
  106583. private_state *b=(private_state*)vd->backend_state;
  106584. bitrate_manager_state *bm=&b->bms;
  106585. if(bm && bm->managed)return(1);
  106586. return(0);
  106587. }
  106588. /* finish taking in the block we just processed */
  106589. int vorbis_bitrate_addblock(vorbis_block *vb){
  106590. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106591. vorbis_dsp_state *vd=vb->vd;
  106592. private_state *b=(private_state*)vd->backend_state;
  106593. bitrate_manager_state *bm=&b->bms;
  106594. vorbis_info *vi=vd->vi;
  106595. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106596. bitrate_manager_info *bi=&ci->bi;
  106597. int choice=rint(bm->avgfloat);
  106598. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106599. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  106600. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  106601. int samples=ci->blocksizes[vb->W]>>1;
  106602. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106603. if(!bm->managed){
  106604. /* not a bitrate managed stream, but for API simplicity, we'll
  106605. buffer the packet to keep the code path clean */
  106606. if(bm->vb)return(-1); /* one has been submitted without
  106607. being claimed */
  106608. bm->vb=vb;
  106609. return(0);
  106610. }
  106611. bm->vb=vb;
  106612. /* look ahead for avg floater */
  106613. if(bm->avg_bitsper>0){
  106614. double slew=0.;
  106615. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106616. double slewlimit= 15./bi->slew_damp;
  106617. /* choosing a new floater:
  106618. if we're over target, we slew down
  106619. if we're under target, we slew up
  106620. choose slew as follows: look through packetblobs of this frame
  106621. and set slew as the first in the appropriate direction that
  106622. gives us the slew we want. This may mean no slew if delta is
  106623. already favorable.
  106624. Then limit slew to slew max */
  106625. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106626. while(choice>0 && this_bits>avg_target_bits &&
  106627. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106628. choice--;
  106629. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106630. }
  106631. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106632. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  106633. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106634. choice++;
  106635. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106636. }
  106637. }
  106638. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  106639. if(slew<-slewlimit)slew=-slewlimit;
  106640. if(slew>slewlimit)slew=slewlimit;
  106641. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  106642. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106643. }
  106644. /* enforce min(if used) on the current floater (if used) */
  106645. if(bm->min_bitsper>0){
  106646. /* do we need to force the bitrate up? */
  106647. if(this_bits<min_target_bits){
  106648. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  106649. choice++;
  106650. if(choice>=PACKETBLOBS)break;
  106651. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106652. }
  106653. }
  106654. }
  106655. /* enforce max (if used) on the current floater (if used) */
  106656. if(bm->max_bitsper>0){
  106657. /* do we need to force the bitrate down? */
  106658. if(this_bits>max_target_bits){
  106659. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  106660. choice--;
  106661. if(choice<0)break;
  106662. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106663. }
  106664. }
  106665. }
  106666. /* Choice of packetblobs now made based on floater, and min/max
  106667. requirements. Now boundary check extreme choices */
  106668. if(choice<0){
  106669. /* choosing a smaller packetblob is insufficient to trim bitrate.
  106670. frame will need to be truncated */
  106671. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  106672. bm->choice=choice=0;
  106673. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  106674. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  106675. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106676. }
  106677. }else{
  106678. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  106679. if(choice>=PACKETBLOBS)
  106680. choice=PACKETBLOBS-1;
  106681. bm->choice=choice;
  106682. /* prop up bitrate according to demand. pad this frame out with zeroes */
  106683. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  106684. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  106685. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106686. }
  106687. /* now we have the final packet and the final packet size. Update statistics */
  106688. /* min and max reservoir */
  106689. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  106690. if(max_target_bits>0 && this_bits>max_target_bits){
  106691. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106692. }else if(min_target_bits>0 && this_bits<min_target_bits){
  106693. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106694. }else{
  106695. /* inbetween; we want to take reservoir toward but not past desired_fill */
  106696. if(bm->minmax_reservoir>desired_fill){
  106697. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  106698. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106699. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  106700. }else{
  106701. bm->minmax_reservoir=desired_fill;
  106702. }
  106703. }else{
  106704. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  106705. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106706. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  106707. }else{
  106708. bm->minmax_reservoir=desired_fill;
  106709. }
  106710. }
  106711. }
  106712. }
  106713. /* avg reservoir */
  106714. if(bm->avg_bitsper>0){
  106715. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106716. bm->avg_reservoir+=this_bits-avg_target_bits;
  106717. }
  106718. return(0);
  106719. }
  106720. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  106721. private_state *b=(private_state*)vd->backend_state;
  106722. bitrate_manager_state *bm=&b->bms;
  106723. vorbis_block *vb=bm->vb;
  106724. int choice=PACKETBLOBS/2;
  106725. if(!vb)return 0;
  106726. if(op){
  106727. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106728. if(vorbis_bitrate_managed(vb))
  106729. choice=bm->choice;
  106730. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  106731. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  106732. op->b_o_s=0;
  106733. op->e_o_s=vb->eofflag;
  106734. op->granulepos=vb->granulepos;
  106735. op->packetno=vb->sequence; /* for sake of completeness */
  106736. }
  106737. bm->vb=0;
  106738. return(1);
  106739. }
  106740. #endif
  106741. /********* End of inlined file: bitrate.c *********/
  106742. /********* Start of inlined file: block.c *********/
  106743. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106744. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106745. // tasks..
  106746. #if JUCE_MSVC
  106747. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106748. #endif
  106749. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106750. #if JUCE_USE_OGGVORBIS
  106751. #include <stdio.h>
  106752. #include <stdlib.h>
  106753. #include <string.h>
  106754. /********* Start of inlined file: window.h *********/
  106755. #ifndef _V_WINDOW_
  106756. #define _V_WINDOW_
  106757. extern float *_vorbis_window_get(int n);
  106758. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  106759. int lW,int W,int nW);
  106760. #endif
  106761. /********* End of inlined file: window.h *********/
  106762. /********* Start of inlined file: lpc.h *********/
  106763. #ifndef _V_LPC_H_
  106764. #define _V_LPC_H_
  106765. /* simple linear scale LPC code */
  106766. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  106767. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  106768. float *data,long n);
  106769. #endif
  106770. /********* End of inlined file: lpc.h *********/
  106771. /* pcm accumulator examples (not exhaustive):
  106772. <-------------- lW ---------------->
  106773. <--------------- W ---------------->
  106774. : .....|..... _______________ |
  106775. : .''' | '''_--- | |\ |
  106776. :.....''' |_____--- '''......| | \_______|
  106777. :.................|__________________|_______|__|______|
  106778. |<------ Sl ------>| > Sr < |endW
  106779. |beginSl |endSl | |endSr
  106780. |beginW |endlW |beginSr
  106781. |< lW >|
  106782. <--------------- W ---------------->
  106783. | | .. ______________ |
  106784. | | ' `/ | ---_ |
  106785. |___.'___/`. | ---_____|
  106786. |_______|__|_______|_________________|
  106787. | >|Sl|< |<------ Sr ----->|endW
  106788. | | |endSl |beginSr |endSr
  106789. |beginW | |endlW
  106790. mult[0] |beginSl mult[n]
  106791. <-------------- lW ----------------->
  106792. |<--W-->|
  106793. : .............. ___ | |
  106794. : .''' |`/ \ | |
  106795. :.....''' |/`....\|...|
  106796. :.........................|___|___|___|
  106797. |Sl |Sr |endW
  106798. | | |endSr
  106799. | |beginSr
  106800. | |endSl
  106801. |beginSl
  106802. |beginW
  106803. */
  106804. /* block abstraction setup *********************************************/
  106805. #ifndef WORD_ALIGN
  106806. #define WORD_ALIGN 8
  106807. #endif
  106808. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  106809. int i;
  106810. memset(vb,0,sizeof(*vb));
  106811. vb->vd=v;
  106812. vb->localalloc=0;
  106813. vb->localstore=NULL;
  106814. if(v->analysisp){
  106815. vorbis_block_internal *vbi=(vorbis_block_internal*)
  106816. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  106817. vbi->ampmax=-9999;
  106818. for(i=0;i<PACKETBLOBS;i++){
  106819. if(i==PACKETBLOBS/2){
  106820. vbi->packetblob[i]=&vb->opb;
  106821. }else{
  106822. vbi->packetblob[i]=
  106823. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  106824. }
  106825. oggpack_writeinit(vbi->packetblob[i]);
  106826. }
  106827. }
  106828. return(0);
  106829. }
  106830. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  106831. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  106832. if(bytes+vb->localtop>vb->localalloc){
  106833. /* can't just _ogg_realloc... there are outstanding pointers */
  106834. if(vb->localstore){
  106835. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  106836. vb->totaluse+=vb->localtop;
  106837. link->next=vb->reap;
  106838. link->ptr=vb->localstore;
  106839. vb->reap=link;
  106840. }
  106841. /* highly conservative */
  106842. vb->localalloc=bytes;
  106843. vb->localstore=_ogg_malloc(vb->localalloc);
  106844. vb->localtop=0;
  106845. }
  106846. {
  106847. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  106848. vb->localtop+=bytes;
  106849. return ret;
  106850. }
  106851. }
  106852. /* reap the chain, pull the ripcord */
  106853. void _vorbis_block_ripcord(vorbis_block *vb){
  106854. /* reap the chain */
  106855. struct alloc_chain *reap=vb->reap;
  106856. while(reap){
  106857. struct alloc_chain *next=reap->next;
  106858. _ogg_free(reap->ptr);
  106859. memset(reap,0,sizeof(*reap));
  106860. _ogg_free(reap);
  106861. reap=next;
  106862. }
  106863. /* consolidate storage */
  106864. if(vb->totaluse){
  106865. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  106866. vb->localalloc+=vb->totaluse;
  106867. vb->totaluse=0;
  106868. }
  106869. /* pull the ripcord */
  106870. vb->localtop=0;
  106871. vb->reap=NULL;
  106872. }
  106873. int vorbis_block_clear(vorbis_block *vb){
  106874. int i;
  106875. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106876. _vorbis_block_ripcord(vb);
  106877. if(vb->localstore)_ogg_free(vb->localstore);
  106878. if(vbi){
  106879. for(i=0;i<PACKETBLOBS;i++){
  106880. oggpack_writeclear(vbi->packetblob[i]);
  106881. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  106882. }
  106883. _ogg_free(vbi);
  106884. }
  106885. memset(vb,0,sizeof(*vb));
  106886. return(0);
  106887. }
  106888. /* Analysis side code, but directly related to blocking. Thus it's
  106889. here and not in analysis.c (which is for analysis transforms only).
  106890. The init is here because some of it is shared */
  106891. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  106892. int i;
  106893. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106894. private_state *b=NULL;
  106895. int hs;
  106896. if(ci==NULL) return 1;
  106897. hs=ci->halfrate_flag;
  106898. memset(v,0,sizeof(*v));
  106899. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  106900. v->vi=vi;
  106901. b->modebits=ilog2(ci->modes);
  106902. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  106903. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  106904. /* MDCT is tranform 0 */
  106905. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106906. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106907. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  106908. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  106909. /* Vorbis I uses only window type 0 */
  106910. b->window[0]=ilog2(ci->blocksizes[0])-6;
  106911. b->window[1]=ilog2(ci->blocksizes[1])-6;
  106912. if(encp){ /* encode/decode differ here */
  106913. /* analysis always needs an fft */
  106914. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  106915. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  106916. /* finish the codebooks */
  106917. if(!ci->fullbooks){
  106918. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106919. for(i=0;i<ci->books;i++)
  106920. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  106921. }
  106922. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  106923. for(i=0;i<ci->psys;i++){
  106924. _vp_psy_init(b->psy+i,
  106925. ci->psy_param[i],
  106926. &ci->psy_g_param,
  106927. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  106928. vi->rate);
  106929. }
  106930. v->analysisp=1;
  106931. }else{
  106932. /* finish the codebooks */
  106933. if(!ci->fullbooks){
  106934. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106935. for(i=0;i<ci->books;i++){
  106936. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  106937. /* decode codebooks are now standalone after init */
  106938. vorbis_staticbook_destroy(ci->book_param[i]);
  106939. ci->book_param[i]=NULL;
  106940. }
  106941. }
  106942. }
  106943. /* initialize the storage vectors. blocksize[1] is small for encode,
  106944. but the correct size for decode */
  106945. v->pcm_storage=ci->blocksizes[1];
  106946. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  106947. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  106948. {
  106949. int i;
  106950. for(i=0;i<vi->channels;i++)
  106951. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  106952. }
  106953. /* all 1 (large block) or 0 (small block) */
  106954. /* explicitly set for the sake of clarity */
  106955. v->lW=0; /* previous window size */
  106956. v->W=0; /* current window size */
  106957. /* all vector indexes */
  106958. v->centerW=ci->blocksizes[1]/2;
  106959. v->pcm_current=v->centerW;
  106960. /* initialize all the backend lookups */
  106961. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  106962. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  106963. for(i=0;i<ci->floors;i++)
  106964. b->flr[i]=_floor_P[ci->floor_type[i]]->
  106965. look(v,ci->floor_param[i]);
  106966. for(i=0;i<ci->residues;i++)
  106967. b->residue[i]=_residue_P[ci->residue_type[i]]->
  106968. look(v,ci->residue_param[i]);
  106969. return 0;
  106970. }
  106971. /* arbitrary settings and spec-mandated numbers get filled in here */
  106972. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106973. private_state *b=NULL;
  106974. if(_vds_shared_init(v,vi,1))return 1;
  106975. b=(private_state*)v->backend_state;
  106976. b->psy_g_look=_vp_global_look(vi);
  106977. /* Initialize the envelope state storage */
  106978. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  106979. _ve_envelope_init(b->ve,vi);
  106980. vorbis_bitrate_init(vi,&b->bms);
  106981. /* compressed audio packets start after the headers
  106982. with sequence number 3 */
  106983. v->sequence=3;
  106984. return(0);
  106985. }
  106986. void vorbis_dsp_clear(vorbis_dsp_state *v){
  106987. int i;
  106988. if(v){
  106989. vorbis_info *vi=v->vi;
  106990. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  106991. private_state *b=(private_state*)v->backend_state;
  106992. if(b){
  106993. if(b->ve){
  106994. _ve_envelope_clear(b->ve);
  106995. _ogg_free(b->ve);
  106996. }
  106997. if(b->transform[0]){
  106998. mdct_clear((mdct_lookup*) b->transform[0][0]);
  106999. _ogg_free(b->transform[0][0]);
  107000. _ogg_free(b->transform[0]);
  107001. }
  107002. if(b->transform[1]){
  107003. mdct_clear((mdct_lookup*) b->transform[1][0]);
  107004. _ogg_free(b->transform[1][0]);
  107005. _ogg_free(b->transform[1]);
  107006. }
  107007. if(b->flr){
  107008. for(i=0;i<ci->floors;i++)
  107009. _floor_P[ci->floor_type[i]]->
  107010. free_look(b->flr[i]);
  107011. _ogg_free(b->flr);
  107012. }
  107013. if(b->residue){
  107014. for(i=0;i<ci->residues;i++)
  107015. _residue_P[ci->residue_type[i]]->
  107016. free_look(b->residue[i]);
  107017. _ogg_free(b->residue);
  107018. }
  107019. if(b->psy){
  107020. for(i=0;i<ci->psys;i++)
  107021. _vp_psy_clear(b->psy+i);
  107022. _ogg_free(b->psy);
  107023. }
  107024. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  107025. vorbis_bitrate_clear(&b->bms);
  107026. drft_clear(&b->fft_look[0]);
  107027. drft_clear(&b->fft_look[1]);
  107028. }
  107029. if(v->pcm){
  107030. for(i=0;i<vi->channels;i++)
  107031. if(v->pcm[i])_ogg_free(v->pcm[i]);
  107032. _ogg_free(v->pcm);
  107033. if(v->pcmret)_ogg_free(v->pcmret);
  107034. }
  107035. if(b){
  107036. /* free header, header1, header2 */
  107037. if(b->header)_ogg_free(b->header);
  107038. if(b->header1)_ogg_free(b->header1);
  107039. if(b->header2)_ogg_free(b->header2);
  107040. _ogg_free(b);
  107041. }
  107042. memset(v,0,sizeof(*v));
  107043. }
  107044. }
  107045. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  107046. int i;
  107047. vorbis_info *vi=v->vi;
  107048. private_state *b=(private_state*)v->backend_state;
  107049. /* free header, header1, header2 */
  107050. if(b->header)_ogg_free(b->header);b->header=NULL;
  107051. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  107052. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  107053. /* Do we have enough storage space for the requested buffer? If not,
  107054. expand the PCM (and envelope) storage */
  107055. if(v->pcm_current+vals>=v->pcm_storage){
  107056. v->pcm_storage=v->pcm_current+vals*2;
  107057. for(i=0;i<vi->channels;i++){
  107058. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  107059. }
  107060. }
  107061. for(i=0;i<vi->channels;i++)
  107062. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  107063. return(v->pcmret);
  107064. }
  107065. static void _preextrapolate_helper(vorbis_dsp_state *v){
  107066. int i;
  107067. int order=32;
  107068. float *lpc=(float*)alloca(order*sizeof(*lpc));
  107069. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  107070. long j;
  107071. v->preextrapolate=1;
  107072. if(v->pcm_current-v->centerW>order*2){ /* safety */
  107073. for(i=0;i<v->vi->channels;i++){
  107074. /* need to run the extrapolation in reverse! */
  107075. for(j=0;j<v->pcm_current;j++)
  107076. work[j]=v->pcm[i][v->pcm_current-j-1];
  107077. /* prime as above */
  107078. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  107079. /* run the predictor filter */
  107080. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  107081. order,
  107082. work+v->pcm_current-v->centerW,
  107083. v->centerW);
  107084. for(j=0;j<v->pcm_current;j++)
  107085. v->pcm[i][v->pcm_current-j-1]=work[j];
  107086. }
  107087. }
  107088. }
  107089. /* call with val<=0 to set eof */
  107090. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  107091. vorbis_info *vi=v->vi;
  107092. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107093. if(vals<=0){
  107094. int order=32;
  107095. int i;
  107096. float *lpc=(float*) alloca(order*sizeof(*lpc));
  107097. /* if it wasn't done earlier (very short sample) */
  107098. if(!v->preextrapolate)
  107099. _preextrapolate_helper(v);
  107100. /* We're encoding the end of the stream. Just make sure we have
  107101. [at least] a few full blocks of zeroes at the end. */
  107102. /* actually, we don't want zeroes; that could drop a large
  107103. amplitude off a cliff, creating spread spectrum noise that will
  107104. suck to encode. Extrapolate for the sake of cleanliness. */
  107105. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  107106. v->eofflag=v->pcm_current;
  107107. v->pcm_current+=ci->blocksizes[1]*3;
  107108. for(i=0;i<vi->channels;i++){
  107109. if(v->eofflag>order*2){
  107110. /* extrapolate with LPC to fill in */
  107111. long n;
  107112. /* make a predictor filter */
  107113. n=v->eofflag;
  107114. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  107115. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  107116. /* run the predictor filter */
  107117. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  107118. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  107119. }else{
  107120. /* not enough data to extrapolate (unlikely to happen due to
  107121. guarding the overlap, but bulletproof in case that
  107122. assumtion goes away). zeroes will do. */
  107123. memset(v->pcm[i]+v->eofflag,0,
  107124. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  107125. }
  107126. }
  107127. }else{
  107128. if(v->pcm_current+vals>v->pcm_storage)
  107129. return(OV_EINVAL);
  107130. v->pcm_current+=vals;
  107131. /* we may want to reverse extrapolate the beginning of a stream
  107132. too... in case we're beginning on a cliff! */
  107133. /* clumsy, but simple. It only runs once, so simple is good. */
  107134. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  107135. _preextrapolate_helper(v);
  107136. }
  107137. return(0);
  107138. }
  107139. /* do the deltas, envelope shaping, pre-echo and determine the size of
  107140. the next block on which to continue analysis */
  107141. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  107142. int i;
  107143. vorbis_info *vi=v->vi;
  107144. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107145. private_state *b=(private_state*)v->backend_state;
  107146. vorbis_look_psy_global *g=b->psy_g_look;
  107147. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  107148. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  107149. /* check to see if we're started... */
  107150. if(!v->preextrapolate)return(0);
  107151. /* check to see if we're done... */
  107152. if(v->eofflag==-1)return(0);
  107153. /* By our invariant, we have lW, W and centerW set. Search for
  107154. the next boundary so we can determine nW (the next window size)
  107155. which lets us compute the shape of the current block's window */
  107156. /* we do an envelope search even on a single blocksize; we may still
  107157. be throwing more bits at impulses, and envelope search handles
  107158. marking impulses too. */
  107159. {
  107160. long bp=_ve_envelope_search(v);
  107161. if(bp==-1){
  107162. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  107163. full long block */
  107164. v->nW=0;
  107165. }else{
  107166. if(ci->blocksizes[0]==ci->blocksizes[1])
  107167. v->nW=0;
  107168. else
  107169. v->nW=bp;
  107170. }
  107171. }
  107172. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  107173. {
  107174. /* center of next block + next block maximum right side. */
  107175. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  107176. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  107177. although this check is
  107178. less strict that the
  107179. _ve_envelope_search,
  107180. the search is not run
  107181. if we only use one
  107182. block size */
  107183. }
  107184. /* fill in the block. Note that for a short window, lW and nW are *short*
  107185. regardless of actual settings in the stream */
  107186. _vorbis_block_ripcord(vb);
  107187. vb->lW=v->lW;
  107188. vb->W=v->W;
  107189. vb->nW=v->nW;
  107190. if(v->W){
  107191. if(!v->lW || !v->nW){
  107192. vbi->blocktype=BLOCKTYPE_TRANSITION;
  107193. /*fprintf(stderr,"-");*/
  107194. }else{
  107195. vbi->blocktype=BLOCKTYPE_LONG;
  107196. /*fprintf(stderr,"_");*/
  107197. }
  107198. }else{
  107199. if(_ve_envelope_mark(v)){
  107200. vbi->blocktype=BLOCKTYPE_IMPULSE;
  107201. /*fprintf(stderr,"|");*/
  107202. }else{
  107203. vbi->blocktype=BLOCKTYPE_PADDING;
  107204. /*fprintf(stderr,".");*/
  107205. }
  107206. }
  107207. vb->vd=v;
  107208. vb->sequence=v->sequence++;
  107209. vb->granulepos=v->granulepos;
  107210. vb->pcmend=ci->blocksizes[v->W];
  107211. /* copy the vectors; this uses the local storage in vb */
  107212. /* this tracks 'strongest peak' for later psychoacoustics */
  107213. /* moved to the global psy state; clean this mess up */
  107214. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  107215. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  107216. vbi->ampmax=g->ampmax;
  107217. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  107218. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  107219. for(i=0;i<vi->channels;i++){
  107220. vbi->pcmdelay[i]=
  107221. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107222. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107223. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  107224. /* before we added the delay
  107225. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  107226. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  107227. */
  107228. }
  107229. /* handle eof detection: eof==0 means that we've not yet received EOF
  107230. eof>0 marks the last 'real' sample in pcm[]
  107231. eof<0 'no more to do'; doesn't get here */
  107232. if(v->eofflag){
  107233. if(v->centerW>=v->eofflag){
  107234. v->eofflag=-1;
  107235. vb->eofflag=1;
  107236. return(1);
  107237. }
  107238. }
  107239. /* advance storage vectors and clean up */
  107240. {
  107241. int new_centerNext=ci->blocksizes[1]/2;
  107242. int movementW=centerNext-new_centerNext;
  107243. if(movementW>0){
  107244. _ve_envelope_shift(b->ve,movementW);
  107245. v->pcm_current-=movementW;
  107246. for(i=0;i<vi->channels;i++)
  107247. memmove(v->pcm[i],v->pcm[i]+movementW,
  107248. v->pcm_current*sizeof(*v->pcm[i]));
  107249. v->lW=v->W;
  107250. v->W=v->nW;
  107251. v->centerW=new_centerNext;
  107252. if(v->eofflag){
  107253. v->eofflag-=movementW;
  107254. if(v->eofflag<=0)v->eofflag=-1;
  107255. /* do not add padding to end of stream! */
  107256. if(v->centerW>=v->eofflag){
  107257. v->granulepos+=movementW-(v->centerW-v->eofflag);
  107258. }else{
  107259. v->granulepos+=movementW;
  107260. }
  107261. }else{
  107262. v->granulepos+=movementW;
  107263. }
  107264. }
  107265. }
  107266. /* done */
  107267. return(1);
  107268. }
  107269. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  107270. vorbis_info *vi=v->vi;
  107271. codec_setup_info *ci;
  107272. int hs;
  107273. if(!v->backend_state)return -1;
  107274. if(!vi)return -1;
  107275. ci=(codec_setup_info*) vi->codec_setup;
  107276. if(!ci)return -1;
  107277. hs=ci->halfrate_flag;
  107278. v->centerW=ci->blocksizes[1]>>(hs+1);
  107279. v->pcm_current=v->centerW>>hs;
  107280. v->pcm_returned=-1;
  107281. v->granulepos=-1;
  107282. v->sequence=-1;
  107283. v->eofflag=0;
  107284. ((private_state *)(v->backend_state))->sample_count=-1;
  107285. return(0);
  107286. }
  107287. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  107288. if(_vds_shared_init(v,vi,0)) return 1;
  107289. vorbis_synthesis_restart(v);
  107290. return 0;
  107291. }
  107292. /* Unlike in analysis, the window is only partially applied for each
  107293. block. The time domain envelope is not yet handled at the point of
  107294. calling (as it relies on the previous block). */
  107295. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  107296. vorbis_info *vi=v->vi;
  107297. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107298. private_state *b=(private_state*)v->backend_state;
  107299. int hs=ci->halfrate_flag;
  107300. int i,j;
  107301. if(!vb)return(OV_EINVAL);
  107302. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  107303. v->lW=v->W;
  107304. v->W=vb->W;
  107305. v->nW=-1;
  107306. if((v->sequence==-1)||
  107307. (v->sequence+1 != vb->sequence)){
  107308. v->granulepos=-1; /* out of sequence; lose count */
  107309. b->sample_count=-1;
  107310. }
  107311. v->sequence=vb->sequence;
  107312. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  107313. was called on block */
  107314. int n=ci->blocksizes[v->W]>>(hs+1);
  107315. int n0=ci->blocksizes[0]>>(hs+1);
  107316. int n1=ci->blocksizes[1]>>(hs+1);
  107317. int thisCenter;
  107318. int prevCenter;
  107319. v->glue_bits+=vb->glue_bits;
  107320. v->time_bits+=vb->time_bits;
  107321. v->floor_bits+=vb->floor_bits;
  107322. v->res_bits+=vb->res_bits;
  107323. if(v->centerW){
  107324. thisCenter=n1;
  107325. prevCenter=0;
  107326. }else{
  107327. thisCenter=0;
  107328. prevCenter=n1;
  107329. }
  107330. /* v->pcm is now used like a two-stage double buffer. We don't want
  107331. to have to constantly shift *or* adjust memory usage. Don't
  107332. accept a new block until the old is shifted out */
  107333. for(j=0;j<vi->channels;j++){
  107334. /* the overlap/add section */
  107335. if(v->lW){
  107336. if(v->W){
  107337. /* large/large */
  107338. float *w=_vorbis_window_get(b->window[1]-hs);
  107339. float *pcm=v->pcm[j]+prevCenter;
  107340. float *p=vb->pcm[j];
  107341. for(i=0;i<n1;i++)
  107342. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  107343. }else{
  107344. /* large/small */
  107345. float *w=_vorbis_window_get(b->window[0]-hs);
  107346. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  107347. float *p=vb->pcm[j];
  107348. for(i=0;i<n0;i++)
  107349. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107350. }
  107351. }else{
  107352. if(v->W){
  107353. /* small/large */
  107354. float *w=_vorbis_window_get(b->window[0]-hs);
  107355. float *pcm=v->pcm[j]+prevCenter;
  107356. float *p=vb->pcm[j]+n1/2-n0/2;
  107357. for(i=0;i<n0;i++)
  107358. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107359. for(;i<n1/2+n0/2;i++)
  107360. pcm[i]=p[i];
  107361. }else{
  107362. /* small/small */
  107363. float *w=_vorbis_window_get(b->window[0]-hs);
  107364. float *pcm=v->pcm[j]+prevCenter;
  107365. float *p=vb->pcm[j];
  107366. for(i=0;i<n0;i++)
  107367. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107368. }
  107369. }
  107370. /* the copy section */
  107371. {
  107372. float *pcm=v->pcm[j]+thisCenter;
  107373. float *p=vb->pcm[j]+n;
  107374. for(i=0;i<n;i++)
  107375. pcm[i]=p[i];
  107376. }
  107377. }
  107378. if(v->centerW)
  107379. v->centerW=0;
  107380. else
  107381. v->centerW=n1;
  107382. /* deal with initial packet state; we do this using the explicit
  107383. pcm_returned==-1 flag otherwise we're sensitive to first block
  107384. being short or long */
  107385. if(v->pcm_returned==-1){
  107386. v->pcm_returned=thisCenter;
  107387. v->pcm_current=thisCenter;
  107388. }else{
  107389. v->pcm_returned=prevCenter;
  107390. v->pcm_current=prevCenter+
  107391. ((ci->blocksizes[v->lW]/4+
  107392. ci->blocksizes[v->W]/4)>>hs);
  107393. }
  107394. }
  107395. /* track the frame number... This is for convenience, but also
  107396. making sure our last packet doesn't end with added padding. If
  107397. the last packet is partial, the number of samples we'll have to
  107398. return will be past the vb->granulepos.
  107399. This is not foolproof! It will be confused if we begin
  107400. decoding at the last page after a seek or hole. In that case,
  107401. we don't have a starting point to judge where the last frame
  107402. is. For this reason, vorbisfile will always try to make sure
  107403. it reads the last two marked pages in proper sequence */
  107404. if(b->sample_count==-1){
  107405. b->sample_count=0;
  107406. }else{
  107407. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107408. }
  107409. if(v->granulepos==-1){
  107410. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  107411. v->granulepos=vb->granulepos;
  107412. /* is this a short page? */
  107413. if(b->sample_count>v->granulepos){
  107414. /* corner case; if this is both the first and last audio page,
  107415. then spec says the end is cut, not beginning */
  107416. if(vb->eofflag){
  107417. /* trim the end */
  107418. /* no preceeding granulepos; assume we started at zero (we'd
  107419. have to in a short single-page stream) */
  107420. /* granulepos could be -1 due to a seek, but that would result
  107421. in a long count, not short count */
  107422. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  107423. }else{
  107424. /* trim the beginning */
  107425. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  107426. if(v->pcm_returned>v->pcm_current)
  107427. v->pcm_returned=v->pcm_current;
  107428. }
  107429. }
  107430. }
  107431. }else{
  107432. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107433. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  107434. if(v->granulepos>vb->granulepos){
  107435. long extra=v->granulepos-vb->granulepos;
  107436. if(extra)
  107437. if(vb->eofflag){
  107438. /* partial last frame. Strip the extra samples off */
  107439. v->pcm_current-=extra>>hs;
  107440. } /* else {Shouldn't happen *unless* the bitstream is out of
  107441. spec. Either way, believe the bitstream } */
  107442. } /* else {Shouldn't happen *unless* the bitstream is out of
  107443. spec. Either way, believe the bitstream } */
  107444. v->granulepos=vb->granulepos;
  107445. }
  107446. }
  107447. /* Update, cleanup */
  107448. if(vb->eofflag)v->eofflag=1;
  107449. return(0);
  107450. }
  107451. /* pcm==NULL indicates we just want the pending samples, no more */
  107452. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  107453. vorbis_info *vi=v->vi;
  107454. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  107455. if(pcm){
  107456. int i;
  107457. for(i=0;i<vi->channels;i++)
  107458. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107459. *pcm=v->pcmret;
  107460. }
  107461. return(v->pcm_current-v->pcm_returned);
  107462. }
  107463. return(0);
  107464. }
  107465. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  107466. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  107467. v->pcm_returned+=n;
  107468. return(0);
  107469. }
  107470. /* intended for use with a specific vorbisfile feature; we want access
  107471. to the [usually synthetic/postextrapolated] buffer and lapping at
  107472. the end of a decode cycle, specifically, a half-short-block worth.
  107473. This funtion works like pcmout above, except it will also expose
  107474. this implicit buffer data not normally decoded. */
  107475. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  107476. vorbis_info *vi=v->vi;
  107477. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107478. int hs=ci->halfrate_flag;
  107479. int n=ci->blocksizes[v->W]>>(hs+1);
  107480. int n0=ci->blocksizes[0]>>(hs+1);
  107481. int n1=ci->blocksizes[1]>>(hs+1);
  107482. int i,j;
  107483. if(v->pcm_returned<0)return 0;
  107484. /* our returned data ends at pcm_returned; because the synthesis pcm
  107485. buffer is a two-fragment ring, that means our data block may be
  107486. fragmented by buffering, wrapping or a short block not filling
  107487. out a buffer. To simplify things, we unfragment if it's at all
  107488. possibly needed. Otherwise, we'd need to call lapout more than
  107489. once as well as hold additional dsp state. Opt for
  107490. simplicity. */
  107491. /* centerW was advanced by blockin; it would be the center of the
  107492. *next* block */
  107493. if(v->centerW==n1){
  107494. /* the data buffer wraps; swap the halves */
  107495. /* slow, sure, small */
  107496. for(j=0;j<vi->channels;j++){
  107497. float *p=v->pcm[j];
  107498. for(i=0;i<n1;i++){
  107499. float temp=p[i];
  107500. p[i]=p[i+n1];
  107501. p[i+n1]=temp;
  107502. }
  107503. }
  107504. v->pcm_current-=n1;
  107505. v->pcm_returned-=n1;
  107506. v->centerW=0;
  107507. }
  107508. /* solidify buffer into contiguous space */
  107509. if((v->lW^v->W)==1){
  107510. /* long/short or short/long */
  107511. for(j=0;j<vi->channels;j++){
  107512. float *s=v->pcm[j];
  107513. float *d=v->pcm[j]+(n1-n0)/2;
  107514. for(i=(n1+n0)/2-1;i>=0;--i)
  107515. d[i]=s[i];
  107516. }
  107517. v->pcm_returned+=(n1-n0)/2;
  107518. v->pcm_current+=(n1-n0)/2;
  107519. }else{
  107520. if(v->lW==0){
  107521. /* short/short */
  107522. for(j=0;j<vi->channels;j++){
  107523. float *s=v->pcm[j];
  107524. float *d=v->pcm[j]+n1-n0;
  107525. for(i=n0-1;i>=0;--i)
  107526. d[i]=s[i];
  107527. }
  107528. v->pcm_returned+=n1-n0;
  107529. v->pcm_current+=n1-n0;
  107530. }
  107531. }
  107532. if(pcm){
  107533. int i;
  107534. for(i=0;i<vi->channels;i++)
  107535. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107536. *pcm=v->pcmret;
  107537. }
  107538. return(n1+n-v->pcm_returned);
  107539. }
  107540. float *vorbis_window(vorbis_dsp_state *v,int W){
  107541. vorbis_info *vi=v->vi;
  107542. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  107543. int hs=ci->halfrate_flag;
  107544. private_state *b=(private_state*)v->backend_state;
  107545. if(b->window[W]-1<0)return NULL;
  107546. return _vorbis_window_get(b->window[W]-hs);
  107547. }
  107548. #endif
  107549. /********* End of inlined file: block.c *********/
  107550. /********* Start of inlined file: codebook.c *********/
  107551. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107552. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107553. // tasks..
  107554. #if JUCE_MSVC
  107555. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107556. #endif
  107557. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107558. #if JUCE_USE_OGGVORBIS
  107559. #include <stdlib.h>
  107560. #include <string.h>
  107561. #include <math.h>
  107562. /* packs the given codebook into the bitstream **************************/
  107563. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  107564. long i,j;
  107565. int ordered=0;
  107566. /* first the basic parameters */
  107567. oggpack_write(opb,0x564342,24);
  107568. oggpack_write(opb,c->dim,16);
  107569. oggpack_write(opb,c->entries,24);
  107570. /* pack the codewords. There are two packings; length ordered and
  107571. length random. Decide between the two now. */
  107572. for(i=1;i<c->entries;i++)
  107573. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  107574. if(i==c->entries)ordered=1;
  107575. if(ordered){
  107576. /* length ordered. We only need to say how many codewords of
  107577. each length. The actual codewords are generated
  107578. deterministically */
  107579. long count=0;
  107580. oggpack_write(opb,1,1); /* ordered */
  107581. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  107582. for(i=1;i<c->entries;i++){
  107583. long thisx=c->lengthlist[i];
  107584. long last=c->lengthlist[i-1];
  107585. if(thisx>last){
  107586. for(j=last;j<thisx;j++){
  107587. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107588. count=i;
  107589. }
  107590. }
  107591. }
  107592. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107593. }else{
  107594. /* length random. Again, we don't code the codeword itself, just
  107595. the length. This time, though, we have to encode each length */
  107596. oggpack_write(opb,0,1); /* unordered */
  107597. /* algortihmic mapping has use for 'unused entries', which we tag
  107598. here. The algorithmic mapping happens as usual, but the unused
  107599. entry has no codeword. */
  107600. for(i=0;i<c->entries;i++)
  107601. if(c->lengthlist[i]==0)break;
  107602. if(i==c->entries){
  107603. oggpack_write(opb,0,1); /* no unused entries */
  107604. for(i=0;i<c->entries;i++)
  107605. oggpack_write(opb,c->lengthlist[i]-1,5);
  107606. }else{
  107607. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  107608. for(i=0;i<c->entries;i++){
  107609. if(c->lengthlist[i]==0){
  107610. oggpack_write(opb,0,1);
  107611. }else{
  107612. oggpack_write(opb,1,1);
  107613. oggpack_write(opb,c->lengthlist[i]-1,5);
  107614. }
  107615. }
  107616. }
  107617. }
  107618. /* is the entry number the desired return value, or do we have a
  107619. mapping? If we have a mapping, what type? */
  107620. oggpack_write(opb,c->maptype,4);
  107621. switch(c->maptype){
  107622. case 0:
  107623. /* no mapping */
  107624. break;
  107625. case 1:case 2:
  107626. /* implicitly populated value mapping */
  107627. /* explicitly populated value mapping */
  107628. if(!c->quantlist){
  107629. /* no quantlist? error */
  107630. return(-1);
  107631. }
  107632. /* values that define the dequantization */
  107633. oggpack_write(opb,c->q_min,32);
  107634. oggpack_write(opb,c->q_delta,32);
  107635. oggpack_write(opb,c->q_quant-1,4);
  107636. oggpack_write(opb,c->q_sequencep,1);
  107637. {
  107638. int quantvals;
  107639. switch(c->maptype){
  107640. case 1:
  107641. /* a single column of (c->entries/c->dim) quantized values for
  107642. building a full value list algorithmically (square lattice) */
  107643. quantvals=_book_maptype1_quantvals(c);
  107644. break;
  107645. case 2:
  107646. /* every value (c->entries*c->dim total) specified explicitly */
  107647. quantvals=c->entries*c->dim;
  107648. break;
  107649. default: /* NOT_REACHABLE */
  107650. quantvals=-1;
  107651. }
  107652. /* quantized values */
  107653. for(i=0;i<quantvals;i++)
  107654. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  107655. }
  107656. break;
  107657. default:
  107658. /* error case; we don't have any other map types now */
  107659. return(-1);
  107660. }
  107661. return(0);
  107662. }
  107663. /* unpacks a codebook from the packet buffer into the codebook struct,
  107664. readies the codebook auxiliary structures for decode *************/
  107665. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  107666. long i,j;
  107667. memset(s,0,sizeof(*s));
  107668. s->allocedp=1;
  107669. /* make sure alignment is correct */
  107670. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  107671. /* first the basic parameters */
  107672. s->dim=oggpack_read(opb,16);
  107673. s->entries=oggpack_read(opb,24);
  107674. if(s->entries==-1)goto _eofout;
  107675. /* codeword ordering.... length ordered or unordered? */
  107676. switch((int)oggpack_read(opb,1)){
  107677. case 0:
  107678. /* unordered */
  107679. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107680. /* allocated but unused entries? */
  107681. if(oggpack_read(opb,1)){
  107682. /* yes, unused entries */
  107683. for(i=0;i<s->entries;i++){
  107684. if(oggpack_read(opb,1)){
  107685. long num=oggpack_read(opb,5);
  107686. if(num==-1)goto _eofout;
  107687. s->lengthlist[i]=num+1;
  107688. }else
  107689. s->lengthlist[i]=0;
  107690. }
  107691. }else{
  107692. /* all entries used; no tagging */
  107693. for(i=0;i<s->entries;i++){
  107694. long num=oggpack_read(opb,5);
  107695. if(num==-1)goto _eofout;
  107696. s->lengthlist[i]=num+1;
  107697. }
  107698. }
  107699. break;
  107700. case 1:
  107701. /* ordered */
  107702. {
  107703. long length=oggpack_read(opb,5)+1;
  107704. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107705. for(i=0;i<s->entries;){
  107706. long num=oggpack_read(opb,_ilog(s->entries-i));
  107707. if(num==-1)goto _eofout;
  107708. for(j=0;j<num && i<s->entries;j++,i++)
  107709. s->lengthlist[i]=length;
  107710. length++;
  107711. }
  107712. }
  107713. break;
  107714. default:
  107715. /* EOF */
  107716. return(-1);
  107717. }
  107718. /* Do we have a mapping to unpack? */
  107719. switch((s->maptype=oggpack_read(opb,4))){
  107720. case 0:
  107721. /* no mapping */
  107722. break;
  107723. case 1: case 2:
  107724. /* implicitly populated value mapping */
  107725. /* explicitly populated value mapping */
  107726. s->q_min=oggpack_read(opb,32);
  107727. s->q_delta=oggpack_read(opb,32);
  107728. s->q_quant=oggpack_read(opb,4)+1;
  107729. s->q_sequencep=oggpack_read(opb,1);
  107730. {
  107731. int quantvals=0;
  107732. switch(s->maptype){
  107733. case 1:
  107734. quantvals=_book_maptype1_quantvals(s);
  107735. break;
  107736. case 2:
  107737. quantvals=s->entries*s->dim;
  107738. break;
  107739. }
  107740. /* quantized values */
  107741. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  107742. for(i=0;i<quantvals;i++)
  107743. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  107744. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  107745. }
  107746. break;
  107747. default:
  107748. goto _errout;
  107749. }
  107750. /* all set */
  107751. return(0);
  107752. _errout:
  107753. _eofout:
  107754. vorbis_staticbook_clear(s);
  107755. return(-1);
  107756. }
  107757. /* returns the number of bits ************************************************/
  107758. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  107759. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  107760. return(book->c->lengthlist[a]);
  107761. }
  107762. /* One the encode side, our vector writers are each designed for a
  107763. specific purpose, and the encoder is not flexible without modification:
  107764. The LSP vector coder uses a single stage nearest-match with no
  107765. interleave, so no step and no error return. This is specced by floor0
  107766. and doesn't change.
  107767. Residue0 encoding interleaves, uses multiple stages, and each stage
  107768. peels of a specific amount of resolution from a lattice (thus we want
  107769. to match by threshold, not nearest match). Residue doesn't *have* to
  107770. be encoded that way, but to change it, one will need to add more
  107771. infrastructure on the encode side (decode side is specced and simpler) */
  107772. /* floor0 LSP (single stage, non interleaved, nearest match) */
  107773. /* returns entry number and *modifies a* to the quantization value *****/
  107774. int vorbis_book_errorv(codebook *book,float *a){
  107775. int dim=book->dim,k;
  107776. int best=_best(book,a,1);
  107777. for(k=0;k<dim;k++)
  107778. a[k]=(book->valuelist+best*dim)[k];
  107779. return(best);
  107780. }
  107781. /* returns the number of bits and *modifies a* to the quantization value *****/
  107782. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  107783. int k,dim=book->dim;
  107784. for(k=0;k<dim;k++)
  107785. a[k]=(book->valuelist+best*dim)[k];
  107786. return(vorbis_book_encode(book,best,b));
  107787. }
  107788. /* the 'eliminate the decode tree' optimization actually requires the
  107789. codewords to be MSb first, not LSb. This is an annoying inelegancy
  107790. (and one of the first places where carefully thought out design
  107791. turned out to be wrong; Vorbis II and future Ogg codecs should go
  107792. to an MSb bitpacker), but not actually the huge hit it appears to
  107793. be. The first-stage decode table catches most words so that
  107794. bitreverse is not in the main execution path. */
  107795. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  107796. int read=book->dec_maxlength;
  107797. long lo,hi;
  107798. long lok = oggpack_look(b,book->dec_firsttablen);
  107799. if (lok >= 0) {
  107800. long entry = book->dec_firsttable[lok];
  107801. if(entry&0x80000000UL){
  107802. lo=(entry>>15)&0x7fff;
  107803. hi=book->used_entries-(entry&0x7fff);
  107804. }else{
  107805. oggpack_adv(b, book->dec_codelengths[entry-1]);
  107806. return(entry-1);
  107807. }
  107808. }else{
  107809. lo=0;
  107810. hi=book->used_entries;
  107811. }
  107812. lok = oggpack_look(b, read);
  107813. while(lok<0 && read>1)
  107814. lok = oggpack_look(b, --read);
  107815. if(lok<0)return -1;
  107816. /* bisect search for the codeword in the ordered list */
  107817. {
  107818. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  107819. while(hi-lo>1){
  107820. long p=(hi-lo)>>1;
  107821. long test=book->codelist[lo+p]>testword;
  107822. lo+=p&(test-1);
  107823. hi-=p&(-test);
  107824. }
  107825. if(book->dec_codelengths[lo]<=read){
  107826. oggpack_adv(b, book->dec_codelengths[lo]);
  107827. return(lo);
  107828. }
  107829. }
  107830. oggpack_adv(b, read);
  107831. return(-1);
  107832. }
  107833. /* Decode side is specced and easier, because we don't need to find
  107834. matches using different criteria; we simply read and map. There are
  107835. two things we need to do 'depending':
  107836. We may need to support interleave. We don't really, but it's
  107837. convenient to do it here rather than rebuild the vector later.
  107838. Cascades may be additive or multiplicitive; this is not inherent in
  107839. the codebook, but set in the code using the codebook. Like
  107840. interleaving, it's easiest to do it here.
  107841. addmul==0 -> declarative (set the value)
  107842. addmul==1 -> additive
  107843. addmul==2 -> multiplicitive */
  107844. /* returns the [original, not compacted] entry number or -1 on eof *********/
  107845. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  107846. long packed_entry=decode_packed_entry_number(book,b);
  107847. if(packed_entry>=0)
  107848. return(book->dec_index[packed_entry]);
  107849. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  107850. return(packed_entry);
  107851. }
  107852. /* returns 0 on OK or -1 on eof *************************************/
  107853. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107854. int step=n/book->dim;
  107855. long *entry = (long*)alloca(sizeof(*entry)*step);
  107856. float **t = (float**)alloca(sizeof(*t)*step);
  107857. int i,j,o;
  107858. for (i = 0; i < step; i++) {
  107859. entry[i]=decode_packed_entry_number(book,b);
  107860. if(entry[i]==-1)return(-1);
  107861. t[i] = book->valuelist+entry[i]*book->dim;
  107862. }
  107863. for(i=0,o=0;i<book->dim;i++,o+=step)
  107864. for (j=0;j<step;j++)
  107865. a[o+j]+=t[j][i];
  107866. return(0);
  107867. }
  107868. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107869. int i,j,entry;
  107870. float *t;
  107871. if(book->dim>8){
  107872. for(i=0;i<n;){
  107873. entry = decode_packed_entry_number(book,b);
  107874. if(entry==-1)return(-1);
  107875. t = book->valuelist+entry*book->dim;
  107876. for (j=0;j<book->dim;)
  107877. a[i++]+=t[j++];
  107878. }
  107879. }else{
  107880. for(i=0;i<n;){
  107881. entry = decode_packed_entry_number(book,b);
  107882. if(entry==-1)return(-1);
  107883. t = book->valuelist+entry*book->dim;
  107884. j=0;
  107885. switch((int)book->dim){
  107886. case 8:
  107887. a[i++]+=t[j++];
  107888. case 7:
  107889. a[i++]+=t[j++];
  107890. case 6:
  107891. a[i++]+=t[j++];
  107892. case 5:
  107893. a[i++]+=t[j++];
  107894. case 4:
  107895. a[i++]+=t[j++];
  107896. case 3:
  107897. a[i++]+=t[j++];
  107898. case 2:
  107899. a[i++]+=t[j++];
  107900. case 1:
  107901. a[i++]+=t[j++];
  107902. case 0:
  107903. break;
  107904. }
  107905. }
  107906. }
  107907. return(0);
  107908. }
  107909. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  107910. int i,j,entry;
  107911. float *t;
  107912. for(i=0;i<n;){
  107913. entry = decode_packed_entry_number(book,b);
  107914. if(entry==-1)return(-1);
  107915. t = book->valuelist+entry*book->dim;
  107916. for (j=0;j<book->dim;)
  107917. a[i++]=t[j++];
  107918. }
  107919. return(0);
  107920. }
  107921. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  107922. oggpack_buffer *b,int n){
  107923. long i,j,entry;
  107924. int chptr=0;
  107925. for(i=offset/ch;i<(offset+n)/ch;){
  107926. entry = decode_packed_entry_number(book,b);
  107927. if(entry==-1)return(-1);
  107928. {
  107929. const float *t = book->valuelist+entry*book->dim;
  107930. for (j=0;j<book->dim;j++){
  107931. a[chptr++][i]+=t[j];
  107932. if(chptr==ch){
  107933. chptr=0;
  107934. i++;
  107935. }
  107936. }
  107937. }
  107938. }
  107939. return(0);
  107940. }
  107941. #ifdef _V_SELFTEST
  107942. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  107943. number of vectors through (keeping track of the quantized values),
  107944. and decode using the unpacked book. quantized version of in should
  107945. exactly equal out */
  107946. #include <stdio.h>
  107947. #include "vorbis/book/lsp20_0.vqh"
  107948. #include "vorbis/book/res0a_13.vqh"
  107949. #define TESTSIZE 40
  107950. float test1[TESTSIZE]={
  107951. 0.105939f,
  107952. 0.215373f,
  107953. 0.429117f,
  107954. 0.587974f,
  107955. 0.181173f,
  107956. 0.296583f,
  107957. 0.515707f,
  107958. 0.715261f,
  107959. 0.162327f,
  107960. 0.263834f,
  107961. 0.342876f,
  107962. 0.406025f,
  107963. 0.103571f,
  107964. 0.223561f,
  107965. 0.368513f,
  107966. 0.540313f,
  107967. 0.136672f,
  107968. 0.395882f,
  107969. 0.587183f,
  107970. 0.652476f,
  107971. 0.114338f,
  107972. 0.417300f,
  107973. 0.525486f,
  107974. 0.698679f,
  107975. 0.147492f,
  107976. 0.324481f,
  107977. 0.643089f,
  107978. 0.757582f,
  107979. 0.139556f,
  107980. 0.215795f,
  107981. 0.324559f,
  107982. 0.399387f,
  107983. 0.120236f,
  107984. 0.267420f,
  107985. 0.446940f,
  107986. 0.608760f,
  107987. 0.115587f,
  107988. 0.287234f,
  107989. 0.571081f,
  107990. 0.708603f,
  107991. };
  107992. float test3[TESTSIZE]={
  107993. 0,1,-2,3,4,-5,6,7,8,9,
  107994. 8,-2,7,-1,4,6,8,3,1,-9,
  107995. 10,11,12,13,14,15,26,17,18,19,
  107996. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  107997. static_codebook *testlist[]={&_vq_book_lsp20_0,
  107998. &_vq_book_res0a_13,NULL};
  107999. float *testvec[]={test1,test3};
  108000. int main(){
  108001. oggpack_buffer write;
  108002. oggpack_buffer read;
  108003. long ptr=0,i;
  108004. oggpack_writeinit(&write);
  108005. fprintf(stderr,"Testing codebook abstraction...:\n");
  108006. while(testlist[ptr]){
  108007. codebook c;
  108008. static_codebook s;
  108009. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  108010. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  108011. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  108012. memset(iv,0,sizeof(*iv)*TESTSIZE);
  108013. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  108014. /* pack the codebook, write the testvector */
  108015. oggpack_reset(&write);
  108016. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  108017. we can write */
  108018. vorbis_staticbook_pack(testlist[ptr],&write);
  108019. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  108020. for(i=0;i<TESTSIZE;i+=c.dim){
  108021. int best=_best(&c,qv+i,1);
  108022. vorbis_book_encodev(&c,best,qv+i,&write);
  108023. }
  108024. vorbis_book_clear(&c);
  108025. fprintf(stderr,"OK.\n");
  108026. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  108027. /* transfer the write data to a read buffer and unpack/read */
  108028. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  108029. if(vorbis_staticbook_unpack(&read,&s)){
  108030. fprintf(stderr,"Error unpacking codebook.\n");
  108031. exit(1);
  108032. }
  108033. if(vorbis_book_init_decode(&c,&s)){
  108034. fprintf(stderr,"Error initializing codebook.\n");
  108035. exit(1);
  108036. }
  108037. for(i=0;i<TESTSIZE;i+=c.dim)
  108038. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  108039. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  108040. exit(1);
  108041. }
  108042. for(i=0;i<TESTSIZE;i++)
  108043. if(fabs(qv[i]-iv[i])>.000001){
  108044. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  108045. iv[i],qv[i],i);
  108046. exit(1);
  108047. }
  108048. fprintf(stderr,"OK\n");
  108049. ptr++;
  108050. }
  108051. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  108052. exit(0);
  108053. }
  108054. #endif
  108055. #endif
  108056. /********* End of inlined file: codebook.c *********/
  108057. /********* Start of inlined file: envelope.c *********/
  108058. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108059. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108060. // tasks..
  108061. #if JUCE_MSVC
  108062. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108063. #endif
  108064. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108065. #if JUCE_USE_OGGVORBIS
  108066. #include <stdlib.h>
  108067. #include <string.h>
  108068. #include <stdio.h>
  108069. #include <math.h>
  108070. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  108071. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108072. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108073. int ch=vi->channels;
  108074. int i,j;
  108075. int n=e->winlength=128;
  108076. e->searchstep=64; /* not random */
  108077. e->minenergy=gi->preecho_minenergy;
  108078. e->ch=ch;
  108079. e->storage=128;
  108080. e->cursor=ci->blocksizes[1]/2;
  108081. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  108082. mdct_init(&e->mdct,n);
  108083. for(i=0;i<n;i++){
  108084. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  108085. e->mdct_win[i]*=e->mdct_win[i];
  108086. }
  108087. /* magic follows */
  108088. e->band[0].begin=2; e->band[0].end=4;
  108089. e->band[1].begin=4; e->band[1].end=5;
  108090. e->band[2].begin=6; e->band[2].end=6;
  108091. e->band[3].begin=9; e->band[3].end=8;
  108092. e->band[4].begin=13; e->band[4].end=8;
  108093. e->band[5].begin=17; e->band[5].end=8;
  108094. e->band[6].begin=22; e->band[6].end=8;
  108095. for(j=0;j<VE_BANDS;j++){
  108096. n=e->band[j].end;
  108097. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  108098. for(i=0;i<n;i++){
  108099. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  108100. e->band[j].total+=e->band[j].window[i];
  108101. }
  108102. e->band[j].total=1./e->band[j].total;
  108103. }
  108104. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  108105. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  108106. }
  108107. void _ve_envelope_clear(envelope_lookup *e){
  108108. int i;
  108109. mdct_clear(&e->mdct);
  108110. for(i=0;i<VE_BANDS;i++)
  108111. _ogg_free(e->band[i].window);
  108112. _ogg_free(e->mdct_win);
  108113. _ogg_free(e->filter);
  108114. _ogg_free(e->mark);
  108115. memset(e,0,sizeof(*e));
  108116. }
  108117. /* fairly straight threshhold-by-band based until we find something
  108118. that works better and isn't patented. */
  108119. static int _ve_amp(envelope_lookup *ve,
  108120. vorbis_info_psy_global *gi,
  108121. float *data,
  108122. envelope_band *bands,
  108123. envelope_filter_state *filters,
  108124. long pos){
  108125. long n=ve->winlength;
  108126. int ret=0;
  108127. long i,j;
  108128. float decay;
  108129. /* we want to have a 'minimum bar' for energy, else we're just
  108130. basing blocks on quantization noise that outweighs the signal
  108131. itself (for low power signals) */
  108132. float minV=ve->minenergy;
  108133. float *vec=(float*) alloca(n*sizeof(*vec));
  108134. /* stretch is used to gradually lengthen the number of windows
  108135. considered prevoius-to-potential-trigger */
  108136. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  108137. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  108138. if(penalty<0.f)penalty=0.f;
  108139. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  108140. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  108141. totalshift+pos*ve->searchstep);*/
  108142. /* window and transform */
  108143. for(i=0;i<n;i++)
  108144. vec[i]=data[i]*ve->mdct_win[i];
  108145. mdct_forward(&ve->mdct,vec,vec);
  108146. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  108147. /* near-DC spreading function; this has nothing to do with
  108148. psychoacoustics, just sidelobe leakage and window size */
  108149. {
  108150. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  108151. int ptr=filters->nearptr;
  108152. /* the accumulation is regularly refreshed from scratch to avoid
  108153. floating point creep */
  108154. if(ptr==0){
  108155. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  108156. filters->nearDC_partialacc=temp;
  108157. }else{
  108158. decay=filters->nearDC_acc+=temp;
  108159. filters->nearDC_partialacc+=temp;
  108160. }
  108161. filters->nearDC_acc-=filters->nearDC[ptr];
  108162. filters->nearDC[ptr]=temp;
  108163. decay*=(1./(VE_NEARDC+1));
  108164. filters->nearptr++;
  108165. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  108166. decay=todB(&decay)*.5-15.f;
  108167. }
  108168. /* perform spreading and limiting, also smooth the spectrum. yes,
  108169. the MDCT results in all real coefficients, but it still *behaves*
  108170. like real/imaginary pairs */
  108171. for(i=0;i<n/2;i+=2){
  108172. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  108173. val=todB(&val)*.5f;
  108174. if(val<decay)val=decay;
  108175. if(val<minV)val=minV;
  108176. vec[i>>1]=val;
  108177. decay-=8.;
  108178. }
  108179. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  108180. /* perform preecho/postecho triggering by band */
  108181. for(j=0;j<VE_BANDS;j++){
  108182. float acc=0.;
  108183. float valmax,valmin;
  108184. /* accumulate amplitude */
  108185. for(i=0;i<bands[j].end;i++)
  108186. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  108187. acc*=bands[j].total;
  108188. /* convert amplitude to delta */
  108189. {
  108190. int p,thisx=filters[j].ampptr;
  108191. float postmax,postmin,premax=-99999.f,premin=99999.f;
  108192. p=thisx;
  108193. p--;
  108194. if(p<0)p+=VE_AMP;
  108195. postmax=max(acc,filters[j].ampbuf[p]);
  108196. postmin=min(acc,filters[j].ampbuf[p]);
  108197. for(i=0;i<stretch;i++){
  108198. p--;
  108199. if(p<0)p+=VE_AMP;
  108200. premax=max(premax,filters[j].ampbuf[p]);
  108201. premin=min(premin,filters[j].ampbuf[p]);
  108202. }
  108203. valmin=postmin-premin;
  108204. valmax=postmax-premax;
  108205. /*filters[j].markers[pos]=valmax;*/
  108206. filters[j].ampbuf[thisx]=acc;
  108207. filters[j].ampptr++;
  108208. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  108209. }
  108210. /* look at min/max, decide trigger */
  108211. if(valmax>gi->preecho_thresh[j]+penalty){
  108212. ret|=1;
  108213. ret|=4;
  108214. }
  108215. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  108216. }
  108217. return(ret);
  108218. }
  108219. #if 0
  108220. static int seq=0;
  108221. static ogg_int64_t totalshift=-1024;
  108222. #endif
  108223. long _ve_envelope_search(vorbis_dsp_state *v){
  108224. vorbis_info *vi=v->vi;
  108225. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108226. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108227. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108228. long i,j;
  108229. int first=ve->current/ve->searchstep;
  108230. int last=v->pcm_current/ve->searchstep-VE_WIN;
  108231. if(first<0)first=0;
  108232. /* make sure we have enough storage to match the PCM */
  108233. if(last+VE_WIN+VE_POST>ve->storage){
  108234. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  108235. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  108236. }
  108237. for(j=first;j<last;j++){
  108238. int ret=0;
  108239. ve->stretch++;
  108240. if(ve->stretch>VE_MAXSTRETCH*2)
  108241. ve->stretch=VE_MAXSTRETCH*2;
  108242. for(i=0;i<ve->ch;i++){
  108243. float *pcm=v->pcm[i]+ve->searchstep*(j);
  108244. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  108245. }
  108246. ve->mark[j+VE_POST]=0;
  108247. if(ret&1){
  108248. ve->mark[j]=1;
  108249. ve->mark[j+1]=1;
  108250. }
  108251. if(ret&2){
  108252. ve->mark[j]=1;
  108253. if(j>0)ve->mark[j-1]=1;
  108254. }
  108255. if(ret&4)ve->stretch=-1;
  108256. }
  108257. ve->current=last*ve->searchstep;
  108258. {
  108259. long centerW=v->centerW;
  108260. long testW=
  108261. centerW+
  108262. ci->blocksizes[v->W]/4+
  108263. ci->blocksizes[1]/2+
  108264. ci->blocksizes[0]/4;
  108265. j=ve->cursor;
  108266. while(j<ve->current-(ve->searchstep)){/* account for postecho
  108267. working back one window */
  108268. if(j>=testW)return(1);
  108269. ve->cursor=j;
  108270. if(ve->mark[j/ve->searchstep]){
  108271. if(j>centerW){
  108272. #if 0
  108273. if(j>ve->curmark){
  108274. float *marker=alloca(v->pcm_current*sizeof(*marker));
  108275. int l,m;
  108276. memset(marker,0,sizeof(*marker)*v->pcm_current);
  108277. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  108278. seq,
  108279. (totalshift+ve->cursor)/44100.,
  108280. (totalshift+j)/44100.);
  108281. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  108282. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  108283. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  108284. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  108285. for(m=0;m<VE_BANDS;m++){
  108286. char buf[80];
  108287. sprintf(buf,"delL%d",m);
  108288. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  108289. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108290. }
  108291. for(m=0;m<VE_BANDS;m++){
  108292. char buf[80];
  108293. sprintf(buf,"delR%d",m);
  108294. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  108295. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108296. }
  108297. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  108298. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  108299. seq++;
  108300. }
  108301. #endif
  108302. ve->curmark=j;
  108303. if(j>=testW)return(1);
  108304. return(0);
  108305. }
  108306. }
  108307. j+=ve->searchstep;
  108308. }
  108309. }
  108310. return(-1);
  108311. }
  108312. int _ve_envelope_mark(vorbis_dsp_state *v){
  108313. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108314. vorbis_info *vi=v->vi;
  108315. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108316. long centerW=v->centerW;
  108317. long beginW=centerW-ci->blocksizes[v->W]/4;
  108318. long endW=centerW+ci->blocksizes[v->W]/4;
  108319. if(v->W){
  108320. beginW-=ci->blocksizes[v->lW]/4;
  108321. endW+=ci->blocksizes[v->nW]/4;
  108322. }else{
  108323. beginW-=ci->blocksizes[0]/4;
  108324. endW+=ci->blocksizes[0]/4;
  108325. }
  108326. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  108327. {
  108328. long first=beginW/ve->searchstep;
  108329. long last=endW/ve->searchstep;
  108330. long i;
  108331. for(i=first;i<last;i++)
  108332. if(ve->mark[i])return(1);
  108333. }
  108334. return(0);
  108335. }
  108336. void _ve_envelope_shift(envelope_lookup *e,long shift){
  108337. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  108338. ahead of ve->current */
  108339. int smallshift=shift/e->searchstep;
  108340. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  108341. #if 0
  108342. for(i=0;i<VE_BANDS*e->ch;i++)
  108343. memmove(e->filter[i].markers,
  108344. e->filter[i].markers+smallshift,
  108345. (1024-smallshift)*sizeof(*(*e->filter).markers));
  108346. totalshift+=shift;
  108347. #endif
  108348. e->current-=shift;
  108349. if(e->curmark>=0)
  108350. e->curmark-=shift;
  108351. e->cursor-=shift;
  108352. }
  108353. #endif
  108354. /********* End of inlined file: envelope.c *********/
  108355. /********* Start of inlined file: floor0.c *********/
  108356. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108357. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108358. // tasks..
  108359. #if JUCE_MSVC
  108360. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108361. #endif
  108362. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108363. #if JUCE_USE_OGGVORBIS
  108364. #include <stdlib.h>
  108365. #include <string.h>
  108366. #include <math.h>
  108367. /********* Start of inlined file: lsp.h *********/
  108368. #ifndef _V_LSP_H_
  108369. #define _V_LSP_H_
  108370. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  108371. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  108372. float *lsp,int m,
  108373. float amp,float ampoffset);
  108374. #endif
  108375. /********* End of inlined file: lsp.h *********/
  108376. #include <stdio.h>
  108377. typedef struct {
  108378. int ln;
  108379. int m;
  108380. int **linearmap;
  108381. int n[2];
  108382. vorbis_info_floor0 *vi;
  108383. long bits;
  108384. long frames;
  108385. } vorbis_look_floor0;
  108386. /***********************************************/
  108387. static void floor0_free_info(vorbis_info_floor *i){
  108388. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  108389. if(info){
  108390. memset(info,0,sizeof(*info));
  108391. _ogg_free(info);
  108392. }
  108393. }
  108394. static void floor0_free_look(vorbis_look_floor *i){
  108395. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108396. if(look){
  108397. if(look->linearmap){
  108398. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  108399. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  108400. _ogg_free(look->linearmap);
  108401. }
  108402. memset(look,0,sizeof(*look));
  108403. _ogg_free(look);
  108404. }
  108405. }
  108406. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108407. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108408. int j;
  108409. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  108410. info->order=oggpack_read(opb,8);
  108411. info->rate=oggpack_read(opb,16);
  108412. info->barkmap=oggpack_read(opb,16);
  108413. info->ampbits=oggpack_read(opb,6);
  108414. info->ampdB=oggpack_read(opb,8);
  108415. info->numbooks=oggpack_read(opb,4)+1;
  108416. if(info->order<1)goto err_out;
  108417. if(info->rate<1)goto err_out;
  108418. if(info->barkmap<1)goto err_out;
  108419. if(info->numbooks<1)goto err_out;
  108420. for(j=0;j<info->numbooks;j++){
  108421. info->books[j]=oggpack_read(opb,8);
  108422. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  108423. }
  108424. return(info);
  108425. err_out:
  108426. floor0_free_info(info);
  108427. return(NULL);
  108428. }
  108429. /* initialize Bark scale and normalization lookups. We could do this
  108430. with static tables, but Vorbis allows a number of possible
  108431. combinations, so it's best to do it computationally.
  108432. The below is authoritative in terms of defining scale mapping.
  108433. Note that the scale depends on the sampling rate as well as the
  108434. linear block and mapping sizes */
  108435. static void floor0_map_lazy_init(vorbis_block *vb,
  108436. vorbis_info_floor *infoX,
  108437. vorbis_look_floor0 *look){
  108438. if(!look->linearmap[vb->W]){
  108439. vorbis_dsp_state *vd=vb->vd;
  108440. vorbis_info *vi=vd->vi;
  108441. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108442. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  108443. int W=vb->W;
  108444. int n=ci->blocksizes[W]/2,j;
  108445. /* we choose a scaling constant so that:
  108446. floor(bark(rate/2-1)*C)=mapped-1
  108447. floor(bark(rate/2)*C)=mapped */
  108448. float scale=look->ln/toBARK(info->rate/2.f);
  108449. /* the mapping from a linear scale to a smaller bark scale is
  108450. straightforward. We do *not* make sure that the linear mapping
  108451. does not skip bark-scale bins; the decoder simply skips them and
  108452. the encoder may do what it wishes in filling them. They're
  108453. necessary in some mapping combinations to keep the scale spacing
  108454. accurate */
  108455. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  108456. for(j=0;j<n;j++){
  108457. int val=floor( toBARK((info->rate/2.f)/n*j)
  108458. *scale); /* bark numbers represent band edges */
  108459. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  108460. look->linearmap[W][j]=val;
  108461. }
  108462. look->linearmap[W][j]=-1;
  108463. look->n[W]=n;
  108464. }
  108465. }
  108466. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  108467. vorbis_info_floor *i){
  108468. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  108469. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  108470. look->m=info->order;
  108471. look->ln=info->barkmap;
  108472. look->vi=info;
  108473. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  108474. return look;
  108475. }
  108476. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  108477. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108478. vorbis_info_floor0 *info=look->vi;
  108479. int j,k;
  108480. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  108481. if(ampraw>0){ /* also handles the -1 out of data case */
  108482. long maxval=(1<<info->ampbits)-1;
  108483. float amp=(float)ampraw/maxval*info->ampdB;
  108484. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  108485. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  108486. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  108487. codebook *b=ci->fullbooks+info->books[booknum];
  108488. float last=0.f;
  108489. /* the additional b->dim is a guard against any possible stack
  108490. smash; b->dim is provably more than we can overflow the
  108491. vector */
  108492. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  108493. for(j=0;j<look->m;j+=b->dim)
  108494. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  108495. for(j=0;j<look->m;){
  108496. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  108497. last=lsp[j-1];
  108498. }
  108499. lsp[look->m]=amp;
  108500. return(lsp);
  108501. }
  108502. }
  108503. eop:
  108504. return(NULL);
  108505. }
  108506. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  108507. void *memo,float *out){
  108508. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108509. vorbis_info_floor0 *info=look->vi;
  108510. floor0_map_lazy_init(vb,info,look);
  108511. if(memo){
  108512. float *lsp=(float *)memo;
  108513. float amp=lsp[look->m];
  108514. /* take the coefficients back to a spectral envelope curve */
  108515. vorbis_lsp_to_curve(out,
  108516. look->linearmap[vb->W],
  108517. look->n[vb->W],
  108518. look->ln,
  108519. lsp,look->m,amp,(float)info->ampdB);
  108520. return(1);
  108521. }
  108522. memset(out,0,sizeof(*out)*look->n[vb->W]);
  108523. return(0);
  108524. }
  108525. /* export hooks */
  108526. vorbis_func_floor floor0_exportbundle={
  108527. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  108528. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  108529. };
  108530. #endif
  108531. /********* End of inlined file: floor0.c *********/
  108532. /********* Start of inlined file: floor1.c *********/
  108533. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108534. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108535. // tasks..
  108536. #if JUCE_MSVC
  108537. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108538. #endif
  108539. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108540. #if JUCE_USE_OGGVORBIS
  108541. #include <stdlib.h>
  108542. #include <string.h>
  108543. #include <math.h>
  108544. #include <stdio.h>
  108545. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  108546. typedef struct {
  108547. int sorted_index[VIF_POSIT+2];
  108548. int forward_index[VIF_POSIT+2];
  108549. int reverse_index[VIF_POSIT+2];
  108550. int hineighbor[VIF_POSIT];
  108551. int loneighbor[VIF_POSIT];
  108552. int posts;
  108553. int n;
  108554. int quant_q;
  108555. vorbis_info_floor1 *vi;
  108556. long phrasebits;
  108557. long postbits;
  108558. long frames;
  108559. } vorbis_look_floor1;
  108560. typedef struct lsfit_acc{
  108561. long x0;
  108562. long x1;
  108563. long xa;
  108564. long ya;
  108565. long x2a;
  108566. long y2a;
  108567. long xya;
  108568. long an;
  108569. } lsfit_acc;
  108570. /***********************************************/
  108571. static void floor1_free_info(vorbis_info_floor *i){
  108572. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108573. if(info){
  108574. memset(info,0,sizeof(*info));
  108575. _ogg_free(info);
  108576. }
  108577. }
  108578. static void floor1_free_look(vorbis_look_floor *i){
  108579. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  108580. if(look){
  108581. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  108582. (float)look->phrasebits/look->frames,
  108583. (float)look->postbits/look->frames,
  108584. (float)(look->postbits+look->phrasebits)/look->frames);*/
  108585. memset(look,0,sizeof(*look));
  108586. _ogg_free(look);
  108587. }
  108588. }
  108589. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  108590. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108591. int j,k;
  108592. int count=0;
  108593. int rangebits;
  108594. int maxposit=info->postlist[1];
  108595. int maxclass=-1;
  108596. /* save out partitions */
  108597. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  108598. for(j=0;j<info->partitions;j++){
  108599. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  108600. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108601. }
  108602. /* save out partition classes */
  108603. for(j=0;j<maxclass+1;j++){
  108604. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  108605. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  108606. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  108607. for(k=0;k<(1<<info->class_subs[j]);k++)
  108608. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  108609. }
  108610. /* save out the post list */
  108611. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  108612. oggpack_write(opb,ilog2(maxposit),4);
  108613. rangebits=ilog2(maxposit);
  108614. for(j=0,k=0;j<info->partitions;j++){
  108615. count+=info->class_dim[info->partitionclass[j]];
  108616. for(;k<count;k++)
  108617. oggpack_write(opb,info->postlist[k+2],rangebits);
  108618. }
  108619. }
  108620. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108621. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108622. int j,k,count=0,maxclass=-1,rangebits;
  108623. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  108624. /* read partitions */
  108625. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  108626. for(j=0;j<info->partitions;j++){
  108627. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  108628. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108629. }
  108630. /* read partition classes */
  108631. for(j=0;j<maxclass+1;j++){
  108632. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  108633. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  108634. if(info->class_subs[j]<0)
  108635. goto err_out;
  108636. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  108637. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  108638. goto err_out;
  108639. for(k=0;k<(1<<info->class_subs[j]);k++){
  108640. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  108641. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  108642. goto err_out;
  108643. }
  108644. }
  108645. /* read the post list */
  108646. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  108647. rangebits=oggpack_read(opb,4);
  108648. for(j=0,k=0;j<info->partitions;j++){
  108649. count+=info->class_dim[info->partitionclass[j]];
  108650. for(;k<count;k++){
  108651. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  108652. if(t<0 || t>=(1<<rangebits))
  108653. goto err_out;
  108654. }
  108655. }
  108656. info->postlist[0]=0;
  108657. info->postlist[1]=1<<rangebits;
  108658. return(info);
  108659. err_out:
  108660. floor1_free_info(info);
  108661. return(NULL);
  108662. }
  108663. static int icomp(const void *a,const void *b){
  108664. return(**(int **)a-**(int **)b);
  108665. }
  108666. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  108667. vorbis_info_floor *in){
  108668. int *sortpointer[VIF_POSIT+2];
  108669. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  108670. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  108671. int i,j,n=0;
  108672. look->vi=info;
  108673. look->n=info->postlist[1];
  108674. /* we drop each position value in-between already decoded values,
  108675. and use linear interpolation to predict each new value past the
  108676. edges. The positions are read in the order of the position
  108677. list... we precompute the bounding positions in the lookup. Of
  108678. course, the neighbors can change (if a position is declined), but
  108679. this is an initial mapping */
  108680. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  108681. n+=2;
  108682. look->posts=n;
  108683. /* also store a sorted position index */
  108684. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  108685. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  108686. /* points from sort order back to range number */
  108687. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  108688. /* points from range order to sorted position */
  108689. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  108690. /* we actually need the post values too */
  108691. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  108692. /* quantize values to multiplier spec */
  108693. switch(info->mult){
  108694. case 1: /* 1024 -> 256 */
  108695. look->quant_q=256;
  108696. break;
  108697. case 2: /* 1024 -> 128 */
  108698. look->quant_q=128;
  108699. break;
  108700. case 3: /* 1024 -> 86 */
  108701. look->quant_q=86;
  108702. break;
  108703. case 4: /* 1024 -> 64 */
  108704. look->quant_q=64;
  108705. break;
  108706. }
  108707. /* discover our neighbors for decode where we don't use fit flags
  108708. (that would push the neighbors outward) */
  108709. for(i=0;i<n-2;i++){
  108710. int lo=0;
  108711. int hi=1;
  108712. int lx=0;
  108713. int hx=look->n;
  108714. int currentx=info->postlist[i+2];
  108715. for(j=0;j<i+2;j++){
  108716. int x=info->postlist[j];
  108717. if(x>lx && x<currentx){
  108718. lo=j;
  108719. lx=x;
  108720. }
  108721. if(x<hx && x>currentx){
  108722. hi=j;
  108723. hx=x;
  108724. }
  108725. }
  108726. look->loneighbor[i]=lo;
  108727. look->hineighbor[i]=hi;
  108728. }
  108729. return(look);
  108730. }
  108731. static int render_point(int x0,int x1,int y0,int y1,int x){
  108732. y0&=0x7fff; /* mask off flag */
  108733. y1&=0x7fff;
  108734. {
  108735. int dy=y1-y0;
  108736. int adx=x1-x0;
  108737. int ady=abs(dy);
  108738. int err=ady*(x-x0);
  108739. int off=err/adx;
  108740. if(dy<0)return(y0-off);
  108741. return(y0+off);
  108742. }
  108743. }
  108744. static int vorbis_dBquant(const float *x){
  108745. int i= *x*7.3142857f+1023.5f;
  108746. if(i>1023)return(1023);
  108747. if(i<0)return(0);
  108748. return i;
  108749. }
  108750. static float FLOOR1_fromdB_LOOKUP[256]={
  108751. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  108752. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  108753. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  108754. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  108755. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  108756. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  108757. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  108758. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  108759. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  108760. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  108761. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  108762. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  108763. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  108764. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  108765. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  108766. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  108767. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  108768. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  108769. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  108770. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  108771. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  108772. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  108773. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  108774. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  108775. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  108776. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  108777. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  108778. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  108779. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  108780. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  108781. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  108782. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  108783. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  108784. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  108785. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  108786. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  108787. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  108788. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  108789. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  108790. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  108791. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  108792. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  108793. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  108794. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  108795. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  108796. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  108797. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  108798. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  108799. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  108800. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  108801. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  108802. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  108803. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  108804. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  108805. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  108806. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  108807. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  108808. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  108809. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  108810. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  108811. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  108812. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  108813. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  108814. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  108815. };
  108816. static void render_line(int x0,int x1,int y0,int y1,float *d){
  108817. int dy=y1-y0;
  108818. int adx=x1-x0;
  108819. int ady=abs(dy);
  108820. int base=dy/adx;
  108821. int sy=(dy<0?base-1:base+1);
  108822. int x=x0;
  108823. int y=y0;
  108824. int err=0;
  108825. ady-=abs(base*adx);
  108826. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108827. while(++x<x1){
  108828. err=err+ady;
  108829. if(err>=adx){
  108830. err-=adx;
  108831. y+=sy;
  108832. }else{
  108833. y+=base;
  108834. }
  108835. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108836. }
  108837. }
  108838. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  108839. int dy=y1-y0;
  108840. int adx=x1-x0;
  108841. int ady=abs(dy);
  108842. int base=dy/adx;
  108843. int sy=(dy<0?base-1:base+1);
  108844. int x=x0;
  108845. int y=y0;
  108846. int err=0;
  108847. ady-=abs(base*adx);
  108848. d[x]=y;
  108849. while(++x<x1){
  108850. err=err+ady;
  108851. if(err>=adx){
  108852. err-=adx;
  108853. y+=sy;
  108854. }else{
  108855. y+=base;
  108856. }
  108857. d[x]=y;
  108858. }
  108859. }
  108860. /* the floor has already been filtered to only include relevant sections */
  108861. static int accumulate_fit(const float *flr,const float *mdct,
  108862. int x0, int x1,lsfit_acc *a,
  108863. int n,vorbis_info_floor1 *info){
  108864. long i;
  108865. 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;
  108866. memset(a,0,sizeof(*a));
  108867. a->x0=x0;
  108868. a->x1=x1;
  108869. if(x1>=n)x1=n-1;
  108870. for(i=x0;i<=x1;i++){
  108871. int quantized=vorbis_dBquant(flr+i);
  108872. if(quantized){
  108873. if(mdct[i]+info->twofitatten>=flr[i]){
  108874. xa += i;
  108875. ya += quantized;
  108876. x2a += i*i;
  108877. y2a += quantized*quantized;
  108878. xya += i*quantized;
  108879. na++;
  108880. }else{
  108881. xb += i;
  108882. yb += quantized;
  108883. x2b += i*i;
  108884. y2b += quantized*quantized;
  108885. xyb += i*quantized;
  108886. nb++;
  108887. }
  108888. }
  108889. }
  108890. xb+=xa;
  108891. yb+=ya;
  108892. x2b+=x2a;
  108893. y2b+=y2a;
  108894. xyb+=xya;
  108895. nb+=na;
  108896. /* weight toward the actually used frequencies if we meet the threshhold */
  108897. {
  108898. int weight=nb*info->twofitweight/(na+1);
  108899. a->xa=xa*weight+xb;
  108900. a->ya=ya*weight+yb;
  108901. a->x2a=x2a*weight+x2b;
  108902. a->y2a=y2a*weight+y2b;
  108903. a->xya=xya*weight+xyb;
  108904. a->an=na*weight+nb;
  108905. }
  108906. return(na);
  108907. }
  108908. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  108909. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  108910. long x0=a[0].x0;
  108911. long x1=a[fits-1].x1;
  108912. for(i=0;i<fits;i++){
  108913. x+=a[i].xa;
  108914. y+=a[i].ya;
  108915. x2+=a[i].x2a;
  108916. y2+=a[i].y2a;
  108917. xy+=a[i].xya;
  108918. an+=a[i].an;
  108919. }
  108920. if(*y0>=0){
  108921. x+= x0;
  108922. y+= *y0;
  108923. x2+= x0 * x0;
  108924. y2+= *y0 * *y0;
  108925. xy+= *y0 * x0;
  108926. an++;
  108927. }
  108928. if(*y1>=0){
  108929. x+= x1;
  108930. y+= *y1;
  108931. x2+= x1 * x1;
  108932. y2+= *y1 * *y1;
  108933. xy+= *y1 * x1;
  108934. an++;
  108935. }
  108936. if(an){
  108937. /* need 64 bit multiplies, which C doesn't give portably as int */
  108938. double fx=x;
  108939. double fy=y;
  108940. double fx2=x2;
  108941. double fxy=xy;
  108942. double denom=1./(an*fx2-fx*fx);
  108943. double a=(fy*fx2-fxy*fx)*denom;
  108944. double b=(an*fxy-fx*fy)*denom;
  108945. *y0=rint(a+b*x0);
  108946. *y1=rint(a+b*x1);
  108947. /* limit to our range! */
  108948. if(*y0>1023)*y0=1023;
  108949. if(*y1>1023)*y1=1023;
  108950. if(*y0<0)*y0=0;
  108951. if(*y1<0)*y1=0;
  108952. }else{
  108953. *y0=0;
  108954. *y1=0;
  108955. }
  108956. }
  108957. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  108958. long y=0;
  108959. int i;
  108960. for(i=0;i<fits && y==0;i++)
  108961. y+=a[i].ya;
  108962. *y0=*y1=y;
  108963. }*/
  108964. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  108965. const float *mdct,
  108966. vorbis_info_floor1 *info){
  108967. int dy=y1-y0;
  108968. int adx=x1-x0;
  108969. int ady=abs(dy);
  108970. int base=dy/adx;
  108971. int sy=(dy<0?base-1:base+1);
  108972. int x=x0;
  108973. int y=y0;
  108974. int err=0;
  108975. int val=vorbis_dBquant(mask+x);
  108976. int mse=0;
  108977. int n=0;
  108978. ady-=abs(base*adx);
  108979. mse=(y-val);
  108980. mse*=mse;
  108981. n++;
  108982. if(mdct[x]+info->twofitatten>=mask[x]){
  108983. if(y+info->maxover<val)return(1);
  108984. if(y-info->maxunder>val)return(1);
  108985. }
  108986. while(++x<x1){
  108987. err=err+ady;
  108988. if(err>=adx){
  108989. err-=adx;
  108990. y+=sy;
  108991. }else{
  108992. y+=base;
  108993. }
  108994. val=vorbis_dBquant(mask+x);
  108995. mse+=((y-val)*(y-val));
  108996. n++;
  108997. if(mdct[x]+info->twofitatten>=mask[x]){
  108998. if(val){
  108999. if(y+info->maxover<val)return(1);
  109000. if(y-info->maxunder>val)return(1);
  109001. }
  109002. }
  109003. }
  109004. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  109005. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  109006. if(mse/n>info->maxerr)return(1);
  109007. return(0);
  109008. }
  109009. static int post_Y(int *A,int *B,int pos){
  109010. if(A[pos]<0)
  109011. return B[pos];
  109012. if(B[pos]<0)
  109013. return A[pos];
  109014. return (A[pos]+B[pos])>>1;
  109015. }
  109016. int *floor1_fit(vorbis_block *vb,void *look_,
  109017. const float *logmdct, /* in */
  109018. const float *logmask){
  109019. long i,j;
  109020. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  109021. vorbis_info_floor1 *info=look->vi;
  109022. long n=look->n;
  109023. long posts=look->posts;
  109024. long nonzero=0;
  109025. lsfit_acc fits[VIF_POSIT+1];
  109026. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  109027. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  109028. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  109029. int hineighbor[VIF_POSIT+2];
  109030. int *output=NULL;
  109031. int memo[VIF_POSIT+2];
  109032. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  109033. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  109034. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  109035. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  109036. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  109037. /* quantize the relevant floor points and collect them into line fit
  109038. structures (one per minimal division) at the same time */
  109039. if(posts==0){
  109040. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  109041. }else{
  109042. for(i=0;i<posts-1;i++)
  109043. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  109044. look->sorted_index[i+1],fits+i,
  109045. n,info);
  109046. }
  109047. if(nonzero){
  109048. /* start by fitting the implicit base case.... */
  109049. int y0=-200;
  109050. int y1=-200;
  109051. fit_line(fits,posts-1,&y0,&y1);
  109052. fit_valueA[0]=y0;
  109053. fit_valueB[0]=y0;
  109054. fit_valueB[1]=y1;
  109055. fit_valueA[1]=y1;
  109056. /* Non degenerate case */
  109057. /* start progressive splitting. This is a greedy, non-optimal
  109058. algorithm, but simple and close enough to the best
  109059. answer. */
  109060. for(i=2;i<posts;i++){
  109061. int sortpos=look->reverse_index[i];
  109062. int ln=loneighbor[sortpos];
  109063. int hn=hineighbor[sortpos];
  109064. /* eliminate repeat searches of a particular range with a memo */
  109065. if(memo[ln]!=hn){
  109066. /* haven't performed this error search yet */
  109067. int lsortpos=look->reverse_index[ln];
  109068. int hsortpos=look->reverse_index[hn];
  109069. memo[ln]=hn;
  109070. {
  109071. /* A note: we want to bound/minimize *local*, not global, error */
  109072. int lx=info->postlist[ln];
  109073. int hx=info->postlist[hn];
  109074. int ly=post_Y(fit_valueA,fit_valueB,ln);
  109075. int hy=post_Y(fit_valueA,fit_valueB,hn);
  109076. if(ly==-1 || hy==-1){
  109077. exit(1);
  109078. }
  109079. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  109080. /* outside error bounds/begin search area. Split it. */
  109081. int ly0=-200;
  109082. int ly1=-200;
  109083. int hy0=-200;
  109084. int hy1=-200;
  109085. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  109086. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  109087. /* store new edge values */
  109088. fit_valueB[ln]=ly0;
  109089. if(ln==0)fit_valueA[ln]=ly0;
  109090. fit_valueA[i]=ly1;
  109091. fit_valueB[i]=hy0;
  109092. fit_valueA[hn]=hy1;
  109093. if(hn==1)fit_valueB[hn]=hy1;
  109094. if(ly1>=0 || hy0>=0){
  109095. /* store new neighbor values */
  109096. for(j=sortpos-1;j>=0;j--)
  109097. if(hineighbor[j]==hn)
  109098. hineighbor[j]=i;
  109099. else
  109100. break;
  109101. for(j=sortpos+1;j<posts;j++)
  109102. if(loneighbor[j]==ln)
  109103. loneighbor[j]=i;
  109104. else
  109105. break;
  109106. }
  109107. }else{
  109108. fit_valueA[i]=-200;
  109109. fit_valueB[i]=-200;
  109110. }
  109111. }
  109112. }
  109113. }
  109114. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109115. output[0]=post_Y(fit_valueA,fit_valueB,0);
  109116. output[1]=post_Y(fit_valueA,fit_valueB,1);
  109117. /* fill in posts marked as not using a fit; we will zero
  109118. back out to 'unused' when encoding them so long as curve
  109119. interpolation doesn't force them into use */
  109120. for(i=2;i<posts;i++){
  109121. int ln=look->loneighbor[i-2];
  109122. int hn=look->hineighbor[i-2];
  109123. int x0=info->postlist[ln];
  109124. int x1=info->postlist[hn];
  109125. int y0=output[ln];
  109126. int y1=output[hn];
  109127. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109128. int vx=post_Y(fit_valueA,fit_valueB,i);
  109129. if(vx>=0 && predicted!=vx){
  109130. output[i]=vx;
  109131. }else{
  109132. output[i]= predicted|0x8000;
  109133. }
  109134. }
  109135. }
  109136. return(output);
  109137. }
  109138. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  109139. int *A,int *B,
  109140. int del){
  109141. long i;
  109142. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  109143. long posts=look->posts;
  109144. int *output=NULL;
  109145. if(A && B){
  109146. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  109147. for(i=0;i<posts;i++){
  109148. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  109149. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  109150. }
  109151. }
  109152. return(output);
  109153. }
  109154. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  109155. void*look_,
  109156. int *post,int *ilogmask){
  109157. long i,j;
  109158. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  109159. vorbis_info_floor1 *info=look->vi;
  109160. long posts=look->posts;
  109161. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109162. int out[VIF_POSIT+2];
  109163. static_codebook **sbooks=ci->book_param;
  109164. codebook *books=ci->fullbooks;
  109165. static long seq=0;
  109166. /* quantize values to multiplier spec */
  109167. if(post){
  109168. for(i=0;i<posts;i++){
  109169. int val=post[i]&0x7fff;
  109170. switch(info->mult){
  109171. case 1: /* 1024 -> 256 */
  109172. val>>=2;
  109173. break;
  109174. case 2: /* 1024 -> 128 */
  109175. val>>=3;
  109176. break;
  109177. case 3: /* 1024 -> 86 */
  109178. val/=12;
  109179. break;
  109180. case 4: /* 1024 -> 64 */
  109181. val>>=4;
  109182. break;
  109183. }
  109184. post[i]=val | (post[i]&0x8000);
  109185. }
  109186. out[0]=post[0];
  109187. out[1]=post[1];
  109188. /* find prediction values for each post and subtract them */
  109189. for(i=2;i<posts;i++){
  109190. int ln=look->loneighbor[i-2];
  109191. int hn=look->hineighbor[i-2];
  109192. int x0=info->postlist[ln];
  109193. int x1=info->postlist[hn];
  109194. int y0=post[ln];
  109195. int y1=post[hn];
  109196. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109197. if((post[i]&0x8000) || (predicted==post[i])){
  109198. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  109199. in interpolation */
  109200. out[i]=0;
  109201. }else{
  109202. int headroom=(look->quant_q-predicted<predicted?
  109203. look->quant_q-predicted:predicted);
  109204. int val=post[i]-predicted;
  109205. /* at this point the 'deviation' value is in the range +/- max
  109206. range, but the real, unique range can always be mapped to
  109207. only [0-maxrange). So we want to wrap the deviation into
  109208. this limited range, but do it in the way that least screws
  109209. an essentially gaussian probability distribution. */
  109210. if(val<0)
  109211. if(val<-headroom)
  109212. val=headroom-val-1;
  109213. else
  109214. val=-1-(val<<1);
  109215. else
  109216. if(val>=headroom)
  109217. val= val+headroom;
  109218. else
  109219. val<<=1;
  109220. out[i]=val;
  109221. post[ln]&=0x7fff;
  109222. post[hn]&=0x7fff;
  109223. }
  109224. }
  109225. /* we have everything we need. pack it out */
  109226. /* mark nontrivial floor */
  109227. oggpack_write(opb,1,1);
  109228. /* beginning/end post */
  109229. look->frames++;
  109230. look->postbits+=ilog(look->quant_q-1)*2;
  109231. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  109232. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  109233. /* partition by partition */
  109234. for(i=0,j=2;i<info->partitions;i++){
  109235. int classx=info->partitionclass[i];
  109236. int cdim=info->class_dim[classx];
  109237. int csubbits=info->class_subs[classx];
  109238. int csub=1<<csubbits;
  109239. int bookas[8]={0,0,0,0,0,0,0,0};
  109240. int cval=0;
  109241. int cshift=0;
  109242. int k,l;
  109243. /* generate the partition's first stage cascade value */
  109244. if(csubbits){
  109245. int maxval[8];
  109246. for(k=0;k<csub;k++){
  109247. int booknum=info->class_subbook[classx][k];
  109248. if(booknum<0){
  109249. maxval[k]=1;
  109250. }else{
  109251. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  109252. }
  109253. }
  109254. for(k=0;k<cdim;k++){
  109255. for(l=0;l<csub;l++){
  109256. int val=out[j+k];
  109257. if(val<maxval[l]){
  109258. bookas[k]=l;
  109259. break;
  109260. }
  109261. }
  109262. cval|= bookas[k]<<cshift;
  109263. cshift+=csubbits;
  109264. }
  109265. /* write it */
  109266. look->phrasebits+=
  109267. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  109268. #ifdef TRAIN_FLOOR1
  109269. {
  109270. FILE *of;
  109271. char buffer[80];
  109272. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  109273. vb->pcmend/2,posts-2,class);
  109274. of=fopen(buffer,"a");
  109275. fprintf(of,"%d\n",cval);
  109276. fclose(of);
  109277. }
  109278. #endif
  109279. }
  109280. /* write post values */
  109281. for(k=0;k<cdim;k++){
  109282. int book=info->class_subbook[classx][bookas[k]];
  109283. if(book>=0){
  109284. /* hack to allow training with 'bad' books */
  109285. if(out[j+k]<(books+book)->entries)
  109286. look->postbits+=vorbis_book_encode(books+book,
  109287. out[j+k],opb);
  109288. /*else
  109289. fprintf(stderr,"+!");*/
  109290. #ifdef TRAIN_FLOOR1
  109291. {
  109292. FILE *of;
  109293. char buffer[80];
  109294. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  109295. vb->pcmend/2,posts-2,class,bookas[k]);
  109296. of=fopen(buffer,"a");
  109297. fprintf(of,"%d\n",out[j+k]);
  109298. fclose(of);
  109299. }
  109300. #endif
  109301. }
  109302. }
  109303. j+=cdim;
  109304. }
  109305. {
  109306. /* generate quantized floor equivalent to what we'd unpack in decode */
  109307. /* render the lines */
  109308. int hx=0;
  109309. int lx=0;
  109310. int ly=post[0]*info->mult;
  109311. for(j=1;j<look->posts;j++){
  109312. int current=look->forward_index[j];
  109313. int hy=post[current]&0x7fff;
  109314. if(hy==post[current]){
  109315. hy*=info->mult;
  109316. hx=info->postlist[current];
  109317. render_line0(lx,hx,ly,hy,ilogmask);
  109318. lx=hx;
  109319. ly=hy;
  109320. }
  109321. }
  109322. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  109323. seq++;
  109324. return(1);
  109325. }
  109326. }else{
  109327. oggpack_write(opb,0,1);
  109328. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  109329. seq++;
  109330. return(0);
  109331. }
  109332. }
  109333. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  109334. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109335. vorbis_info_floor1 *info=look->vi;
  109336. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109337. int i,j,k;
  109338. codebook *books=ci->fullbooks;
  109339. /* unpack wrapped/predicted values from stream */
  109340. if(oggpack_read(&vb->opb,1)==1){
  109341. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  109342. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109343. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109344. /* partition by partition */
  109345. for(i=0,j=2;i<info->partitions;i++){
  109346. int classx=info->partitionclass[i];
  109347. int cdim=info->class_dim[classx];
  109348. int csubbits=info->class_subs[classx];
  109349. int csub=1<<csubbits;
  109350. int cval=0;
  109351. /* decode the partition's first stage cascade value */
  109352. if(csubbits){
  109353. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  109354. if(cval==-1)goto eop;
  109355. }
  109356. for(k=0;k<cdim;k++){
  109357. int book=info->class_subbook[classx][cval&(csub-1)];
  109358. cval>>=csubbits;
  109359. if(book>=0){
  109360. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  109361. goto eop;
  109362. }else{
  109363. fit_value[j+k]=0;
  109364. }
  109365. }
  109366. j+=cdim;
  109367. }
  109368. /* unwrap positive values and reconsitute via linear interpolation */
  109369. for(i=2;i<look->posts;i++){
  109370. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  109371. info->postlist[look->hineighbor[i-2]],
  109372. fit_value[look->loneighbor[i-2]],
  109373. fit_value[look->hineighbor[i-2]],
  109374. info->postlist[i]);
  109375. int hiroom=look->quant_q-predicted;
  109376. int loroom=predicted;
  109377. int room=(hiroom<loroom?hiroom:loroom)<<1;
  109378. int val=fit_value[i];
  109379. if(val){
  109380. if(val>=room){
  109381. if(hiroom>loroom){
  109382. val = val-loroom;
  109383. }else{
  109384. val = -1-(val-hiroom);
  109385. }
  109386. }else{
  109387. if(val&1){
  109388. val= -((val+1)>>1);
  109389. }else{
  109390. val>>=1;
  109391. }
  109392. }
  109393. fit_value[i]=val+predicted;
  109394. fit_value[look->loneighbor[i-2]]&=0x7fff;
  109395. fit_value[look->hineighbor[i-2]]&=0x7fff;
  109396. }else{
  109397. fit_value[i]=predicted|0x8000;
  109398. }
  109399. }
  109400. return(fit_value);
  109401. }
  109402. eop:
  109403. return(NULL);
  109404. }
  109405. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  109406. float *out){
  109407. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109408. vorbis_info_floor1 *info=look->vi;
  109409. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109410. int n=ci->blocksizes[vb->W]/2;
  109411. int j;
  109412. if(memo){
  109413. /* render the lines */
  109414. int *fit_value=(int *)memo;
  109415. int hx=0;
  109416. int lx=0;
  109417. int ly=fit_value[0]*info->mult;
  109418. for(j=1;j<look->posts;j++){
  109419. int current=look->forward_index[j];
  109420. int hy=fit_value[current]&0x7fff;
  109421. if(hy==fit_value[current]){
  109422. hy*=info->mult;
  109423. hx=info->postlist[current];
  109424. render_line(lx,hx,ly,hy,out);
  109425. lx=hx;
  109426. ly=hy;
  109427. }
  109428. }
  109429. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  109430. return(1);
  109431. }
  109432. memset(out,0,sizeof(*out)*n);
  109433. return(0);
  109434. }
  109435. /* export hooks */
  109436. vorbis_func_floor floor1_exportbundle={
  109437. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  109438. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  109439. };
  109440. #endif
  109441. /********* End of inlined file: floor1.c *********/
  109442. /********* Start of inlined file: info.c *********/
  109443. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109444. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109445. // tasks..
  109446. #if JUCE_MSVC
  109447. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109448. #endif
  109449. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109450. #if JUCE_USE_OGGVORBIS
  109451. /* general handling of the header and the vorbis_info structure (and
  109452. substructures) */
  109453. #include <stdlib.h>
  109454. #include <string.h>
  109455. #include <ctype.h>
  109456. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  109457. while(bytes--){
  109458. oggpack_write(o,*s++,8);
  109459. }
  109460. }
  109461. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  109462. while(bytes--){
  109463. *buf++=oggpack_read(o,8);
  109464. }
  109465. }
  109466. void vorbis_comment_init(vorbis_comment *vc){
  109467. memset(vc,0,sizeof(*vc));
  109468. }
  109469. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  109470. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  109471. (vc->comments+2)*sizeof(*vc->user_comments));
  109472. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  109473. (vc->comments+2)*sizeof(*vc->comment_lengths));
  109474. vc->comment_lengths[vc->comments]=strlen(comment);
  109475. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  109476. strcpy(vc->user_comments[vc->comments], comment);
  109477. vc->comments++;
  109478. vc->user_comments[vc->comments]=NULL;
  109479. }
  109480. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  109481. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  109482. strcpy(comment, tag);
  109483. strcat(comment, "=");
  109484. strcat(comment, contents);
  109485. vorbis_comment_add(vc, comment);
  109486. }
  109487. /* This is more or less the same as strncasecmp - but that doesn't exist
  109488. * everywhere, and this is a fairly trivial function, so we include it */
  109489. static int tagcompare(const char *s1, const char *s2, int n){
  109490. int c=0;
  109491. while(c < n){
  109492. if(toupper(s1[c]) != toupper(s2[c]))
  109493. return !0;
  109494. c++;
  109495. }
  109496. return 0;
  109497. }
  109498. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  109499. long i;
  109500. int found = 0;
  109501. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109502. char *fulltag = (char*)alloca(taglen+ 1);
  109503. strcpy(fulltag, tag);
  109504. strcat(fulltag, "=");
  109505. for(i=0;i<vc->comments;i++){
  109506. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  109507. if(count == found)
  109508. /* We return a pointer to the data, not a copy */
  109509. return vc->user_comments[i] + taglen;
  109510. else
  109511. found++;
  109512. }
  109513. }
  109514. return NULL; /* didn't find anything */
  109515. }
  109516. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  109517. int i,count=0;
  109518. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109519. char *fulltag = (char*)alloca(taglen+1);
  109520. strcpy(fulltag,tag);
  109521. strcat(fulltag, "=");
  109522. for(i=0;i<vc->comments;i++){
  109523. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  109524. count++;
  109525. }
  109526. return count;
  109527. }
  109528. void vorbis_comment_clear(vorbis_comment *vc){
  109529. if(vc){
  109530. long i;
  109531. for(i=0;i<vc->comments;i++)
  109532. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  109533. if(vc->user_comments)_ogg_free(vc->user_comments);
  109534. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  109535. if(vc->vendor)_ogg_free(vc->vendor);
  109536. }
  109537. memset(vc,0,sizeof(*vc));
  109538. }
  109539. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  109540. They may be equal, but short will never ge greater than long */
  109541. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  109542. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  109543. return ci ? ci->blocksizes[zo] : -1;
  109544. }
  109545. /* used by synthesis, which has a full, alloced vi */
  109546. void vorbis_info_init(vorbis_info *vi){
  109547. memset(vi,0,sizeof(*vi));
  109548. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  109549. }
  109550. void vorbis_info_clear(vorbis_info *vi){
  109551. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109552. int i;
  109553. if(ci){
  109554. for(i=0;i<ci->modes;i++)
  109555. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  109556. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  109557. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  109558. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  109559. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  109560. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  109561. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  109562. for(i=0;i<ci->books;i++){
  109563. if(ci->book_param[i]){
  109564. /* knows if the book was not alloced */
  109565. vorbis_staticbook_destroy(ci->book_param[i]);
  109566. }
  109567. if(ci->fullbooks)
  109568. vorbis_book_clear(ci->fullbooks+i);
  109569. }
  109570. if(ci->fullbooks)
  109571. _ogg_free(ci->fullbooks);
  109572. for(i=0;i<ci->psys;i++)
  109573. _vi_psy_free(ci->psy_param[i]);
  109574. _ogg_free(ci);
  109575. }
  109576. memset(vi,0,sizeof(*vi));
  109577. }
  109578. /* Header packing/unpacking ********************************************/
  109579. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  109580. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109581. if(!ci)return(OV_EFAULT);
  109582. vi->version=oggpack_read(opb,32);
  109583. if(vi->version!=0)return(OV_EVERSION);
  109584. vi->channels=oggpack_read(opb,8);
  109585. vi->rate=oggpack_read(opb,32);
  109586. vi->bitrate_upper=oggpack_read(opb,32);
  109587. vi->bitrate_nominal=oggpack_read(opb,32);
  109588. vi->bitrate_lower=oggpack_read(opb,32);
  109589. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  109590. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  109591. if(vi->rate<1)goto err_out;
  109592. if(vi->channels<1)goto err_out;
  109593. if(ci->blocksizes[0]<8)goto err_out;
  109594. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  109595. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109596. return(0);
  109597. err_out:
  109598. vorbis_info_clear(vi);
  109599. return(OV_EBADHEADER);
  109600. }
  109601. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  109602. int i;
  109603. int vendorlen=oggpack_read(opb,32);
  109604. if(vendorlen<0)goto err_out;
  109605. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  109606. _v_readstring(opb,vc->vendor,vendorlen);
  109607. vc->comments=oggpack_read(opb,32);
  109608. if(vc->comments<0)goto err_out;
  109609. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  109610. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  109611. for(i=0;i<vc->comments;i++){
  109612. int len=oggpack_read(opb,32);
  109613. if(len<0)goto err_out;
  109614. vc->comment_lengths[i]=len;
  109615. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  109616. _v_readstring(opb,vc->user_comments[i],len);
  109617. }
  109618. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109619. return(0);
  109620. err_out:
  109621. vorbis_comment_clear(vc);
  109622. return(OV_EBADHEADER);
  109623. }
  109624. /* all of the real encoding details are here. The modes, books,
  109625. everything */
  109626. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  109627. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109628. int i;
  109629. if(!ci)return(OV_EFAULT);
  109630. /* codebooks */
  109631. ci->books=oggpack_read(opb,8)+1;
  109632. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  109633. for(i=0;i<ci->books;i++){
  109634. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  109635. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  109636. }
  109637. /* time backend settings; hooks are unused */
  109638. {
  109639. int times=oggpack_read(opb,6)+1;
  109640. for(i=0;i<times;i++){
  109641. int test=oggpack_read(opb,16);
  109642. if(test<0 || test>=VI_TIMEB)goto err_out;
  109643. }
  109644. }
  109645. /* floor backend settings */
  109646. ci->floors=oggpack_read(opb,6)+1;
  109647. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  109648. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  109649. for(i=0;i<ci->floors;i++){
  109650. ci->floor_type[i]=oggpack_read(opb,16);
  109651. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  109652. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  109653. if(!ci->floor_param[i])goto err_out;
  109654. }
  109655. /* residue backend settings */
  109656. ci->residues=oggpack_read(opb,6)+1;
  109657. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  109658. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  109659. for(i=0;i<ci->residues;i++){
  109660. ci->residue_type[i]=oggpack_read(opb,16);
  109661. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  109662. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  109663. if(!ci->residue_param[i])goto err_out;
  109664. }
  109665. /* map backend settings */
  109666. ci->maps=oggpack_read(opb,6)+1;
  109667. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  109668. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  109669. for(i=0;i<ci->maps;i++){
  109670. ci->map_type[i]=oggpack_read(opb,16);
  109671. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  109672. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  109673. if(!ci->map_param[i])goto err_out;
  109674. }
  109675. /* mode settings */
  109676. ci->modes=oggpack_read(opb,6)+1;
  109677. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  109678. for(i=0;i<ci->modes;i++){
  109679. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  109680. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  109681. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  109682. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  109683. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  109684. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  109685. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  109686. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  109687. }
  109688. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  109689. return(0);
  109690. err_out:
  109691. vorbis_info_clear(vi);
  109692. return(OV_EBADHEADER);
  109693. }
  109694. /* The Vorbis header is in three packets; the initial small packet in
  109695. the first page that identifies basic parameters, a second packet
  109696. with bitstream comments and a third packet that holds the
  109697. codebook. */
  109698. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  109699. oggpack_buffer opb;
  109700. if(op){
  109701. oggpack_readinit(&opb,op->packet,op->bytes);
  109702. /* Which of the three types of header is this? */
  109703. /* Also verify header-ness, vorbis */
  109704. {
  109705. char buffer[6];
  109706. int packtype=oggpack_read(&opb,8);
  109707. memset(buffer,0,6);
  109708. _v_readstring(&opb,buffer,6);
  109709. if(memcmp(buffer,"vorbis",6)){
  109710. /* not a vorbis header */
  109711. return(OV_ENOTVORBIS);
  109712. }
  109713. switch(packtype){
  109714. case 0x01: /* least significant *bit* is read first */
  109715. if(!op->b_o_s){
  109716. /* Not the initial packet */
  109717. return(OV_EBADHEADER);
  109718. }
  109719. if(vi->rate!=0){
  109720. /* previously initialized info header */
  109721. return(OV_EBADHEADER);
  109722. }
  109723. return(_vorbis_unpack_info(vi,&opb));
  109724. case 0x03: /* least significant *bit* is read first */
  109725. if(vi->rate==0){
  109726. /* um... we didn't get the initial header */
  109727. return(OV_EBADHEADER);
  109728. }
  109729. return(_vorbis_unpack_comment(vc,&opb));
  109730. case 0x05: /* least significant *bit* is read first */
  109731. if(vi->rate==0 || vc->vendor==NULL){
  109732. /* um... we didn;t get the initial header or comments yet */
  109733. return(OV_EBADHEADER);
  109734. }
  109735. return(_vorbis_unpack_books(vi,&opb));
  109736. default:
  109737. /* Not a valid vorbis header type */
  109738. return(OV_EBADHEADER);
  109739. break;
  109740. }
  109741. }
  109742. }
  109743. return(OV_EBADHEADER);
  109744. }
  109745. /* pack side **********************************************************/
  109746. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  109747. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109748. if(!ci)return(OV_EFAULT);
  109749. /* preamble */
  109750. oggpack_write(opb,0x01,8);
  109751. _v_writestring(opb,"vorbis", 6);
  109752. /* basic information about the stream */
  109753. oggpack_write(opb,0x00,32);
  109754. oggpack_write(opb,vi->channels,8);
  109755. oggpack_write(opb,vi->rate,32);
  109756. oggpack_write(opb,vi->bitrate_upper,32);
  109757. oggpack_write(opb,vi->bitrate_nominal,32);
  109758. oggpack_write(opb,vi->bitrate_lower,32);
  109759. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  109760. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  109761. oggpack_write(opb,1,1);
  109762. return(0);
  109763. }
  109764. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  109765. char temp[]="Xiph.Org libVorbis I 20050304";
  109766. int bytes = strlen(temp);
  109767. /* preamble */
  109768. oggpack_write(opb,0x03,8);
  109769. _v_writestring(opb,"vorbis", 6);
  109770. /* vendor */
  109771. oggpack_write(opb,bytes,32);
  109772. _v_writestring(opb,temp, bytes);
  109773. /* comments */
  109774. oggpack_write(opb,vc->comments,32);
  109775. if(vc->comments){
  109776. int i;
  109777. for(i=0;i<vc->comments;i++){
  109778. if(vc->user_comments[i]){
  109779. oggpack_write(opb,vc->comment_lengths[i],32);
  109780. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  109781. }else{
  109782. oggpack_write(opb,0,32);
  109783. }
  109784. }
  109785. }
  109786. oggpack_write(opb,1,1);
  109787. return(0);
  109788. }
  109789. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  109790. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109791. int i;
  109792. if(!ci)return(OV_EFAULT);
  109793. oggpack_write(opb,0x05,8);
  109794. _v_writestring(opb,"vorbis", 6);
  109795. /* books */
  109796. oggpack_write(opb,ci->books-1,8);
  109797. for(i=0;i<ci->books;i++)
  109798. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  109799. /* times; hook placeholders */
  109800. oggpack_write(opb,0,6);
  109801. oggpack_write(opb,0,16);
  109802. /* floors */
  109803. oggpack_write(opb,ci->floors-1,6);
  109804. for(i=0;i<ci->floors;i++){
  109805. oggpack_write(opb,ci->floor_type[i],16);
  109806. if(_floor_P[ci->floor_type[i]]->pack)
  109807. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  109808. else
  109809. goto err_out;
  109810. }
  109811. /* residues */
  109812. oggpack_write(opb,ci->residues-1,6);
  109813. for(i=0;i<ci->residues;i++){
  109814. oggpack_write(opb,ci->residue_type[i],16);
  109815. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  109816. }
  109817. /* maps */
  109818. oggpack_write(opb,ci->maps-1,6);
  109819. for(i=0;i<ci->maps;i++){
  109820. oggpack_write(opb,ci->map_type[i],16);
  109821. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  109822. }
  109823. /* modes */
  109824. oggpack_write(opb,ci->modes-1,6);
  109825. for(i=0;i<ci->modes;i++){
  109826. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  109827. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  109828. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  109829. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  109830. }
  109831. oggpack_write(opb,1,1);
  109832. return(0);
  109833. err_out:
  109834. return(-1);
  109835. }
  109836. int vorbis_commentheader_out(vorbis_comment *vc,
  109837. ogg_packet *op){
  109838. oggpack_buffer opb;
  109839. oggpack_writeinit(&opb);
  109840. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  109841. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109842. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  109843. op->bytes=oggpack_bytes(&opb);
  109844. op->b_o_s=0;
  109845. op->e_o_s=0;
  109846. op->granulepos=0;
  109847. op->packetno=1;
  109848. return 0;
  109849. }
  109850. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  109851. vorbis_comment *vc,
  109852. ogg_packet *op,
  109853. ogg_packet *op_comm,
  109854. ogg_packet *op_code){
  109855. int ret=OV_EIMPL;
  109856. vorbis_info *vi=v->vi;
  109857. oggpack_buffer opb;
  109858. private_state *b=(private_state*)v->backend_state;
  109859. if(!b){
  109860. ret=OV_EFAULT;
  109861. goto err_out;
  109862. }
  109863. /* first header packet **********************************************/
  109864. oggpack_writeinit(&opb);
  109865. if(_vorbis_pack_info(&opb,vi))goto err_out;
  109866. /* build the packet */
  109867. if(b->header)_ogg_free(b->header);
  109868. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109869. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  109870. op->packet=b->header;
  109871. op->bytes=oggpack_bytes(&opb);
  109872. op->b_o_s=1;
  109873. op->e_o_s=0;
  109874. op->granulepos=0;
  109875. op->packetno=0;
  109876. /* second header packet (comments) **********************************/
  109877. oggpack_reset(&opb);
  109878. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  109879. if(b->header1)_ogg_free(b->header1);
  109880. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109881. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  109882. op_comm->packet=b->header1;
  109883. op_comm->bytes=oggpack_bytes(&opb);
  109884. op_comm->b_o_s=0;
  109885. op_comm->e_o_s=0;
  109886. op_comm->granulepos=0;
  109887. op_comm->packetno=1;
  109888. /* third header packet (modes/codebooks) ****************************/
  109889. oggpack_reset(&opb);
  109890. if(_vorbis_pack_books(&opb,vi))goto err_out;
  109891. if(b->header2)_ogg_free(b->header2);
  109892. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109893. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  109894. op_code->packet=b->header2;
  109895. op_code->bytes=oggpack_bytes(&opb);
  109896. op_code->b_o_s=0;
  109897. op_code->e_o_s=0;
  109898. op_code->granulepos=0;
  109899. op_code->packetno=2;
  109900. oggpack_writeclear(&opb);
  109901. return(0);
  109902. err_out:
  109903. oggpack_writeclear(&opb);
  109904. memset(op,0,sizeof(*op));
  109905. memset(op_comm,0,sizeof(*op_comm));
  109906. memset(op_code,0,sizeof(*op_code));
  109907. if(b->header)_ogg_free(b->header);
  109908. if(b->header1)_ogg_free(b->header1);
  109909. if(b->header2)_ogg_free(b->header2);
  109910. b->header=NULL;
  109911. b->header1=NULL;
  109912. b->header2=NULL;
  109913. return(ret);
  109914. }
  109915. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  109916. if(granulepos>=0)
  109917. return((double)granulepos/v->vi->rate);
  109918. return(-1);
  109919. }
  109920. #endif
  109921. /********* End of inlined file: info.c *********/
  109922. /********* Start of inlined file: lpc.c *********/
  109923. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  109924. are derived from code written by Jutta Degener and Carsten Bormann;
  109925. thus we include their copyright below. The entirety of this file
  109926. is freely redistributable on the condition that both of these
  109927. copyright notices are preserved without modification. */
  109928. /* Preserved Copyright: *********************************************/
  109929. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  109930. Technische Universita"t Berlin
  109931. Any use of this software is permitted provided that this notice is not
  109932. removed and that neither the authors nor the Technische Universita"t
  109933. Berlin are deemed to have made any representations as to the
  109934. suitability of this software for any purpose nor are held responsible
  109935. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  109936. THIS SOFTWARE.
  109937. As a matter of courtesy, the authors request to be informed about uses
  109938. this software has found, about bugs in this software, and about any
  109939. improvements that may be of general interest.
  109940. Berlin, 28.11.1994
  109941. Jutta Degener
  109942. Carsten Bormann
  109943. *********************************************************************/
  109944. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109945. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109946. // tasks..
  109947. #if JUCE_MSVC
  109948. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109949. #endif
  109950. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109951. #if JUCE_USE_OGGVORBIS
  109952. #include <stdlib.h>
  109953. #include <string.h>
  109954. #include <math.h>
  109955. /* Autocorrelation LPC coeff generation algorithm invented by
  109956. N. Levinson in 1947, modified by J. Durbin in 1959. */
  109957. /* Input : n elements of time doamin data
  109958. Output: m lpc coefficients, excitation energy */
  109959. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  109960. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  109961. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  109962. double error;
  109963. int i,j;
  109964. /* autocorrelation, p+1 lag coefficients */
  109965. j=m+1;
  109966. while(j--){
  109967. double d=0; /* double needed for accumulator depth */
  109968. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  109969. aut[j]=d;
  109970. }
  109971. /* Generate lpc coefficients from autocorr values */
  109972. error=aut[0];
  109973. for(i=0;i<m;i++){
  109974. double r= -aut[i+1];
  109975. if(error==0){
  109976. memset(lpci,0,m*sizeof(*lpci));
  109977. return 0;
  109978. }
  109979. /* Sum up this iteration's reflection coefficient; note that in
  109980. Vorbis we don't save it. If anyone wants to recycle this code
  109981. and needs reflection coefficients, save the results of 'r' from
  109982. each iteration. */
  109983. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  109984. r/=error;
  109985. /* Update LPC coefficients and total error */
  109986. lpc[i]=r;
  109987. for(j=0;j<i/2;j++){
  109988. double tmp=lpc[j];
  109989. lpc[j]+=r*lpc[i-1-j];
  109990. lpc[i-1-j]+=r*tmp;
  109991. }
  109992. if(i%2)lpc[j]+=lpc[j]*r;
  109993. error*=1.f-r*r;
  109994. }
  109995. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  109996. /* we need the error value to know how big an impulse to hit the
  109997. filter with later */
  109998. return error;
  109999. }
  110000. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110001. float *data,long n){
  110002. /* in: coeff[0...m-1] LPC coefficients
  110003. prime[0...m-1] initial values (allocated size of n+m-1)
  110004. out: data[0...n-1] data samples */
  110005. long i,j,o,p;
  110006. float y;
  110007. float *work=(float*)alloca(sizeof(*work)*(m+n));
  110008. if(!prime)
  110009. for(i=0;i<m;i++)
  110010. work[i]=0.f;
  110011. else
  110012. for(i=0;i<m;i++)
  110013. work[i]=prime[i];
  110014. for(i=0;i<n;i++){
  110015. y=0;
  110016. o=i;
  110017. p=m;
  110018. for(j=0;j<m;j++)
  110019. y-=work[o++]*coeff[--p];
  110020. data[i]=work[o]=y;
  110021. }
  110022. }
  110023. #endif
  110024. /********* End of inlined file: lpc.c *********/
  110025. /********* Start of inlined file: lsp.c *********/
  110026. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  110027. an iterative root polisher (CACM algorithm 283). It *is* possible
  110028. to confuse this algorithm into not converging; that should only
  110029. happen with absurdly closely spaced roots (very sharp peaks in the
  110030. LPC f response) which in turn should be impossible in our use of
  110031. the code. If this *does* happen anyway, it's a bug in the floor
  110032. finder; find the cause of the confusion (probably a single bin
  110033. spike or accidental near-float-limit resolution problems) and
  110034. correct it. */
  110035. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110036. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110037. // tasks..
  110038. #if JUCE_MSVC
  110039. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110040. #endif
  110041. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110042. #if JUCE_USE_OGGVORBIS
  110043. #include <math.h>
  110044. #include <string.h>
  110045. #include <stdlib.h>
  110046. /********* Start of inlined file: lookup.h *********/
  110047. #ifndef _V_LOOKUP_H_
  110048. #ifdef FLOAT_LOOKUP
  110049. extern float vorbis_coslook(float a);
  110050. extern float vorbis_invsqlook(float a);
  110051. extern float vorbis_invsq2explook(int a);
  110052. extern float vorbis_fromdBlook(float a);
  110053. #endif
  110054. #ifdef INT_LOOKUP
  110055. extern long vorbis_invsqlook_i(long a,long e);
  110056. extern long vorbis_coslook_i(long a);
  110057. extern float vorbis_fromdBlook_i(long a);
  110058. #endif
  110059. #endif
  110060. /********* End of inlined file: lookup.h *********/
  110061. /* three possible LSP to f curve functions; the exact computation
  110062. (float), a lookup based float implementation, and an integer
  110063. implementation. The float lookup is likely the optimal choice on
  110064. any machine with an FPU. The integer implementation is *not* fixed
  110065. point (due to the need for a large dynamic range and thus a
  110066. seperately tracked exponent) and thus much more complex than the
  110067. relatively simple float implementations. It's mostly for future
  110068. work on a fully fixed point implementation for processors like the
  110069. ARM family. */
  110070. /* undefine both for the 'old' but more precise implementation */
  110071. #define FLOAT_LOOKUP
  110072. #undef INT_LOOKUP
  110073. #ifdef FLOAT_LOOKUP
  110074. /********* Start of inlined file: lookup.c *********/
  110075. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110076. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110077. // tasks..
  110078. #if JUCE_MSVC
  110079. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110080. #endif
  110081. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110082. #if JUCE_USE_OGGVORBIS
  110083. #include <math.h>
  110084. /********* Start of inlined file: lookup.h *********/
  110085. #ifndef _V_LOOKUP_H_
  110086. #ifdef FLOAT_LOOKUP
  110087. extern float vorbis_coslook(float a);
  110088. extern float vorbis_invsqlook(float a);
  110089. extern float vorbis_invsq2explook(int a);
  110090. extern float vorbis_fromdBlook(float a);
  110091. #endif
  110092. #ifdef INT_LOOKUP
  110093. extern long vorbis_invsqlook_i(long a,long e);
  110094. extern long vorbis_coslook_i(long a);
  110095. extern float vorbis_fromdBlook_i(long a);
  110096. #endif
  110097. #endif
  110098. /********* End of inlined file: lookup.h *********/
  110099. /********* Start of inlined file: lookup_data.h *********/
  110100. #ifndef _V_LOOKUP_DATA_H_
  110101. #ifdef FLOAT_LOOKUP
  110102. #define COS_LOOKUP_SZ 128
  110103. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110104. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110105. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110106. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110107. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110108. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110109. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110110. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110111. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110112. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110113. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110114. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110115. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110116. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110117. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110118. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110119. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110120. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110121. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110122. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110123. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110124. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110125. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110126. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110127. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110128. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110129. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110130. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110131. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110132. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110133. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110134. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110135. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110136. -1.0000000000000f,
  110137. };
  110138. #define INVSQ_LOOKUP_SZ 32
  110139. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110140. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110141. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110142. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110143. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110144. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110145. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110146. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110147. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110148. 1.000000000000f,
  110149. };
  110150. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110151. #define INVSQ2EXP_LOOKUP_MAX 32
  110152. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110153. INVSQ2EXP_LOOKUP_MIN+1]={
  110154. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110155. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110156. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110157. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110158. 256.f, 181.019336f, 128.f, 90.50966799f,
  110159. 64.f, 45.254834f, 32.f, 22.627417f,
  110160. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110161. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110162. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110163. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110164. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110165. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110166. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110167. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110168. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110169. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110170. 1.525878906e-05f,
  110171. };
  110172. #endif
  110173. #define FROMdB_LOOKUP_SZ 35
  110174. #define FROMdB2_LOOKUP_SZ 32
  110175. #define FROMdB_SHIFT 5
  110176. #define FROMdB2_SHIFT 3
  110177. #define FROMdB2_MASK 31
  110178. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110179. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110180. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110181. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110182. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110183. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110184. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110185. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110186. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110187. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110188. };
  110189. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110190. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110191. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110192. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110193. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110194. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110195. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110196. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110197. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110198. };
  110199. #ifdef INT_LOOKUP
  110200. #define INVSQ_LOOKUP_I_SHIFT 10
  110201. #define INVSQ_LOOKUP_I_MASK 1023
  110202. static long INVSQ_LOOKUP_I[64+1]={
  110203. 92682l, 91966l, 91267l, 90583l,
  110204. 89915l, 89261l, 88621l, 87995l,
  110205. 87381l, 86781l, 86192l, 85616l,
  110206. 85051l, 84497l, 83953l, 83420l,
  110207. 82897l, 82384l, 81880l, 81385l,
  110208. 80899l, 80422l, 79953l, 79492l,
  110209. 79039l, 78594l, 78156l, 77726l,
  110210. 77302l, 76885l, 76475l, 76072l,
  110211. 75674l, 75283l, 74898l, 74519l,
  110212. 74146l, 73778l, 73415l, 73058l,
  110213. 72706l, 72359l, 72016l, 71679l,
  110214. 71347l, 71019l, 70695l, 70376l,
  110215. 70061l, 69750l, 69444l, 69141l,
  110216. 68842l, 68548l, 68256l, 67969l,
  110217. 67685l, 67405l, 67128l, 66855l,
  110218. 66585l, 66318l, 66054l, 65794l,
  110219. 65536l,
  110220. };
  110221. #define COS_LOOKUP_I_SHIFT 9
  110222. #define COS_LOOKUP_I_MASK 511
  110223. #define COS_LOOKUP_I_SZ 128
  110224. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110225. 16384l, 16379l, 16364l, 16340l,
  110226. 16305l, 16261l, 16207l, 16143l,
  110227. 16069l, 15986l, 15893l, 15791l,
  110228. 15679l, 15557l, 15426l, 15286l,
  110229. 15137l, 14978l, 14811l, 14635l,
  110230. 14449l, 14256l, 14053l, 13842l,
  110231. 13623l, 13395l, 13160l, 12916l,
  110232. 12665l, 12406l, 12140l, 11866l,
  110233. 11585l, 11297l, 11003l, 10702l,
  110234. 10394l, 10080l, 9760l, 9434l,
  110235. 9102l, 8765l, 8423l, 8076l,
  110236. 7723l, 7366l, 7005l, 6639l,
  110237. 6270l, 5897l, 5520l, 5139l,
  110238. 4756l, 4370l, 3981l, 3590l,
  110239. 3196l, 2801l, 2404l, 2006l,
  110240. 1606l, 1205l, 804l, 402l,
  110241. 0l, -401l, -803l, -1204l,
  110242. -1605l, -2005l, -2403l, -2800l,
  110243. -3195l, -3589l, -3980l, -4369l,
  110244. -4755l, -5138l, -5519l, -5896l,
  110245. -6269l, -6638l, -7004l, -7365l,
  110246. -7722l, -8075l, -8422l, -8764l,
  110247. -9101l, -9433l, -9759l, -10079l,
  110248. -10393l, -10701l, -11002l, -11296l,
  110249. -11584l, -11865l, -12139l, -12405l,
  110250. -12664l, -12915l, -13159l, -13394l,
  110251. -13622l, -13841l, -14052l, -14255l,
  110252. -14448l, -14634l, -14810l, -14977l,
  110253. -15136l, -15285l, -15425l, -15556l,
  110254. -15678l, -15790l, -15892l, -15985l,
  110255. -16068l, -16142l, -16206l, -16260l,
  110256. -16304l, -16339l, -16363l, -16378l,
  110257. -16383l,
  110258. };
  110259. #endif
  110260. #endif
  110261. /********* End of inlined file: lookup_data.h *********/
  110262. #ifdef FLOAT_LOOKUP
  110263. /* interpolated lookup based cos function, domain 0 to PI only */
  110264. float vorbis_coslook(float a){
  110265. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110266. int i=vorbis_ftoi(d-.5);
  110267. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110268. }
  110269. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110270. float vorbis_invsqlook(float a){
  110271. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110272. int i=vorbis_ftoi(d-.5f);
  110273. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110274. }
  110275. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110276. float vorbis_invsq2explook(int a){
  110277. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110278. }
  110279. #include <stdio.h>
  110280. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110281. float vorbis_fromdBlook(float a){
  110282. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110283. return (i<0)?1.f:
  110284. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110285. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110286. }
  110287. #endif
  110288. #ifdef INT_LOOKUP
  110289. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110290. 16.16 format
  110291. returns in m.8 format */
  110292. long vorbis_invsqlook_i(long a,long e){
  110293. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110294. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110295. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110296. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110297. d)>>16); /* result 1.16 */
  110298. e+=32;
  110299. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110300. e=(e>>1)-8;
  110301. return(val>>e);
  110302. }
  110303. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110304. /* a is in n.12 format */
  110305. float vorbis_fromdBlook_i(long a){
  110306. int i=(-a)>>(12-FROMdB2_SHIFT);
  110307. return (i<0)?1.f:
  110308. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110309. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110310. }
  110311. /* interpolated lookup based cos function, domain 0 to PI only */
  110312. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110313. long vorbis_coslook_i(long a){
  110314. int i=a>>COS_LOOKUP_I_SHIFT;
  110315. int d=a&COS_LOOKUP_I_MASK;
  110316. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110317. COS_LOOKUP_I_SHIFT);
  110318. }
  110319. #endif
  110320. #endif
  110321. /********* End of inlined file: lookup.c *********/
  110322. /* catch this in the build system; we #include for
  110323. compilers (like gcc) that can't inline across
  110324. modules */
  110325. /* side effect: changes *lsp to cosines of lsp */
  110326. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110327. float amp,float ampoffset){
  110328. int i;
  110329. float wdel=M_PI/ln;
  110330. vorbis_fpu_control fpu;
  110331. (void) fpu; // to avoid an unused variable warning
  110332. vorbis_fpu_setround(&fpu);
  110333. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  110334. i=0;
  110335. while(i<n){
  110336. int k=map[i];
  110337. int qexp;
  110338. float p=.7071067812f;
  110339. float q=.7071067812f;
  110340. float w=vorbis_coslook(wdel*k);
  110341. float *ftmp=lsp;
  110342. int c=m>>1;
  110343. do{
  110344. q*=ftmp[0]-w;
  110345. p*=ftmp[1]-w;
  110346. ftmp+=2;
  110347. }while(--c);
  110348. if(m&1){
  110349. /* odd order filter; slightly assymetric */
  110350. /* the last coefficient */
  110351. q*=ftmp[0]-w;
  110352. q*=q;
  110353. p*=p*(1.f-w*w);
  110354. }else{
  110355. /* even order filter; still symmetric */
  110356. q*=q*(1.f+w);
  110357. p*=p*(1.f-w);
  110358. }
  110359. q=frexp(p+q,&qexp);
  110360. q=vorbis_fromdBlook(amp*
  110361. vorbis_invsqlook(q)*
  110362. vorbis_invsq2explook(qexp+m)-
  110363. ampoffset);
  110364. do{
  110365. curve[i++]*=q;
  110366. }while(map[i]==k);
  110367. }
  110368. vorbis_fpu_restore(fpu);
  110369. }
  110370. #else
  110371. #ifdef INT_LOOKUP
  110372. /********* Start of inlined file: lookup.c *********/
  110373. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110374. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110375. // tasks..
  110376. #if JUCE_MSVC
  110377. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110378. #endif
  110379. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110380. #if JUCE_USE_OGGVORBIS
  110381. #include <math.h>
  110382. /********* Start of inlined file: lookup.h *********/
  110383. #ifndef _V_LOOKUP_H_
  110384. #ifdef FLOAT_LOOKUP
  110385. extern float vorbis_coslook(float a);
  110386. extern float vorbis_invsqlook(float a);
  110387. extern float vorbis_invsq2explook(int a);
  110388. extern float vorbis_fromdBlook(float a);
  110389. #endif
  110390. #ifdef INT_LOOKUP
  110391. extern long vorbis_invsqlook_i(long a,long e);
  110392. extern long vorbis_coslook_i(long a);
  110393. extern float vorbis_fromdBlook_i(long a);
  110394. #endif
  110395. #endif
  110396. /********* End of inlined file: lookup.h *********/
  110397. /********* Start of inlined file: lookup_data.h *********/
  110398. #ifndef _V_LOOKUP_DATA_H_
  110399. #ifdef FLOAT_LOOKUP
  110400. #define COS_LOOKUP_SZ 128
  110401. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110402. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110403. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110404. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110405. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110406. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110407. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110408. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110409. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110410. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110411. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110412. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110413. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110414. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110415. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110416. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110417. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110418. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110419. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110420. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110421. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110422. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110423. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110424. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110425. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110426. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110427. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110428. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110429. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110430. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110431. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110432. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110433. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110434. -1.0000000000000f,
  110435. };
  110436. #define INVSQ_LOOKUP_SZ 32
  110437. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110438. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110439. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110440. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110441. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110442. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110443. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110444. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110445. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110446. 1.000000000000f,
  110447. };
  110448. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110449. #define INVSQ2EXP_LOOKUP_MAX 32
  110450. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110451. INVSQ2EXP_LOOKUP_MIN+1]={
  110452. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110453. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110454. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110455. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110456. 256.f, 181.019336f, 128.f, 90.50966799f,
  110457. 64.f, 45.254834f, 32.f, 22.627417f,
  110458. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110459. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110460. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110461. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110462. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110463. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110464. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110465. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110466. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110467. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110468. 1.525878906e-05f,
  110469. };
  110470. #endif
  110471. #define FROMdB_LOOKUP_SZ 35
  110472. #define FROMdB2_LOOKUP_SZ 32
  110473. #define FROMdB_SHIFT 5
  110474. #define FROMdB2_SHIFT 3
  110475. #define FROMdB2_MASK 31
  110476. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110477. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110478. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110479. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110480. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110481. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110482. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110483. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110484. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110485. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110486. };
  110487. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110488. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110489. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110490. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110491. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110492. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110493. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110494. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110495. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110496. };
  110497. #ifdef INT_LOOKUP
  110498. #define INVSQ_LOOKUP_I_SHIFT 10
  110499. #define INVSQ_LOOKUP_I_MASK 1023
  110500. static long INVSQ_LOOKUP_I[64+1]={
  110501. 92682l, 91966l, 91267l, 90583l,
  110502. 89915l, 89261l, 88621l, 87995l,
  110503. 87381l, 86781l, 86192l, 85616l,
  110504. 85051l, 84497l, 83953l, 83420l,
  110505. 82897l, 82384l, 81880l, 81385l,
  110506. 80899l, 80422l, 79953l, 79492l,
  110507. 79039l, 78594l, 78156l, 77726l,
  110508. 77302l, 76885l, 76475l, 76072l,
  110509. 75674l, 75283l, 74898l, 74519l,
  110510. 74146l, 73778l, 73415l, 73058l,
  110511. 72706l, 72359l, 72016l, 71679l,
  110512. 71347l, 71019l, 70695l, 70376l,
  110513. 70061l, 69750l, 69444l, 69141l,
  110514. 68842l, 68548l, 68256l, 67969l,
  110515. 67685l, 67405l, 67128l, 66855l,
  110516. 66585l, 66318l, 66054l, 65794l,
  110517. 65536l,
  110518. };
  110519. #define COS_LOOKUP_I_SHIFT 9
  110520. #define COS_LOOKUP_I_MASK 511
  110521. #define COS_LOOKUP_I_SZ 128
  110522. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110523. 16384l, 16379l, 16364l, 16340l,
  110524. 16305l, 16261l, 16207l, 16143l,
  110525. 16069l, 15986l, 15893l, 15791l,
  110526. 15679l, 15557l, 15426l, 15286l,
  110527. 15137l, 14978l, 14811l, 14635l,
  110528. 14449l, 14256l, 14053l, 13842l,
  110529. 13623l, 13395l, 13160l, 12916l,
  110530. 12665l, 12406l, 12140l, 11866l,
  110531. 11585l, 11297l, 11003l, 10702l,
  110532. 10394l, 10080l, 9760l, 9434l,
  110533. 9102l, 8765l, 8423l, 8076l,
  110534. 7723l, 7366l, 7005l, 6639l,
  110535. 6270l, 5897l, 5520l, 5139l,
  110536. 4756l, 4370l, 3981l, 3590l,
  110537. 3196l, 2801l, 2404l, 2006l,
  110538. 1606l, 1205l, 804l, 402l,
  110539. 0l, -401l, -803l, -1204l,
  110540. -1605l, -2005l, -2403l, -2800l,
  110541. -3195l, -3589l, -3980l, -4369l,
  110542. -4755l, -5138l, -5519l, -5896l,
  110543. -6269l, -6638l, -7004l, -7365l,
  110544. -7722l, -8075l, -8422l, -8764l,
  110545. -9101l, -9433l, -9759l, -10079l,
  110546. -10393l, -10701l, -11002l, -11296l,
  110547. -11584l, -11865l, -12139l, -12405l,
  110548. -12664l, -12915l, -13159l, -13394l,
  110549. -13622l, -13841l, -14052l, -14255l,
  110550. -14448l, -14634l, -14810l, -14977l,
  110551. -15136l, -15285l, -15425l, -15556l,
  110552. -15678l, -15790l, -15892l, -15985l,
  110553. -16068l, -16142l, -16206l, -16260l,
  110554. -16304l, -16339l, -16363l, -16378l,
  110555. -16383l,
  110556. };
  110557. #endif
  110558. #endif
  110559. /********* End of inlined file: lookup_data.h *********/
  110560. #ifdef FLOAT_LOOKUP
  110561. /* interpolated lookup based cos function, domain 0 to PI only */
  110562. float vorbis_coslook(float a){
  110563. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110564. int i=vorbis_ftoi(d-.5);
  110565. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110566. }
  110567. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110568. float vorbis_invsqlook(float a){
  110569. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110570. int i=vorbis_ftoi(d-.5f);
  110571. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110572. }
  110573. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110574. float vorbis_invsq2explook(int a){
  110575. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110576. }
  110577. #include <stdio.h>
  110578. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110579. float vorbis_fromdBlook(float a){
  110580. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110581. return (i<0)?1.f:
  110582. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110583. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110584. }
  110585. #endif
  110586. #ifdef INT_LOOKUP
  110587. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110588. 16.16 format
  110589. returns in m.8 format */
  110590. long vorbis_invsqlook_i(long a,long e){
  110591. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110592. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110593. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110594. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110595. d)>>16); /* result 1.16 */
  110596. e+=32;
  110597. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110598. e=(e>>1)-8;
  110599. return(val>>e);
  110600. }
  110601. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110602. /* a is in n.12 format */
  110603. float vorbis_fromdBlook_i(long a){
  110604. int i=(-a)>>(12-FROMdB2_SHIFT);
  110605. return (i<0)?1.f:
  110606. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110607. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110608. }
  110609. /* interpolated lookup based cos function, domain 0 to PI only */
  110610. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110611. long vorbis_coslook_i(long a){
  110612. int i=a>>COS_LOOKUP_I_SHIFT;
  110613. int d=a&COS_LOOKUP_I_MASK;
  110614. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110615. COS_LOOKUP_I_SHIFT);
  110616. }
  110617. #endif
  110618. #endif
  110619. /********* End of inlined file: lookup.c *********/
  110620. /* catch this in the build system; we #include for
  110621. compilers (like gcc) that can't inline across
  110622. modules */
  110623. static int MLOOP_1[64]={
  110624. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  110625. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  110626. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110627. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110628. };
  110629. static int MLOOP_2[64]={
  110630. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  110631. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  110632. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110633. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110634. };
  110635. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  110636. /* side effect: changes *lsp to cosines of lsp */
  110637. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110638. float amp,float ampoffset){
  110639. /* 0 <= m < 256 */
  110640. /* set up for using all int later */
  110641. int i;
  110642. int ampoffseti=rint(ampoffset*4096.f);
  110643. int ampi=rint(amp*16.f);
  110644. long *ilsp=alloca(m*sizeof(*ilsp));
  110645. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  110646. i=0;
  110647. while(i<n){
  110648. int j,k=map[i];
  110649. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  110650. unsigned long qi=46341;
  110651. int qexp=0,shift;
  110652. long wi=vorbis_coslook_i(k*65536/ln);
  110653. qi*=labs(ilsp[0]-wi);
  110654. pi*=labs(ilsp[1]-wi);
  110655. for(j=3;j<m;j+=2){
  110656. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110657. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110658. shift=MLOOP_3[(pi|qi)>>16];
  110659. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110660. pi=(pi>>shift)*labs(ilsp[j]-wi);
  110661. qexp+=shift;
  110662. }
  110663. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110664. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110665. shift=MLOOP_3[(pi|qi)>>16];
  110666. /* pi,qi normalized collectively, both tracked using qexp */
  110667. if(m&1){
  110668. /* odd order filter; slightly assymetric */
  110669. /* the last coefficient */
  110670. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110671. pi=(pi>>shift)<<14;
  110672. qexp+=shift;
  110673. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110674. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110675. shift=MLOOP_3[(pi|qi)>>16];
  110676. pi>>=shift;
  110677. qi>>=shift;
  110678. qexp+=shift-14*((m+1)>>1);
  110679. pi=((pi*pi)>>16);
  110680. qi=((qi*qi)>>16);
  110681. qexp=qexp*2+m;
  110682. pi*=(1<<14)-((wi*wi)>>14);
  110683. qi+=pi>>14;
  110684. }else{
  110685. /* even order filter; still symmetric */
  110686. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  110687. worth tracking step by step */
  110688. pi>>=shift;
  110689. qi>>=shift;
  110690. qexp+=shift-7*m;
  110691. pi=((pi*pi)>>16);
  110692. qi=((qi*qi)>>16);
  110693. qexp=qexp*2+m;
  110694. pi*=(1<<14)-wi;
  110695. qi*=(1<<14)+wi;
  110696. qi=(qi+pi)>>14;
  110697. }
  110698. /* we've let the normalization drift because it wasn't important;
  110699. however, for the lookup, things must be normalized again. We
  110700. need at most one right shift or a number of left shifts */
  110701. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  110702. qi>>=1; qexp++;
  110703. }else
  110704. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  110705. qi<<=1; qexp--;
  110706. }
  110707. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  110708. vorbis_invsqlook_i(qi,qexp)-
  110709. /* m.8, m+n<=8 */
  110710. ampoffseti); /* 8.12[0] */
  110711. curve[i]*=amp;
  110712. while(map[++i]==k)curve[i]*=amp;
  110713. }
  110714. }
  110715. #else
  110716. /* old, nonoptimized but simple version for any poor sap who needs to
  110717. figure out what the hell this code does, or wants the other
  110718. fraction of a dB precision */
  110719. /* side effect: changes *lsp to cosines of lsp */
  110720. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110721. float amp,float ampoffset){
  110722. int i;
  110723. float wdel=M_PI/ln;
  110724. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  110725. i=0;
  110726. while(i<n){
  110727. int j,k=map[i];
  110728. float p=.5f;
  110729. float q=.5f;
  110730. float w=2.f*cos(wdel*k);
  110731. for(j=1;j<m;j+=2){
  110732. q *= w-lsp[j-1];
  110733. p *= w-lsp[j];
  110734. }
  110735. if(j==m){
  110736. /* odd order filter; slightly assymetric */
  110737. /* the last coefficient */
  110738. q*=w-lsp[j-1];
  110739. p*=p*(4.f-w*w);
  110740. q*=q;
  110741. }else{
  110742. /* even order filter; still symmetric */
  110743. p*=p*(2.f-w);
  110744. q*=q*(2.f+w);
  110745. }
  110746. q=fromdB(amp/sqrt(p+q)-ampoffset);
  110747. curve[i]*=q;
  110748. while(map[++i]==k)curve[i]*=q;
  110749. }
  110750. }
  110751. #endif
  110752. #endif
  110753. static void cheby(float *g, int ord) {
  110754. int i, j;
  110755. g[0] *= .5f;
  110756. for(i=2; i<= ord; i++) {
  110757. for(j=ord; j >= i; j--) {
  110758. g[j-2] -= g[j];
  110759. g[j] += g[j];
  110760. }
  110761. }
  110762. }
  110763. static int comp(const void *a,const void *b){
  110764. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  110765. }
  110766. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  110767. but there are root sets for which it gets into limit cycles
  110768. (exacerbated by zero suppression) and fails. We can't afford to
  110769. fail, even if the failure is 1 in 100,000,000, so we now use
  110770. Laguerre and later polish with Newton-Raphson (which can then
  110771. afford to fail) */
  110772. #define EPSILON 10e-7
  110773. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  110774. int i,m;
  110775. double lastdelta=0.f;
  110776. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  110777. for(i=0;i<=ord;i++)defl[i]=a[i];
  110778. for(m=ord;m>0;m--){
  110779. double newx=0.f,delta;
  110780. /* iterate a root */
  110781. while(1){
  110782. double p=defl[m],pp=0.f,ppp=0.f,denom;
  110783. /* eval the polynomial and its first two derivatives */
  110784. for(i=m;i>0;i--){
  110785. ppp = newx*ppp + pp;
  110786. pp = newx*pp + p;
  110787. p = newx*p + defl[i-1];
  110788. }
  110789. /* Laguerre's method */
  110790. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  110791. if(denom<0)
  110792. return(-1); /* complex root! The LPC generator handed us a bad filter */
  110793. if(pp>0){
  110794. denom = pp + sqrt(denom);
  110795. if(denom<EPSILON)denom=EPSILON;
  110796. }else{
  110797. denom = pp - sqrt(denom);
  110798. if(denom>-(EPSILON))denom=-(EPSILON);
  110799. }
  110800. delta = m*p/denom;
  110801. newx -= delta;
  110802. if(delta<0.f)delta*=-1;
  110803. if(fabs(delta/newx)<10e-12)break;
  110804. lastdelta=delta;
  110805. }
  110806. r[m-1]=newx;
  110807. /* forward deflation */
  110808. for(i=m;i>0;i--)
  110809. defl[i-1]+=newx*defl[i];
  110810. defl++;
  110811. }
  110812. return(0);
  110813. }
  110814. /* for spit-and-polish only */
  110815. static int Newton_Raphson(float *a,int ord,float *r){
  110816. int i, k, count=0;
  110817. double error=1.f;
  110818. double *root=(double*)alloca(ord*sizeof(*root));
  110819. for(i=0; i<ord;i++) root[i] = r[i];
  110820. while(error>1e-20){
  110821. error=0;
  110822. for(i=0; i<ord; i++) { /* Update each point. */
  110823. double pp=0.,delta;
  110824. double rooti=root[i];
  110825. double p=a[ord];
  110826. for(k=ord-1; k>= 0; k--) {
  110827. pp= pp* rooti + p;
  110828. p = p * rooti + a[k];
  110829. }
  110830. delta = p/pp;
  110831. root[i] -= delta;
  110832. error+= delta*delta;
  110833. }
  110834. if(count>40)return(-1);
  110835. count++;
  110836. }
  110837. /* Replaced the original bubble sort with a real sort. With your
  110838. help, we can eliminate the bubble sort in our lifetime. --Monty */
  110839. for(i=0; i<ord;i++) r[i] = root[i];
  110840. return(0);
  110841. }
  110842. /* Convert lpc coefficients to lsp coefficients */
  110843. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  110844. int order2=(m+1)>>1;
  110845. int g1_order,g2_order;
  110846. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  110847. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  110848. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  110849. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  110850. int i;
  110851. /* even and odd are slightly different base cases */
  110852. g1_order=(m+1)>>1;
  110853. g2_order=(m) >>1;
  110854. /* Compute the lengths of the x polynomials. */
  110855. /* Compute the first half of K & R F1 & F2 polynomials. */
  110856. /* Compute half of the symmetric and antisymmetric polynomials. */
  110857. /* Remove the roots at +1 and -1. */
  110858. g1[g1_order] = 1.f;
  110859. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  110860. g2[g2_order] = 1.f;
  110861. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  110862. if(g1_order>g2_order){
  110863. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  110864. }else{
  110865. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  110866. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  110867. }
  110868. /* Convert into polynomials in cos(alpha) */
  110869. cheby(g1,g1_order);
  110870. cheby(g2,g2_order);
  110871. /* Find the roots of the 2 even polynomials.*/
  110872. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  110873. Laguerre_With_Deflation(g2,g2_order,g2r))
  110874. return(-1);
  110875. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  110876. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  110877. qsort(g1r,g1_order,sizeof(*g1r),comp);
  110878. qsort(g2r,g2_order,sizeof(*g2r),comp);
  110879. for(i=0;i<g1_order;i++)
  110880. lsp[i*2] = acos(g1r[i]);
  110881. for(i=0;i<g2_order;i++)
  110882. lsp[i*2+1] = acos(g2r[i]);
  110883. return(0);
  110884. }
  110885. #endif
  110886. /********* End of inlined file: lsp.c *********/
  110887. /********* Start of inlined file: mapping0.c *********/
  110888. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110889. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110890. // tasks..
  110891. #if JUCE_MSVC
  110892. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110893. #endif
  110894. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110895. #if JUCE_USE_OGGVORBIS
  110896. #include <stdlib.h>
  110897. #include <stdio.h>
  110898. #include <string.h>
  110899. #include <math.h>
  110900. /* simplistic, wasteful way of doing this (unique lookup for each
  110901. mode/submapping); there should be a central repository for
  110902. identical lookups. That will require minor work, so I'm putting it
  110903. off as low priority.
  110904. Why a lookup for each backend in a given mode? Because the
  110905. blocksize is set by the mode, and low backend lookups may require
  110906. parameters from other areas of the mode/mapping */
  110907. static void mapping0_free_info(vorbis_info_mapping *i){
  110908. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  110909. if(info){
  110910. memset(info,0,sizeof(*info));
  110911. _ogg_free(info);
  110912. }
  110913. }
  110914. static int ilog3(unsigned int v){
  110915. int ret=0;
  110916. if(v)--v;
  110917. while(v){
  110918. ret++;
  110919. v>>=1;
  110920. }
  110921. return(ret);
  110922. }
  110923. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  110924. oggpack_buffer *opb){
  110925. int i;
  110926. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  110927. /* another 'we meant to do it this way' hack... up to beta 4, we
  110928. packed 4 binary zeros here to signify one submapping in use. We
  110929. now redefine that to mean four bitflags that indicate use of
  110930. deeper features; bit0:submappings, bit1:coupling,
  110931. bit2,3:reserved. This is backward compatable with all actual uses
  110932. of the beta code. */
  110933. if(info->submaps>1){
  110934. oggpack_write(opb,1,1);
  110935. oggpack_write(opb,info->submaps-1,4);
  110936. }else
  110937. oggpack_write(opb,0,1);
  110938. if(info->coupling_steps>0){
  110939. oggpack_write(opb,1,1);
  110940. oggpack_write(opb,info->coupling_steps-1,8);
  110941. for(i=0;i<info->coupling_steps;i++){
  110942. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  110943. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  110944. }
  110945. }else
  110946. oggpack_write(opb,0,1);
  110947. oggpack_write(opb,0,2); /* 2,3:reserved */
  110948. /* we don't write the channel submappings if we only have one... */
  110949. if(info->submaps>1){
  110950. for(i=0;i<vi->channels;i++)
  110951. oggpack_write(opb,info->chmuxlist[i],4);
  110952. }
  110953. for(i=0;i<info->submaps;i++){
  110954. oggpack_write(opb,0,8); /* time submap unused */
  110955. oggpack_write(opb,info->floorsubmap[i],8);
  110956. oggpack_write(opb,info->residuesubmap[i],8);
  110957. }
  110958. }
  110959. /* also responsible for range checking */
  110960. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  110961. int i;
  110962. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  110963. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110964. memset(info,0,sizeof(*info));
  110965. if(oggpack_read(opb,1))
  110966. info->submaps=oggpack_read(opb,4)+1;
  110967. else
  110968. info->submaps=1;
  110969. if(oggpack_read(opb,1)){
  110970. info->coupling_steps=oggpack_read(opb,8)+1;
  110971. for(i=0;i<info->coupling_steps;i++){
  110972. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  110973. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  110974. if(testM<0 ||
  110975. testA<0 ||
  110976. testM==testA ||
  110977. testM>=vi->channels ||
  110978. testA>=vi->channels) goto err_out;
  110979. }
  110980. }
  110981. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  110982. if(info->submaps>1){
  110983. for(i=0;i<vi->channels;i++){
  110984. info->chmuxlist[i]=oggpack_read(opb,4);
  110985. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  110986. }
  110987. }
  110988. for(i=0;i<info->submaps;i++){
  110989. oggpack_read(opb,8); /* time submap unused */
  110990. info->floorsubmap[i]=oggpack_read(opb,8);
  110991. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  110992. info->residuesubmap[i]=oggpack_read(opb,8);
  110993. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  110994. }
  110995. return info;
  110996. err_out:
  110997. mapping0_free_info(info);
  110998. return(NULL);
  110999. }
  111000. #if 0
  111001. static long seq=0;
  111002. static ogg_int64_t total=0;
  111003. static float FLOOR1_fromdB_LOOKUP[256]={
  111004. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  111005. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  111006. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  111007. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  111008. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  111009. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  111010. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  111011. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  111012. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  111013. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  111014. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  111015. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  111016. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  111017. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  111018. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  111019. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  111020. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  111021. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  111022. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  111023. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  111024. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  111025. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  111026. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  111027. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  111028. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  111029. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  111030. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  111031. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  111032. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  111033. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  111034. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  111035. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  111036. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  111037. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  111038. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  111039. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  111040. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  111041. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  111042. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  111043. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  111044. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  111045. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  111046. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  111047. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  111048. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  111049. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  111050. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  111051. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  111052. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  111053. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  111054. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  111055. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  111056. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  111057. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  111058. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  111059. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  111060. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  111061. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  111062. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  111063. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  111064. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  111065. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  111066. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  111067. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  111068. };
  111069. #endif
  111070. extern int *floor1_fit(vorbis_block *vb,void *look,
  111071. const float *logmdct, /* in */
  111072. const float *logmask);
  111073. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  111074. int *A,int *B,
  111075. int del);
  111076. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  111077. void*look,
  111078. int *post,int *ilogmask);
  111079. static int mapping0_forward(vorbis_block *vb){
  111080. vorbis_dsp_state *vd=vb->vd;
  111081. vorbis_info *vi=vd->vi;
  111082. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111083. private_state *b=(private_state*)vb->vd->backend_state;
  111084. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111085. int n=vb->pcmend;
  111086. int i,j,k;
  111087. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  111088. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  111089. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  111090. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  111091. float global_ampmax=vbi->ampmax;
  111092. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  111093. int blocktype=vbi->blocktype;
  111094. int modenumber=vb->W;
  111095. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  111096. vorbis_look_psy *psy_look=
  111097. b->psy+blocktype+(vb->W?2:0);
  111098. vb->mode=modenumber;
  111099. for(i=0;i<vi->channels;i++){
  111100. float scale=4.f/n;
  111101. float scale_dB;
  111102. float *pcm =vb->pcm[i];
  111103. float *logfft =pcm;
  111104. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111105. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  111106. todB estimation used on IEEE 754
  111107. compliant machines had a bug that
  111108. returned dB values about a third
  111109. of a decibel too high. The bug
  111110. was harmless because tunings
  111111. implicitly took that into
  111112. account. However, fixing the bug
  111113. in the estimator requires
  111114. changing all the tunings as well.
  111115. For now, it's easier to sync
  111116. things back up here, and
  111117. recalibrate the tunings in the
  111118. next major model upgrade. */
  111119. #if 0
  111120. if(vi->channels==2)
  111121. if(i==0)
  111122. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  111123. else
  111124. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  111125. #endif
  111126. /* window the PCM data */
  111127. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  111128. #if 0
  111129. if(vi->channels==2)
  111130. if(i==0)
  111131. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  111132. else
  111133. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  111134. #endif
  111135. /* transform the PCM data */
  111136. /* only MDCT right now.... */
  111137. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  111138. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  111139. drft_forward(&b->fft_look[vb->W],pcm);
  111140. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  111141. original todB estimation used on
  111142. IEEE 754 compliant machines had a
  111143. bug that returned dB values about
  111144. a third of a decibel too high.
  111145. The bug was harmless because
  111146. tunings implicitly took that into
  111147. account. However, fixing the bug
  111148. in the estimator requires
  111149. changing all the tunings as well.
  111150. For now, it's easier to sync
  111151. things back up here, and
  111152. recalibrate the tunings in the
  111153. next major model upgrade. */
  111154. local_ampmax[i]=logfft[0];
  111155. for(j=1;j<n-1;j+=2){
  111156. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  111157. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  111158. .345 is a hack; the original todB
  111159. estimation used on IEEE 754
  111160. compliant machines had a bug that
  111161. returned dB values about a third
  111162. of a decibel too high. The bug
  111163. was harmless because tunings
  111164. implicitly took that into
  111165. account. However, fixing the bug
  111166. in the estimator requires
  111167. changing all the tunings as well.
  111168. For now, it's easier to sync
  111169. things back up here, and
  111170. recalibrate the tunings in the
  111171. next major model upgrade. */
  111172. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  111173. }
  111174. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  111175. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  111176. #if 0
  111177. if(vi->channels==2){
  111178. if(i==0){
  111179. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  111180. }else{
  111181. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  111182. }
  111183. }
  111184. #endif
  111185. }
  111186. {
  111187. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  111188. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  111189. for(i=0;i<vi->channels;i++){
  111190. /* the encoder setup assumes that all the modes used by any
  111191. specific bitrate tweaking use the same floor */
  111192. int submap=info->chmuxlist[i];
  111193. /* the following makes things clearer to *me* anyway */
  111194. float *mdct =gmdct[i];
  111195. float *logfft =vb->pcm[i];
  111196. float *logmdct =logfft+n/2;
  111197. float *logmask =logfft;
  111198. vb->mode=modenumber;
  111199. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  111200. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  111201. for(j=0;j<n/2;j++)
  111202. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  111203. todB estimation used on IEEE 754
  111204. compliant machines had a bug that
  111205. returned dB values about a third
  111206. of a decibel too high. The bug
  111207. was harmless because tunings
  111208. implicitly took that into
  111209. account. However, fixing the bug
  111210. in the estimator requires
  111211. changing all the tunings as well.
  111212. For now, it's easier to sync
  111213. things back up here, and
  111214. recalibrate the tunings in the
  111215. next major model upgrade. */
  111216. #if 0
  111217. if(vi->channels==2){
  111218. if(i==0)
  111219. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  111220. else
  111221. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  111222. }else{
  111223. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  111224. }
  111225. #endif
  111226. /* first step; noise masking. Not only does 'noise masking'
  111227. give us curves from which we can decide how much resolution
  111228. to give noise parts of the spectrum, it also implicitly hands
  111229. us a tonality estimate (the larger the value in the
  111230. 'noise_depth' vector, the more tonal that area is) */
  111231. _vp_noisemask(psy_look,
  111232. logmdct,
  111233. noise); /* noise does not have by-frequency offset
  111234. bias applied yet */
  111235. #if 0
  111236. if(vi->channels==2){
  111237. if(i==0)
  111238. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  111239. else
  111240. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  111241. }
  111242. #endif
  111243. /* second step: 'all the other crap'; all the stuff that isn't
  111244. computed/fit for bitrate management goes in the second psy
  111245. vector. This includes tone masking, peak limiting and ATH */
  111246. _vp_tonemask(psy_look,
  111247. logfft,
  111248. tone,
  111249. global_ampmax,
  111250. local_ampmax[i]);
  111251. #if 0
  111252. if(vi->channels==2){
  111253. if(i==0)
  111254. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  111255. else
  111256. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  111257. }
  111258. #endif
  111259. /* third step; we offset the noise vectors, overlay tone
  111260. masking. We then do a floor1-specific line fit. If we're
  111261. performing bitrate management, the line fit is performed
  111262. multiple times for up/down tweakage on demand. */
  111263. #if 0
  111264. {
  111265. float aotuv[psy_look->n];
  111266. #endif
  111267. _vp_offset_and_mix(psy_look,
  111268. noise,
  111269. tone,
  111270. 1,
  111271. logmask,
  111272. mdct,
  111273. logmdct);
  111274. #if 0
  111275. if(vi->channels==2){
  111276. if(i==0)
  111277. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  111278. else
  111279. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  111280. }
  111281. }
  111282. #endif
  111283. #if 0
  111284. if(vi->channels==2){
  111285. if(i==0)
  111286. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  111287. else
  111288. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  111289. }
  111290. #endif
  111291. /* this algorithm is hardwired to floor 1 for now; abort out if
  111292. we're *not* floor1. This won't happen unless someone has
  111293. broken the encode setup lib. Guard it anyway. */
  111294. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  111295. floor_posts[i][PACKETBLOBS/2]=
  111296. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111297. logmdct,
  111298. logmask);
  111299. /* are we managing bitrate? If so, perform two more fits for
  111300. later rate tweaking (fits represent hi/lo) */
  111301. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  111302. /* higher rate by way of lower noise curve */
  111303. _vp_offset_and_mix(psy_look,
  111304. noise,
  111305. tone,
  111306. 2,
  111307. logmask,
  111308. mdct,
  111309. logmdct);
  111310. #if 0
  111311. if(vi->channels==2){
  111312. if(i==0)
  111313. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  111314. else
  111315. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  111316. }
  111317. #endif
  111318. floor_posts[i][PACKETBLOBS-1]=
  111319. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111320. logmdct,
  111321. logmask);
  111322. /* lower rate by way of higher noise curve */
  111323. _vp_offset_and_mix(psy_look,
  111324. noise,
  111325. tone,
  111326. 0,
  111327. logmask,
  111328. mdct,
  111329. logmdct);
  111330. #if 0
  111331. if(vi->channels==2)
  111332. if(i==0)
  111333. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  111334. else
  111335. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  111336. #endif
  111337. floor_posts[i][0]=
  111338. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111339. logmdct,
  111340. logmask);
  111341. /* we also interpolate a range of intermediate curves for
  111342. intermediate rates */
  111343. for(k=1;k<PACKETBLOBS/2;k++)
  111344. floor_posts[i][k]=
  111345. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111346. floor_posts[i][0],
  111347. floor_posts[i][PACKETBLOBS/2],
  111348. k*65536/(PACKETBLOBS/2));
  111349. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  111350. floor_posts[i][k]=
  111351. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111352. floor_posts[i][PACKETBLOBS/2],
  111353. floor_posts[i][PACKETBLOBS-1],
  111354. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  111355. }
  111356. }
  111357. }
  111358. vbi->ampmax=global_ampmax;
  111359. /*
  111360. the next phases are performed once for vbr-only and PACKETBLOB
  111361. times for bitrate managed modes.
  111362. 1) encode actual mode being used
  111363. 2) encode the floor for each channel, compute coded mask curve/res
  111364. 3) normalize and couple.
  111365. 4) encode residue
  111366. 5) save packet bytes to the packetblob vector
  111367. */
  111368. /* iterate over the many masking curve fits we've created */
  111369. {
  111370. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  111371. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  111372. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111373. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  111374. float **mag_memo;
  111375. int **mag_sort;
  111376. if(info->coupling_steps){
  111377. mag_memo=_vp_quantize_couple_memo(vb,
  111378. &ci->psy_g_param,
  111379. psy_look,
  111380. info,
  111381. gmdct);
  111382. mag_sort=_vp_quantize_couple_sort(vb,
  111383. psy_look,
  111384. info,
  111385. mag_memo);
  111386. hf_reduction(&ci->psy_g_param,
  111387. psy_look,
  111388. info,
  111389. mag_memo);
  111390. }
  111391. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  111392. if(psy_look->vi->normal_channel_p){
  111393. for(i=0;i<vi->channels;i++){
  111394. float *mdct =gmdct[i];
  111395. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  111396. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  111397. }
  111398. }
  111399. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  111400. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  111401. k++){
  111402. oggpack_buffer *opb=vbi->packetblob[k];
  111403. /* start out our new packet blob with packet type and mode */
  111404. /* Encode the packet type */
  111405. oggpack_write(opb,0,1);
  111406. /* Encode the modenumber */
  111407. /* Encode frame mode, pre,post windowsize, then dispatch */
  111408. oggpack_write(opb,modenumber,b->modebits);
  111409. if(vb->W){
  111410. oggpack_write(opb,vb->lW,1);
  111411. oggpack_write(opb,vb->nW,1);
  111412. }
  111413. /* encode floor, compute masking curve, sep out residue */
  111414. for(i=0;i<vi->channels;i++){
  111415. int submap=info->chmuxlist[i];
  111416. float *mdct =gmdct[i];
  111417. float *res =vb->pcm[i];
  111418. int *ilogmask=ilogmaskch[i]=
  111419. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111420. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  111421. floor_posts[i][k],
  111422. ilogmask);
  111423. #if 0
  111424. {
  111425. char buf[80];
  111426. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  111427. float work[n/2];
  111428. for(j=0;j<n/2;j++)
  111429. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  111430. _analysis_output(buf,seq,work,n/2,1,1,0);
  111431. }
  111432. #endif
  111433. _vp_remove_floor(psy_look,
  111434. mdct,
  111435. ilogmask,
  111436. res,
  111437. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111438. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  111439. #if 0
  111440. {
  111441. char buf[80];
  111442. float work[n/2];
  111443. for(j=0;j<n/2;j++)
  111444. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  111445. sprintf(buf,"resI%c%d",i?'R':'L',k);
  111446. _analysis_output(buf,seq,work,n/2,1,1,0);
  111447. }
  111448. #endif
  111449. }
  111450. /* our iteration is now based on masking curve, not prequant and
  111451. coupling. Only one prequant/coupling step */
  111452. /* quantize/couple */
  111453. /* incomplete implementation that assumes the tree is all depth
  111454. one, or no tree at all */
  111455. if(info->coupling_steps){
  111456. _vp_couple(k,
  111457. &ci->psy_g_param,
  111458. psy_look,
  111459. info,
  111460. vb->pcm,
  111461. mag_memo,
  111462. mag_sort,
  111463. ilogmaskch,
  111464. nonzero,
  111465. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111466. }
  111467. /* classify and encode by submap */
  111468. for(i=0;i<info->submaps;i++){
  111469. int ch_in_bundle=0;
  111470. long **classifications;
  111471. int resnum=info->residuesubmap[i];
  111472. for(j=0;j<vi->channels;j++){
  111473. if(info->chmuxlist[j]==i){
  111474. zerobundle[ch_in_bundle]=0;
  111475. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  111476. res_bundle[ch_in_bundle]=vb->pcm[j];
  111477. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  111478. }
  111479. }
  111480. classifications=_residue_P[ci->residue_type[resnum]]->
  111481. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  111482. _residue_P[ci->residue_type[resnum]]->
  111483. forward(opb,vb,b->residue[resnum],
  111484. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  111485. }
  111486. /* ok, done encoding. Next protopacket. */
  111487. }
  111488. }
  111489. #if 0
  111490. seq++;
  111491. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  111492. #endif
  111493. return(0);
  111494. }
  111495. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  111496. vorbis_dsp_state *vd=vb->vd;
  111497. vorbis_info *vi=vd->vi;
  111498. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111499. private_state *b=(private_state*)vd->backend_state;
  111500. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  111501. int i,j;
  111502. long n=vb->pcmend=ci->blocksizes[vb->W];
  111503. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  111504. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111505. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  111506. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  111507. /* recover the spectral envelope; store it in the PCM vector for now */
  111508. for(i=0;i<vi->channels;i++){
  111509. int submap=info->chmuxlist[i];
  111510. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111511. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  111512. if(floormemo[i])
  111513. nonzero[i]=1;
  111514. else
  111515. nonzero[i]=0;
  111516. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  111517. }
  111518. /* channel coupling can 'dirty' the nonzero listing */
  111519. for(i=0;i<info->coupling_steps;i++){
  111520. if(nonzero[info->coupling_mag[i]] ||
  111521. nonzero[info->coupling_ang[i]]){
  111522. nonzero[info->coupling_mag[i]]=1;
  111523. nonzero[info->coupling_ang[i]]=1;
  111524. }
  111525. }
  111526. /* recover the residue into our working vectors */
  111527. for(i=0;i<info->submaps;i++){
  111528. int ch_in_bundle=0;
  111529. for(j=0;j<vi->channels;j++){
  111530. if(info->chmuxlist[j]==i){
  111531. if(nonzero[j])
  111532. zerobundle[ch_in_bundle]=1;
  111533. else
  111534. zerobundle[ch_in_bundle]=0;
  111535. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  111536. }
  111537. }
  111538. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  111539. inverse(vb,b->residue[info->residuesubmap[i]],
  111540. pcmbundle,zerobundle,ch_in_bundle);
  111541. }
  111542. /* channel coupling */
  111543. for(i=info->coupling_steps-1;i>=0;i--){
  111544. float *pcmM=vb->pcm[info->coupling_mag[i]];
  111545. float *pcmA=vb->pcm[info->coupling_ang[i]];
  111546. for(j=0;j<n/2;j++){
  111547. float mag=pcmM[j];
  111548. float ang=pcmA[j];
  111549. if(mag>0)
  111550. if(ang>0){
  111551. pcmM[j]=mag;
  111552. pcmA[j]=mag-ang;
  111553. }else{
  111554. pcmA[j]=mag;
  111555. pcmM[j]=mag+ang;
  111556. }
  111557. else
  111558. if(ang>0){
  111559. pcmM[j]=mag;
  111560. pcmA[j]=mag+ang;
  111561. }else{
  111562. pcmA[j]=mag;
  111563. pcmM[j]=mag-ang;
  111564. }
  111565. }
  111566. }
  111567. /* compute and apply spectral envelope */
  111568. for(i=0;i<vi->channels;i++){
  111569. float *pcm=vb->pcm[i];
  111570. int submap=info->chmuxlist[i];
  111571. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111572. inverse2(vb,b->flr[info->floorsubmap[submap]],
  111573. floormemo[i],pcm);
  111574. }
  111575. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  111576. /* only MDCT right now.... */
  111577. for(i=0;i<vi->channels;i++){
  111578. float *pcm=vb->pcm[i];
  111579. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  111580. }
  111581. /* all done! */
  111582. return(0);
  111583. }
  111584. /* export hooks */
  111585. vorbis_func_mapping mapping0_exportbundle={
  111586. &mapping0_pack,
  111587. &mapping0_unpack,
  111588. &mapping0_free_info,
  111589. &mapping0_forward,
  111590. &mapping0_inverse
  111591. };
  111592. #endif
  111593. /********* End of inlined file: mapping0.c *********/
  111594. /********* Start of inlined file: mdct.c *********/
  111595. /* this can also be run as an integer transform by uncommenting a
  111596. define in mdct.h; the integerization is a first pass and although
  111597. it's likely stable for Vorbis, the dynamic range is constrained and
  111598. roundoff isn't done (so it's noisy). Consider it functional, but
  111599. only a starting point. There's no point on a machine with an FPU */
  111600. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111601. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111602. // tasks..
  111603. #if JUCE_MSVC
  111604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111605. #endif
  111606. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111607. #if JUCE_USE_OGGVORBIS
  111608. #include <stdio.h>
  111609. #include <stdlib.h>
  111610. #include <string.h>
  111611. #include <math.h>
  111612. /* build lookups for trig functions; also pre-figure scaling and
  111613. some window function algebra. */
  111614. void mdct_init(mdct_lookup *lookup,int n){
  111615. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  111616. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  111617. int i;
  111618. int n2=n>>1;
  111619. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  111620. lookup->n=n;
  111621. lookup->trig=T;
  111622. lookup->bitrev=bitrev;
  111623. /* trig lookups... */
  111624. for(i=0;i<n/4;i++){
  111625. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  111626. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  111627. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  111628. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  111629. }
  111630. for(i=0;i<n/8;i++){
  111631. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  111632. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  111633. }
  111634. /* bitreverse lookup... */
  111635. {
  111636. int mask=(1<<(log2n-1))-1,i,j;
  111637. int msb=1<<(log2n-2);
  111638. for(i=0;i<n/8;i++){
  111639. int acc=0;
  111640. for(j=0;msb>>j;j++)
  111641. if((msb>>j)&i)acc|=1<<j;
  111642. bitrev[i*2]=((~acc)&mask)-1;
  111643. bitrev[i*2+1]=acc;
  111644. }
  111645. }
  111646. lookup->scale=FLOAT_CONV(4.f/n);
  111647. }
  111648. /* 8 point butterfly (in place, 4 register) */
  111649. STIN void mdct_butterfly_8(DATA_TYPE *x){
  111650. REG_TYPE r0 = x[6] + x[2];
  111651. REG_TYPE r1 = x[6] - x[2];
  111652. REG_TYPE r2 = x[4] + x[0];
  111653. REG_TYPE r3 = x[4] - x[0];
  111654. x[6] = r0 + r2;
  111655. x[4] = r0 - r2;
  111656. r0 = x[5] - x[1];
  111657. r2 = x[7] - x[3];
  111658. x[0] = r1 + r0;
  111659. x[2] = r1 - r0;
  111660. r0 = x[5] + x[1];
  111661. r1 = x[7] + x[3];
  111662. x[3] = r2 + r3;
  111663. x[1] = r2 - r3;
  111664. x[7] = r1 + r0;
  111665. x[5] = r1 - r0;
  111666. }
  111667. /* 16 point butterfly (in place, 4 register) */
  111668. STIN void mdct_butterfly_16(DATA_TYPE *x){
  111669. REG_TYPE r0 = x[1] - x[9];
  111670. REG_TYPE r1 = x[0] - x[8];
  111671. x[8] += x[0];
  111672. x[9] += x[1];
  111673. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  111674. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  111675. r0 = x[3] - x[11];
  111676. r1 = x[10] - x[2];
  111677. x[10] += x[2];
  111678. x[11] += x[3];
  111679. x[2] = r0;
  111680. x[3] = r1;
  111681. r0 = x[12] - x[4];
  111682. r1 = x[13] - x[5];
  111683. x[12] += x[4];
  111684. x[13] += x[5];
  111685. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  111686. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  111687. r0 = x[14] - x[6];
  111688. r1 = x[15] - x[7];
  111689. x[14] += x[6];
  111690. x[15] += x[7];
  111691. x[6] = r0;
  111692. x[7] = r1;
  111693. mdct_butterfly_8(x);
  111694. mdct_butterfly_8(x+8);
  111695. }
  111696. /* 32 point butterfly (in place, 4 register) */
  111697. STIN void mdct_butterfly_32(DATA_TYPE *x){
  111698. REG_TYPE r0 = x[30] - x[14];
  111699. REG_TYPE r1 = x[31] - x[15];
  111700. x[30] += x[14];
  111701. x[31] += x[15];
  111702. x[14] = r0;
  111703. x[15] = r1;
  111704. r0 = x[28] - x[12];
  111705. r1 = x[29] - x[13];
  111706. x[28] += x[12];
  111707. x[29] += x[13];
  111708. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  111709. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  111710. r0 = x[26] - x[10];
  111711. r1 = x[27] - x[11];
  111712. x[26] += x[10];
  111713. x[27] += x[11];
  111714. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  111715. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  111716. r0 = x[24] - x[8];
  111717. r1 = x[25] - x[9];
  111718. x[24] += x[8];
  111719. x[25] += x[9];
  111720. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  111721. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111722. r0 = x[22] - x[6];
  111723. r1 = x[7] - x[23];
  111724. x[22] += x[6];
  111725. x[23] += x[7];
  111726. x[6] = r1;
  111727. x[7] = r0;
  111728. r0 = x[4] - x[20];
  111729. r1 = x[5] - x[21];
  111730. x[20] += x[4];
  111731. x[21] += x[5];
  111732. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  111733. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  111734. r0 = x[2] - x[18];
  111735. r1 = x[3] - x[19];
  111736. x[18] += x[2];
  111737. x[19] += x[3];
  111738. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  111739. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  111740. r0 = x[0] - x[16];
  111741. r1 = x[1] - x[17];
  111742. x[16] += x[0];
  111743. x[17] += x[1];
  111744. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111745. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  111746. mdct_butterfly_16(x);
  111747. mdct_butterfly_16(x+16);
  111748. }
  111749. /* N point first stage butterfly (in place, 2 register) */
  111750. STIN void mdct_butterfly_first(DATA_TYPE *T,
  111751. DATA_TYPE *x,
  111752. int points){
  111753. DATA_TYPE *x1 = x + points - 8;
  111754. DATA_TYPE *x2 = x + (points>>1) - 8;
  111755. REG_TYPE r0;
  111756. REG_TYPE r1;
  111757. do{
  111758. r0 = x1[6] - x2[6];
  111759. r1 = x1[7] - x2[7];
  111760. x1[6] += x2[6];
  111761. x1[7] += x2[7];
  111762. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111763. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111764. r0 = x1[4] - x2[4];
  111765. r1 = x1[5] - x2[5];
  111766. x1[4] += x2[4];
  111767. x1[5] += x2[5];
  111768. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  111769. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  111770. r0 = x1[2] - x2[2];
  111771. r1 = x1[3] - x2[3];
  111772. x1[2] += x2[2];
  111773. x1[3] += x2[3];
  111774. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  111775. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  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[13] + r0 * T[12]);
  111781. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  111782. x1-=8;
  111783. x2-=8;
  111784. T+=16;
  111785. }while(x2>=x);
  111786. }
  111787. /* N/stage point generic N stage butterfly (in place, 2 register) */
  111788. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  111789. DATA_TYPE *x,
  111790. int points,
  111791. int trigint){
  111792. DATA_TYPE *x1 = x + points - 8;
  111793. DATA_TYPE *x2 = x + (points>>1) - 8;
  111794. REG_TYPE r0;
  111795. REG_TYPE r1;
  111796. do{
  111797. r0 = x1[6] - x2[6];
  111798. r1 = x1[7] - x2[7];
  111799. x1[6] += x2[6];
  111800. x1[7] += x2[7];
  111801. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111802. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111803. T+=trigint;
  111804. r0 = x1[4] - x2[4];
  111805. r1 = x1[5] - x2[5];
  111806. x1[4] += x2[4];
  111807. x1[5] += x2[5];
  111808. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111809. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111810. T+=trigint;
  111811. r0 = x1[2] - x2[2];
  111812. r1 = x1[3] - x2[3];
  111813. x1[2] += x2[2];
  111814. x1[3] += x2[3];
  111815. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111816. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111817. T+=trigint;
  111818. r0 = x1[0] - x2[0];
  111819. r1 = x1[1] - x2[1];
  111820. x1[0] += x2[0];
  111821. x1[1] += x2[1];
  111822. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111823. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111824. T+=trigint;
  111825. x1-=8;
  111826. x2-=8;
  111827. }while(x2>=x);
  111828. }
  111829. STIN void mdct_butterflies(mdct_lookup *init,
  111830. DATA_TYPE *x,
  111831. int points){
  111832. DATA_TYPE *T=init->trig;
  111833. int stages=init->log2n-5;
  111834. int i,j;
  111835. if(--stages>0){
  111836. mdct_butterfly_first(T,x,points);
  111837. }
  111838. for(i=1;--stages>0;i++){
  111839. for(j=0;j<(1<<i);j++)
  111840. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  111841. }
  111842. for(j=0;j<points;j+=32)
  111843. mdct_butterfly_32(x+j);
  111844. }
  111845. void mdct_clear(mdct_lookup *l){
  111846. if(l){
  111847. if(l->trig)_ogg_free(l->trig);
  111848. if(l->bitrev)_ogg_free(l->bitrev);
  111849. memset(l,0,sizeof(*l));
  111850. }
  111851. }
  111852. STIN void mdct_bitreverse(mdct_lookup *init,
  111853. DATA_TYPE *x){
  111854. int n = init->n;
  111855. int *bit = init->bitrev;
  111856. DATA_TYPE *w0 = x;
  111857. DATA_TYPE *w1 = x = w0+(n>>1);
  111858. DATA_TYPE *T = init->trig+n;
  111859. do{
  111860. DATA_TYPE *x0 = x+bit[0];
  111861. DATA_TYPE *x1 = x+bit[1];
  111862. REG_TYPE r0 = x0[1] - x1[1];
  111863. REG_TYPE r1 = x0[0] + x1[0];
  111864. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  111865. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  111866. w1 -= 4;
  111867. r0 = HALVE(x0[1] + x1[1]);
  111868. r1 = HALVE(x0[0] - x1[0]);
  111869. w0[0] = r0 + r2;
  111870. w1[2] = r0 - r2;
  111871. w0[1] = r1 + r3;
  111872. w1[3] = r3 - r1;
  111873. x0 = x+bit[2];
  111874. x1 = x+bit[3];
  111875. r0 = x0[1] - x1[1];
  111876. r1 = x0[0] + x1[0];
  111877. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  111878. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  111879. r0 = HALVE(x0[1] + x1[1]);
  111880. r1 = HALVE(x0[0] - x1[0]);
  111881. w0[2] = r0 + r2;
  111882. w1[0] = r0 - r2;
  111883. w0[3] = r1 + r3;
  111884. w1[1] = r3 - r1;
  111885. T += 4;
  111886. bit += 4;
  111887. w0 += 4;
  111888. }while(w0<w1);
  111889. }
  111890. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111891. int n=init->n;
  111892. int n2=n>>1;
  111893. int n4=n>>2;
  111894. /* rotate */
  111895. DATA_TYPE *iX = in+n2-7;
  111896. DATA_TYPE *oX = out+n2+n4;
  111897. DATA_TYPE *T = init->trig+n4;
  111898. do{
  111899. oX -= 4;
  111900. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  111901. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  111902. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  111903. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  111904. iX -= 8;
  111905. T += 4;
  111906. }while(iX>=in);
  111907. iX = in+n2-8;
  111908. oX = out+n2+n4;
  111909. T = init->trig+n4;
  111910. do{
  111911. T -= 4;
  111912. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  111913. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  111914. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  111915. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  111916. iX -= 8;
  111917. oX += 4;
  111918. }while(iX>=in);
  111919. mdct_butterflies(init,out+n2,n2);
  111920. mdct_bitreverse(init,out);
  111921. /* roatate + window */
  111922. {
  111923. DATA_TYPE *oX1=out+n2+n4;
  111924. DATA_TYPE *oX2=out+n2+n4;
  111925. DATA_TYPE *iX =out;
  111926. T =init->trig+n2;
  111927. do{
  111928. oX1-=4;
  111929. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  111930. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  111931. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  111932. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  111933. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  111934. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  111935. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  111936. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  111937. oX2+=4;
  111938. iX += 8;
  111939. T += 8;
  111940. }while(iX<oX1);
  111941. iX=out+n2+n4;
  111942. oX1=out+n4;
  111943. oX2=oX1;
  111944. do{
  111945. oX1-=4;
  111946. iX-=4;
  111947. oX2[0] = -(oX1[3] = iX[3]);
  111948. oX2[1] = -(oX1[2] = iX[2]);
  111949. oX2[2] = -(oX1[1] = iX[1]);
  111950. oX2[3] = -(oX1[0] = iX[0]);
  111951. oX2+=4;
  111952. }while(oX2<iX);
  111953. iX=out+n2+n4;
  111954. oX1=out+n2+n4;
  111955. oX2=out+n2;
  111956. do{
  111957. oX1-=4;
  111958. oX1[0]= iX[3];
  111959. oX1[1]= iX[2];
  111960. oX1[2]= iX[1];
  111961. oX1[3]= iX[0];
  111962. iX+=4;
  111963. }while(oX1>oX2);
  111964. }
  111965. }
  111966. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111967. int n=init->n;
  111968. int n2=n>>1;
  111969. int n4=n>>2;
  111970. int n8=n>>3;
  111971. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  111972. DATA_TYPE *w2=w+n2;
  111973. /* rotate */
  111974. /* window + rotate + step 1 */
  111975. REG_TYPE r0;
  111976. REG_TYPE r1;
  111977. DATA_TYPE *x0=in+n2+n4;
  111978. DATA_TYPE *x1=x0+1;
  111979. DATA_TYPE *T=init->trig+n2;
  111980. int i=0;
  111981. for(i=0;i<n8;i+=2){
  111982. x0 -=4;
  111983. T-=2;
  111984. r0= x0[2] + x1[0];
  111985. r1= x0[0] + x1[2];
  111986. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111987. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111988. x1 +=4;
  111989. }
  111990. x1=in+1;
  111991. for(;i<n2-n8;i+=2){
  111992. T-=2;
  111993. x0 -=4;
  111994. r0= x0[2] - x1[0];
  111995. r1= x0[0] - x1[2];
  111996. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111997. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111998. x1 +=4;
  111999. }
  112000. x0=in+n;
  112001. for(;i<n2;i+=2){
  112002. T-=2;
  112003. x0 -=4;
  112004. r0= -x0[2] - x1[0];
  112005. r1= -x0[0] - x1[2];
  112006. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  112007. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  112008. x1 +=4;
  112009. }
  112010. mdct_butterflies(init,w+n2,n2);
  112011. mdct_bitreverse(init,w);
  112012. /* roatate + window */
  112013. T=init->trig+n2;
  112014. x0=out+n2;
  112015. for(i=0;i<n4;i++){
  112016. x0--;
  112017. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  112018. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  112019. w+=2;
  112020. T+=2;
  112021. }
  112022. }
  112023. #endif
  112024. /********* End of inlined file: mdct.c *********/
  112025. /********* Start of inlined file: psy.c *********/
  112026. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112027. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112028. // tasks..
  112029. #if JUCE_MSVC
  112030. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112031. #endif
  112032. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112033. #if JUCE_USE_OGGVORBIS
  112034. #include <stdlib.h>
  112035. #include <math.h>
  112036. #include <string.h>
  112037. /********* Start of inlined file: masking.h *********/
  112038. #ifndef _V_MASKING_H_
  112039. #define _V_MASKING_H_
  112040. /* more detailed ATH; the bass if flat to save stressing the floor
  112041. overly for only a bin or two of savings. */
  112042. #define MAX_ATH 88
  112043. static float ATH[]={
  112044. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  112045. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  112046. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  112047. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  112048. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  112049. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  112050. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  112051. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  112052. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  112053. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  112054. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  112055. };
  112056. /* The tone masking curves from Ehmer's and Fielder's papers have been
  112057. replaced by an empirically collected data set. The previously
  112058. published values were, far too often, simply on crack. */
  112059. #define EHMER_OFFSET 16
  112060. #define EHMER_MAX 56
  112061. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  112062. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  112063. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  112064. for collection of these curves) */
  112065. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  112066. /* 62.5 Hz */
  112067. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  112068. -60, -60, -60, -60, -62, -62, -65, -73,
  112069. -69, -68, -68, -67, -70, -70, -72, -74,
  112070. -75, -79, -79, -80, -83, -88, -93, -100,
  112071. -110, -999, -999, -999, -999, -999, -999, -999,
  112072. -999, -999, -999, -999, -999, -999, -999, -999,
  112073. -999, -999, -999, -999, -999, -999, -999, -999},
  112074. { -48, -48, -48, -48, -48, -48, -48, -48,
  112075. -48, -48, -48, -48, -48, -53, -61, -66,
  112076. -66, -68, -67, -70, -76, -76, -72, -73,
  112077. -75, -76, -78, -79, -83, -88, -93, -100,
  112078. -110, -999, -999, -999, -999, -999, -999, -999,
  112079. -999, -999, -999, -999, -999, -999, -999, -999,
  112080. -999, -999, -999, -999, -999, -999, -999, -999},
  112081. { -37, -37, -37, -37, -37, -37, -37, -37,
  112082. -38, -40, -42, -46, -48, -53, -55, -62,
  112083. -65, -58, -56, -56, -61, -60, -65, -67,
  112084. -69, -71, -77, -77, -78, -80, -82, -84,
  112085. -88, -93, -98, -106, -112, -999, -999, -999,
  112086. -999, -999, -999, -999, -999, -999, -999, -999,
  112087. -999, -999, -999, -999, -999, -999, -999, -999},
  112088. { -25, -25, -25, -25, -25, -25, -25, -25,
  112089. -25, -26, -27, -29, -32, -38, -48, -52,
  112090. -52, -50, -48, -48, -51, -52, -54, -60,
  112091. -67, -67, -66, -68, -69, -73, -73, -76,
  112092. -80, -81, -81, -85, -85, -86, -88, -93,
  112093. -100, -110, -999, -999, -999, -999, -999, -999,
  112094. -999, -999, -999, -999, -999, -999, -999, -999},
  112095. { -16, -16, -16, -16, -16, -16, -16, -16,
  112096. -17, -19, -20, -22, -26, -28, -31, -40,
  112097. -47, -39, -39, -40, -42, -43, -47, -51,
  112098. -57, -52, -55, -55, -60, -58, -62, -63,
  112099. -70, -67, -69, -72, -73, -77, -80, -82,
  112100. -83, -87, -90, -94, -98, -104, -115, -999,
  112101. -999, -999, -999, -999, -999, -999, -999, -999},
  112102. { -8, -8, -8, -8, -8, -8, -8, -8,
  112103. -8, -8, -10, -11, -15, -19, -25, -30,
  112104. -34, -31, -30, -31, -29, -32, -35, -42,
  112105. -48, -42, -44, -46, -50, -50, -51, -52,
  112106. -59, -54, -55, -55, -58, -62, -63, -66,
  112107. -72, -73, -76, -75, -78, -80, -80, -81,
  112108. -84, -88, -90, -94, -98, -101, -106, -110}},
  112109. /* 88Hz */
  112110. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  112111. -66, -66, -66, -66, -66, -67, -67, -67,
  112112. -76, -72, -71, -74, -76, -76, -75, -78,
  112113. -79, -79, -81, -83, -86, -89, -93, -97,
  112114. -100, -105, -110, -999, -999, -999, -999, -999,
  112115. -999, -999, -999, -999, -999, -999, -999, -999,
  112116. -999, -999, -999, -999, -999, -999, -999, -999},
  112117. { -47, -47, -47, -47, -47, -47, -47, -47,
  112118. -47, -47, -47, -48, -51, -55, -59, -66,
  112119. -66, -66, -67, -66, -68, -69, -70, -74,
  112120. -79, -77, -77, -78, -80, -81, -82, -84,
  112121. -86, -88, -91, -95, -100, -108, -116, -999,
  112122. -999, -999, -999, -999, -999, -999, -999, -999,
  112123. -999, -999, -999, -999, -999, -999, -999, -999},
  112124. { -36, -36, -36, -36, -36, -36, -36, -36,
  112125. -36, -37, -37, -41, -44, -48, -51, -58,
  112126. -62, -60, -57, -59, -59, -60, -63, -65,
  112127. -72, -71, -70, -72, -74, -77, -76, -78,
  112128. -81, -81, -80, -83, -86, -91, -96, -100,
  112129. -105, -110, -999, -999, -999, -999, -999, -999,
  112130. -999, -999, -999, -999, -999, -999, -999, -999},
  112131. { -28, -28, -28, -28, -28, -28, -28, -28,
  112132. -28, -30, -32, -32, -33, -35, -41, -49,
  112133. -50, -49, -47, -48, -48, -52, -51, -57,
  112134. -65, -61, -59, -61, -64, -69, -70, -74,
  112135. -77, -77, -78, -81, -84, -85, -87, -90,
  112136. -92, -96, -100, -107, -112, -999, -999, -999,
  112137. -999, -999, -999, -999, -999, -999, -999, -999},
  112138. { -19, -19, -19, -19, -19, -19, -19, -19,
  112139. -20, -21, -23, -27, -30, -35, -36, -41,
  112140. -46, -44, -42, -40, -41, -41, -43, -48,
  112141. -55, -53, -52, -53, -56, -59, -58, -60,
  112142. -67, -66, -69, -71, -72, -75, -79, -81,
  112143. -84, -87, -90, -93, -97, -101, -107, -114,
  112144. -999, -999, -999, -999, -999, -999, -999, -999},
  112145. { -9, -9, -9, -9, -9, -9, -9, -9,
  112146. -11, -12, -12, -15, -16, -20, -23, -30,
  112147. -37, -34, -33, -34, -31, -32, -32, -38,
  112148. -47, -44, -41, -40, -47, -49, -46, -46,
  112149. -58, -50, -50, -54, -58, -62, -64, -67,
  112150. -67, -70, -72, -76, -79, -83, -87, -91,
  112151. -96, -100, -104, -110, -999, -999, -999, -999}},
  112152. /* 125 Hz */
  112153. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  112154. -62, -62, -63, -64, -66, -67, -66, -68,
  112155. -75, -72, -76, -75, -76, -78, -79, -82,
  112156. -84, -85, -90, -94, -101, -110, -999, -999,
  112157. -999, -999, -999, -999, -999, -999, -999, -999,
  112158. -999, -999, -999, -999, -999, -999, -999, -999,
  112159. -999, -999, -999, -999, -999, -999, -999, -999},
  112160. { -59, -59, -59, -59, -59, -59, -59, -59,
  112161. -59, -59, -59, -60, -60, -61, -63, -66,
  112162. -71, -68, -70, -70, -71, -72, -72, -75,
  112163. -81, -78, -79, -82, -83, -86, -90, -97,
  112164. -103, -113, -999, -999, -999, -999, -999, -999,
  112165. -999, -999, -999, -999, -999, -999, -999, -999,
  112166. -999, -999, -999, -999, -999, -999, -999, -999},
  112167. { -53, -53, -53, -53, -53, -53, -53, -53,
  112168. -53, -54, -55, -57, -56, -57, -55, -61,
  112169. -65, -60, -60, -62, -63, -63, -66, -68,
  112170. -74, -73, -75, -75, -78, -80, -80, -82,
  112171. -85, -90, -96, -101, -108, -999, -999, -999,
  112172. -999, -999, -999, -999, -999, -999, -999, -999,
  112173. -999, -999, -999, -999, -999, -999, -999, -999},
  112174. { -46, -46, -46, -46, -46, -46, -46, -46,
  112175. -46, -46, -47, -47, -47, -47, -48, -51,
  112176. -57, -51, -49, -50, -51, -53, -54, -59,
  112177. -66, -60, -62, -67, -67, -70, -72, -75,
  112178. -76, -78, -81, -85, -88, -94, -97, -104,
  112179. -112, -999, -999, -999, -999, -999, -999, -999,
  112180. -999, -999, -999, -999, -999, -999, -999, -999},
  112181. { -36, -36, -36, -36, -36, -36, -36, -36,
  112182. -39, -41, -42, -42, -39, -38, -41, -43,
  112183. -52, -44, -40, -39, -37, -37, -40, -47,
  112184. -54, -50, -48, -50, -55, -61, -59, -62,
  112185. -66, -66, -66, -69, -69, -73, -74, -74,
  112186. -75, -77, -79, -82, -87, -91, -95, -100,
  112187. -108, -115, -999, -999, -999, -999, -999, -999},
  112188. { -28, -26, -24, -22, -20, -20, -23, -29,
  112189. -30, -31, -28, -27, -28, -28, -28, -35,
  112190. -40, -33, -32, -29, -30, -30, -30, -37,
  112191. -45, -41, -37, -38, -45, -47, -47, -48,
  112192. -53, -49, -48, -50, -49, -49, -51, -52,
  112193. -58, -56, -57, -56, -60, -61, -62, -70,
  112194. -72, -74, -78, -83, -88, -93, -100, -106}},
  112195. /* 177 Hz */
  112196. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112197. -999, -110, -105, -100, -95, -91, -87, -83,
  112198. -80, -78, -76, -78, -78, -81, -83, -85,
  112199. -86, -85, -86, -87, -90, -97, -107, -999,
  112200. -999, -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, -110, -105, -100, -95, -90,
  112204. -85, -81, -77, -73, -70, -67, -67, -68,
  112205. -75, -73, -70, -69, -70, -72, -75, -79,
  112206. -84, -83, -84, -86, -88, -89, -89, -93,
  112207. -98, -105, -112, -999, -999, -999, -999, -999,
  112208. -999, -999, -999, -999, -999, -999, -999, -999,
  112209. -999, -999, -999, -999, -999, -999, -999, -999},
  112210. {-105, -100, -95, -90, -85, -80, -76, -71,
  112211. -68, -68, -65, -63, -63, -62, -62, -64,
  112212. -65, -64, -61, -62, -63, -64, -66, -68,
  112213. -73, -73, -74, -75, -76, -81, -83, -85,
  112214. -88, -89, -92, -95, -100, -108, -999, -999,
  112215. -999, -999, -999, -999, -999, -999, -999, -999,
  112216. -999, -999, -999, -999, -999, -999, -999, -999},
  112217. { -80, -75, -71, -68, -65, -63, -62, -61,
  112218. -61, -61, -61, -59, -56, -57, -53, -50,
  112219. -58, -52, -50, -50, -52, -53, -54, -58,
  112220. -67, -63, -67, -68, -72, -75, -78, -80,
  112221. -81, -81, -82, -85, -89, -90, -93, -97,
  112222. -101, -107, -114, -999, -999, -999, -999, -999,
  112223. -999, -999, -999, -999, -999, -999, -999, -999},
  112224. { -65, -61, -59, -57, -56, -55, -55, -56,
  112225. -56, -57, -55, -53, -52, -47, -44, -44,
  112226. -50, -44, -41, -39, -39, -42, -40, -46,
  112227. -51, -49, -50, -53, -54, -63, -60, -61,
  112228. -62, -66, -66, -66, -70, -73, -74, -75,
  112229. -76, -75, -79, -85, -89, -91, -96, -102,
  112230. -110, -999, -999, -999, -999, -999, -999, -999},
  112231. { -52, -50, -49, -49, -48, -48, -48, -49,
  112232. -50, -50, -49, -46, -43, -39, -35, -33,
  112233. -38, -36, -32, -29, -32, -32, -32, -35,
  112234. -44, -39, -38, -38, -46, -50, -45, -46,
  112235. -53, -50, -50, -50, -54, -54, -53, -53,
  112236. -56, -57, -59, -66, -70, -72, -74, -79,
  112237. -83, -85, -90, -97, -114, -999, -999, -999}},
  112238. /* 250 Hz */
  112239. {{-999, -999, -999, -999, -999, -999, -110, -105,
  112240. -100, -95, -90, -86, -80, -75, -75, -79,
  112241. -80, -79, -80, -81, -82, -88, -95, -103,
  112242. -110, -999, -999, -999, -999, -999, -999, -999,
  112243. -999, -999, -999, -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, -108, -103, -98, -93,
  112247. -88, -83, -79, -78, -75, -71, -67, -68,
  112248. -73, -73, -72, -73, -75, -77, -80, -82,
  112249. -88, -93, -100, -107, -114, -999, -999, -999,
  112250. -999, -999, -999, -999, -999, -999, -999, -999,
  112251. -999, -999, -999, -999, -999, -999, -999, -999,
  112252. -999, -999, -999, -999, -999, -999, -999, -999},
  112253. {-999, -999, -999, -110, -105, -101, -96, -90,
  112254. -86, -81, -77, -73, -69, -66, -61, -62,
  112255. -66, -64, -62, -65, -66, -70, -72, -76,
  112256. -81, -80, -84, -90, -95, -102, -110, -999,
  112257. -999, -999, -999, -999, -999, -999, -999, -999,
  112258. -999, -999, -999, -999, -999, -999, -999, -999,
  112259. -999, -999, -999, -999, -999, -999, -999, -999},
  112260. {-999, -999, -999, -107, -103, -97, -92, -88,
  112261. -83, -79, -74, -70, -66, -59, -53, -58,
  112262. -62, -55, -54, -54, -54, -58, -61, -62,
  112263. -72, -70, -72, -75, -78, -80, -81, -80,
  112264. -83, -83, -88, -93, -100, -107, -115, -999,
  112265. -999, -999, -999, -999, -999, -999, -999, -999,
  112266. -999, -999, -999, -999, -999, -999, -999, -999},
  112267. {-999, -999, -999, -105, -100, -95, -90, -85,
  112268. -80, -75, -70, -66, -62, -56, -48, -44,
  112269. -48, -46, -46, -43, -46, -48, -48, -51,
  112270. -58, -58, -59, -60, -62, -62, -61, -61,
  112271. -65, -64, -65, -68, -70, -74, -75, -78,
  112272. -81, -86, -95, -110, -999, -999, -999, -999,
  112273. -999, -999, -999, -999, -999, -999, -999, -999},
  112274. {-999, -999, -105, -100, -95, -90, -85, -80,
  112275. -75, -70, -65, -61, -55, -49, -39, -33,
  112276. -40, -35, -32, -38, -40, -33, -35, -37,
  112277. -46, -41, -45, -44, -46, -42, -45, -46,
  112278. -52, -50, -50, -50, -54, -54, -55, -57,
  112279. -62, -64, -66, -68, -70, -76, -81, -90,
  112280. -100, -110, -999, -999, -999, -999, -999, -999}},
  112281. /* 354 hz */
  112282. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112283. -105, -98, -90, -85, -82, -83, -80, -78,
  112284. -84, -79, -80, -83, -87, -89, -91, -93,
  112285. -99, -106, -117, -999, -999, -999, -999, -999,
  112286. -999, -999, -999, -999, -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. -105, -98, -90, -85, -80, -75, -70, -68,
  112291. -74, -72, -74, -77, -80, -82, -85, -87,
  112292. -92, -89, -91, -95, -100, -106, -112, -999,
  112293. -999, -999, -999, -999, -999, -999, -999, -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. -105, -98, -90, -83, -75, -71, -63, -64,
  112298. -67, -62, -64, -67, -70, -73, -77, -81,
  112299. -84, -83, -85, -89, -90, -93, -98, -104,
  112300. -109, -114, -999, -999, -999, -999, -999, -999,
  112301. -999, -999, -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. -103, -96, -88, -81, -75, -68, -58, -54,
  112305. -56, -54, -56, -56, -58, -60, -63, -66,
  112306. -74, -69, -72, -72, -75, -74, -77, -81,
  112307. -81, -82, -84, -87, -93, -96, -99, -104,
  112308. -110, -999, -999, -999, -999, -999, -999, -999,
  112309. -999, -999, -999, -999, -999, -999, -999, -999},
  112310. {-999, -999, -999, -999, -999, -108, -102, -96,
  112311. -91, -85, -80, -74, -68, -60, -51, -46,
  112312. -48, -46, -43, -45, -47, -47, -49, -48,
  112313. -56, -53, -55, -58, -57, -63, -58, -60,
  112314. -66, -64, -67, -70, -70, -74, -77, -84,
  112315. -86, -89, -91, -93, -94, -101, -109, -118,
  112316. -999, -999, -999, -999, -999, -999, -999, -999},
  112317. {-999, -999, -999, -108, -103, -98, -93, -88,
  112318. -83, -78, -73, -68, -60, -53, -44, -35,
  112319. -38, -38, -34, -34, -36, -40, -41, -44,
  112320. -51, -45, -46, -47, -46, -54, -50, -49,
  112321. -50, -50, -50, -51, -54, -57, -58, -60,
  112322. -66, -66, -66, -64, -65, -68, -77, -82,
  112323. -87, -95, -110, -999, -999, -999, -999, -999}},
  112324. /* 500 Hz */
  112325. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112326. -107, -102, -97, -92, -87, -83, -78, -75,
  112327. -82, -79, -83, -85, -89, -92, -95, -98,
  112328. -101, -105, -109, -113, -999, -999, -999, -999,
  112329. -999, -999, -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, -106,
  112333. -100, -95, -90, -86, -81, -78, -74, -69,
  112334. -74, -74, -76, -79, -83, -84, -86, -89,
  112335. -92, -97, -93, -100, -103, -107, -110, -999,
  112336. -999, -999, -999, -999, -999, -999, -999, -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, -106, -100,
  112340. -95, -90, -87, -83, -80, -75, -69, -60,
  112341. -66, -66, -68, -70, -74, -78, -79, -81,
  112342. -81, -83, -84, -87, -93, -96, -99, -103,
  112343. -107, -110, -999, -999, -999, -999, -999, -999,
  112344. -999, -999, -999, -999, -999, -999, -999, -999,
  112345. -999, -999, -999, -999, -999, -999, -999, -999},
  112346. {-999, -999, -999, -999, -999, -108, -103, -98,
  112347. -93, -89, -85, -82, -78, -71, -62, -55,
  112348. -58, -58, -54, -54, -55, -59, -61, -62,
  112349. -70, -66, -66, -67, -70, -72, -75, -78,
  112350. -84, -84, -84, -88, -91, -90, -95, -98,
  112351. -102, -103, -106, -110, -999, -999, -999, -999,
  112352. -999, -999, -999, -999, -999, -999, -999, -999},
  112353. {-999, -999, -999, -999, -108, -103, -98, -94,
  112354. -90, -87, -82, -79, -73, -67, -58, -47,
  112355. -50, -45, -41, -45, -48, -44, -44, -49,
  112356. -54, -51, -48, -47, -49, -50, -51, -57,
  112357. -58, -60, -63, -69, -70, -69, -71, -74,
  112358. -78, -82, -90, -95, -101, -105, -110, -999,
  112359. -999, -999, -999, -999, -999, -999, -999, -999},
  112360. {-999, -999, -999, -105, -101, -97, -93, -90,
  112361. -85, -80, -77, -72, -65, -56, -48, -37,
  112362. -40, -36, -34, -40, -50, -47, -38, -41,
  112363. -47, -38, -35, -39, -38, -43, -40, -45,
  112364. -50, -45, -44, -47, -50, -55, -48, -48,
  112365. -52, -66, -70, -76, -82, -90, -97, -105,
  112366. -110, -999, -999, -999, -999, -999, -999, -999}},
  112367. /* 707 Hz */
  112368. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112369. -999, -108, -103, -98, -93, -86, -79, -76,
  112370. -83, -81, -85, -87, -89, -93, -98, -102,
  112371. -107, -112, -999, -999, -999, -999, -999, -999,
  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, -108, -103, -98, -93, -86, -79, -71,
  112377. -77, -74, -77, -79, -81, -84, -85, -90,
  112378. -92, -93, -92, -98, -101, -108, -112, -999,
  112379. -999, -999, -999, -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. -108, -103, -98, -93, -87, -78, -68, -65,
  112384. -66, -62, -65, -67, -70, -73, -75, -78,
  112385. -82, -82, -83, -84, -91, -93, -98, -102,
  112386. -106, -110, -999, -999, -999, -999, -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. -105, -100, -95, -90, -82, -74, -62, -57,
  112391. -58, -56, -51, -52, -52, -54, -54, -58,
  112392. -66, -59, -60, -63, -66, -69, -73, -79,
  112393. -83, -84, -80, -81, -81, -82, -88, -92,
  112394. -98, -105, -113, -999, -999, -999, -999, -999,
  112395. -999, -999, -999, -999, -999, -999, -999, -999},
  112396. {-999, -999, -999, -999, -999, -999, -999, -107,
  112397. -102, -97, -92, -84, -79, -69, -57, -47,
  112398. -52, -47, -44, -45, -50, -52, -42, -42,
  112399. -53, -43, -43, -48, -51, -56, -55, -52,
  112400. -57, -59, -61, -62, -67, -71, -78, -83,
  112401. -86, -94, -98, -103, -110, -999, -999, -999,
  112402. -999, -999, -999, -999, -999, -999, -999, -999},
  112403. {-999, -999, -999, -999, -999, -999, -105, -100,
  112404. -95, -90, -84, -78, -70, -61, -51, -41,
  112405. -40, -38, -40, -46, -52, -51, -41, -40,
  112406. -46, -40, -38, -38, -41, -46, -41, -46,
  112407. -47, -43, -43, -45, -41, -45, -56, -67,
  112408. -68, -83, -87, -90, -95, -102, -107, -113,
  112409. -999, -999, -999, -999, -999, -999, -999, -999}},
  112410. /* 1000 Hz */
  112411. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112412. -999, -109, -105, -101, -96, -91, -84, -77,
  112413. -82, -82, -85, -89, -94, -100, -106, -110,
  112414. -999, -999, -999, -999, -999, -999, -999, -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, -106, -103, -98, -92, -85, -80, -71,
  112420. -75, -72, -76, -80, -84, -86, -89, -93,
  112421. -100, -107, -113, -999, -999, -999, -999, -999,
  112422. -999, -999, -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, -107,
  112426. -104, -101, -97, -92, -88, -84, -80, -64,
  112427. -66, -63, -64, -66, -69, -73, -77, -83,
  112428. -83, -86, -91, -98, -104, -111, -999, -999,
  112429. -999, -999, -999, -999, -999, -999, -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, -107,
  112433. -104, -101, -97, -92, -90, -84, -74, -57,
  112434. -58, -52, -55, -54, -50, -52, -50, -52,
  112435. -63, -62, -69, -76, -77, -78, -78, -79,
  112436. -82, -88, -94, -100, -106, -111, -999, -999,
  112437. -999, -999, -999, -999, -999, -999, -999, -999,
  112438. -999, -999, -999, -999, -999, -999, -999, -999},
  112439. {-999, -999, -999, -999, -999, -999, -106, -102,
  112440. -98, -95, -90, -85, -83, -78, -70, -50,
  112441. -50, -41, -44, -49, -47, -50, -50, -44,
  112442. -55, -46, -47, -48, -48, -54, -49, -49,
  112443. -58, -62, -71, -81, -87, -92, -97, -102,
  112444. -108, -114, -999, -999, -999, -999, -999, -999,
  112445. -999, -999, -999, -999, -999, -999, -999, -999},
  112446. {-999, -999, -999, -999, -999, -999, -106, -102,
  112447. -98, -95, -90, -85, -83, -78, -70, -45,
  112448. -43, -41, -47, -50, -51, -50, -49, -45,
  112449. -47, -41, -44, -41, -39, -43, -38, -37,
  112450. -40, -41, -44, -50, -58, -65, -73, -79,
  112451. -85, -92, -97, -101, -105, -109, -113, -999,
  112452. -999, -999, -999, -999, -999, -999, -999, -999}},
  112453. /* 1414 Hz */
  112454. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112455. -999, -999, -999, -107, -100, -95, -87, -81,
  112456. -85, -83, -88, -93, -100, -107, -114, -999,
  112457. -999, -999, -999, -999, -999, -999, -999, -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, -107, -101, -95, -88, -83, -76,
  112463. -73, -72, -79, -84, -90, -95, -100, -105,
  112464. -110, -115, -999, -999, -999, -999, -999, -999,
  112465. -999, -999, -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, -104, -98, -92, -87, -81, -70,
  112470. -65, -62, -67, -71, -74, -80, -85, -91,
  112471. -95, -99, -103, -108, -111, -114, -999, -999,
  112472. -999, -999, -999, -999, -999, -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, -103, -97, -90, -85, -76, -60,
  112477. -56, -54, -60, -62, -61, -56, -63, -65,
  112478. -73, -74, -77, -75, -78, -81, -86, -87,
  112479. -88, -91, -94, -98, -103, -110, -999, -999,
  112480. -999, -999, -999, -999, -999, -999, -999, -999,
  112481. -999, -999, -999, -999, -999, -999, -999, -999},
  112482. {-999, -999, -999, -999, -999, -999, -999, -105,
  112483. -100, -97, -92, -86, -81, -79, -70, -57,
  112484. -51, -47, -51, -58, -60, -56, -53, -50,
  112485. -58, -52, -50, -50, -53, -55, -64, -69,
  112486. -71, -85, -82, -78, -81, -85, -95, -102,
  112487. -112, -999, -999, -999, -999, -999, -999, -999,
  112488. -999, -999, -999, -999, -999, -999, -999, -999},
  112489. {-999, -999, -999, -999, -999, -999, -999, -105,
  112490. -100, -97, -92, -85, -83, -79, -72, -49,
  112491. -40, -43, -43, -54, -56, -51, -50, -40,
  112492. -43, -38, -36, -35, -37, -38, -37, -44,
  112493. -54, -60, -57, -60, -70, -75, -84, -92,
  112494. -103, -112, -999, -999, -999, -999, -999, -999,
  112495. -999, -999, -999, -999, -999, -999, -999, -999}},
  112496. /* 2000 Hz */
  112497. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112498. -999, -999, -999, -110, -102, -95, -89, -82,
  112499. -83, -84, -90, -92, -99, -107, -113, -999,
  112500. -999, -999, -999, -999, -999, -999, -999, -999,
  112501. -999, -999, -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, -107, -101, -95, -89, -83, -72,
  112506. -74, -78, -85, -88, -88, -90, -92, -98,
  112507. -105, -111, -999, -999, -999, -999, -999, -999,
  112508. -999, -999, -999, -999, -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, -109, -103, -97, -93, -87, -81, -70,
  112513. -70, -67, -75, -73, -76, -79, -81, -83,
  112514. -88, -89, -97, -103, -110, -999, -999, -999,
  112515. -999, -999, -999, -999, -999, -999, -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, -107, -100, -94, -88, -83, -75, -63,
  112520. -59, -59, -63, -66, -60, -62, -67, -67,
  112521. -77, -76, -81, -88, -86, -92, -96, -102,
  112522. -109, -116, -999, -999, -999, -999, -999, -999,
  112523. -999, -999, -999, -999, -999, -999, -999, -999,
  112524. -999, -999, -999, -999, -999, -999, -999, -999},
  112525. {-999, -999, -999, -999, -999, -999, -999, -999,
  112526. -999, -105, -98, -92, -86, -81, -73, -56,
  112527. -52, -47, -55, -60, -58, -52, -51, -45,
  112528. -49, -50, -53, -54, -61, -71, -70, -69,
  112529. -78, -79, -87, -90, -96, -104, -112, -999,
  112530. -999, -999, -999, -999, -999, -999, -999, -999,
  112531. -999, -999, -999, -999, -999, -999, -999, -999},
  112532. {-999, -999, -999, -999, -999, -999, -999, -999,
  112533. -999, -103, -96, -90, -86, -78, -70, -51,
  112534. -42, -47, -48, -55, -54, -54, -53, -42,
  112535. -35, -28, -33, -38, -37, -44, -47, -49,
  112536. -54, -63, -68, -78, -82, -89, -94, -99,
  112537. -104, -109, -114, -999, -999, -999, -999, -999,
  112538. -999, -999, -999, -999, -999, -999, -999, -999}},
  112539. /* 2828 Hz */
  112540. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112541. -999, -999, -999, -999, -110, -100, -90, -79,
  112542. -85, -81, -82, -82, -89, -94, -99, -103,
  112543. -109, -115, -999, -999, -999, -999, -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, -105, -97, -85, -72,
  112549. -74, -70, -70, -70, -76, -85, -91, -93,
  112550. -97, -103, -109, -115, -999, -999, -999, -999,
  112551. -999, -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, -112, -93, -81, -68,
  112556. -62, -60, -60, -57, -63, -70, -77, -82,
  112557. -90, -93, -98, -104, -109, -113, -999, -999,
  112558. -999, -999, -999, -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, -113, -100, -93, -84, -63,
  112563. -58, -48, -53, -54, -52, -52, -57, -64,
  112564. -66, -76, -83, -81, -85, -85, -90, -95,
  112565. -98, -101, -103, -106, -108, -111, -999, -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, -105, -95, -86, -74, -53,
  112570. -50, -38, -43, -49, -43, -42, -39, -39,
  112571. -46, -52, -57, -56, -72, -69, -74, -81,
  112572. -87, -92, -94, -97, -99, -102, -105, -108,
  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, -108, -99, -90, -76, -66, -45,
  112577. -43, -41, -44, -47, -43, -47, -40, -30,
  112578. -31, -31, -39, -33, -40, -41, -43, -53,
  112579. -59, -70, -73, -77, -79, -82, -84, -87,
  112580. -999, -999, -999, -999, -999, -999, -999, -999,
  112581. -999, -999, -999, -999, -999, -999, -999, -999}},
  112582. /* 4000 Hz */
  112583. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112584. -999, -999, -999, -999, -999, -110, -91, -76,
  112585. -75, -85, -93, -98, -104, -110, -999, -999,
  112586. -999, -999, -999, -999, -999, -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, -110, -91, -70,
  112592. -70, -75, -86, -89, -94, -98, -101, -106,
  112593. -110, -999, -999, -999, -999, -999, -999, -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, -110, -95, -80, -60,
  112599. -65, -64, -74, -83, -88, -91, -95, -99,
  112600. -103, -107, -110, -999, -999, -999, -999, -999,
  112601. -999, -999, -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, -110, -95, -80, -58,
  112606. -55, -49, -66, -68, -71, -78, -78, -80,
  112607. -88, -85, -89, -97, -100, -105, -110, -999,
  112608. -999, -999, -999, -999, -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, -110, -95, -80, -53,
  112613. -52, -41, -59, -59, -49, -58, -56, -63,
  112614. -86, -79, -90, -93, -98, -103, -107, -112,
  112615. -999, -999, -999, -999, -999, -999, -999, -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, -110, -97, -91, -73, -45,
  112620. -40, -33, -53, -61, -49, -54, -50, -50,
  112621. -60, -52, -67, -74, -81, -92, -96, -100,
  112622. -105, -110, -999, -999, -999, -999, -999, -999,
  112623. -999, -999, -999, -999, -999, -999, -999, -999,
  112624. -999, -999, -999, -999, -999, -999, -999, -999}},
  112625. /* 5657 Hz */
  112626. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112627. -999, -999, -999, -113, -106, -99, -92, -77,
  112628. -80, -88, -97, -106, -115, -999, -999, -999,
  112629. -999, -999, -999, -999, -999, -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, -116, -109, -102, -95, -89, -74,
  112635. -72, -88, -87, -95, -102, -109, -116, -999,
  112636. -999, -999, -999, -999, -999, -999, -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, -116, -109, -102, -95, -89, -75,
  112642. -66, -74, -77, -78, -86, -87, -90, -96,
  112643. -105, -115, -999, -999, -999, -999, -999, -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, -115, -108, -101, -94, -88, -66,
  112649. -56, -61, -70, -65, -78, -72, -83, -84,
  112650. -93, -98, -105, -110, -999, -999, -999, -999,
  112651. -999, -999, -999, -999, -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, -110, -105, -95, -89, -82, -57,
  112656. -52, -52, -59, -56, -59, -58, -69, -67,
  112657. -88, -82, -82, -89, -94, -100, -108, -999,
  112658. -999, -999, -999, -999, -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, -110, -101, -96, -90, -83, -77, -54,
  112663. -43, -38, -50, -48, -52, -48, -42, -42,
  112664. -51, -52, -53, -59, -65, -71, -78, -85,
  112665. -95, -999, -999, -999, -999, -999, -999, -999,
  112666. -999, -999, -999, -999, -999, -999, -999, -999,
  112667. -999, -999, -999, -999, -999, -999, -999, -999}},
  112668. /* 8000 Hz */
  112669. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112670. -999, -999, -999, -999, -120, -105, -86, -68,
  112671. -78, -79, -90, -100, -110, -999, -999, -999,
  112672. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -120, -105, -86, -66,
  112678. -73, -77, -88, -96, -105, -115, -999, -999,
  112679. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -120, -105, -92, -80, -61,
  112685. -64, -68, -80, -87, -92, -100, -110, -999,
  112686. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -120, -104, -91, -79, -52,
  112692. -60, -54, -64, -69, -77, -80, -82, -84,
  112693. -85, -87, -88, -90, -999, -999, -999, -999,
  112694. -999, -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, -118, -100, -87, -77, -49,
  112699. -50, -44, -58, -61, -61, -67, -65, -62,
  112700. -62, -62, -65, -68, -999, -999, -999, -999,
  112701. -999, -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, -115, -98, -84, -62, -49,
  112706. -44, -38, -46, -49, -49, -46, -39, -37,
  112707. -39, -40, -42, -43, -999, -999, -999, -999,
  112708. -999, -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. /* 11314 Hz */
  112712. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112713. -999, -999, -999, -999, -999, -110, -88, -74,
  112714. -77, -82, -82, -85, -90, -94, -99, -104,
  112715. -999, -999, -999, -999, -999, -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, -110, -88, -66,
  112721. -70, -81, -80, -81, -84, -88, -91, -93,
  112722. -999, -999, -999, -999, -999, -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, -110, -88, -61,
  112728. -63, -70, -71, -74, -77, -80, -83, -85,
  112729. -999, -999, -999, -999, -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, -110, -86, -62,
  112735. -63, -62, -62, -58, -52, -50, -50, -52,
  112736. -54, -999, -999, -999, -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, -118, -108, -84, -53,
  112742. -50, -50, -50, -55, -47, -45, -40, -40,
  112743. -40, -999, -999, -999, -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, -118, -100, -73, -43,
  112749. -37, -42, -43, -53, -38, -37, -35, -35,
  112750. -38, -999, -999, -999, -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. /* 16000 Hz */
  112755. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112756. -999, -999, -999, -110, -100, -91, -84, -74,
  112757. -80, -80, -80, -80, -80, -999, -999, -999,
  112758. -999, -999, -999, -999, -999, -999, -999, -999,
  112759. -999, -999, -999, -999, -999, -999, -999, -999,
  112760. -999, -999, -999, -999, -999, -999, -999, -999,
  112761. -999, -999, -999, -999, -999, -999, -999, -999},
  112762. {-999, -999, -999, -999, -999, -999, -999, -999,
  112763. -999, -999, -999, -110, -100, -91, -84, -74,
  112764. -68, -68, -68, -68, -68, -999, -999, -999,
  112765. -999, -999, -999, -999, -999, -999, -999, -999,
  112766. -999, -999, -999, -999, -999, -999, -999, -999,
  112767. -999, -999, -999, -999, -999, -999, -999, -999,
  112768. -999, -999, -999, -999, -999, -999, -999, -999},
  112769. {-999, -999, -999, -999, -999, -999, -999, -999,
  112770. -999, -999, -999, -110, -100, -86, -78, -70,
  112771. -60, -45, -30, -21, -999, -999, -999, -999,
  112772. -999, -999, -999, -999, -999, -999, -999, -999,
  112773. -999, -999, -999, -999, -999, -999, -999, -999,
  112774. -999, -999, -999, -999, -999, -999, -999, -999,
  112775. -999, -999, -999, -999, -999, -999, -999, -999},
  112776. {-999, -999, -999, -999, -999, -999, -999, -999,
  112777. -999, -999, -999, -110, -100, -87, -78, -67,
  112778. -48, -38, -29, -21, -999, -999, -999, -999,
  112779. -999, -999, -999, -999, -999, -999, -999, -999,
  112780. -999, -999, -999, -999, -999, -999, -999, -999,
  112781. -999, -999, -999, -999, -999, -999, -999, -999,
  112782. -999, -999, -999, -999, -999, -999, -999, -999},
  112783. {-999, -999, -999, -999, -999, -999, -999, -999,
  112784. -999, -999, -999, -110, -100, -86, -69, -56,
  112785. -45, -35, -33, -29, -999, -999, -999, -999,
  112786. -999, -999, -999, -999, -999, -999, -999, -999,
  112787. -999, -999, -999, -999, -999, -999, -999, -999,
  112788. -999, -999, -999, -999, -999, -999, -999, -999,
  112789. -999, -999, -999, -999, -999, -999, -999, -999},
  112790. {-999, -999, -999, -999, -999, -999, -999, -999,
  112791. -999, -999, -999, -110, -100, -83, -71, -48,
  112792. -27, -38, -37, -34, -999, -999, -999, -999,
  112793. -999, -999, -999, -999, -999, -999, -999, -999,
  112794. -999, -999, -999, -999, -999, -999, -999, -999,
  112795. -999, -999, -999, -999, -999, -999, -999, -999,
  112796. -999, -999, -999, -999, -999, -999, -999, -999}}
  112797. };
  112798. #endif
  112799. /********* End of inlined file: masking.h *********/
  112800. #define NEGINF -9999.f
  112801. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  112802. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  112803. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  112804. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112805. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112806. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  112807. look->channels=vi->channels;
  112808. look->ampmax=-9999.;
  112809. look->gi=gi;
  112810. return(look);
  112811. }
  112812. void _vp_global_free(vorbis_look_psy_global *look){
  112813. if(look){
  112814. memset(look,0,sizeof(*look));
  112815. _ogg_free(look);
  112816. }
  112817. }
  112818. void _vi_gpsy_free(vorbis_info_psy_global *i){
  112819. if(i){
  112820. memset(i,0,sizeof(*i));
  112821. _ogg_free(i);
  112822. }
  112823. }
  112824. void _vi_psy_free(vorbis_info_psy *i){
  112825. if(i){
  112826. memset(i,0,sizeof(*i));
  112827. _ogg_free(i);
  112828. }
  112829. }
  112830. static void min_curve(float *c,
  112831. float *c2){
  112832. int i;
  112833. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  112834. }
  112835. static void max_curve(float *c,
  112836. float *c2){
  112837. int i;
  112838. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  112839. }
  112840. static void attenuate_curve(float *c,float att){
  112841. int i;
  112842. for(i=0;i<EHMER_MAX;i++)
  112843. c[i]+=att;
  112844. }
  112845. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  112846. float center_boost, float center_decay_rate){
  112847. int i,j,k,m;
  112848. float ath[EHMER_MAX];
  112849. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  112850. float athc[P_LEVELS][EHMER_MAX];
  112851. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  112852. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  112853. memset(workc,0,sizeof(workc));
  112854. for(i=0;i<P_BANDS;i++){
  112855. /* we add back in the ATH to avoid low level curves falling off to
  112856. -infinity and unnecessarily cutting off high level curves in the
  112857. curve limiting (last step). */
  112858. /* A half-band's settings must be valid over the whole band, and
  112859. it's better to mask too little than too much */
  112860. int ath_offset=i*4;
  112861. for(j=0;j<EHMER_MAX;j++){
  112862. float min=999.;
  112863. for(k=0;k<4;k++)
  112864. if(j+k+ath_offset<MAX_ATH){
  112865. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  112866. }else{
  112867. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  112868. }
  112869. ath[j]=min;
  112870. }
  112871. /* copy curves into working space, replicate the 50dB curve to 30
  112872. and 40, replicate the 100dB curve to 110 */
  112873. for(j=0;j<6;j++)
  112874. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  112875. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112876. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112877. /* apply centered curve boost/decay */
  112878. for(j=0;j<P_LEVELS;j++){
  112879. for(k=0;k<EHMER_MAX;k++){
  112880. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  112881. if(adj<0. && center_boost>0)adj=0.;
  112882. if(adj>0. && center_boost<0)adj=0.;
  112883. workc[i][j][k]+=adj;
  112884. }
  112885. }
  112886. /* normalize curves so the driving amplitude is 0dB */
  112887. /* make temp curves with the ATH overlayed */
  112888. for(j=0;j<P_LEVELS;j++){
  112889. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  112890. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  112891. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  112892. max_curve(athc[j],workc[i][j]);
  112893. }
  112894. /* Now limit the louder curves.
  112895. the idea is this: We don't know what the playback attenuation
  112896. will be; 0dB SL moves every time the user twiddles the volume
  112897. knob. So that means we have to use a single 'most pessimal' curve
  112898. for all masking amplitudes, right? Wrong. The *loudest* sound
  112899. can be in (we assume) a range of ...+100dB] SL. However, sounds
  112900. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  112901. etc... */
  112902. for(j=1;j<P_LEVELS;j++){
  112903. min_curve(athc[j],athc[j-1]);
  112904. min_curve(workc[i][j],athc[j]);
  112905. }
  112906. }
  112907. for(i=0;i<P_BANDS;i++){
  112908. int hi_curve,lo_curve,bin;
  112909. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  112910. /* low frequency curves are measured with greater resolution than
  112911. the MDCT/FFT will actually give us; we want the curve applied
  112912. to the tone data to be pessimistic and thus apply the minimum
  112913. masking possible for a given bin. That means that a single bin
  112914. could span more than one octave and that the curve will be a
  112915. composite of multiple octaves. It also may mean that a single
  112916. bin may span > an eighth of an octave and that the eighth
  112917. octave values may also be composited. */
  112918. /* which octave curves will we be compositing? */
  112919. bin=floor(fromOC(i*.5)/binHz);
  112920. lo_curve= ceil(toOC(bin*binHz+1)*2);
  112921. hi_curve= floor(toOC((bin+1)*binHz)*2);
  112922. if(lo_curve>i)lo_curve=i;
  112923. if(lo_curve<0)lo_curve=0;
  112924. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  112925. for(m=0;m<P_LEVELS;m++){
  112926. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  112927. for(j=0;j<n;j++)brute_buffer[j]=999.;
  112928. /* render the curve into bins, then pull values back into curve.
  112929. The point is that any inherent subsampling aliasing results in
  112930. a safe minimum */
  112931. for(k=lo_curve;k<=hi_curve;k++){
  112932. int l=0;
  112933. for(j=0;j<EHMER_MAX;j++){
  112934. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  112935. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  112936. if(lo_bin<0)lo_bin=0;
  112937. if(lo_bin>n)lo_bin=n;
  112938. if(lo_bin<l)l=lo_bin;
  112939. if(hi_bin<0)hi_bin=0;
  112940. if(hi_bin>n)hi_bin=n;
  112941. for(;l<hi_bin && l<n;l++)
  112942. if(brute_buffer[l]>workc[k][m][j])
  112943. brute_buffer[l]=workc[k][m][j];
  112944. }
  112945. for(;l<n;l++)
  112946. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112947. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112948. }
  112949. /* be equally paranoid about being valid up to next half ocatve */
  112950. if(i+1<P_BANDS){
  112951. int l=0;
  112952. k=i+1;
  112953. for(j=0;j<EHMER_MAX;j++){
  112954. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  112955. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  112956. if(lo_bin<0)lo_bin=0;
  112957. if(lo_bin>n)lo_bin=n;
  112958. if(lo_bin<l)l=lo_bin;
  112959. if(hi_bin<0)hi_bin=0;
  112960. if(hi_bin>n)hi_bin=n;
  112961. for(;l<hi_bin && l<n;l++)
  112962. if(brute_buffer[l]>workc[k][m][j])
  112963. brute_buffer[l]=workc[k][m][j];
  112964. }
  112965. for(;l<n;l++)
  112966. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112967. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112968. }
  112969. for(j=0;j<EHMER_MAX;j++){
  112970. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  112971. if(bin<0){
  112972. ret[i][m][j+2]=-999.;
  112973. }else{
  112974. if(bin>=n){
  112975. ret[i][m][j+2]=-999.;
  112976. }else{
  112977. ret[i][m][j+2]=brute_buffer[bin];
  112978. }
  112979. }
  112980. }
  112981. /* add fenceposts */
  112982. for(j=0;j<EHMER_OFFSET;j++)
  112983. if(ret[i][m][j+2]>-200.f)break;
  112984. ret[i][m][0]=j;
  112985. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  112986. if(ret[i][m][j+2]>-200.f)
  112987. break;
  112988. ret[i][m][1]=j;
  112989. }
  112990. }
  112991. return(ret);
  112992. }
  112993. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  112994. vorbis_info_psy_global *gi,int n,long rate){
  112995. long i,j,lo=-99,hi=1;
  112996. long maxoc;
  112997. memset(p,0,sizeof(*p));
  112998. p->eighth_octave_lines=gi->eighth_octave_lines;
  112999. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  113000. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  113001. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  113002. p->total_octave_lines=maxoc-p->firstoc+1;
  113003. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  113004. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  113005. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  113006. p->vi=vi;
  113007. p->n=n;
  113008. p->rate=rate;
  113009. /* AoTuV HF weighting */
  113010. p->m_val = 1.;
  113011. if(rate < 26000) p->m_val = 0;
  113012. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  113013. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  113014. /* set up the lookups for a given blocksize and sample rate */
  113015. for(i=0,j=0;i<MAX_ATH-1;i++){
  113016. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  113017. float base=ATH[i];
  113018. if(j<endpos){
  113019. float delta=(ATH[i+1]-base)/(endpos-j);
  113020. for(;j<endpos && j<n;j++){
  113021. p->ath[j]=base+100.;
  113022. base+=delta;
  113023. }
  113024. }
  113025. }
  113026. for(i=0;i<n;i++){
  113027. float bark=toBARK(rate/(2*n)*i);
  113028. for(;lo+vi->noisewindowlomin<i &&
  113029. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  113030. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  113031. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  113032. p->bark[i]=((lo-1)<<16)+(hi-1);
  113033. }
  113034. for(i=0;i<n;i++)
  113035. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  113036. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  113037. vi->tone_centerboost,vi->tone_decay);
  113038. /* set up rolling noise median */
  113039. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  113040. for(i=0;i<P_NOISECURVES;i++)
  113041. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  113042. for(i=0;i<n;i++){
  113043. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  113044. int inthalfoc;
  113045. float del;
  113046. if(halfoc<0)halfoc=0;
  113047. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  113048. inthalfoc=(int)halfoc;
  113049. del=halfoc-inthalfoc;
  113050. for(j=0;j<P_NOISECURVES;j++)
  113051. p->noiseoffset[j][i]=
  113052. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  113053. p->vi->noiseoff[j][inthalfoc+1]*del;
  113054. }
  113055. #if 0
  113056. {
  113057. static int ls=0;
  113058. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  113059. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  113060. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  113061. }
  113062. #endif
  113063. }
  113064. void _vp_psy_clear(vorbis_look_psy *p){
  113065. int i,j;
  113066. if(p){
  113067. if(p->ath)_ogg_free(p->ath);
  113068. if(p->octave)_ogg_free(p->octave);
  113069. if(p->bark)_ogg_free(p->bark);
  113070. if(p->tonecurves){
  113071. for(i=0;i<P_BANDS;i++){
  113072. for(j=0;j<P_LEVELS;j++){
  113073. _ogg_free(p->tonecurves[i][j]);
  113074. }
  113075. _ogg_free(p->tonecurves[i]);
  113076. }
  113077. _ogg_free(p->tonecurves);
  113078. }
  113079. if(p->noiseoffset){
  113080. for(i=0;i<P_NOISECURVES;i++){
  113081. _ogg_free(p->noiseoffset[i]);
  113082. }
  113083. _ogg_free(p->noiseoffset);
  113084. }
  113085. memset(p,0,sizeof(*p));
  113086. }
  113087. }
  113088. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  113089. static void seed_curve(float *seed,
  113090. const float **curves,
  113091. float amp,
  113092. int oc, int n,
  113093. int linesper,float dBoffset){
  113094. int i,post1;
  113095. int seedptr;
  113096. const float *posts,*curve;
  113097. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  113098. choice=max(choice,0);
  113099. choice=min(choice,P_LEVELS-1);
  113100. posts=curves[choice];
  113101. curve=posts+2;
  113102. post1=(int)posts[1];
  113103. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  113104. for(i=posts[0];i<post1;i++){
  113105. if(seedptr>0){
  113106. float lin=amp+curve[i];
  113107. if(seed[seedptr]<lin)seed[seedptr]=lin;
  113108. }
  113109. seedptr+=linesper;
  113110. if(seedptr>=n)break;
  113111. }
  113112. }
  113113. static void seed_loop(vorbis_look_psy *p,
  113114. const float ***curves,
  113115. const float *f,
  113116. const float *flr,
  113117. float *seed,
  113118. float specmax){
  113119. vorbis_info_psy *vi=p->vi;
  113120. long n=p->n,i;
  113121. float dBoffset=vi->max_curve_dB-specmax;
  113122. /* prime the working vector with peak values */
  113123. for(i=0;i<n;i++){
  113124. float max=f[i];
  113125. long oc=p->octave[i];
  113126. while(i+1<n && p->octave[i+1]==oc){
  113127. i++;
  113128. if(f[i]>max)max=f[i];
  113129. }
  113130. if(max+6.f>flr[i]){
  113131. oc=oc>>p->shiftoc;
  113132. if(oc>=P_BANDS)oc=P_BANDS-1;
  113133. if(oc<0)oc=0;
  113134. seed_curve(seed,
  113135. curves[oc],
  113136. max,
  113137. p->octave[i]-p->firstoc,
  113138. p->total_octave_lines,
  113139. p->eighth_octave_lines,
  113140. dBoffset);
  113141. }
  113142. }
  113143. }
  113144. static void seed_chase(float *seeds, int linesper, long n){
  113145. long *posstack=(long*)alloca(n*sizeof(*posstack));
  113146. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  113147. long stack=0;
  113148. long pos=0;
  113149. long i;
  113150. for(i=0;i<n;i++){
  113151. if(stack<2){
  113152. posstack[stack]=i;
  113153. ampstack[stack++]=seeds[i];
  113154. }else{
  113155. while(1){
  113156. if(seeds[i]<ampstack[stack-1]){
  113157. posstack[stack]=i;
  113158. ampstack[stack++]=seeds[i];
  113159. break;
  113160. }else{
  113161. if(i<posstack[stack-1]+linesper){
  113162. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  113163. i<posstack[stack-2]+linesper){
  113164. /* we completely overlap, making stack-1 irrelevant. pop it */
  113165. stack--;
  113166. continue;
  113167. }
  113168. }
  113169. posstack[stack]=i;
  113170. ampstack[stack++]=seeds[i];
  113171. break;
  113172. }
  113173. }
  113174. }
  113175. }
  113176. /* the stack now contains only the positions that are relevant. Scan
  113177. 'em straight through */
  113178. for(i=0;i<stack;i++){
  113179. long endpos;
  113180. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  113181. endpos=posstack[i+1];
  113182. }else{
  113183. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  113184. discarded in short frames */
  113185. }
  113186. if(endpos>n)endpos=n;
  113187. for(;pos<endpos;pos++)
  113188. seeds[pos]=ampstack[i];
  113189. }
  113190. /* there. Linear time. I now remember this was on a problem set I
  113191. had in Grad Skool... I didn't solve it at the time ;-) */
  113192. }
  113193. /* bleaugh, this is more complicated than it needs to be */
  113194. #include<stdio.h>
  113195. static void max_seeds(vorbis_look_psy *p,
  113196. float *seed,
  113197. float *flr){
  113198. long n=p->total_octave_lines;
  113199. int linesper=p->eighth_octave_lines;
  113200. long linpos=0;
  113201. long pos;
  113202. seed_chase(seed,linesper,n); /* for masking */
  113203. pos=p->octave[0]-p->firstoc-(linesper>>1);
  113204. while(linpos+1<p->n){
  113205. float minV=seed[pos];
  113206. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  113207. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  113208. while(pos+1<=end){
  113209. pos++;
  113210. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  113211. minV=seed[pos];
  113212. }
  113213. end=pos+p->firstoc;
  113214. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  113215. if(flr[linpos]<minV)flr[linpos]=minV;
  113216. }
  113217. {
  113218. float minV=seed[p->total_octave_lines-1];
  113219. for(;linpos<p->n;linpos++)
  113220. if(flr[linpos]<minV)flr[linpos]=minV;
  113221. }
  113222. }
  113223. static void bark_noise_hybridmp(int n,const long *b,
  113224. const float *f,
  113225. float *noise,
  113226. const float offset,
  113227. const int fixed){
  113228. float *N=(float*) alloca(n*sizeof(*N));
  113229. float *X=(float*) alloca(n*sizeof(*N));
  113230. float *XX=(float*) alloca(n*sizeof(*N));
  113231. float *Y=(float*) alloca(n*sizeof(*N));
  113232. float *XY=(float*) alloca(n*sizeof(*N));
  113233. float tN, tX, tXX, tY, tXY;
  113234. int i;
  113235. int lo, hi;
  113236. float R, A, B, D;
  113237. float w, x, y;
  113238. tN = tX = tXX = tY = tXY = 0.f;
  113239. y = f[0] + offset;
  113240. if (y < 1.f) y = 1.f;
  113241. w = y * y * .5;
  113242. tN += w;
  113243. tX += w;
  113244. tY += w * y;
  113245. N[0] = tN;
  113246. X[0] = tX;
  113247. XX[0] = tXX;
  113248. Y[0] = tY;
  113249. XY[0] = tXY;
  113250. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  113251. y = f[i] + offset;
  113252. if (y < 1.f) y = 1.f;
  113253. w = y * y;
  113254. tN += w;
  113255. tX += w * x;
  113256. tXX += w * x * x;
  113257. tY += w * y;
  113258. tXY += w * x * y;
  113259. N[i] = tN;
  113260. X[i] = tX;
  113261. XX[i] = tXX;
  113262. Y[i] = tY;
  113263. XY[i] = tXY;
  113264. }
  113265. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113266. lo = b[i] >> 16;
  113267. if( lo>=0 ) break;
  113268. hi = b[i] & 0xffff;
  113269. tN = N[hi] + N[-lo];
  113270. tX = X[hi] - X[-lo];
  113271. tXX = XX[hi] + XX[-lo];
  113272. tY = Y[hi] + Y[-lo];
  113273. tXY = XY[hi] - XY[-lo];
  113274. A = tY * tXX - tX * tXY;
  113275. B = tN * tXY - tX * tY;
  113276. D = tN * tXX - tX * tX;
  113277. R = (A + x * B) / D;
  113278. if (R < 0.f)
  113279. R = 0.f;
  113280. noise[i] = R - offset;
  113281. }
  113282. for ( ;; i++, x += 1.f) {
  113283. lo = b[i] >> 16;
  113284. hi = b[i] & 0xffff;
  113285. if(hi>=n)break;
  113286. tN = N[hi] - N[lo];
  113287. tX = X[hi] - X[lo];
  113288. tXX = XX[hi] - XX[lo];
  113289. tY = Y[hi] - Y[lo];
  113290. tXY = XY[hi] - XY[lo];
  113291. A = tY * tXX - tX * tXY;
  113292. B = tN * tXY - tX * tY;
  113293. D = tN * tXX - tX * tX;
  113294. R = (A + x * B) / D;
  113295. if (R < 0.f) R = 0.f;
  113296. noise[i] = R - offset;
  113297. }
  113298. for ( ; i < n; i++, x += 1.f) {
  113299. R = (A + x * B) / D;
  113300. if (R < 0.f) R = 0.f;
  113301. noise[i] = R - offset;
  113302. }
  113303. if (fixed <= 0) return;
  113304. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113305. hi = i + fixed / 2;
  113306. lo = hi - fixed;
  113307. if(lo>=0)break;
  113308. tN = N[hi] + N[-lo];
  113309. tX = X[hi] - X[-lo];
  113310. tXX = XX[hi] + XX[-lo];
  113311. tY = Y[hi] + Y[-lo];
  113312. tXY = XY[hi] - XY[-lo];
  113313. A = tY * tXX - tX * tXY;
  113314. B = tN * tXY - tX * tY;
  113315. D = tN * tXX - tX * tX;
  113316. R = (A + x * B) / D;
  113317. if (R - offset < noise[i]) noise[i] = R - offset;
  113318. }
  113319. for ( ;; i++, x += 1.f) {
  113320. hi = i + fixed / 2;
  113321. lo = hi - fixed;
  113322. if(hi>=n)break;
  113323. tN = N[hi] - N[lo];
  113324. tX = X[hi] - X[lo];
  113325. tXX = XX[hi] - XX[lo];
  113326. tY = Y[hi] - Y[lo];
  113327. tXY = XY[hi] - XY[lo];
  113328. A = tY * tXX - tX * tXY;
  113329. B = tN * tXY - tX * tY;
  113330. D = tN * tXX - tX * tX;
  113331. R = (A + x * B) / D;
  113332. if (R - offset < noise[i]) noise[i] = R - offset;
  113333. }
  113334. for ( ; i < n; i++, x += 1.f) {
  113335. R = (A + x * B) / D;
  113336. if (R - offset < noise[i]) noise[i] = R - offset;
  113337. }
  113338. }
  113339. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  113340. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  113341. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  113342. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  113343. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  113344. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  113345. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  113346. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  113347. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  113348. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  113349. 973377.F, 913981.F, 858210.F, 805842.F,
  113350. 756669.F, 710497.F, 667142.F, 626433.F,
  113351. 588208.F, 552316.F, 518613.F, 486967.F,
  113352. 457252.F, 429351.F, 403152.F, 378551.F,
  113353. 355452.F, 333762.F, 313396.F, 294273.F,
  113354. 276316.F, 259455.F, 243623.F, 228757.F,
  113355. 214798.F, 201691.F, 189384.F, 177828.F,
  113356. 166977.F, 156788.F, 147221.F, 138237.F,
  113357. 129802.F, 121881.F, 114444.F, 107461.F,
  113358. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  113359. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  113360. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  113361. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  113362. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  113363. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  113364. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  113365. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  113366. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  113367. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  113368. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  113369. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  113370. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  113371. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  113372. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  113373. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  113374. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  113375. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  113376. 1084.32F, 1018.15F, 956.024F, 897.687F,
  113377. 842.910F, 791.475F, 743.179F, 697.830F,
  113378. 655.249F, 615.265F, 577.722F, 542.469F,
  113379. 509.367F, 478.286F, 449.101F, 421.696F,
  113380. 395.964F, 371.803F, 349.115F, 327.812F,
  113381. 307.809F, 289.026F, 271.390F, 254.830F,
  113382. 239.280F, 224.679F, 210.969F, 198.096F,
  113383. 186.008F, 174.658F, 164.000F, 153.993F,
  113384. 144.596F, 135.773F, 127.488F, 119.708F,
  113385. 112.404F, 105.545F, 99.1046F, 93.0572F,
  113386. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  113387. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  113388. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  113389. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  113390. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  113391. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  113392. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  113393. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  113394. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  113395. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  113396. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  113397. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  113398. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  113399. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  113400. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  113401. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  113402. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  113403. 1.20790F, 1.13419F, 1.06499F, 1.F
  113404. };
  113405. void _vp_remove_floor(vorbis_look_psy *p,
  113406. float *mdct,
  113407. int *codedflr,
  113408. float *residue,
  113409. int sliding_lowpass){
  113410. int i,n=p->n;
  113411. if(sliding_lowpass>n)sliding_lowpass=n;
  113412. for(i=0;i<sliding_lowpass;i++){
  113413. residue[i]=
  113414. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  113415. }
  113416. for(;i<n;i++)
  113417. residue[i]=0.;
  113418. }
  113419. void _vp_noisemask(vorbis_look_psy *p,
  113420. float *logmdct,
  113421. float *logmask){
  113422. int i,n=p->n;
  113423. float *work=(float*) alloca(n*sizeof(*work));
  113424. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  113425. 140.,-1);
  113426. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  113427. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  113428. p->vi->noisewindowfixed);
  113429. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  113430. #if 0
  113431. {
  113432. static int seq=0;
  113433. float work2[n];
  113434. for(i=0;i<n;i++){
  113435. work2[i]=logmask[i]+work[i];
  113436. }
  113437. if(seq&1)
  113438. _analysis_output("median2R",seq/2,work,n,1,0,0);
  113439. else
  113440. _analysis_output("median2L",seq/2,work,n,1,0,0);
  113441. if(seq&1)
  113442. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  113443. else
  113444. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  113445. seq++;
  113446. }
  113447. #endif
  113448. for(i=0;i<n;i++){
  113449. int dB=logmask[i]+.5;
  113450. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  113451. if(dB<0)dB=0;
  113452. logmask[i]= work[i]+p->vi->noisecompand[dB];
  113453. }
  113454. }
  113455. void _vp_tonemask(vorbis_look_psy *p,
  113456. float *logfft,
  113457. float *logmask,
  113458. float global_specmax,
  113459. float local_specmax){
  113460. int i,n=p->n;
  113461. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  113462. float att=local_specmax+p->vi->ath_adjatt;
  113463. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  113464. /* set the ATH (floating below localmax, not global max by a
  113465. specified att) */
  113466. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  113467. for(i=0;i<n;i++)
  113468. logmask[i]=p->ath[i]+att;
  113469. /* tone masking */
  113470. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  113471. max_seeds(p,seed,logmask);
  113472. }
  113473. void _vp_offset_and_mix(vorbis_look_psy *p,
  113474. float *noise,
  113475. float *tone,
  113476. int offset_select,
  113477. float *logmask,
  113478. float *mdct,
  113479. float *logmdct){
  113480. int i,n=p->n;
  113481. float de, coeffi, cx;/* AoTuV */
  113482. float toneatt=p->vi->tone_masteratt[offset_select];
  113483. cx = p->m_val;
  113484. for(i=0;i<n;i++){
  113485. float val= noise[i]+p->noiseoffset[offset_select][i];
  113486. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  113487. logmask[i]=max(val,tone[i]+toneatt);
  113488. /* AoTuV */
  113489. /** @ M1 **
  113490. The following codes improve a noise problem.
  113491. A fundamental idea uses the value of masking and carries out
  113492. the relative compensation of the MDCT.
  113493. However, this code is not perfect and all noise problems cannot be solved.
  113494. by Aoyumi @ 2004/04/18
  113495. */
  113496. if(offset_select == 1) {
  113497. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  113498. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  113499. if(val > coeffi){
  113500. /* mdct value is > -17.2 dB below floor */
  113501. de = 1.0-((val-coeffi)*0.005*cx);
  113502. /* pro-rated attenuation:
  113503. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  113504. -0.77 dB boost if mdct value is 0dB (relative to floor)
  113505. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  113506. etc... */
  113507. if(de < 0) de = 0.0001;
  113508. }else
  113509. /* mdct value is <= -17.2 dB below floor */
  113510. de = 1.0-((val-coeffi)*0.0003*cx);
  113511. /* pro-rated attenuation:
  113512. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  113513. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  113514. etc... */
  113515. mdct[i] *= de;
  113516. }
  113517. }
  113518. }
  113519. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  113520. vorbis_info *vi=vd->vi;
  113521. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113522. vorbis_info_psy_global *gi=&ci->psy_g_param;
  113523. int n=ci->blocksizes[vd->W]/2;
  113524. float secs=(float)n/vi->rate;
  113525. amp+=secs*gi->ampmax_att_per_sec;
  113526. if(amp<-9999)amp=-9999;
  113527. return(amp);
  113528. }
  113529. static void couple_lossless(float A, float B,
  113530. float *qA, float *qB){
  113531. int test1=fabs(*qA)>fabs(*qB);
  113532. test1-= fabs(*qA)<fabs(*qB);
  113533. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  113534. if(test1==1){
  113535. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  113536. }else{
  113537. float temp=*qB;
  113538. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  113539. *qA=temp;
  113540. }
  113541. if(*qB>fabs(*qA)*1.9999f){
  113542. *qB= -fabs(*qA)*2.f;
  113543. *qA= -*qA;
  113544. }
  113545. }
  113546. static float hypot_lookup[32]={
  113547. -0.009935, -0.011245, -0.012726, -0.014397,
  113548. -0.016282, -0.018407, -0.020800, -0.023494,
  113549. -0.026522, -0.029923, -0.033737, -0.038010,
  113550. -0.042787, -0.048121, -0.054064, -0.060671,
  113551. -0.068000, -0.076109, -0.085054, -0.094892,
  113552. -0.105675, -0.117451, -0.130260, -0.144134,
  113553. -0.159093, -0.175146, -0.192286, -0.210490,
  113554. -0.229718, -0.249913, -0.271001, -0.292893};
  113555. static void precomputed_couple_point(float premag,
  113556. int floorA,int floorB,
  113557. float *mag, float *ang){
  113558. int test=(floorA>floorB)-1;
  113559. int offset=31-abs(floorA-floorB);
  113560. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  113561. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  113562. *mag=premag*floormag;
  113563. *ang=0.f;
  113564. }
  113565. /* just like below, this is currently set up to only do
  113566. single-step-depth coupling. Otherwise, we'd have to do more
  113567. copying (which will be inevitable later) */
  113568. /* doing the real circular magnitude calculation is audibly superior
  113569. to (A+B)/sqrt(2) */
  113570. static float dipole_hypot(float a, float b){
  113571. if(a>0.){
  113572. if(b>0.)return sqrt(a*a+b*b);
  113573. if(a>-b)return sqrt(a*a-b*b);
  113574. return -sqrt(b*b-a*a);
  113575. }
  113576. if(b<0.)return -sqrt(a*a+b*b);
  113577. if(-a>b)return -sqrt(a*a-b*b);
  113578. return sqrt(b*b-a*a);
  113579. }
  113580. static float round_hypot(float a, float b){
  113581. if(a>0.){
  113582. if(b>0.)return sqrt(a*a+b*b);
  113583. if(a>-b)return sqrt(a*a+b*b);
  113584. return -sqrt(b*b+a*a);
  113585. }
  113586. if(b<0.)return -sqrt(a*a+b*b);
  113587. if(-a>b)return -sqrt(a*a+b*b);
  113588. return sqrt(b*b+a*a);
  113589. }
  113590. /* revert to round hypot for now */
  113591. float **_vp_quantize_couple_memo(vorbis_block *vb,
  113592. vorbis_info_psy_global *g,
  113593. vorbis_look_psy *p,
  113594. vorbis_info_mapping0 *vi,
  113595. float **mdct){
  113596. int i,j,n=p->n;
  113597. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113598. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113599. for(i=0;i<vi->coupling_steps;i++){
  113600. float *mdctM=mdct[vi->coupling_mag[i]];
  113601. float *mdctA=mdct[vi->coupling_ang[i]];
  113602. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113603. for(j=0;j<limit;j++)
  113604. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  113605. for(;j<n;j++)
  113606. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  113607. }
  113608. return(ret);
  113609. }
  113610. /* this is for per-channel noise normalization */
  113611. static int apsort(const void *a, const void *b){
  113612. float f1=fabs(**(float**)a);
  113613. float f2=fabs(**(float**)b);
  113614. return (f1<f2)-(f1>f2);
  113615. }
  113616. int **_vp_quantize_couple_sort(vorbis_block *vb,
  113617. vorbis_look_psy *p,
  113618. vorbis_info_mapping0 *vi,
  113619. float **mags){
  113620. if(p->vi->normal_point_p){
  113621. int i,j,k,n=p->n;
  113622. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113623. int partition=p->vi->normal_partition;
  113624. float **work=(float**) alloca(sizeof(*work)*partition);
  113625. for(i=0;i<vi->coupling_steps;i++){
  113626. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113627. for(j=0;j<n;j+=partition){
  113628. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  113629. qsort(work,partition,sizeof(*work),apsort);
  113630. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  113631. }
  113632. }
  113633. return(ret);
  113634. }
  113635. return(NULL);
  113636. }
  113637. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  113638. float *magnitudes,int *sortedindex){
  113639. int i,j,n=p->n;
  113640. vorbis_info_psy *vi=p->vi;
  113641. int partition=vi->normal_partition;
  113642. float **work=(float**) alloca(sizeof(*work)*partition);
  113643. int start=vi->normal_start;
  113644. for(j=start;j<n;j+=partition){
  113645. if(j+partition>n)partition=n-j;
  113646. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  113647. qsort(work,partition,sizeof(*work),apsort);
  113648. for(i=0;i<partition;i++){
  113649. sortedindex[i+j-start]=work[i]-magnitudes;
  113650. }
  113651. }
  113652. }
  113653. void _vp_noise_normalize(vorbis_look_psy *p,
  113654. float *in,float *out,int *sortedindex){
  113655. int flag=0,i,j=0,n=p->n;
  113656. vorbis_info_psy *vi=p->vi;
  113657. int partition=vi->normal_partition;
  113658. int start=vi->normal_start;
  113659. if(start>n)start=n;
  113660. if(vi->normal_channel_p){
  113661. for(;j<start;j++)
  113662. out[j]=rint(in[j]);
  113663. for(;j+partition<=n;j+=partition){
  113664. float acc=0.;
  113665. int k;
  113666. for(i=j;i<j+partition;i++)
  113667. acc+=in[i]*in[i];
  113668. for(i=0;i<partition;i++){
  113669. k=sortedindex[i+j-start];
  113670. if(in[k]*in[k]>=.25f){
  113671. out[k]=rint(in[k]);
  113672. acc-=in[k]*in[k];
  113673. flag=1;
  113674. }else{
  113675. if(acc<vi->normal_thresh)break;
  113676. out[k]=unitnorm(in[k]);
  113677. acc-=1.;
  113678. }
  113679. }
  113680. for(;i<partition;i++){
  113681. k=sortedindex[i+j-start];
  113682. out[k]=0.;
  113683. }
  113684. }
  113685. }
  113686. for(;j<n;j++)
  113687. out[j]=rint(in[j]);
  113688. }
  113689. void _vp_couple(int blobno,
  113690. vorbis_info_psy_global *g,
  113691. vorbis_look_psy *p,
  113692. vorbis_info_mapping0 *vi,
  113693. float **res,
  113694. float **mag_memo,
  113695. int **mag_sort,
  113696. int **ifloor,
  113697. int *nonzero,
  113698. int sliding_lowpass){
  113699. int i,j,k,n=p->n;
  113700. /* perform any requested channel coupling */
  113701. /* point stereo can only be used in a first stage (in this encoder)
  113702. because of the dependency on floor lookups */
  113703. for(i=0;i<vi->coupling_steps;i++){
  113704. /* once we're doing multistage coupling in which a channel goes
  113705. through more than one coupling step, the floor vector
  113706. magnitudes will also have to be recalculated an propogated
  113707. along with PCM. Right now, we're not (that will wait until 5.1
  113708. most likely), so the code isn't here yet. The memory management
  113709. here is all assuming single depth couplings anyway. */
  113710. /* make sure coupling a zero and a nonzero channel results in two
  113711. nonzero channels. */
  113712. if(nonzero[vi->coupling_mag[i]] ||
  113713. nonzero[vi->coupling_ang[i]]){
  113714. float *rM=res[vi->coupling_mag[i]];
  113715. float *rA=res[vi->coupling_ang[i]];
  113716. float *qM=rM+n;
  113717. float *qA=rA+n;
  113718. int *floorM=ifloor[vi->coupling_mag[i]];
  113719. int *floorA=ifloor[vi->coupling_ang[i]];
  113720. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  113721. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  113722. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  113723. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  113724. int pointlimit=limit;
  113725. nonzero[vi->coupling_mag[i]]=1;
  113726. nonzero[vi->coupling_ang[i]]=1;
  113727. /* The threshold of a stereo is changed with the size of n */
  113728. if(n > 1000)
  113729. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  113730. for(j=0;j<p->n;j+=partition){
  113731. float acc=0.f;
  113732. for(k=0;k<partition;k++){
  113733. int l=k+j;
  113734. if(l<sliding_lowpass){
  113735. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  113736. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  113737. precomputed_couple_point(mag_memo[i][l],
  113738. floorM[l],floorA[l],
  113739. qM+l,qA+l);
  113740. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  113741. }else{
  113742. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  113743. }
  113744. }else{
  113745. qM[l]=0.;
  113746. qA[l]=0.;
  113747. }
  113748. }
  113749. if(p->vi->normal_point_p){
  113750. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  113751. int l=mag_sort[i][j+k];
  113752. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  113753. qM[l]=unitnorm(qM[l]);
  113754. acc-=1.f;
  113755. }
  113756. }
  113757. }
  113758. }
  113759. }
  113760. }
  113761. }
  113762. /* AoTuV */
  113763. /** @ M2 **
  113764. The boost problem by the combination of noise normalization and point stereo is eased.
  113765. However, this is a temporary patch.
  113766. by Aoyumi @ 2004/04/18
  113767. */
  113768. void hf_reduction(vorbis_info_psy_global *g,
  113769. vorbis_look_psy *p,
  113770. vorbis_info_mapping0 *vi,
  113771. float **mdct){
  113772. int i,j,n=p->n, de=0.3*p->m_val;
  113773. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113774. for(i=0; i<vi->coupling_steps; i++){
  113775. /* for(j=start; j<limit; j++){} // ???*/
  113776. for(j=limit; j<n; j++)
  113777. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  113778. }
  113779. }
  113780. #endif
  113781. /********* End of inlined file: psy.c *********/
  113782. /********* Start of inlined file: registry.c *********/
  113783. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113784. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113785. // tasks..
  113786. #if JUCE_MSVC
  113787. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113788. #endif
  113789. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113790. #if JUCE_USE_OGGVORBIS
  113791. /* seems like major overkill now; the backend numbers will grow into
  113792. the infrastructure soon enough */
  113793. extern vorbis_func_floor floor0_exportbundle;
  113794. extern vorbis_func_floor floor1_exportbundle;
  113795. extern vorbis_func_residue residue0_exportbundle;
  113796. extern vorbis_func_residue residue1_exportbundle;
  113797. extern vorbis_func_residue residue2_exportbundle;
  113798. extern vorbis_func_mapping mapping0_exportbundle;
  113799. vorbis_func_floor *_floor_P[]={
  113800. &floor0_exportbundle,
  113801. &floor1_exportbundle,
  113802. };
  113803. vorbis_func_residue *_residue_P[]={
  113804. &residue0_exportbundle,
  113805. &residue1_exportbundle,
  113806. &residue2_exportbundle,
  113807. };
  113808. vorbis_func_mapping *_mapping_P[]={
  113809. &mapping0_exportbundle,
  113810. };
  113811. #endif
  113812. /********* End of inlined file: registry.c *********/
  113813. /********* Start of inlined file: res0.c *********/
  113814. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  113815. encode/decode loops are coded for clarity and performance is not
  113816. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  113817. it's slow. */
  113818. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113819. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113820. // tasks..
  113821. #if JUCE_MSVC
  113822. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113823. #endif
  113824. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113825. #if JUCE_USE_OGGVORBIS
  113826. #include <stdlib.h>
  113827. #include <string.h>
  113828. #include <math.h>
  113829. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113830. #include <stdio.h>
  113831. #endif
  113832. typedef struct {
  113833. vorbis_info_residue0 *info;
  113834. int parts;
  113835. int stages;
  113836. codebook *fullbooks;
  113837. codebook *phrasebook;
  113838. codebook ***partbooks;
  113839. int partvals;
  113840. int **decodemap;
  113841. long postbits;
  113842. long phrasebits;
  113843. long frames;
  113844. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  113845. int train_seq;
  113846. long *training_data[8][64];
  113847. float training_max[8][64];
  113848. float training_min[8][64];
  113849. float tmin;
  113850. float tmax;
  113851. #endif
  113852. } vorbis_look_residue0;
  113853. void res0_free_info(vorbis_info_residue *i){
  113854. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  113855. if(info){
  113856. memset(info,0,sizeof(*info));
  113857. _ogg_free(info);
  113858. }
  113859. }
  113860. void res0_free_look(vorbis_look_residue *i){
  113861. int j;
  113862. if(i){
  113863. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  113864. #ifdef TRAIN_RES
  113865. {
  113866. int j,k,l;
  113867. for(j=0;j<look->parts;j++){
  113868. /*fprintf(stderr,"partition %d: ",j);*/
  113869. for(k=0;k<8;k++)
  113870. if(look->training_data[k][j]){
  113871. char buffer[80];
  113872. FILE *of;
  113873. codebook *statebook=look->partbooks[j][k];
  113874. /* long and short into the same bucket by current convention */
  113875. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  113876. of=fopen(buffer,"a");
  113877. for(l=0;l<statebook->entries;l++)
  113878. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  113879. fclose(of);
  113880. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  113881. look->training_min[k][j],look->training_max[k][j]);*/
  113882. _ogg_free(look->training_data[k][j]);
  113883. look->training_data[k][j]=NULL;
  113884. }
  113885. /*fprintf(stderr,"\n");*/
  113886. }
  113887. }
  113888. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  113889. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  113890. (float)look->phrasebits/look->frames,
  113891. (float)look->postbits/look->frames,
  113892. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113893. #endif
  113894. /*vorbis_info_residue0 *info=look->info;
  113895. fprintf(stderr,
  113896. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  113897. "(%g/frame) \n",look->frames,look->phrasebits,
  113898. look->resbitsflat,
  113899. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  113900. for(j=0;j<look->parts;j++){
  113901. long acc=0;
  113902. fprintf(stderr,"\t[%d] == ",j);
  113903. for(k=0;k<look->stages;k++)
  113904. if((info->secondstages[j]>>k)&1){
  113905. fprintf(stderr,"%ld,",look->resbits[j][k]);
  113906. acc+=look->resbits[j][k];
  113907. }
  113908. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  113909. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  113910. }
  113911. fprintf(stderr,"\n");*/
  113912. for(j=0;j<look->parts;j++)
  113913. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  113914. _ogg_free(look->partbooks);
  113915. for(j=0;j<look->partvals;j++)
  113916. _ogg_free(look->decodemap[j]);
  113917. _ogg_free(look->decodemap);
  113918. memset(look,0,sizeof(*look));
  113919. _ogg_free(look);
  113920. }
  113921. }
  113922. static int icount(unsigned int v){
  113923. int ret=0;
  113924. while(v){
  113925. ret+=v&1;
  113926. v>>=1;
  113927. }
  113928. return(ret);
  113929. }
  113930. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  113931. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113932. int j,acc=0;
  113933. oggpack_write(opb,info->begin,24);
  113934. oggpack_write(opb,info->end,24);
  113935. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  113936. code with a partitioned book */
  113937. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  113938. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  113939. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  113940. bitmask of one indicates this partition class has bits to write
  113941. this pass */
  113942. for(j=0;j<info->partitions;j++){
  113943. if(ilog(info->secondstages[j])>3){
  113944. /* yes, this is a minor hack due to not thinking ahead */
  113945. oggpack_write(opb,info->secondstages[j],3);
  113946. oggpack_write(opb,1,1);
  113947. oggpack_write(opb,info->secondstages[j]>>3,5);
  113948. }else
  113949. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  113950. acc+=icount(info->secondstages[j]);
  113951. }
  113952. for(j=0;j<acc;j++)
  113953. oggpack_write(opb,info->booklist[j],8);
  113954. }
  113955. /* vorbis_info is for range checking */
  113956. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  113957. int j,acc=0;
  113958. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  113959. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113960. info->begin=oggpack_read(opb,24);
  113961. info->end=oggpack_read(opb,24);
  113962. info->grouping=oggpack_read(opb,24)+1;
  113963. info->partitions=oggpack_read(opb,6)+1;
  113964. info->groupbook=oggpack_read(opb,8);
  113965. for(j=0;j<info->partitions;j++){
  113966. int cascade=oggpack_read(opb,3);
  113967. if(oggpack_read(opb,1))
  113968. cascade|=(oggpack_read(opb,5)<<3);
  113969. info->secondstages[j]=cascade;
  113970. acc+=icount(cascade);
  113971. }
  113972. for(j=0;j<acc;j++)
  113973. info->booklist[j]=oggpack_read(opb,8);
  113974. if(info->groupbook>=ci->books)goto errout;
  113975. for(j=0;j<acc;j++)
  113976. if(info->booklist[j]>=ci->books)goto errout;
  113977. return(info);
  113978. errout:
  113979. res0_free_info(info);
  113980. return(NULL);
  113981. }
  113982. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  113983. vorbis_info_residue *vr){
  113984. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113985. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  113986. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  113987. int j,k,acc=0;
  113988. int dim;
  113989. int maxstage=0;
  113990. look->info=info;
  113991. look->parts=info->partitions;
  113992. look->fullbooks=ci->fullbooks;
  113993. look->phrasebook=ci->fullbooks+info->groupbook;
  113994. dim=look->phrasebook->dim;
  113995. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  113996. for(j=0;j<look->parts;j++){
  113997. int stages=ilog(info->secondstages[j]);
  113998. if(stages){
  113999. if(stages>maxstage)maxstage=stages;
  114000. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  114001. for(k=0;k<stages;k++)
  114002. if(info->secondstages[j]&(1<<k)){
  114003. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  114004. #ifdef TRAIN_RES
  114005. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  114006. sizeof(***look->training_data));
  114007. #endif
  114008. }
  114009. }
  114010. }
  114011. look->partvals=rint(pow((float)look->parts,(float)dim));
  114012. look->stages=maxstage;
  114013. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  114014. for(j=0;j<look->partvals;j++){
  114015. long val=j;
  114016. long mult=look->partvals/look->parts;
  114017. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  114018. for(k=0;k<dim;k++){
  114019. long deco=val/mult;
  114020. val-=deco*mult;
  114021. mult/=look->parts;
  114022. look->decodemap[j][k]=deco;
  114023. }
  114024. }
  114025. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114026. {
  114027. static int train_seq=0;
  114028. look->train_seq=train_seq++;
  114029. }
  114030. #endif
  114031. return(look);
  114032. }
  114033. /* break an abstraction and copy some code for performance purposes */
  114034. static int local_book_besterror(codebook *book,float *a){
  114035. int dim=book->dim,i,k,o;
  114036. int best=0;
  114037. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114038. /* find the quant val of each scalar */
  114039. for(k=0,o=dim;k<dim;++k){
  114040. float val=a[--o];
  114041. i=tt->threshvals>>1;
  114042. if(val<tt->quantthresh[i]){
  114043. if(val<tt->quantthresh[i-1]){
  114044. for(--i;i>0;--i)
  114045. if(val>=tt->quantthresh[i-1])
  114046. break;
  114047. }
  114048. }else{
  114049. for(++i;i<tt->threshvals-1;++i)
  114050. if(val<tt->quantthresh[i])break;
  114051. }
  114052. best=(best*tt->quantvals)+tt->quantmap[i];
  114053. }
  114054. /* regular lattices are easy :-) */
  114055. if(book->c->lengthlist[best]<=0){
  114056. const static_codebook *c=book->c;
  114057. int i,j;
  114058. float bestf=0.f;
  114059. float *e=book->valuelist;
  114060. best=-1;
  114061. for(i=0;i<book->entries;i++){
  114062. if(c->lengthlist[i]>0){
  114063. float thisx=0.f;
  114064. for(j=0;j<dim;j++){
  114065. float val=(e[j]-a[j]);
  114066. thisx+=val*val;
  114067. }
  114068. if(best==-1 || thisx<bestf){
  114069. bestf=thisx;
  114070. best=i;
  114071. }
  114072. }
  114073. e+=dim;
  114074. }
  114075. }
  114076. {
  114077. float *ptr=book->valuelist+best*dim;
  114078. for(i=0;i<dim;i++)
  114079. *a++ -= *ptr++;
  114080. }
  114081. return(best);
  114082. }
  114083. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  114084. codebook *book,long *acc){
  114085. int i,bits=0;
  114086. int dim=book->dim;
  114087. int step=n/dim;
  114088. for(i=0;i<step;i++){
  114089. int entry=local_book_besterror(book,vec+i*dim);
  114090. #ifdef TRAIN_RES
  114091. acc[entry]++;
  114092. #endif
  114093. bits+=vorbis_book_encode(book,entry,opb);
  114094. }
  114095. return(bits);
  114096. }
  114097. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  114098. float **in,int ch){
  114099. long i,j,k;
  114100. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114101. vorbis_info_residue0 *info=look->info;
  114102. /* move all this setup out later */
  114103. int samples_per_partition=info->grouping;
  114104. int possible_partitions=info->partitions;
  114105. int n=info->end-info->begin;
  114106. int partvals=n/samples_per_partition;
  114107. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  114108. float scale=100./samples_per_partition;
  114109. /* we find the partition type for each partition of each
  114110. channel. We'll go back and do the interleaved encoding in a
  114111. bit. For now, clarity */
  114112. for(i=0;i<ch;i++){
  114113. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  114114. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  114115. }
  114116. for(i=0;i<partvals;i++){
  114117. int offset=i*samples_per_partition+info->begin;
  114118. for(j=0;j<ch;j++){
  114119. float max=0.;
  114120. float ent=0.;
  114121. for(k=0;k<samples_per_partition;k++){
  114122. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  114123. ent+=fabs(rint(in[j][offset+k]));
  114124. }
  114125. ent*=scale;
  114126. for(k=0;k<possible_partitions-1;k++)
  114127. if(max<=info->classmetric1[k] &&
  114128. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  114129. break;
  114130. partword[j][i]=k;
  114131. }
  114132. }
  114133. #ifdef TRAIN_RESAUX
  114134. {
  114135. FILE *of;
  114136. char buffer[80];
  114137. for(i=0;i<ch;i++){
  114138. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114139. of=fopen(buffer,"a");
  114140. for(j=0;j<partvals;j++)
  114141. fprintf(of,"%ld, ",partword[i][j]);
  114142. fprintf(of,"\n");
  114143. fclose(of);
  114144. }
  114145. }
  114146. #endif
  114147. look->frames++;
  114148. return(partword);
  114149. }
  114150. /* designed for stereo or other modes where the partition size is an
  114151. integer multiple of the number of channels encoded in the current
  114152. submap */
  114153. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  114154. int ch){
  114155. long i,j,k,l;
  114156. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114157. vorbis_info_residue0 *info=look->info;
  114158. /* move all this setup out later */
  114159. int samples_per_partition=info->grouping;
  114160. int possible_partitions=info->partitions;
  114161. int n=info->end-info->begin;
  114162. int partvals=n/samples_per_partition;
  114163. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  114164. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  114165. FILE *of;
  114166. char buffer[80];
  114167. #endif
  114168. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  114169. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  114170. for(i=0,l=info->begin/ch;i<partvals;i++){
  114171. float magmax=0.f;
  114172. float angmax=0.f;
  114173. for(j=0;j<samples_per_partition;j+=ch){
  114174. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  114175. for(k=1;k<ch;k++)
  114176. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  114177. l++;
  114178. }
  114179. for(j=0;j<possible_partitions-1;j++)
  114180. if(magmax<=info->classmetric1[j] &&
  114181. angmax<=info->classmetric2[j])
  114182. break;
  114183. partword[0][i]=j;
  114184. }
  114185. #ifdef TRAIN_RESAUX
  114186. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114187. of=fopen(buffer,"a");
  114188. for(i=0;i<partvals;i++)
  114189. fprintf(of,"%ld, ",partword[0][i]);
  114190. fprintf(of,"\n");
  114191. fclose(of);
  114192. #endif
  114193. look->frames++;
  114194. return(partword);
  114195. }
  114196. static int _01forward(oggpack_buffer *opb,
  114197. vorbis_block *vb,vorbis_look_residue *vl,
  114198. float **in,int ch,
  114199. long **partword,
  114200. int (*encode)(oggpack_buffer *,float *,int,
  114201. codebook *,long *)){
  114202. long i,j,k,s;
  114203. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114204. vorbis_info_residue0 *info=look->info;
  114205. /* move all this setup out later */
  114206. int samples_per_partition=info->grouping;
  114207. int possible_partitions=info->partitions;
  114208. int partitions_per_word=look->phrasebook->dim;
  114209. int n=info->end-info->begin;
  114210. int partvals=n/samples_per_partition;
  114211. long resbits[128];
  114212. long resvals[128];
  114213. #ifdef TRAIN_RES
  114214. for(i=0;i<ch;i++)
  114215. for(j=info->begin;j<info->end;j++){
  114216. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  114217. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  114218. }
  114219. #endif
  114220. memset(resbits,0,sizeof(resbits));
  114221. memset(resvals,0,sizeof(resvals));
  114222. /* we code the partition words for each channel, then the residual
  114223. words for a partition per channel until we've written all the
  114224. residual words for that partition word. Then write the next
  114225. partition channel words... */
  114226. for(s=0;s<look->stages;s++){
  114227. for(i=0;i<partvals;){
  114228. /* first we encode a partition codeword for each channel */
  114229. if(s==0){
  114230. for(j=0;j<ch;j++){
  114231. long val=partword[j][i];
  114232. for(k=1;k<partitions_per_word;k++){
  114233. val*=possible_partitions;
  114234. if(i+k<partvals)
  114235. val+=partword[j][i+k];
  114236. }
  114237. /* training hack */
  114238. if(val<look->phrasebook->entries)
  114239. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  114240. #if 0 /*def TRAIN_RES*/
  114241. else
  114242. fprintf(stderr,"!");
  114243. #endif
  114244. }
  114245. }
  114246. /* now we encode interleaved residual values for the partitions */
  114247. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  114248. long offset=i*samples_per_partition+info->begin;
  114249. for(j=0;j<ch;j++){
  114250. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  114251. if(info->secondstages[partword[j][i]]&(1<<s)){
  114252. codebook *statebook=look->partbooks[partword[j][i]][s];
  114253. if(statebook){
  114254. int ret;
  114255. long *accumulator=NULL;
  114256. #ifdef TRAIN_RES
  114257. accumulator=look->training_data[s][partword[j][i]];
  114258. {
  114259. int l;
  114260. float *samples=in[j]+offset;
  114261. for(l=0;l<samples_per_partition;l++){
  114262. if(samples[l]<look->training_min[s][partword[j][i]])
  114263. look->training_min[s][partword[j][i]]=samples[l];
  114264. if(samples[l]>look->training_max[s][partword[j][i]])
  114265. look->training_max[s][partword[j][i]]=samples[l];
  114266. }
  114267. }
  114268. #endif
  114269. ret=encode(opb,in[j]+offset,samples_per_partition,
  114270. statebook,accumulator);
  114271. look->postbits+=ret;
  114272. resbits[partword[j][i]]+=ret;
  114273. }
  114274. }
  114275. }
  114276. }
  114277. }
  114278. }
  114279. /*{
  114280. long total=0;
  114281. long totalbits=0;
  114282. fprintf(stderr,"%d :: ",vb->mode);
  114283. for(k=0;k<possible_partitions;k++){
  114284. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  114285. total+=resvals[k];
  114286. totalbits+=resbits[k];
  114287. }
  114288. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  114289. }*/
  114290. return(0);
  114291. }
  114292. /* a truncated packet here just means 'stop working'; it's not an error */
  114293. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114294. float **in,int ch,
  114295. long (*decodepart)(codebook *, float *,
  114296. oggpack_buffer *,int)){
  114297. long i,j,k,l,s;
  114298. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114299. vorbis_info_residue0 *info=look->info;
  114300. /* move all this setup out later */
  114301. int samples_per_partition=info->grouping;
  114302. int partitions_per_word=look->phrasebook->dim;
  114303. int n=info->end-info->begin;
  114304. int partvals=n/samples_per_partition;
  114305. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114306. int ***partword=(int***)alloca(ch*sizeof(*partword));
  114307. for(j=0;j<ch;j++)
  114308. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  114309. for(s=0;s<look->stages;s++){
  114310. /* each loop decodes on partition codeword containing
  114311. partitions_pre_word partitions */
  114312. for(i=0,l=0;i<partvals;l++){
  114313. if(s==0){
  114314. /* fetch the partition word for each channel */
  114315. for(j=0;j<ch;j++){
  114316. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114317. if(temp==-1)goto eopbreak;
  114318. partword[j][l]=look->decodemap[temp];
  114319. if(partword[j][l]==NULL)goto errout;
  114320. }
  114321. }
  114322. /* now we decode residual values for the partitions */
  114323. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114324. for(j=0;j<ch;j++){
  114325. long offset=info->begin+i*samples_per_partition;
  114326. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  114327. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  114328. if(stagebook){
  114329. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  114330. samples_per_partition)==-1)goto eopbreak;
  114331. }
  114332. }
  114333. }
  114334. }
  114335. }
  114336. errout:
  114337. eopbreak:
  114338. return(0);
  114339. }
  114340. #if 0
  114341. /* residue 0 and 1 are just slight variants of one another. 0 is
  114342. interleaved, 1 is not */
  114343. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  114344. float **in,int *nonzero,int ch){
  114345. /* we encode only the nonzero parts of a bundle */
  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(_01class(vb,vl,in,used,_interleaved_testhack));*/
  114352. return(_01class(vb,vl,in,used));
  114353. else
  114354. return(0);
  114355. }
  114356. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  114357. float **in,float **out,int *nonzero,int ch,
  114358. long **partword){
  114359. /* we encode only the nonzero parts of a bundle */
  114360. int i,j,used=0,n=vb->pcmend/2;
  114361. for(i=0;i<ch;i++)
  114362. if(nonzero[i]){
  114363. if(out)
  114364. for(j=0;j<n;j++)
  114365. out[i][j]+=in[i][j];
  114366. in[used++]=in[i];
  114367. }
  114368. if(used){
  114369. int ret=_01forward(vb,vl,in,used,partword,
  114370. _interleaved_encodepart);
  114371. if(out){
  114372. used=0;
  114373. for(i=0;i<ch;i++)
  114374. if(nonzero[i]){
  114375. for(j=0;j<n;j++)
  114376. out[i][j]-=in[used][j];
  114377. used++;
  114378. }
  114379. }
  114380. return(ret);
  114381. }else{
  114382. return(0);
  114383. }
  114384. }
  114385. #endif
  114386. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114387. float **in,int *nonzero,int ch){
  114388. int i,used=0;
  114389. for(i=0;i<ch;i++)
  114390. if(nonzero[i])
  114391. in[used++]=in[i];
  114392. if(used)
  114393. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  114394. else
  114395. return(0);
  114396. }
  114397. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  114398. float **in,float **out,int *nonzero,int ch,
  114399. long **partword){
  114400. int i,j,used=0,n=vb->pcmend/2;
  114401. for(i=0;i<ch;i++)
  114402. if(nonzero[i]){
  114403. if(out)
  114404. for(j=0;j<n;j++)
  114405. out[i][j]+=in[i][j];
  114406. in[used++]=in[i];
  114407. }
  114408. if(used){
  114409. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  114410. if(out){
  114411. used=0;
  114412. for(i=0;i<ch;i++)
  114413. if(nonzero[i]){
  114414. for(j=0;j<n;j++)
  114415. out[i][j]-=in[used][j];
  114416. used++;
  114417. }
  114418. }
  114419. return(ret);
  114420. }else{
  114421. return(0);
  114422. }
  114423. }
  114424. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  114425. float **in,int *nonzero,int ch){
  114426. int i,used=0;
  114427. for(i=0;i<ch;i++)
  114428. if(nonzero[i])
  114429. in[used++]=in[i];
  114430. if(used)
  114431. return(_01class(vb,vl,in,used));
  114432. else
  114433. return(0);
  114434. }
  114435. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114436. float **in,int *nonzero,int ch){
  114437. int i,used=0;
  114438. for(i=0;i<ch;i++)
  114439. if(nonzero[i])
  114440. in[used++]=in[i];
  114441. if(used)
  114442. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  114443. else
  114444. return(0);
  114445. }
  114446. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  114447. float **in,int *nonzero,int ch){
  114448. int i,used=0;
  114449. for(i=0;i<ch;i++)
  114450. if(nonzero[i])used++;
  114451. if(used)
  114452. return(_2class(vb,vl,in,ch));
  114453. else
  114454. return(0);
  114455. }
  114456. /* res2 is slightly more different; all the channels are interleaved
  114457. into a single vector and encoded. */
  114458. int res2_forward(oggpack_buffer *opb,
  114459. vorbis_block *vb,vorbis_look_residue *vl,
  114460. float **in,float **out,int *nonzero,int ch,
  114461. long **partword){
  114462. long i,j,k,n=vb->pcmend/2,used=0;
  114463. /* don't duplicate the code; use a working vector hack for now and
  114464. reshape ourselves into a single channel res1 */
  114465. /* ugly; reallocs for each coupling pass :-( */
  114466. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  114467. for(i=0;i<ch;i++){
  114468. float *pcm=in[i];
  114469. if(nonzero[i])used++;
  114470. for(j=0,k=i;j<n;j++,k+=ch)
  114471. work[k]=pcm[j];
  114472. }
  114473. if(used){
  114474. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  114475. /* update the sofar vector */
  114476. if(out){
  114477. for(i=0;i<ch;i++){
  114478. float *pcm=in[i];
  114479. float *sofar=out[i];
  114480. for(j=0,k=i;j<n;j++,k+=ch)
  114481. sofar[j]+=pcm[j]-work[k];
  114482. }
  114483. }
  114484. return(ret);
  114485. }else{
  114486. return(0);
  114487. }
  114488. }
  114489. /* duplicate code here as speed is somewhat more important */
  114490. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114491. float **in,int *nonzero,int ch){
  114492. long i,k,l,s;
  114493. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114494. vorbis_info_residue0 *info=look->info;
  114495. /* move all this setup out later */
  114496. int samples_per_partition=info->grouping;
  114497. int partitions_per_word=look->phrasebook->dim;
  114498. int n=info->end-info->begin;
  114499. int partvals=n/samples_per_partition;
  114500. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114501. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  114502. for(i=0;i<ch;i++)if(nonzero[i])break;
  114503. if(i==ch)return(0); /* no nonzero vectors */
  114504. for(s=0;s<look->stages;s++){
  114505. for(i=0,l=0;i<partvals;l++){
  114506. if(s==0){
  114507. /* fetch the partition word */
  114508. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114509. if(temp==-1)goto eopbreak;
  114510. partword[l]=look->decodemap[temp];
  114511. if(partword[l]==NULL)goto errout;
  114512. }
  114513. /* now we decode residual values for the partitions */
  114514. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114515. if(info->secondstages[partword[l][k]]&(1<<s)){
  114516. codebook *stagebook=look->partbooks[partword[l][k]][s];
  114517. if(stagebook){
  114518. if(vorbis_book_decodevv_add(stagebook,in,
  114519. i*samples_per_partition+info->begin,ch,
  114520. &vb->opb,samples_per_partition)==-1)
  114521. goto eopbreak;
  114522. }
  114523. }
  114524. }
  114525. }
  114526. errout:
  114527. eopbreak:
  114528. return(0);
  114529. }
  114530. vorbis_func_residue residue0_exportbundle={
  114531. NULL,
  114532. &res0_unpack,
  114533. &res0_look,
  114534. &res0_free_info,
  114535. &res0_free_look,
  114536. NULL,
  114537. NULL,
  114538. &res0_inverse
  114539. };
  114540. vorbis_func_residue residue1_exportbundle={
  114541. &res0_pack,
  114542. &res0_unpack,
  114543. &res0_look,
  114544. &res0_free_info,
  114545. &res0_free_look,
  114546. &res1_class,
  114547. &res1_forward,
  114548. &res1_inverse
  114549. };
  114550. vorbis_func_residue residue2_exportbundle={
  114551. &res0_pack,
  114552. &res0_unpack,
  114553. &res0_look,
  114554. &res0_free_info,
  114555. &res0_free_look,
  114556. &res2_class,
  114557. &res2_forward,
  114558. &res2_inverse
  114559. };
  114560. #endif
  114561. /********* End of inlined file: res0.c *********/
  114562. /********* Start of inlined file: sharedbook.c *********/
  114563. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114564. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114565. // tasks..
  114566. #if JUCE_MSVC
  114567. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114568. #endif
  114569. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114570. #if JUCE_USE_OGGVORBIS
  114571. #include <stdlib.h>
  114572. #include <math.h>
  114573. #include <string.h>
  114574. /**** pack/unpack helpers ******************************************/
  114575. int _ilog(unsigned int v){
  114576. int ret=0;
  114577. while(v){
  114578. ret++;
  114579. v>>=1;
  114580. }
  114581. return(ret);
  114582. }
  114583. /* 32 bit float (not IEEE; nonnormalized mantissa +
  114584. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  114585. Why not IEEE? It's just not that important here. */
  114586. #define VQ_FEXP 10
  114587. #define VQ_FMAN 21
  114588. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  114589. /* doesn't currently guard under/overflow */
  114590. long _float32_pack(float val){
  114591. int sign=0;
  114592. long exp;
  114593. long mant;
  114594. if(val<0){
  114595. sign=0x80000000;
  114596. val= -val;
  114597. }
  114598. exp= floor(log(val)/log(2.f));
  114599. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  114600. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  114601. return(sign|exp|mant);
  114602. }
  114603. float _float32_unpack(long val){
  114604. double mant=val&0x1fffff;
  114605. int sign=val&0x80000000;
  114606. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  114607. if(sign)mant= -mant;
  114608. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  114609. }
  114610. /* given a list of word lengths, generate a list of codewords. Works
  114611. for length ordered or unordered, always assigns the lowest valued
  114612. codewords first. Extended to handle unused entries (length 0) */
  114613. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  114614. long i,j,count=0;
  114615. ogg_uint32_t marker[33];
  114616. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  114617. memset(marker,0,sizeof(marker));
  114618. for(i=0;i<n;i++){
  114619. long length=l[i];
  114620. if(length>0){
  114621. ogg_uint32_t entry=marker[length];
  114622. /* when we claim a node for an entry, we also claim the nodes
  114623. below it (pruning off the imagined tree that may have dangled
  114624. from it) as well as blocking the use of any nodes directly
  114625. above for leaves */
  114626. /* update ourself */
  114627. if(length<32 && (entry>>length)){
  114628. /* error condition; the lengths must specify an overpopulated tree */
  114629. _ogg_free(r);
  114630. return(NULL);
  114631. }
  114632. r[count++]=entry;
  114633. /* Look to see if the next shorter marker points to the node
  114634. above. if so, update it and repeat. */
  114635. {
  114636. for(j=length;j>0;j--){
  114637. if(marker[j]&1){
  114638. /* have to jump branches */
  114639. if(j==1)
  114640. marker[1]++;
  114641. else
  114642. marker[j]=marker[j-1]<<1;
  114643. break; /* invariant says next upper marker would already
  114644. have been moved if it was on the same path */
  114645. }
  114646. marker[j]++;
  114647. }
  114648. }
  114649. /* prune the tree; the implicit invariant says all the longer
  114650. markers were dangling from our just-taken node. Dangle them
  114651. from our *new* node. */
  114652. for(j=length+1;j<33;j++)
  114653. if((marker[j]>>1) == entry){
  114654. entry=marker[j];
  114655. marker[j]=marker[j-1]<<1;
  114656. }else
  114657. break;
  114658. }else
  114659. if(sparsecount==0)count++;
  114660. }
  114661. /* bitreverse the words because our bitwise packer/unpacker is LSb
  114662. endian */
  114663. for(i=0,count=0;i<n;i++){
  114664. ogg_uint32_t temp=0;
  114665. for(j=0;j<l[i];j++){
  114666. temp<<=1;
  114667. temp|=(r[count]>>j)&1;
  114668. }
  114669. if(sparsecount){
  114670. if(l[i])
  114671. r[count++]=temp;
  114672. }else
  114673. r[count++]=temp;
  114674. }
  114675. return(r);
  114676. }
  114677. /* there might be a straightforward one-line way to do the below
  114678. that's portable and totally safe against roundoff, but I haven't
  114679. thought of it. Therefore, we opt on the side of caution */
  114680. long _book_maptype1_quantvals(const static_codebook *b){
  114681. long vals=floor(pow((float)b->entries,1.f/b->dim));
  114682. /* the above *should* be reliable, but we'll not assume that FP is
  114683. ever reliable when bitstream sync is at stake; verify via integer
  114684. means that vals really is the greatest value of dim for which
  114685. vals^b->bim <= b->entries */
  114686. /* treat the above as an initial guess */
  114687. while(1){
  114688. long acc=1;
  114689. long acc1=1;
  114690. int i;
  114691. for(i=0;i<b->dim;i++){
  114692. acc*=vals;
  114693. acc1*=vals+1;
  114694. }
  114695. if(acc<=b->entries && acc1>b->entries){
  114696. return(vals);
  114697. }else{
  114698. if(acc>b->entries){
  114699. vals--;
  114700. }else{
  114701. vals++;
  114702. }
  114703. }
  114704. }
  114705. }
  114706. /* unpack the quantized list of values for encode/decode ***********/
  114707. /* we need to deal with two map types: in map type 1, the values are
  114708. generated algorithmically (each column of the vector counts through
  114709. the values in the quant vector). in map type 2, all the values came
  114710. in in an explicit list. Both value lists must be unpacked */
  114711. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  114712. long j,k,count=0;
  114713. if(b->maptype==1 || b->maptype==2){
  114714. int quantvals;
  114715. float mindel=_float32_unpack(b->q_min);
  114716. float delta=_float32_unpack(b->q_delta);
  114717. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  114718. /* maptype 1 and 2 both use a quantized value vector, but
  114719. different sizes */
  114720. switch(b->maptype){
  114721. case 1:
  114722. /* most of the time, entries%dimensions == 0, but we need to be
  114723. well defined. We define that the possible vales at each
  114724. scalar is values == entries/dim. If entries%dim != 0, we'll
  114725. have 'too few' values (values*dim<entries), which means that
  114726. we'll have 'left over' entries; left over entries use zeroed
  114727. values (and are wasted). So don't generate codebooks like
  114728. that */
  114729. quantvals=_book_maptype1_quantvals(b);
  114730. for(j=0;j<b->entries;j++){
  114731. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114732. float last=0.f;
  114733. int indexdiv=1;
  114734. for(k=0;k<b->dim;k++){
  114735. int index= (j/indexdiv)%quantvals;
  114736. float val=b->quantlist[index];
  114737. val=fabs(val)*delta+mindel+last;
  114738. if(b->q_sequencep)last=val;
  114739. if(sparsemap)
  114740. r[sparsemap[count]*b->dim+k]=val;
  114741. else
  114742. r[count*b->dim+k]=val;
  114743. indexdiv*=quantvals;
  114744. }
  114745. count++;
  114746. }
  114747. }
  114748. break;
  114749. case 2:
  114750. for(j=0;j<b->entries;j++){
  114751. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114752. float last=0.f;
  114753. for(k=0;k<b->dim;k++){
  114754. float val=b->quantlist[j*b->dim+k];
  114755. val=fabs(val)*delta+mindel+last;
  114756. if(b->q_sequencep)last=val;
  114757. if(sparsemap)
  114758. r[sparsemap[count]*b->dim+k]=val;
  114759. else
  114760. r[count*b->dim+k]=val;
  114761. }
  114762. count++;
  114763. }
  114764. }
  114765. break;
  114766. }
  114767. return(r);
  114768. }
  114769. return(NULL);
  114770. }
  114771. void vorbis_staticbook_clear(static_codebook *b){
  114772. if(b->allocedp){
  114773. if(b->quantlist)_ogg_free(b->quantlist);
  114774. if(b->lengthlist)_ogg_free(b->lengthlist);
  114775. if(b->nearest_tree){
  114776. _ogg_free(b->nearest_tree->ptr0);
  114777. _ogg_free(b->nearest_tree->ptr1);
  114778. _ogg_free(b->nearest_tree->p);
  114779. _ogg_free(b->nearest_tree->q);
  114780. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  114781. _ogg_free(b->nearest_tree);
  114782. }
  114783. if(b->thresh_tree){
  114784. _ogg_free(b->thresh_tree->quantthresh);
  114785. _ogg_free(b->thresh_tree->quantmap);
  114786. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  114787. _ogg_free(b->thresh_tree);
  114788. }
  114789. memset(b,0,sizeof(*b));
  114790. }
  114791. }
  114792. void vorbis_staticbook_destroy(static_codebook *b){
  114793. if(b->allocedp){
  114794. vorbis_staticbook_clear(b);
  114795. _ogg_free(b);
  114796. }
  114797. }
  114798. void vorbis_book_clear(codebook *b){
  114799. /* static book is not cleared; we're likely called on the lookup and
  114800. the static codebook belongs to the info struct */
  114801. if(b->valuelist)_ogg_free(b->valuelist);
  114802. if(b->codelist)_ogg_free(b->codelist);
  114803. if(b->dec_index)_ogg_free(b->dec_index);
  114804. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  114805. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  114806. memset(b,0,sizeof(*b));
  114807. }
  114808. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  114809. memset(c,0,sizeof(*c));
  114810. c->c=s;
  114811. c->entries=s->entries;
  114812. c->used_entries=s->entries;
  114813. c->dim=s->dim;
  114814. c->codelist=_make_words(s->lengthlist,s->entries,0);
  114815. c->valuelist=_book_unquantize(s,s->entries,NULL);
  114816. return(0);
  114817. }
  114818. static int sort32a(const void *a,const void *b){
  114819. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  114820. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  114821. }
  114822. /* decode codebook arrangement is more heavily optimized than encode */
  114823. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  114824. int i,j,n=0,tabn;
  114825. int *sortindex;
  114826. memset(c,0,sizeof(*c));
  114827. /* count actually used entries */
  114828. for(i=0;i<s->entries;i++)
  114829. if(s->lengthlist[i]>0)
  114830. n++;
  114831. c->entries=s->entries;
  114832. c->used_entries=n;
  114833. c->dim=s->dim;
  114834. /* two different remappings go on here.
  114835. First, we collapse the likely sparse codebook down only to
  114836. actually represented values/words. This collapsing needs to be
  114837. indexed as map-valueless books are used to encode original entry
  114838. positions as integers.
  114839. Second, we reorder all vectors, including the entry index above,
  114840. by sorted bitreversed codeword to allow treeless decode. */
  114841. {
  114842. /* perform sort */
  114843. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  114844. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  114845. if(codes==NULL)goto err_out;
  114846. for(i=0;i<n;i++){
  114847. codes[i]=ogg_bitreverse(codes[i]);
  114848. codep[i]=codes+i;
  114849. }
  114850. qsort(codep,n,sizeof(*codep),sort32a);
  114851. sortindex=(int*)alloca(n*sizeof(*sortindex));
  114852. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  114853. /* the index is a reverse index */
  114854. for(i=0;i<n;i++){
  114855. int position=codep[i]-codes;
  114856. sortindex[position]=i;
  114857. }
  114858. for(i=0;i<n;i++)
  114859. c->codelist[sortindex[i]]=codes[i];
  114860. _ogg_free(codes);
  114861. }
  114862. c->valuelist=_book_unquantize(s,n,sortindex);
  114863. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  114864. for(n=0,i=0;i<s->entries;i++)
  114865. if(s->lengthlist[i]>0)
  114866. c->dec_index[sortindex[n++]]=i;
  114867. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  114868. for(n=0,i=0;i<s->entries;i++)
  114869. if(s->lengthlist[i]>0)
  114870. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  114871. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  114872. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  114873. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  114874. tabn=1<<c->dec_firsttablen;
  114875. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  114876. c->dec_maxlength=0;
  114877. for(i=0;i<n;i++){
  114878. if(c->dec_maxlength<c->dec_codelengths[i])
  114879. c->dec_maxlength=c->dec_codelengths[i];
  114880. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  114881. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  114882. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  114883. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  114884. }
  114885. }
  114886. /* now fill in 'unused' entries in the firsttable with hi/lo search
  114887. hints for the non-direct-hits */
  114888. {
  114889. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  114890. long lo=0,hi=0;
  114891. for(i=0;i<tabn;i++){
  114892. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  114893. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  114894. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  114895. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  114896. /* we only actually have 15 bits per hint to play with here.
  114897. In order to overflow gracefully (nothing breaks, efficiency
  114898. just drops), encode as the difference from the extremes. */
  114899. {
  114900. unsigned long loval=lo;
  114901. unsigned long hival=n-hi;
  114902. if(loval>0x7fff)loval=0x7fff;
  114903. if(hival>0x7fff)hival=0x7fff;
  114904. c->dec_firsttable[ogg_bitreverse(word)]=
  114905. 0x80000000UL | (loval<<15) | hival;
  114906. }
  114907. }
  114908. }
  114909. }
  114910. return(0);
  114911. err_out:
  114912. vorbis_book_clear(c);
  114913. return(-1);
  114914. }
  114915. static float _dist(int el,float *ref, float *b,int step){
  114916. int i;
  114917. float acc=0.f;
  114918. for(i=0;i<el;i++){
  114919. float val=(ref[i]-b[i*step]);
  114920. acc+=val*val;
  114921. }
  114922. return(acc);
  114923. }
  114924. int _best(codebook *book, float *a, int step){
  114925. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114926. #if 0
  114927. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  114928. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  114929. #endif
  114930. int dim=book->dim;
  114931. int k,o;
  114932. /*int savebest=-1;
  114933. float saverr;*/
  114934. /* do we have a threshhold encode hint? */
  114935. if(tt){
  114936. int index=0,i;
  114937. /* find the quant val of each scalar */
  114938. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114939. i=tt->threshvals>>1;
  114940. if(a[o]<tt->quantthresh[i]){
  114941. for(;i>0;i--)
  114942. if(a[o]>=tt->quantthresh[i-1])
  114943. break;
  114944. }else{
  114945. for(i++;i<tt->threshvals-1;i++)
  114946. if(a[o]<tt->quantthresh[i])break;
  114947. }
  114948. index=(index*tt->quantvals)+tt->quantmap[i];
  114949. }
  114950. /* regular lattices are easy :-) */
  114951. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  114952. use a decision tree after all
  114953. and fall through*/
  114954. return(index);
  114955. }
  114956. #if 0
  114957. /* do we have a pigeonhole encode hint? */
  114958. if(pt){
  114959. const static_codebook *c=book->c;
  114960. int i,besti=-1;
  114961. float best=0.f;
  114962. int entry=0;
  114963. /* dealing with sequentialness is a pain in the ass */
  114964. if(c->q_sequencep){
  114965. int pv;
  114966. long mul=1;
  114967. float qlast=0;
  114968. for(k=0,o=0;k<dim;k++,o+=step){
  114969. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  114970. if(pv<0 || pv>=pt->mapentries)break;
  114971. entry+=pt->pigeonmap[pv]*mul;
  114972. mul*=pt->quantvals;
  114973. qlast+=pv*pt->del+pt->min;
  114974. }
  114975. }else{
  114976. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114977. int pv=(int)((a[o]-pt->min)/pt->del);
  114978. if(pv<0 || pv>=pt->mapentries)break;
  114979. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  114980. }
  114981. }
  114982. /* must be within the pigeonholable range; if we quant outside (or
  114983. in an entry that we define no list for), brute force it */
  114984. if(k==dim && pt->fitlength[entry]){
  114985. /* search the abbreviated list */
  114986. long *list=pt->fitlist+pt->fitmap[entry];
  114987. for(i=0;i<pt->fitlength[entry];i++){
  114988. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  114989. if(besti==-1 || this<best){
  114990. best=this;
  114991. besti=list[i];
  114992. }
  114993. }
  114994. return(besti);
  114995. }
  114996. }
  114997. if(nt){
  114998. /* optimized using the decision tree */
  114999. while(1){
  115000. float c=0.f;
  115001. float *p=book->valuelist+nt->p[ptr];
  115002. float *q=book->valuelist+nt->q[ptr];
  115003. for(k=0,o=0;k<dim;k++,o+=step)
  115004. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  115005. if(c>0.f) /* in A */
  115006. ptr= -nt->ptr0[ptr];
  115007. else /* in B */
  115008. ptr= -nt->ptr1[ptr];
  115009. if(ptr<=0)break;
  115010. }
  115011. return(-ptr);
  115012. }
  115013. #endif
  115014. /* brute force it! */
  115015. {
  115016. const static_codebook *c=book->c;
  115017. int i,besti=-1;
  115018. float best=0.f;
  115019. float *e=book->valuelist;
  115020. for(i=0;i<book->entries;i++){
  115021. if(c->lengthlist[i]>0){
  115022. float thisx=_dist(dim,e,a,step);
  115023. if(besti==-1 || thisx<best){
  115024. best=thisx;
  115025. besti=i;
  115026. }
  115027. }
  115028. e+=dim;
  115029. }
  115030. /*if(savebest!=-1 && savebest!=besti){
  115031. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  115032. "original:");
  115033. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  115034. fprintf(stderr,"\n"
  115035. "pigeonhole (entry %d, err %g):",savebest,saverr);
  115036. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  115037. (book->valuelist+savebest*dim)[i]);
  115038. fprintf(stderr,"\n"
  115039. "bruteforce (entry %d, err %g):",besti,best);
  115040. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  115041. (book->valuelist+besti*dim)[i]);
  115042. fprintf(stderr,"\n");
  115043. }*/
  115044. return(besti);
  115045. }
  115046. }
  115047. long vorbis_book_codeword(codebook *book,int entry){
  115048. if(book->c) /* only use with encode; decode optimizations are
  115049. allowed to break this */
  115050. return book->codelist[entry];
  115051. return -1;
  115052. }
  115053. long vorbis_book_codelen(codebook *book,int entry){
  115054. if(book->c) /* only use with encode; decode optimizations are
  115055. allowed to break this */
  115056. return book->c->lengthlist[entry];
  115057. return -1;
  115058. }
  115059. #ifdef _V_SELFTEST
  115060. /* Unit tests of the dequantizer; this stuff will be OK
  115061. cross-platform, I simply want to be sure that special mapping cases
  115062. actually work properly; a bug could go unnoticed for a while */
  115063. #include <stdio.h>
  115064. /* cases:
  115065. no mapping
  115066. full, explicit mapping
  115067. algorithmic mapping
  115068. nonsequential
  115069. sequential
  115070. */
  115071. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  115072. static long partial_quantlist1[]={0,7,2};
  115073. /* no mapping */
  115074. static_codebook test1={
  115075. 4,16,
  115076. NULL,
  115077. 0,
  115078. 0,0,0,0,
  115079. NULL,
  115080. NULL,NULL
  115081. };
  115082. static float *test1_result=NULL;
  115083. /* linear, full mapping, nonsequential */
  115084. static_codebook test2={
  115085. 4,3,
  115086. NULL,
  115087. 2,
  115088. -533200896,1611661312,4,0,
  115089. full_quantlist1,
  115090. NULL,NULL
  115091. };
  115092. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  115093. /* linear, full mapping, sequential */
  115094. static_codebook test3={
  115095. 4,3,
  115096. NULL,
  115097. 2,
  115098. -533200896,1611661312,4,1,
  115099. full_quantlist1,
  115100. NULL,NULL
  115101. };
  115102. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  115103. /* linear, algorithmic mapping, nonsequential */
  115104. static_codebook test4={
  115105. 3,27,
  115106. NULL,
  115107. 1,
  115108. -533200896,1611661312,4,0,
  115109. partial_quantlist1,
  115110. NULL,NULL
  115111. };
  115112. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  115113. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  115114. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  115115. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  115116. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  115117. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  115118. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  115119. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  115120. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  115121. /* linear, algorithmic mapping, sequential */
  115122. static_codebook test5={
  115123. 3,27,
  115124. NULL,
  115125. 1,
  115126. -533200896,1611661312,4,1,
  115127. partial_quantlist1,
  115128. NULL,NULL
  115129. };
  115130. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  115131. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  115132. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  115133. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  115134. -3, 1, 5, 4, 8,12, -1, 3, 7,
  115135. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  115136. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  115137. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  115138. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  115139. void run_test(static_codebook *b,float *comp){
  115140. float *out=_book_unquantize(b,b->entries,NULL);
  115141. int i;
  115142. if(comp){
  115143. if(!out){
  115144. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  115145. exit(1);
  115146. }
  115147. for(i=0;i<b->entries*b->dim;i++)
  115148. if(fabs(out[i]-comp[i])>.0001){
  115149. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  115150. "position %d, %g != %g\n",i,out[i],comp[i]);
  115151. exit(1);
  115152. }
  115153. }else{
  115154. if(out){
  115155. fprintf(stderr,"_book_unquantize returned a value array: \n"
  115156. " correct result should have been NULL\n");
  115157. exit(1);
  115158. }
  115159. }
  115160. }
  115161. int main(){
  115162. /* run the nine dequant tests, and compare to the hand-rolled results */
  115163. fprintf(stderr,"Dequant test 1... ");
  115164. run_test(&test1,test1_result);
  115165. fprintf(stderr,"OK\nDequant test 2... ");
  115166. run_test(&test2,test2_result);
  115167. fprintf(stderr,"OK\nDequant test 3... ");
  115168. run_test(&test3,test3_result);
  115169. fprintf(stderr,"OK\nDequant test 4... ");
  115170. run_test(&test4,test4_result);
  115171. fprintf(stderr,"OK\nDequant test 5... ");
  115172. run_test(&test5,test5_result);
  115173. fprintf(stderr,"OK\n\n");
  115174. return(0);
  115175. }
  115176. #endif
  115177. #endif
  115178. /********* End of inlined file: sharedbook.c *********/
  115179. /********* Start of inlined file: smallft.c *********/
  115180. /* FFT implementation from OggSquish, minus cosine transforms,
  115181. * minus all but radix 2/4 case. In Vorbis we only need this
  115182. * cut-down version.
  115183. *
  115184. * To do more than just power-of-two sized vectors, see the full
  115185. * version I wrote for NetLib.
  115186. *
  115187. * Note that the packing is a little strange; rather than the FFT r/i
  115188. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  115189. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  115190. * FORTRAN version
  115191. */
  115192. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115193. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115194. // tasks..
  115195. #if JUCE_MSVC
  115196. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115197. #endif
  115198. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115199. #if JUCE_USE_OGGVORBIS
  115200. #include <stdlib.h>
  115201. #include <string.h>
  115202. #include <math.h>
  115203. static void drfti1(int n, float *wa, int *ifac){
  115204. static int ntryh[4] = { 4,2,3,5 };
  115205. static float tpi = 6.28318530717958648f;
  115206. float arg,argh,argld,fi;
  115207. int ntry=0,i,j=-1;
  115208. int k1, l1, l2, ib;
  115209. int ld, ii, ip, is, nq, nr;
  115210. int ido, ipm, nfm1;
  115211. int nl=n;
  115212. int nf=0;
  115213. L101:
  115214. j++;
  115215. if (j < 4)
  115216. ntry=ntryh[j];
  115217. else
  115218. ntry+=2;
  115219. L104:
  115220. nq=nl/ntry;
  115221. nr=nl-ntry*nq;
  115222. if (nr!=0) goto L101;
  115223. nf++;
  115224. ifac[nf+1]=ntry;
  115225. nl=nq;
  115226. if(ntry!=2)goto L107;
  115227. if(nf==1)goto L107;
  115228. for (i=1;i<nf;i++){
  115229. ib=nf-i+1;
  115230. ifac[ib+1]=ifac[ib];
  115231. }
  115232. ifac[2] = 2;
  115233. L107:
  115234. if(nl!=1)goto L104;
  115235. ifac[0]=n;
  115236. ifac[1]=nf;
  115237. argh=tpi/n;
  115238. is=0;
  115239. nfm1=nf-1;
  115240. l1=1;
  115241. if(nfm1==0)return;
  115242. for (k1=0;k1<nfm1;k1++){
  115243. ip=ifac[k1+2];
  115244. ld=0;
  115245. l2=l1*ip;
  115246. ido=n/l2;
  115247. ipm=ip-1;
  115248. for (j=0;j<ipm;j++){
  115249. ld+=l1;
  115250. i=is;
  115251. argld=(float)ld*argh;
  115252. fi=0.f;
  115253. for (ii=2;ii<ido;ii+=2){
  115254. fi+=1.f;
  115255. arg=fi*argld;
  115256. wa[i++]=cos(arg);
  115257. wa[i++]=sin(arg);
  115258. }
  115259. is+=ido;
  115260. }
  115261. l1=l2;
  115262. }
  115263. }
  115264. static void fdrffti(int n, float *wsave, int *ifac){
  115265. if (n == 1) return;
  115266. drfti1(n, wsave+n, ifac);
  115267. }
  115268. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  115269. int i,k;
  115270. float ti2,tr2;
  115271. int t0,t1,t2,t3,t4,t5,t6;
  115272. t1=0;
  115273. t0=(t2=l1*ido);
  115274. t3=ido<<1;
  115275. for(k=0;k<l1;k++){
  115276. ch[t1<<1]=cc[t1]+cc[t2];
  115277. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  115278. t1+=ido;
  115279. t2+=ido;
  115280. }
  115281. if(ido<2)return;
  115282. if(ido==2)goto L105;
  115283. t1=0;
  115284. t2=t0;
  115285. for(k=0;k<l1;k++){
  115286. t3=t2;
  115287. t4=(t1<<1)+(ido<<1);
  115288. t5=t1;
  115289. t6=t1+t1;
  115290. for(i=2;i<ido;i+=2){
  115291. t3+=2;
  115292. t4-=2;
  115293. t5+=2;
  115294. t6+=2;
  115295. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115296. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115297. ch[t6]=cc[t5]+ti2;
  115298. ch[t4]=ti2-cc[t5];
  115299. ch[t6-1]=cc[t5-1]+tr2;
  115300. ch[t4-1]=cc[t5-1]-tr2;
  115301. }
  115302. t1+=ido;
  115303. t2+=ido;
  115304. }
  115305. if(ido%2==1)return;
  115306. L105:
  115307. t3=(t2=(t1=ido)-1);
  115308. t2+=t0;
  115309. for(k=0;k<l1;k++){
  115310. ch[t1]=-cc[t2];
  115311. ch[t1-1]=cc[t3];
  115312. t1+=ido<<1;
  115313. t2+=ido;
  115314. t3+=ido;
  115315. }
  115316. }
  115317. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  115318. float *wa2,float *wa3){
  115319. static float hsqt2 = .70710678118654752f;
  115320. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115321. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115322. t0=l1*ido;
  115323. t1=t0;
  115324. t4=t1<<1;
  115325. t2=t1+(t1<<1);
  115326. t3=0;
  115327. for(k=0;k<l1;k++){
  115328. tr1=cc[t1]+cc[t2];
  115329. tr2=cc[t3]+cc[t4];
  115330. ch[t5=t3<<2]=tr1+tr2;
  115331. ch[(ido<<2)+t5-1]=tr2-tr1;
  115332. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  115333. ch[t5]=cc[t2]-cc[t1];
  115334. t1+=ido;
  115335. t2+=ido;
  115336. t3+=ido;
  115337. t4+=ido;
  115338. }
  115339. if(ido<2)return;
  115340. if(ido==2)goto L105;
  115341. t1=0;
  115342. for(k=0;k<l1;k++){
  115343. t2=t1;
  115344. t4=t1<<2;
  115345. t5=(t6=ido<<1)+t4;
  115346. for(i=2;i<ido;i+=2){
  115347. t3=(t2+=2);
  115348. t4+=2;
  115349. t5-=2;
  115350. t3+=t0;
  115351. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115352. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115353. t3+=t0;
  115354. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  115355. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  115356. t3+=t0;
  115357. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  115358. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  115359. tr1=cr2+cr4;
  115360. tr4=cr4-cr2;
  115361. ti1=ci2+ci4;
  115362. ti4=ci2-ci4;
  115363. ti2=cc[t2]+ci3;
  115364. ti3=cc[t2]-ci3;
  115365. tr2=cc[t2-1]+cr3;
  115366. tr3=cc[t2-1]-cr3;
  115367. ch[t4-1]=tr1+tr2;
  115368. ch[t4]=ti1+ti2;
  115369. ch[t5-1]=tr3-ti4;
  115370. ch[t5]=tr4-ti3;
  115371. ch[t4+t6-1]=ti4+tr3;
  115372. ch[t4+t6]=tr4+ti3;
  115373. ch[t5+t6-1]=tr2-tr1;
  115374. ch[t5+t6]=ti1-ti2;
  115375. }
  115376. t1+=ido;
  115377. }
  115378. if(ido&1)return;
  115379. L105:
  115380. t2=(t1=t0+ido-1)+(t0<<1);
  115381. t3=ido<<2;
  115382. t4=ido;
  115383. t5=ido<<1;
  115384. t6=ido;
  115385. for(k=0;k<l1;k++){
  115386. ti1=-hsqt2*(cc[t1]+cc[t2]);
  115387. tr1=hsqt2*(cc[t1]-cc[t2]);
  115388. ch[t4-1]=tr1+cc[t6-1];
  115389. ch[t4+t5-1]=cc[t6-1]-tr1;
  115390. ch[t4]=ti1-cc[t1+t0];
  115391. ch[t4+t5]=ti1+cc[t1+t0];
  115392. t1+=ido;
  115393. t2+=ido;
  115394. t4+=t3;
  115395. t6+=ido;
  115396. }
  115397. }
  115398. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115399. float *c2,float *ch,float *ch2,float *wa){
  115400. static float tpi=6.283185307179586f;
  115401. int idij,ipph,i,j,k,l,ic,ik,is;
  115402. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115403. float dc2,ai1,ai2,ar1,ar2,ds2;
  115404. int nbd;
  115405. float dcp,arg,dsp,ar1h,ar2h;
  115406. int idp2,ipp2;
  115407. arg=tpi/(float)ip;
  115408. dcp=cos(arg);
  115409. dsp=sin(arg);
  115410. ipph=(ip+1)>>1;
  115411. ipp2=ip;
  115412. idp2=ido;
  115413. nbd=(ido-1)>>1;
  115414. t0=l1*ido;
  115415. t10=ip*ido;
  115416. if(ido==1)goto L119;
  115417. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  115418. t1=0;
  115419. for(j=1;j<ip;j++){
  115420. t1+=t0;
  115421. t2=t1;
  115422. for(k=0;k<l1;k++){
  115423. ch[t2]=c1[t2];
  115424. t2+=ido;
  115425. }
  115426. }
  115427. is=-ido;
  115428. t1=0;
  115429. if(nbd>l1){
  115430. for(j=1;j<ip;j++){
  115431. t1+=t0;
  115432. is+=ido;
  115433. t2= -ido+t1;
  115434. for(k=0;k<l1;k++){
  115435. idij=is-1;
  115436. t2+=ido;
  115437. t3=t2;
  115438. for(i=2;i<ido;i+=2){
  115439. idij+=2;
  115440. t3+=2;
  115441. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115442. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115443. }
  115444. }
  115445. }
  115446. }else{
  115447. for(j=1;j<ip;j++){
  115448. is+=ido;
  115449. idij=is-1;
  115450. t1+=t0;
  115451. t2=t1;
  115452. for(i=2;i<ido;i+=2){
  115453. idij+=2;
  115454. t2+=2;
  115455. t3=t2;
  115456. for(k=0;k<l1;k++){
  115457. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115458. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115459. t3+=ido;
  115460. }
  115461. }
  115462. }
  115463. }
  115464. t1=0;
  115465. t2=ipp2*t0;
  115466. if(nbd<l1){
  115467. for(j=1;j<ipph;j++){
  115468. t1+=t0;
  115469. t2-=t0;
  115470. t3=t1;
  115471. t4=t2;
  115472. for(i=2;i<ido;i+=2){
  115473. t3+=2;
  115474. t4+=2;
  115475. t5=t3-ido;
  115476. t6=t4-ido;
  115477. for(k=0;k<l1;k++){
  115478. t5+=ido;
  115479. t6+=ido;
  115480. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115481. c1[t6-1]=ch[t5]-ch[t6];
  115482. c1[t5]=ch[t5]+ch[t6];
  115483. c1[t6]=ch[t6-1]-ch[t5-1];
  115484. }
  115485. }
  115486. }
  115487. }else{
  115488. for(j=1;j<ipph;j++){
  115489. t1+=t0;
  115490. t2-=t0;
  115491. t3=t1;
  115492. t4=t2;
  115493. for(k=0;k<l1;k++){
  115494. t5=t3;
  115495. t6=t4;
  115496. for(i=2;i<ido;i+=2){
  115497. t5+=2;
  115498. t6+=2;
  115499. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115500. c1[t6-1]=ch[t5]-ch[t6];
  115501. c1[t5]=ch[t5]+ch[t6];
  115502. c1[t6]=ch[t6-1]-ch[t5-1];
  115503. }
  115504. t3+=ido;
  115505. t4+=ido;
  115506. }
  115507. }
  115508. }
  115509. L119:
  115510. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115511. t1=0;
  115512. t2=ipp2*idl1;
  115513. for(j=1;j<ipph;j++){
  115514. t1+=t0;
  115515. t2-=t0;
  115516. t3=t1-ido;
  115517. t4=t2-ido;
  115518. for(k=0;k<l1;k++){
  115519. t3+=ido;
  115520. t4+=ido;
  115521. c1[t3]=ch[t3]+ch[t4];
  115522. c1[t4]=ch[t4]-ch[t3];
  115523. }
  115524. }
  115525. ar1=1.f;
  115526. ai1=0.f;
  115527. t1=0;
  115528. t2=ipp2*idl1;
  115529. t3=(ip-1)*idl1;
  115530. for(l=1;l<ipph;l++){
  115531. t1+=idl1;
  115532. t2-=idl1;
  115533. ar1h=dcp*ar1-dsp*ai1;
  115534. ai1=dcp*ai1+dsp*ar1;
  115535. ar1=ar1h;
  115536. t4=t1;
  115537. t5=t2;
  115538. t6=t3;
  115539. t7=idl1;
  115540. for(ik=0;ik<idl1;ik++){
  115541. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  115542. ch2[t5++]=ai1*c2[t6++];
  115543. }
  115544. dc2=ar1;
  115545. ds2=ai1;
  115546. ar2=ar1;
  115547. ai2=ai1;
  115548. t4=idl1;
  115549. t5=(ipp2-1)*idl1;
  115550. for(j=2;j<ipph;j++){
  115551. t4+=idl1;
  115552. t5-=idl1;
  115553. ar2h=dc2*ar2-ds2*ai2;
  115554. ai2=dc2*ai2+ds2*ar2;
  115555. ar2=ar2h;
  115556. t6=t1;
  115557. t7=t2;
  115558. t8=t4;
  115559. t9=t5;
  115560. for(ik=0;ik<idl1;ik++){
  115561. ch2[t6++]+=ar2*c2[t8++];
  115562. ch2[t7++]+=ai2*c2[t9++];
  115563. }
  115564. }
  115565. }
  115566. t1=0;
  115567. for(j=1;j<ipph;j++){
  115568. t1+=idl1;
  115569. t2=t1;
  115570. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  115571. }
  115572. if(ido<l1)goto L132;
  115573. t1=0;
  115574. t2=0;
  115575. for(k=0;k<l1;k++){
  115576. t3=t1;
  115577. t4=t2;
  115578. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  115579. t1+=ido;
  115580. t2+=t10;
  115581. }
  115582. goto L135;
  115583. L132:
  115584. for(i=0;i<ido;i++){
  115585. t1=i;
  115586. t2=i;
  115587. for(k=0;k<l1;k++){
  115588. cc[t2]=ch[t1];
  115589. t1+=ido;
  115590. t2+=t10;
  115591. }
  115592. }
  115593. L135:
  115594. t1=0;
  115595. t2=ido<<1;
  115596. t3=0;
  115597. t4=ipp2*t0;
  115598. for(j=1;j<ipph;j++){
  115599. t1+=t2;
  115600. t3+=t0;
  115601. t4-=t0;
  115602. t5=t1;
  115603. t6=t3;
  115604. t7=t4;
  115605. for(k=0;k<l1;k++){
  115606. cc[t5-1]=ch[t6];
  115607. cc[t5]=ch[t7];
  115608. t5+=t10;
  115609. t6+=ido;
  115610. t7+=ido;
  115611. }
  115612. }
  115613. if(ido==1)return;
  115614. if(nbd<l1)goto L141;
  115615. t1=-ido;
  115616. t3=0;
  115617. t4=0;
  115618. t5=ipp2*t0;
  115619. for(j=1;j<ipph;j++){
  115620. t1+=t2;
  115621. t3+=t2;
  115622. t4+=t0;
  115623. t5-=t0;
  115624. t6=t1;
  115625. t7=t3;
  115626. t8=t4;
  115627. t9=t5;
  115628. for(k=0;k<l1;k++){
  115629. for(i=2;i<ido;i+=2){
  115630. ic=idp2-i;
  115631. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  115632. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  115633. cc[i+t7]=ch[i+t8]+ch[i+t9];
  115634. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  115635. }
  115636. t6+=t10;
  115637. t7+=t10;
  115638. t8+=ido;
  115639. t9+=ido;
  115640. }
  115641. }
  115642. return;
  115643. L141:
  115644. t1=-ido;
  115645. t3=0;
  115646. t4=0;
  115647. t5=ipp2*t0;
  115648. for(j=1;j<ipph;j++){
  115649. t1+=t2;
  115650. t3+=t2;
  115651. t4+=t0;
  115652. t5-=t0;
  115653. for(i=2;i<ido;i+=2){
  115654. t6=idp2+t1-i;
  115655. t7=i+t3;
  115656. t8=i+t4;
  115657. t9=i+t5;
  115658. for(k=0;k<l1;k++){
  115659. cc[t7-1]=ch[t8-1]+ch[t9-1];
  115660. cc[t6-1]=ch[t8-1]-ch[t9-1];
  115661. cc[t7]=ch[t8]+ch[t9];
  115662. cc[t6]=ch[t9]-ch[t8];
  115663. t6+=t10;
  115664. t7+=t10;
  115665. t8+=ido;
  115666. t9+=ido;
  115667. }
  115668. }
  115669. }
  115670. }
  115671. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  115672. int i,k1,l1,l2;
  115673. int na,kh,nf;
  115674. int ip,iw,ido,idl1,ix2,ix3;
  115675. nf=ifac[1];
  115676. na=1;
  115677. l2=n;
  115678. iw=n;
  115679. for(k1=0;k1<nf;k1++){
  115680. kh=nf-k1;
  115681. ip=ifac[kh+1];
  115682. l1=l2/ip;
  115683. ido=n/l2;
  115684. idl1=ido*l1;
  115685. iw-=(ip-1)*ido;
  115686. na=1-na;
  115687. if(ip!=4)goto L102;
  115688. ix2=iw+ido;
  115689. ix3=ix2+ido;
  115690. if(na!=0)
  115691. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115692. else
  115693. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115694. goto L110;
  115695. L102:
  115696. if(ip!=2)goto L104;
  115697. if(na!=0)goto L103;
  115698. dradf2(ido,l1,c,ch,wa+iw-1);
  115699. goto L110;
  115700. L103:
  115701. dradf2(ido,l1,ch,c,wa+iw-1);
  115702. goto L110;
  115703. L104:
  115704. if(ido==1)na=1-na;
  115705. if(na!=0)goto L109;
  115706. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  115707. na=1;
  115708. goto L110;
  115709. L109:
  115710. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  115711. na=0;
  115712. L110:
  115713. l2=l1;
  115714. }
  115715. if(na==1)return;
  115716. for(i=0;i<n;i++)c[i]=ch[i];
  115717. }
  115718. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  115719. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115720. float ti2,tr2;
  115721. t0=l1*ido;
  115722. t1=0;
  115723. t2=0;
  115724. t3=(ido<<1)-1;
  115725. for(k=0;k<l1;k++){
  115726. ch[t1]=cc[t2]+cc[t3+t2];
  115727. ch[t1+t0]=cc[t2]-cc[t3+t2];
  115728. t2=(t1+=ido)<<1;
  115729. }
  115730. if(ido<2)return;
  115731. if(ido==2)goto L105;
  115732. t1=0;
  115733. t2=0;
  115734. for(k=0;k<l1;k++){
  115735. t3=t1;
  115736. t5=(t4=t2)+(ido<<1);
  115737. t6=t0+t1;
  115738. for(i=2;i<ido;i+=2){
  115739. t3+=2;
  115740. t4+=2;
  115741. t5-=2;
  115742. t6+=2;
  115743. ch[t3-1]=cc[t4-1]+cc[t5-1];
  115744. tr2=cc[t4-1]-cc[t5-1];
  115745. ch[t3]=cc[t4]-cc[t5];
  115746. ti2=cc[t4]+cc[t5];
  115747. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  115748. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  115749. }
  115750. t2=(t1+=ido)<<1;
  115751. }
  115752. if(ido%2==1)return;
  115753. L105:
  115754. t1=ido-1;
  115755. t2=ido-1;
  115756. for(k=0;k<l1;k++){
  115757. ch[t1]=cc[t2]+cc[t2];
  115758. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  115759. t1+=ido;
  115760. t2+=ido<<1;
  115761. }
  115762. }
  115763. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  115764. float *wa2){
  115765. static float taur = -.5f;
  115766. static float taui = .8660254037844386f;
  115767. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115768. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  115769. t0=l1*ido;
  115770. t1=0;
  115771. t2=t0<<1;
  115772. t3=ido<<1;
  115773. t4=ido+(ido<<1);
  115774. t5=0;
  115775. for(k=0;k<l1;k++){
  115776. tr2=cc[t3-1]+cc[t3-1];
  115777. cr2=cc[t5]+(taur*tr2);
  115778. ch[t1]=cc[t5]+tr2;
  115779. ci3=taui*(cc[t3]+cc[t3]);
  115780. ch[t1+t0]=cr2-ci3;
  115781. ch[t1+t2]=cr2+ci3;
  115782. t1+=ido;
  115783. t3+=t4;
  115784. t5+=t4;
  115785. }
  115786. if(ido==1)return;
  115787. t1=0;
  115788. t3=ido<<1;
  115789. for(k=0;k<l1;k++){
  115790. t7=t1+(t1<<1);
  115791. t6=(t5=t7+t3);
  115792. t8=t1;
  115793. t10=(t9=t1+t0)+t0;
  115794. for(i=2;i<ido;i+=2){
  115795. t5+=2;
  115796. t6-=2;
  115797. t7+=2;
  115798. t8+=2;
  115799. t9+=2;
  115800. t10+=2;
  115801. tr2=cc[t5-1]+cc[t6-1];
  115802. cr2=cc[t7-1]+(taur*tr2);
  115803. ch[t8-1]=cc[t7-1]+tr2;
  115804. ti2=cc[t5]-cc[t6];
  115805. ci2=cc[t7]+(taur*ti2);
  115806. ch[t8]=cc[t7]+ti2;
  115807. cr3=taui*(cc[t5-1]-cc[t6-1]);
  115808. ci3=taui*(cc[t5]+cc[t6]);
  115809. dr2=cr2-ci3;
  115810. dr3=cr2+ci3;
  115811. di2=ci2+cr3;
  115812. di3=ci2-cr3;
  115813. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  115814. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  115815. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  115816. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  115817. }
  115818. t1+=ido;
  115819. }
  115820. }
  115821. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  115822. float *wa2,float *wa3){
  115823. static float sqrt2=1.414213562373095f;
  115824. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  115825. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115826. t0=l1*ido;
  115827. t1=0;
  115828. t2=ido<<2;
  115829. t3=0;
  115830. t6=ido<<1;
  115831. for(k=0;k<l1;k++){
  115832. t4=t3+t6;
  115833. t5=t1;
  115834. tr3=cc[t4-1]+cc[t4-1];
  115835. tr4=cc[t4]+cc[t4];
  115836. tr1=cc[t3]-cc[(t4+=t6)-1];
  115837. tr2=cc[t3]+cc[t4-1];
  115838. ch[t5]=tr2+tr3;
  115839. ch[t5+=t0]=tr1-tr4;
  115840. ch[t5+=t0]=tr2-tr3;
  115841. ch[t5+=t0]=tr1+tr4;
  115842. t1+=ido;
  115843. t3+=t2;
  115844. }
  115845. if(ido<2)return;
  115846. if(ido==2)goto L105;
  115847. t1=0;
  115848. for(k=0;k<l1;k++){
  115849. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  115850. t7=t1;
  115851. for(i=2;i<ido;i+=2){
  115852. t2+=2;
  115853. t3+=2;
  115854. t4-=2;
  115855. t5-=2;
  115856. t7+=2;
  115857. ti1=cc[t2]+cc[t5];
  115858. ti2=cc[t2]-cc[t5];
  115859. ti3=cc[t3]-cc[t4];
  115860. tr4=cc[t3]+cc[t4];
  115861. tr1=cc[t2-1]-cc[t5-1];
  115862. tr2=cc[t2-1]+cc[t5-1];
  115863. ti4=cc[t3-1]-cc[t4-1];
  115864. tr3=cc[t3-1]+cc[t4-1];
  115865. ch[t7-1]=tr2+tr3;
  115866. cr3=tr2-tr3;
  115867. ch[t7]=ti2+ti3;
  115868. ci3=ti2-ti3;
  115869. cr2=tr1-tr4;
  115870. cr4=tr1+tr4;
  115871. ci2=ti1+ti4;
  115872. ci4=ti1-ti4;
  115873. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  115874. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  115875. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  115876. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  115877. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  115878. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  115879. }
  115880. t1+=ido;
  115881. }
  115882. if(ido%2 == 1)return;
  115883. L105:
  115884. t1=ido;
  115885. t2=ido<<2;
  115886. t3=ido-1;
  115887. t4=ido+(ido<<1);
  115888. for(k=0;k<l1;k++){
  115889. t5=t3;
  115890. ti1=cc[t1]+cc[t4];
  115891. ti2=cc[t4]-cc[t1];
  115892. tr1=cc[t1-1]-cc[t4-1];
  115893. tr2=cc[t1-1]+cc[t4-1];
  115894. ch[t5]=tr2+tr2;
  115895. ch[t5+=t0]=sqrt2*(tr1-ti1);
  115896. ch[t5+=t0]=ti2+ti2;
  115897. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  115898. t3+=ido;
  115899. t1+=t2;
  115900. t4+=t2;
  115901. }
  115902. }
  115903. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115904. float *c2,float *ch,float *ch2,float *wa){
  115905. static float tpi=6.283185307179586f;
  115906. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  115907. t11,t12;
  115908. float dc2,ai1,ai2,ar1,ar2,ds2;
  115909. int nbd;
  115910. float dcp,arg,dsp,ar1h,ar2h;
  115911. int ipp2;
  115912. t10=ip*ido;
  115913. t0=l1*ido;
  115914. arg=tpi/(float)ip;
  115915. dcp=cos(arg);
  115916. dsp=sin(arg);
  115917. nbd=(ido-1)>>1;
  115918. ipp2=ip;
  115919. ipph=(ip+1)>>1;
  115920. if(ido<l1)goto L103;
  115921. t1=0;
  115922. t2=0;
  115923. for(k=0;k<l1;k++){
  115924. t3=t1;
  115925. t4=t2;
  115926. for(i=0;i<ido;i++){
  115927. ch[t3]=cc[t4];
  115928. t3++;
  115929. t4++;
  115930. }
  115931. t1+=ido;
  115932. t2+=t10;
  115933. }
  115934. goto L106;
  115935. L103:
  115936. t1=0;
  115937. for(i=0;i<ido;i++){
  115938. t2=t1;
  115939. t3=t1;
  115940. for(k=0;k<l1;k++){
  115941. ch[t2]=cc[t3];
  115942. t2+=ido;
  115943. t3+=t10;
  115944. }
  115945. t1++;
  115946. }
  115947. L106:
  115948. t1=0;
  115949. t2=ipp2*t0;
  115950. t7=(t5=ido<<1);
  115951. for(j=1;j<ipph;j++){
  115952. t1+=t0;
  115953. t2-=t0;
  115954. t3=t1;
  115955. t4=t2;
  115956. t6=t5;
  115957. for(k=0;k<l1;k++){
  115958. ch[t3]=cc[t6-1]+cc[t6-1];
  115959. ch[t4]=cc[t6]+cc[t6];
  115960. t3+=ido;
  115961. t4+=ido;
  115962. t6+=t10;
  115963. }
  115964. t5+=t7;
  115965. }
  115966. if (ido == 1)goto L116;
  115967. if(nbd<l1)goto L112;
  115968. t1=0;
  115969. t2=ipp2*t0;
  115970. t7=0;
  115971. for(j=1;j<ipph;j++){
  115972. t1+=t0;
  115973. t2-=t0;
  115974. t3=t1;
  115975. t4=t2;
  115976. t7+=(ido<<1);
  115977. t8=t7;
  115978. for(k=0;k<l1;k++){
  115979. t5=t3;
  115980. t6=t4;
  115981. t9=t8;
  115982. t11=t8;
  115983. for(i=2;i<ido;i+=2){
  115984. t5+=2;
  115985. t6+=2;
  115986. t9+=2;
  115987. t11-=2;
  115988. ch[t5-1]=cc[t9-1]+cc[t11-1];
  115989. ch[t6-1]=cc[t9-1]-cc[t11-1];
  115990. ch[t5]=cc[t9]-cc[t11];
  115991. ch[t6]=cc[t9]+cc[t11];
  115992. }
  115993. t3+=ido;
  115994. t4+=ido;
  115995. t8+=t10;
  115996. }
  115997. }
  115998. goto L116;
  115999. L112:
  116000. t1=0;
  116001. t2=ipp2*t0;
  116002. t7=0;
  116003. for(j=1;j<ipph;j++){
  116004. t1+=t0;
  116005. t2-=t0;
  116006. t3=t1;
  116007. t4=t2;
  116008. t7+=(ido<<1);
  116009. t8=t7;
  116010. t9=t7;
  116011. for(i=2;i<ido;i+=2){
  116012. t3+=2;
  116013. t4+=2;
  116014. t8+=2;
  116015. t9-=2;
  116016. t5=t3;
  116017. t6=t4;
  116018. t11=t8;
  116019. t12=t9;
  116020. for(k=0;k<l1;k++){
  116021. ch[t5-1]=cc[t11-1]+cc[t12-1];
  116022. ch[t6-1]=cc[t11-1]-cc[t12-1];
  116023. ch[t5]=cc[t11]-cc[t12];
  116024. ch[t6]=cc[t11]+cc[t12];
  116025. t5+=ido;
  116026. t6+=ido;
  116027. t11+=t10;
  116028. t12+=t10;
  116029. }
  116030. }
  116031. }
  116032. L116:
  116033. ar1=1.f;
  116034. ai1=0.f;
  116035. t1=0;
  116036. t9=(t2=ipp2*idl1);
  116037. t3=(ip-1)*idl1;
  116038. for(l=1;l<ipph;l++){
  116039. t1+=idl1;
  116040. t2-=idl1;
  116041. ar1h=dcp*ar1-dsp*ai1;
  116042. ai1=dcp*ai1+dsp*ar1;
  116043. ar1=ar1h;
  116044. t4=t1;
  116045. t5=t2;
  116046. t6=0;
  116047. t7=idl1;
  116048. t8=t3;
  116049. for(ik=0;ik<idl1;ik++){
  116050. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  116051. c2[t5++]=ai1*ch2[t8++];
  116052. }
  116053. dc2=ar1;
  116054. ds2=ai1;
  116055. ar2=ar1;
  116056. ai2=ai1;
  116057. t6=idl1;
  116058. t7=t9-idl1;
  116059. for(j=2;j<ipph;j++){
  116060. t6+=idl1;
  116061. t7-=idl1;
  116062. ar2h=dc2*ar2-ds2*ai2;
  116063. ai2=dc2*ai2+ds2*ar2;
  116064. ar2=ar2h;
  116065. t4=t1;
  116066. t5=t2;
  116067. t11=t6;
  116068. t12=t7;
  116069. for(ik=0;ik<idl1;ik++){
  116070. c2[t4++]+=ar2*ch2[t11++];
  116071. c2[t5++]+=ai2*ch2[t12++];
  116072. }
  116073. }
  116074. }
  116075. t1=0;
  116076. for(j=1;j<ipph;j++){
  116077. t1+=idl1;
  116078. t2=t1;
  116079. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  116080. }
  116081. t1=0;
  116082. t2=ipp2*t0;
  116083. for(j=1;j<ipph;j++){
  116084. t1+=t0;
  116085. t2-=t0;
  116086. t3=t1;
  116087. t4=t2;
  116088. for(k=0;k<l1;k++){
  116089. ch[t3]=c1[t3]-c1[t4];
  116090. ch[t4]=c1[t3]+c1[t4];
  116091. t3+=ido;
  116092. t4+=ido;
  116093. }
  116094. }
  116095. if(ido==1)goto L132;
  116096. if(nbd<l1)goto L128;
  116097. t1=0;
  116098. t2=ipp2*t0;
  116099. for(j=1;j<ipph;j++){
  116100. t1+=t0;
  116101. t2-=t0;
  116102. t3=t1;
  116103. t4=t2;
  116104. for(k=0;k<l1;k++){
  116105. t5=t3;
  116106. t6=t4;
  116107. for(i=2;i<ido;i+=2){
  116108. t5+=2;
  116109. t6+=2;
  116110. ch[t5-1]=c1[t5-1]-c1[t6];
  116111. ch[t6-1]=c1[t5-1]+c1[t6];
  116112. ch[t5]=c1[t5]+c1[t6-1];
  116113. ch[t6]=c1[t5]-c1[t6-1];
  116114. }
  116115. t3+=ido;
  116116. t4+=ido;
  116117. }
  116118. }
  116119. goto L132;
  116120. L128:
  116121. t1=0;
  116122. t2=ipp2*t0;
  116123. for(j=1;j<ipph;j++){
  116124. t1+=t0;
  116125. t2-=t0;
  116126. t3=t1;
  116127. t4=t2;
  116128. for(i=2;i<ido;i+=2){
  116129. t3+=2;
  116130. t4+=2;
  116131. t5=t3;
  116132. t6=t4;
  116133. for(k=0;k<l1;k++){
  116134. ch[t5-1]=c1[t5-1]-c1[t6];
  116135. ch[t6-1]=c1[t5-1]+c1[t6];
  116136. ch[t5]=c1[t5]+c1[t6-1];
  116137. ch[t6]=c1[t5]-c1[t6-1];
  116138. t5+=ido;
  116139. t6+=ido;
  116140. }
  116141. }
  116142. }
  116143. L132:
  116144. if(ido==1)return;
  116145. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  116146. t1=0;
  116147. for(j=1;j<ip;j++){
  116148. t2=(t1+=t0);
  116149. for(k=0;k<l1;k++){
  116150. c1[t2]=ch[t2];
  116151. t2+=ido;
  116152. }
  116153. }
  116154. if(nbd>l1)goto L139;
  116155. is= -ido-1;
  116156. t1=0;
  116157. for(j=1;j<ip;j++){
  116158. is+=ido;
  116159. t1+=t0;
  116160. idij=is;
  116161. t2=t1;
  116162. for(i=2;i<ido;i+=2){
  116163. t2+=2;
  116164. idij+=2;
  116165. t3=t2;
  116166. for(k=0;k<l1;k++){
  116167. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116168. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116169. t3+=ido;
  116170. }
  116171. }
  116172. }
  116173. return;
  116174. L139:
  116175. is= -ido-1;
  116176. t1=0;
  116177. for(j=1;j<ip;j++){
  116178. is+=ido;
  116179. t1+=t0;
  116180. t2=t1;
  116181. for(k=0;k<l1;k++){
  116182. idij=is;
  116183. t3=t2;
  116184. for(i=2;i<ido;i+=2){
  116185. idij+=2;
  116186. t3+=2;
  116187. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116188. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116189. }
  116190. t2+=ido;
  116191. }
  116192. }
  116193. }
  116194. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  116195. int i,k1,l1,l2;
  116196. int na;
  116197. int nf,ip,iw,ix2,ix3,ido,idl1;
  116198. nf=ifac[1];
  116199. na=0;
  116200. l1=1;
  116201. iw=1;
  116202. for(k1=0;k1<nf;k1++){
  116203. ip=ifac[k1 + 2];
  116204. l2=ip*l1;
  116205. ido=n/l2;
  116206. idl1=ido*l1;
  116207. if(ip!=4)goto L103;
  116208. ix2=iw+ido;
  116209. ix3=ix2+ido;
  116210. if(na!=0)
  116211. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116212. else
  116213. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116214. na=1-na;
  116215. goto L115;
  116216. L103:
  116217. if(ip!=2)goto L106;
  116218. if(na!=0)
  116219. dradb2(ido,l1,ch,c,wa+iw-1);
  116220. else
  116221. dradb2(ido,l1,c,ch,wa+iw-1);
  116222. na=1-na;
  116223. goto L115;
  116224. L106:
  116225. if(ip!=3)goto L109;
  116226. ix2=iw+ido;
  116227. if(na!=0)
  116228. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  116229. else
  116230. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  116231. na=1-na;
  116232. goto L115;
  116233. L109:
  116234. /* The radix five case can be translated later..... */
  116235. /* if(ip!=5)goto L112;
  116236. ix2=iw+ido;
  116237. ix3=ix2+ido;
  116238. ix4=ix3+ido;
  116239. if(na!=0)
  116240. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116241. else
  116242. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116243. na=1-na;
  116244. goto L115;
  116245. L112:*/
  116246. if(na!=0)
  116247. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116248. else
  116249. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116250. if(ido==1)na=1-na;
  116251. L115:
  116252. l1=l2;
  116253. iw+=(ip-1)*ido;
  116254. }
  116255. if(na==0)return;
  116256. for(i=0;i<n;i++)c[i]=ch[i];
  116257. }
  116258. void drft_forward(drft_lookup *l,float *data){
  116259. if(l->n==1)return;
  116260. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116261. }
  116262. void drft_backward(drft_lookup *l,float *data){
  116263. if (l->n==1)return;
  116264. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116265. }
  116266. void drft_init(drft_lookup *l,int n){
  116267. l->n=n;
  116268. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  116269. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  116270. fdrffti(n, l->trigcache, l->splitcache);
  116271. }
  116272. void drft_clear(drft_lookup *l){
  116273. if(l){
  116274. if(l->trigcache)_ogg_free(l->trigcache);
  116275. if(l->splitcache)_ogg_free(l->splitcache);
  116276. memset(l,0,sizeof(*l));
  116277. }
  116278. }
  116279. #endif
  116280. /********* End of inlined file: smallft.c *********/
  116281. /********* Start of inlined file: synthesis.c *********/
  116282. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116283. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116284. // tasks..
  116285. #if JUCE_MSVC
  116286. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116287. #endif
  116288. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116289. #if JUCE_USE_OGGVORBIS
  116290. #include <stdio.h>
  116291. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  116292. vorbis_dsp_state *vd=vb->vd;
  116293. private_state *b=(private_state*)vd->backend_state;
  116294. vorbis_info *vi=vd->vi;
  116295. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  116296. oggpack_buffer *opb=&vb->opb;
  116297. int type,mode,i;
  116298. /* first things first. Make sure decode is ready */
  116299. _vorbis_block_ripcord(vb);
  116300. oggpack_readinit(opb,op->packet,op->bytes);
  116301. /* Check the packet type */
  116302. if(oggpack_read(opb,1)!=0){
  116303. /* Oops. This is not an audio data packet */
  116304. return(OV_ENOTAUDIO);
  116305. }
  116306. /* read our mode and pre/post windowsize */
  116307. mode=oggpack_read(opb,b->modebits);
  116308. if(mode==-1)return(OV_EBADPACKET);
  116309. vb->mode=mode;
  116310. vb->W=ci->mode_param[mode]->blockflag;
  116311. if(vb->W){
  116312. /* this doesn;t get mapped through mode selection as it's used
  116313. only for window selection */
  116314. vb->lW=oggpack_read(opb,1);
  116315. vb->nW=oggpack_read(opb,1);
  116316. if(vb->nW==-1) return(OV_EBADPACKET);
  116317. }else{
  116318. vb->lW=0;
  116319. vb->nW=0;
  116320. }
  116321. /* more setup */
  116322. vb->granulepos=op->granulepos;
  116323. vb->sequence=op->packetno;
  116324. vb->eofflag=op->e_o_s;
  116325. /* alloc pcm passback storage */
  116326. vb->pcmend=ci->blocksizes[vb->W];
  116327. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  116328. for(i=0;i<vi->channels;i++)
  116329. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  116330. /* unpack_header enforces range checking */
  116331. type=ci->map_type[ci->mode_param[mode]->mapping];
  116332. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  116333. mapping]));
  116334. }
  116335. /* used to track pcm position without actually performing decode.
  116336. Useful for sequential 'fast forward' */
  116337. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  116338. vorbis_dsp_state *vd=vb->vd;
  116339. private_state *b=(private_state*)vd->backend_state;
  116340. vorbis_info *vi=vd->vi;
  116341. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116342. oggpack_buffer *opb=&vb->opb;
  116343. int mode;
  116344. /* first things first. Make sure decode is ready */
  116345. _vorbis_block_ripcord(vb);
  116346. oggpack_readinit(opb,op->packet,op->bytes);
  116347. /* Check the packet type */
  116348. if(oggpack_read(opb,1)!=0){
  116349. /* Oops. This is not an audio data packet */
  116350. return(OV_ENOTAUDIO);
  116351. }
  116352. /* read our mode and pre/post windowsize */
  116353. mode=oggpack_read(opb,b->modebits);
  116354. if(mode==-1)return(OV_EBADPACKET);
  116355. vb->mode=mode;
  116356. vb->W=ci->mode_param[mode]->blockflag;
  116357. if(vb->W){
  116358. vb->lW=oggpack_read(opb,1);
  116359. vb->nW=oggpack_read(opb,1);
  116360. if(vb->nW==-1) return(OV_EBADPACKET);
  116361. }else{
  116362. vb->lW=0;
  116363. vb->nW=0;
  116364. }
  116365. /* more setup */
  116366. vb->granulepos=op->granulepos;
  116367. vb->sequence=op->packetno;
  116368. vb->eofflag=op->e_o_s;
  116369. /* no pcm */
  116370. vb->pcmend=0;
  116371. vb->pcm=NULL;
  116372. return(0);
  116373. }
  116374. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  116375. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116376. oggpack_buffer opb;
  116377. int mode;
  116378. oggpack_readinit(&opb,op->packet,op->bytes);
  116379. /* Check the packet type */
  116380. if(oggpack_read(&opb,1)!=0){
  116381. /* Oops. This is not an audio data packet */
  116382. return(OV_ENOTAUDIO);
  116383. }
  116384. {
  116385. int modebits=0;
  116386. int v=ci->modes;
  116387. while(v>1){
  116388. modebits++;
  116389. v>>=1;
  116390. }
  116391. /* read our mode and pre/post windowsize */
  116392. mode=oggpack_read(&opb,modebits);
  116393. }
  116394. if(mode==-1)return(OV_EBADPACKET);
  116395. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  116396. }
  116397. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  116398. /* set / clear half-sample-rate mode */
  116399. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116400. /* right now, our MDCT can't handle < 64 sample windows. */
  116401. if(ci->blocksizes[0]<=64 && flag)return -1;
  116402. ci->halfrate_flag=(flag?1:0);
  116403. return 0;
  116404. }
  116405. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  116406. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116407. return ci->halfrate_flag;
  116408. }
  116409. #endif
  116410. /********* End of inlined file: synthesis.c *********/
  116411. /********* Start of inlined file: vorbisenc.c *********/
  116412. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116413. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116414. // tasks..
  116415. #if JUCE_MSVC
  116416. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116417. #endif
  116418. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116419. #if JUCE_USE_OGGVORBIS
  116420. #include <stdlib.h>
  116421. #include <string.h>
  116422. #include <math.h>
  116423. /* careful with this; it's using static array sizing to make managing
  116424. all the modes a little less annoying. If we use a residue backend
  116425. with > 12 partition types, or a different division of iteration,
  116426. this needs to be updated. */
  116427. typedef struct {
  116428. static_codebook *books[12][3];
  116429. } static_bookblock;
  116430. typedef struct {
  116431. int res_type;
  116432. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  116433. vorbis_info_residue0 *res;
  116434. static_codebook *book_aux;
  116435. static_codebook *book_aux_managed;
  116436. static_bookblock *books_base;
  116437. static_bookblock *books_base_managed;
  116438. } vorbis_residue_template;
  116439. typedef struct {
  116440. vorbis_info_mapping0 *map;
  116441. vorbis_residue_template *res;
  116442. } vorbis_mapping_template;
  116443. typedef struct vp_adjblock{
  116444. int block[P_BANDS];
  116445. } vp_adjblock;
  116446. typedef struct {
  116447. int data[NOISE_COMPAND_LEVELS];
  116448. } compandblock;
  116449. /* high level configuration information for setting things up
  116450. step-by-step with the detailed vorbis_encode_ctl interface.
  116451. There's a fair amount of redundancy such that interactive setup
  116452. does not directly deal with any vorbis_info or codec_setup_info
  116453. initialization; it's all stored (until full init) in this highlevel
  116454. setup, then flushed out to the real codec setup structs later. */
  116455. typedef struct {
  116456. int att[P_NOISECURVES];
  116457. float boost;
  116458. float decay;
  116459. } att3;
  116460. typedef struct { int data[P_NOISECURVES]; } adj3;
  116461. typedef struct {
  116462. int pre[PACKETBLOBS];
  116463. int post[PACKETBLOBS];
  116464. float kHz[PACKETBLOBS];
  116465. float lowpasskHz[PACKETBLOBS];
  116466. } adj_stereo;
  116467. typedef struct {
  116468. int lo;
  116469. int hi;
  116470. int fixed;
  116471. } noiseguard;
  116472. typedef struct {
  116473. int data[P_NOISECURVES][17];
  116474. } noise3;
  116475. typedef struct {
  116476. int mappings;
  116477. double *rate_mapping;
  116478. double *quality_mapping;
  116479. int coupling_restriction;
  116480. long samplerate_min_restriction;
  116481. long samplerate_max_restriction;
  116482. int *blocksize_short;
  116483. int *blocksize_long;
  116484. att3 *psy_tone_masteratt;
  116485. int *psy_tone_0dB;
  116486. int *psy_tone_dBsuppress;
  116487. vp_adjblock *psy_tone_adj_impulse;
  116488. vp_adjblock *psy_tone_adj_long;
  116489. vp_adjblock *psy_tone_adj_other;
  116490. noiseguard *psy_noiseguards;
  116491. noise3 *psy_noise_bias_impulse;
  116492. noise3 *psy_noise_bias_padding;
  116493. noise3 *psy_noise_bias_trans;
  116494. noise3 *psy_noise_bias_long;
  116495. int *psy_noise_dBsuppress;
  116496. compandblock *psy_noise_compand;
  116497. double *psy_noise_compand_short_mapping;
  116498. double *psy_noise_compand_long_mapping;
  116499. int *psy_noise_normal_start[2];
  116500. int *psy_noise_normal_partition[2];
  116501. double *psy_noise_normal_thresh;
  116502. int *psy_ath_float;
  116503. int *psy_ath_abs;
  116504. double *psy_lowpass;
  116505. vorbis_info_psy_global *global_params;
  116506. double *global_mapping;
  116507. adj_stereo *stereo_modes;
  116508. static_codebook ***floor_books;
  116509. vorbis_info_floor1 *floor_params;
  116510. int *floor_short_mapping;
  116511. int *floor_long_mapping;
  116512. vorbis_mapping_template *maps;
  116513. } ve_setup_data_template;
  116514. /* a few static coder conventions */
  116515. static vorbis_info_mode _mode_template[2]={
  116516. {0,0,0,0},
  116517. {1,0,0,1}
  116518. };
  116519. static vorbis_info_mapping0 _map_nominal[2]={
  116520. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  116521. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  116522. };
  116523. /********* Start of inlined file: setup_44.h *********/
  116524. /********* Start of inlined file: floor_all.h *********/
  116525. /********* Start of inlined file: floor_books.h *********/
  116526. static long _huff_lengthlist_line_256x7_0sub1[] = {
  116527. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  116528. };
  116529. static static_codebook _huff_book_line_256x7_0sub1 = {
  116530. 1, 9,
  116531. _huff_lengthlist_line_256x7_0sub1,
  116532. 0, 0, 0, 0, 0,
  116533. NULL,
  116534. NULL,
  116535. NULL,
  116536. NULL,
  116537. 0
  116538. };
  116539. static long _huff_lengthlist_line_256x7_0sub2[] = {
  116540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  116541. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  116542. };
  116543. static static_codebook _huff_book_line_256x7_0sub2 = {
  116544. 1, 25,
  116545. _huff_lengthlist_line_256x7_0sub2,
  116546. 0, 0, 0, 0, 0,
  116547. NULL,
  116548. NULL,
  116549. NULL,
  116550. NULL,
  116551. 0
  116552. };
  116553. static long _huff_lengthlist_line_256x7_0sub3[] = {
  116554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  116556. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  116557. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  116558. };
  116559. static static_codebook _huff_book_line_256x7_0sub3 = {
  116560. 1, 64,
  116561. _huff_lengthlist_line_256x7_0sub3,
  116562. 0, 0, 0, 0, 0,
  116563. NULL,
  116564. NULL,
  116565. NULL,
  116566. NULL,
  116567. 0
  116568. };
  116569. static long _huff_lengthlist_line_256x7_1sub1[] = {
  116570. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  116571. };
  116572. static static_codebook _huff_book_line_256x7_1sub1 = {
  116573. 1, 9,
  116574. _huff_lengthlist_line_256x7_1sub1,
  116575. 0, 0, 0, 0, 0,
  116576. NULL,
  116577. NULL,
  116578. NULL,
  116579. NULL,
  116580. 0
  116581. };
  116582. static long _huff_lengthlist_line_256x7_1sub2[] = {
  116583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  116584. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  116585. };
  116586. static static_codebook _huff_book_line_256x7_1sub2 = {
  116587. 1, 25,
  116588. _huff_lengthlist_line_256x7_1sub2,
  116589. 0, 0, 0, 0, 0,
  116590. NULL,
  116591. NULL,
  116592. NULL,
  116593. NULL,
  116594. 0
  116595. };
  116596. static long _huff_lengthlist_line_256x7_1sub3[] = {
  116597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  116599. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116600. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  116601. };
  116602. static static_codebook _huff_book_line_256x7_1sub3 = {
  116603. 1, 64,
  116604. _huff_lengthlist_line_256x7_1sub3,
  116605. 0, 0, 0, 0, 0,
  116606. NULL,
  116607. NULL,
  116608. NULL,
  116609. NULL,
  116610. 0
  116611. };
  116612. static long _huff_lengthlist_line_256x7_class0[] = {
  116613. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  116614. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  116615. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  116616. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  116617. };
  116618. static static_codebook _huff_book_line_256x7_class0 = {
  116619. 1, 64,
  116620. _huff_lengthlist_line_256x7_class0,
  116621. 0, 0, 0, 0, 0,
  116622. NULL,
  116623. NULL,
  116624. NULL,
  116625. NULL,
  116626. 0
  116627. };
  116628. static long _huff_lengthlist_line_256x7_class1[] = {
  116629. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  116630. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  116631. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  116632. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  116633. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  116634. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  116635. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  116636. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  116637. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  116638. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  116639. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  116640. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  116641. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116642. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116643. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  116644. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  116645. };
  116646. static static_codebook _huff_book_line_256x7_class1 = {
  116647. 1, 256,
  116648. _huff_lengthlist_line_256x7_class1,
  116649. 0, 0, 0, 0, 0,
  116650. NULL,
  116651. NULL,
  116652. NULL,
  116653. NULL,
  116654. 0
  116655. };
  116656. static long _huff_lengthlist_line_512x17_0sub0[] = {
  116657. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  116658. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  116659. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  116660. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  116661. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  116662. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  116663. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  116664. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  116665. };
  116666. static static_codebook _huff_book_line_512x17_0sub0 = {
  116667. 1, 128,
  116668. _huff_lengthlist_line_512x17_0sub0,
  116669. 0, 0, 0, 0, 0,
  116670. NULL,
  116671. NULL,
  116672. NULL,
  116673. NULL,
  116674. 0
  116675. };
  116676. static long _huff_lengthlist_line_512x17_1sub0[] = {
  116677. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116678. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  116679. };
  116680. static static_codebook _huff_book_line_512x17_1sub0 = {
  116681. 1, 32,
  116682. _huff_lengthlist_line_512x17_1sub0,
  116683. 0, 0, 0, 0, 0,
  116684. NULL,
  116685. NULL,
  116686. NULL,
  116687. NULL,
  116688. 0
  116689. };
  116690. static long _huff_lengthlist_line_512x17_1sub1[] = {
  116691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116693. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  116694. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  116695. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  116696. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  116697. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  116698. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116699. };
  116700. static static_codebook _huff_book_line_512x17_1sub1 = {
  116701. 1, 128,
  116702. _huff_lengthlist_line_512x17_1sub1,
  116703. 0, 0, 0, 0, 0,
  116704. NULL,
  116705. NULL,
  116706. NULL,
  116707. NULL,
  116708. 0
  116709. };
  116710. static long _huff_lengthlist_line_512x17_2sub1[] = {
  116711. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  116712. 5, 3,
  116713. };
  116714. static static_codebook _huff_book_line_512x17_2sub1 = {
  116715. 1, 18,
  116716. _huff_lengthlist_line_512x17_2sub1,
  116717. 0, 0, 0, 0, 0,
  116718. NULL,
  116719. NULL,
  116720. NULL,
  116721. NULL,
  116722. 0
  116723. };
  116724. static long _huff_lengthlist_line_512x17_2sub2[] = {
  116725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116726. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  116727. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  116728. 9, 8,
  116729. };
  116730. static static_codebook _huff_book_line_512x17_2sub2 = {
  116731. 1, 50,
  116732. _huff_lengthlist_line_512x17_2sub2,
  116733. 0, 0, 0, 0, 0,
  116734. NULL,
  116735. NULL,
  116736. NULL,
  116737. NULL,
  116738. 0
  116739. };
  116740. static long _huff_lengthlist_line_512x17_2sub3[] = {
  116741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116744. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  116745. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  116746. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116749. };
  116750. static static_codebook _huff_book_line_512x17_2sub3 = {
  116751. 1, 128,
  116752. _huff_lengthlist_line_512x17_2sub3,
  116753. 0, 0, 0, 0, 0,
  116754. NULL,
  116755. NULL,
  116756. NULL,
  116757. NULL,
  116758. 0
  116759. };
  116760. static long _huff_lengthlist_line_512x17_3sub1[] = {
  116761. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  116762. 5, 5,
  116763. };
  116764. static static_codebook _huff_book_line_512x17_3sub1 = {
  116765. 1, 18,
  116766. _huff_lengthlist_line_512x17_3sub1,
  116767. 0, 0, 0, 0, 0,
  116768. NULL,
  116769. NULL,
  116770. NULL,
  116771. NULL,
  116772. 0
  116773. };
  116774. static long _huff_lengthlist_line_512x17_3sub2[] = {
  116775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116776. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  116777. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  116778. 11,14,
  116779. };
  116780. static static_codebook _huff_book_line_512x17_3sub2 = {
  116781. 1, 50,
  116782. _huff_lengthlist_line_512x17_3sub2,
  116783. 0, 0, 0, 0, 0,
  116784. NULL,
  116785. NULL,
  116786. NULL,
  116787. NULL,
  116788. 0
  116789. };
  116790. static long _huff_lengthlist_line_512x17_3sub3[] = {
  116791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116794. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  116795. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116796. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116797. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116798. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116799. };
  116800. static static_codebook _huff_book_line_512x17_3sub3 = {
  116801. 1, 128,
  116802. _huff_lengthlist_line_512x17_3sub3,
  116803. 0, 0, 0, 0, 0,
  116804. NULL,
  116805. NULL,
  116806. NULL,
  116807. NULL,
  116808. 0
  116809. };
  116810. static long _huff_lengthlist_line_512x17_class1[] = {
  116811. 1, 2, 3, 6, 5, 4, 7, 7,
  116812. };
  116813. static static_codebook _huff_book_line_512x17_class1 = {
  116814. 1, 8,
  116815. _huff_lengthlist_line_512x17_class1,
  116816. 0, 0, 0, 0, 0,
  116817. NULL,
  116818. NULL,
  116819. NULL,
  116820. NULL,
  116821. 0
  116822. };
  116823. static long _huff_lengthlist_line_512x17_class2[] = {
  116824. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  116825. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  116826. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  116827. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  116828. };
  116829. static static_codebook _huff_book_line_512x17_class2 = {
  116830. 1, 64,
  116831. _huff_lengthlist_line_512x17_class2,
  116832. 0, 0, 0, 0, 0,
  116833. NULL,
  116834. NULL,
  116835. NULL,
  116836. NULL,
  116837. 0
  116838. };
  116839. static long _huff_lengthlist_line_512x17_class3[] = {
  116840. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  116841. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  116842. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  116843. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  116844. };
  116845. static static_codebook _huff_book_line_512x17_class3 = {
  116846. 1, 64,
  116847. _huff_lengthlist_line_512x17_class3,
  116848. 0, 0, 0, 0, 0,
  116849. NULL,
  116850. NULL,
  116851. NULL,
  116852. NULL,
  116853. 0
  116854. };
  116855. static long _huff_lengthlist_line_128x4_class0[] = {
  116856. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  116857. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  116858. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  116859. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  116860. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  116861. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  116862. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  116863. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  116864. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  116865. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  116866. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  116867. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  116868. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  116869. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  116870. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  116871. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  116872. };
  116873. static static_codebook _huff_book_line_128x4_class0 = {
  116874. 1, 256,
  116875. _huff_lengthlist_line_128x4_class0,
  116876. 0, 0, 0, 0, 0,
  116877. NULL,
  116878. NULL,
  116879. NULL,
  116880. NULL,
  116881. 0
  116882. };
  116883. static long _huff_lengthlist_line_128x4_0sub0[] = {
  116884. 2, 2, 2, 2,
  116885. };
  116886. static static_codebook _huff_book_line_128x4_0sub0 = {
  116887. 1, 4,
  116888. _huff_lengthlist_line_128x4_0sub0,
  116889. 0, 0, 0, 0, 0,
  116890. NULL,
  116891. NULL,
  116892. NULL,
  116893. NULL,
  116894. 0
  116895. };
  116896. static long _huff_lengthlist_line_128x4_0sub1[] = {
  116897. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  116898. };
  116899. static static_codebook _huff_book_line_128x4_0sub1 = {
  116900. 1, 10,
  116901. _huff_lengthlist_line_128x4_0sub1,
  116902. 0, 0, 0, 0, 0,
  116903. NULL,
  116904. NULL,
  116905. NULL,
  116906. NULL,
  116907. 0
  116908. };
  116909. static long _huff_lengthlist_line_128x4_0sub2[] = {
  116910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  116911. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  116912. };
  116913. static static_codebook _huff_book_line_128x4_0sub2 = {
  116914. 1, 25,
  116915. _huff_lengthlist_line_128x4_0sub2,
  116916. 0, 0, 0, 0, 0,
  116917. NULL,
  116918. NULL,
  116919. NULL,
  116920. NULL,
  116921. 0
  116922. };
  116923. static long _huff_lengthlist_line_128x4_0sub3[] = {
  116924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116926. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  116927. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  116928. };
  116929. static static_codebook _huff_book_line_128x4_0sub3 = {
  116930. 1, 64,
  116931. _huff_lengthlist_line_128x4_0sub3,
  116932. 0, 0, 0, 0, 0,
  116933. NULL,
  116934. NULL,
  116935. NULL,
  116936. NULL,
  116937. 0
  116938. };
  116939. static long _huff_lengthlist_line_256x4_class0[] = {
  116940. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  116941. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  116942. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  116943. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  116944. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  116945. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  116946. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  116947. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  116948. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  116949. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  116950. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  116951. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  116952. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  116953. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  116954. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  116955. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  116956. };
  116957. static static_codebook _huff_book_line_256x4_class0 = {
  116958. 1, 256,
  116959. _huff_lengthlist_line_256x4_class0,
  116960. 0, 0, 0, 0, 0,
  116961. NULL,
  116962. NULL,
  116963. NULL,
  116964. NULL,
  116965. 0
  116966. };
  116967. static long _huff_lengthlist_line_256x4_0sub0[] = {
  116968. 2, 2, 2, 2,
  116969. };
  116970. static static_codebook _huff_book_line_256x4_0sub0 = {
  116971. 1, 4,
  116972. _huff_lengthlist_line_256x4_0sub0,
  116973. 0, 0, 0, 0, 0,
  116974. NULL,
  116975. NULL,
  116976. NULL,
  116977. NULL,
  116978. 0
  116979. };
  116980. static long _huff_lengthlist_line_256x4_0sub1[] = {
  116981. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  116982. };
  116983. static static_codebook _huff_book_line_256x4_0sub1 = {
  116984. 1, 10,
  116985. _huff_lengthlist_line_256x4_0sub1,
  116986. 0, 0, 0, 0, 0,
  116987. NULL,
  116988. NULL,
  116989. NULL,
  116990. NULL,
  116991. 0
  116992. };
  116993. static long _huff_lengthlist_line_256x4_0sub2[] = {
  116994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  116995. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  116996. };
  116997. static static_codebook _huff_book_line_256x4_0sub2 = {
  116998. 1, 25,
  116999. _huff_lengthlist_line_256x4_0sub2,
  117000. 0, 0, 0, 0, 0,
  117001. NULL,
  117002. NULL,
  117003. NULL,
  117004. NULL,
  117005. 0
  117006. };
  117007. static long _huff_lengthlist_line_256x4_0sub3[] = {
  117008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  117010. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  117011. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  117012. };
  117013. static static_codebook _huff_book_line_256x4_0sub3 = {
  117014. 1, 64,
  117015. _huff_lengthlist_line_256x4_0sub3,
  117016. 0, 0, 0, 0, 0,
  117017. NULL,
  117018. NULL,
  117019. NULL,
  117020. NULL,
  117021. 0
  117022. };
  117023. static long _huff_lengthlist_line_128x7_class0[] = {
  117024. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  117025. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  117026. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  117027. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  117028. };
  117029. static static_codebook _huff_book_line_128x7_class0 = {
  117030. 1, 64,
  117031. _huff_lengthlist_line_128x7_class0,
  117032. 0, 0, 0, 0, 0,
  117033. NULL,
  117034. NULL,
  117035. NULL,
  117036. NULL,
  117037. 0
  117038. };
  117039. static long _huff_lengthlist_line_128x7_class1[] = {
  117040. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  117041. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  117042. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  117043. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117044. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  117045. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  117046. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  117047. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  117048. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  117049. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  117050. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  117051. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  117052. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  117053. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  117054. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  117055. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  117056. };
  117057. static static_codebook _huff_book_line_128x7_class1 = {
  117058. 1, 256,
  117059. _huff_lengthlist_line_128x7_class1,
  117060. 0, 0, 0, 0, 0,
  117061. NULL,
  117062. NULL,
  117063. NULL,
  117064. NULL,
  117065. 0
  117066. };
  117067. static long _huff_lengthlist_line_128x7_0sub1[] = {
  117068. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  117069. };
  117070. static static_codebook _huff_book_line_128x7_0sub1 = {
  117071. 1, 9,
  117072. _huff_lengthlist_line_128x7_0sub1,
  117073. 0, 0, 0, 0, 0,
  117074. NULL,
  117075. NULL,
  117076. NULL,
  117077. NULL,
  117078. 0
  117079. };
  117080. static long _huff_lengthlist_line_128x7_0sub2[] = {
  117081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  117082. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  117083. };
  117084. static static_codebook _huff_book_line_128x7_0sub2 = {
  117085. 1, 25,
  117086. _huff_lengthlist_line_128x7_0sub2,
  117087. 0, 0, 0, 0, 0,
  117088. NULL,
  117089. NULL,
  117090. NULL,
  117091. NULL,
  117092. 0
  117093. };
  117094. static long _huff_lengthlist_line_128x7_0sub3[] = {
  117095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  117097. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117098. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  117099. };
  117100. static static_codebook _huff_book_line_128x7_0sub3 = {
  117101. 1, 64,
  117102. _huff_lengthlist_line_128x7_0sub3,
  117103. 0, 0, 0, 0, 0,
  117104. NULL,
  117105. NULL,
  117106. NULL,
  117107. NULL,
  117108. 0
  117109. };
  117110. static long _huff_lengthlist_line_128x7_1sub1[] = {
  117111. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  117112. };
  117113. static static_codebook _huff_book_line_128x7_1sub1 = {
  117114. 1, 9,
  117115. _huff_lengthlist_line_128x7_1sub1,
  117116. 0, 0, 0, 0, 0,
  117117. NULL,
  117118. NULL,
  117119. NULL,
  117120. NULL,
  117121. 0
  117122. };
  117123. static long _huff_lengthlist_line_128x7_1sub2[] = {
  117124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  117125. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  117126. };
  117127. static static_codebook _huff_book_line_128x7_1sub2 = {
  117128. 1, 25,
  117129. _huff_lengthlist_line_128x7_1sub2,
  117130. 0, 0, 0, 0, 0,
  117131. NULL,
  117132. NULL,
  117133. NULL,
  117134. NULL,
  117135. 0
  117136. };
  117137. static long _huff_lengthlist_line_128x7_1sub3[] = {
  117138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  117140. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  117141. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  117142. };
  117143. static static_codebook _huff_book_line_128x7_1sub3 = {
  117144. 1, 64,
  117145. _huff_lengthlist_line_128x7_1sub3,
  117146. 0, 0, 0, 0, 0,
  117147. NULL,
  117148. NULL,
  117149. NULL,
  117150. NULL,
  117151. 0
  117152. };
  117153. static long _huff_lengthlist_line_128x11_class1[] = {
  117154. 1, 6, 3, 7, 2, 4, 5, 7,
  117155. };
  117156. static static_codebook _huff_book_line_128x11_class1 = {
  117157. 1, 8,
  117158. _huff_lengthlist_line_128x11_class1,
  117159. 0, 0, 0, 0, 0,
  117160. NULL,
  117161. NULL,
  117162. NULL,
  117163. NULL,
  117164. 0
  117165. };
  117166. static long _huff_lengthlist_line_128x11_class2[] = {
  117167. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  117168. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  117169. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  117170. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  117171. };
  117172. static static_codebook _huff_book_line_128x11_class2 = {
  117173. 1, 64,
  117174. _huff_lengthlist_line_128x11_class2,
  117175. 0, 0, 0, 0, 0,
  117176. NULL,
  117177. NULL,
  117178. NULL,
  117179. NULL,
  117180. 0
  117181. };
  117182. static long _huff_lengthlist_line_128x11_class3[] = {
  117183. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  117184. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  117185. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  117186. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  117187. };
  117188. static static_codebook _huff_book_line_128x11_class3 = {
  117189. 1, 64,
  117190. _huff_lengthlist_line_128x11_class3,
  117191. 0, 0, 0, 0, 0,
  117192. NULL,
  117193. NULL,
  117194. NULL,
  117195. NULL,
  117196. 0
  117197. };
  117198. static long _huff_lengthlist_line_128x11_0sub0[] = {
  117199. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117200. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  117201. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  117202. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  117203. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  117204. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  117205. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  117206. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117207. };
  117208. static static_codebook _huff_book_line_128x11_0sub0 = {
  117209. 1, 128,
  117210. _huff_lengthlist_line_128x11_0sub0,
  117211. 0, 0, 0, 0, 0,
  117212. NULL,
  117213. NULL,
  117214. NULL,
  117215. NULL,
  117216. 0
  117217. };
  117218. static long _huff_lengthlist_line_128x11_1sub0[] = {
  117219. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117220. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  117221. };
  117222. static static_codebook _huff_book_line_128x11_1sub0 = {
  117223. 1, 32,
  117224. _huff_lengthlist_line_128x11_1sub0,
  117225. 0, 0, 0, 0, 0,
  117226. NULL,
  117227. NULL,
  117228. NULL,
  117229. NULL,
  117230. 0
  117231. };
  117232. static long _huff_lengthlist_line_128x11_1sub1[] = {
  117233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117235. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117236. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  117237. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  117238. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  117239. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  117240. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  117241. };
  117242. static static_codebook _huff_book_line_128x11_1sub1 = {
  117243. 1, 128,
  117244. _huff_lengthlist_line_128x11_1sub1,
  117245. 0, 0, 0, 0, 0,
  117246. NULL,
  117247. NULL,
  117248. NULL,
  117249. NULL,
  117250. 0
  117251. };
  117252. static long _huff_lengthlist_line_128x11_2sub1[] = {
  117253. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  117254. 5, 5,
  117255. };
  117256. static static_codebook _huff_book_line_128x11_2sub1 = {
  117257. 1, 18,
  117258. _huff_lengthlist_line_128x11_2sub1,
  117259. 0, 0, 0, 0, 0,
  117260. NULL,
  117261. NULL,
  117262. NULL,
  117263. NULL,
  117264. 0
  117265. };
  117266. static long _huff_lengthlist_line_128x11_2sub2[] = {
  117267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117268. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  117269. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  117270. 8,11,
  117271. };
  117272. static static_codebook _huff_book_line_128x11_2sub2 = {
  117273. 1, 50,
  117274. _huff_lengthlist_line_128x11_2sub2,
  117275. 0, 0, 0, 0, 0,
  117276. NULL,
  117277. NULL,
  117278. NULL,
  117279. NULL,
  117280. 0
  117281. };
  117282. static long _huff_lengthlist_line_128x11_2sub3[] = {
  117283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117286. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  117287. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117288. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117289. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117290. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117291. };
  117292. static static_codebook _huff_book_line_128x11_2sub3 = {
  117293. 1, 128,
  117294. _huff_lengthlist_line_128x11_2sub3,
  117295. 0, 0, 0, 0, 0,
  117296. NULL,
  117297. NULL,
  117298. NULL,
  117299. NULL,
  117300. 0
  117301. };
  117302. static long _huff_lengthlist_line_128x11_3sub1[] = {
  117303. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  117304. 5, 4,
  117305. };
  117306. static static_codebook _huff_book_line_128x11_3sub1 = {
  117307. 1, 18,
  117308. _huff_lengthlist_line_128x11_3sub1,
  117309. 0, 0, 0, 0, 0,
  117310. NULL,
  117311. NULL,
  117312. NULL,
  117313. NULL,
  117314. 0
  117315. };
  117316. static long _huff_lengthlist_line_128x11_3sub2[] = {
  117317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117318. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  117319. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  117320. 12, 6,
  117321. };
  117322. static static_codebook _huff_book_line_128x11_3sub2 = {
  117323. 1, 50,
  117324. _huff_lengthlist_line_128x11_3sub2,
  117325. 0, 0, 0, 0, 0,
  117326. NULL,
  117327. NULL,
  117328. NULL,
  117329. NULL,
  117330. 0
  117331. };
  117332. static long _huff_lengthlist_line_128x11_3sub3[] = {
  117333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117336. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  117337. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  117338. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117339. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117340. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  117341. };
  117342. static static_codebook _huff_book_line_128x11_3sub3 = {
  117343. 1, 128,
  117344. _huff_lengthlist_line_128x11_3sub3,
  117345. 0, 0, 0, 0, 0,
  117346. NULL,
  117347. NULL,
  117348. NULL,
  117349. NULL,
  117350. 0
  117351. };
  117352. static long _huff_lengthlist_line_128x17_class1[] = {
  117353. 1, 3, 4, 7, 2, 5, 6, 7,
  117354. };
  117355. static static_codebook _huff_book_line_128x17_class1 = {
  117356. 1, 8,
  117357. _huff_lengthlist_line_128x17_class1,
  117358. 0, 0, 0, 0, 0,
  117359. NULL,
  117360. NULL,
  117361. NULL,
  117362. NULL,
  117363. 0
  117364. };
  117365. static long _huff_lengthlist_line_128x17_class2[] = {
  117366. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  117367. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  117368. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  117369. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  117370. };
  117371. static static_codebook _huff_book_line_128x17_class2 = {
  117372. 1, 64,
  117373. _huff_lengthlist_line_128x17_class2,
  117374. 0, 0, 0, 0, 0,
  117375. NULL,
  117376. NULL,
  117377. NULL,
  117378. NULL,
  117379. 0
  117380. };
  117381. static long _huff_lengthlist_line_128x17_class3[] = {
  117382. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  117383. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  117384. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  117385. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  117386. };
  117387. static static_codebook _huff_book_line_128x17_class3 = {
  117388. 1, 64,
  117389. _huff_lengthlist_line_128x17_class3,
  117390. 0, 0, 0, 0, 0,
  117391. NULL,
  117392. NULL,
  117393. NULL,
  117394. NULL,
  117395. 0
  117396. };
  117397. static long _huff_lengthlist_line_128x17_0sub0[] = {
  117398. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117399. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  117400. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  117401. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  117402. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  117403. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  117404. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  117405. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117406. };
  117407. static static_codebook _huff_book_line_128x17_0sub0 = {
  117408. 1, 128,
  117409. _huff_lengthlist_line_128x17_0sub0,
  117410. 0, 0, 0, 0, 0,
  117411. NULL,
  117412. NULL,
  117413. NULL,
  117414. NULL,
  117415. 0
  117416. };
  117417. static long _huff_lengthlist_line_128x17_1sub0[] = {
  117418. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117419. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  117420. };
  117421. static static_codebook _huff_book_line_128x17_1sub0 = {
  117422. 1, 32,
  117423. _huff_lengthlist_line_128x17_1sub0,
  117424. 0, 0, 0, 0, 0,
  117425. NULL,
  117426. NULL,
  117427. NULL,
  117428. NULL,
  117429. 0
  117430. };
  117431. static long _huff_lengthlist_line_128x17_1sub1[] = {
  117432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117434. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  117435. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  117436. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  117437. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  117438. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  117439. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  117440. };
  117441. static static_codebook _huff_book_line_128x17_1sub1 = {
  117442. 1, 128,
  117443. _huff_lengthlist_line_128x17_1sub1,
  117444. 0, 0, 0, 0, 0,
  117445. NULL,
  117446. NULL,
  117447. NULL,
  117448. NULL,
  117449. 0
  117450. };
  117451. static long _huff_lengthlist_line_128x17_2sub1[] = {
  117452. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  117453. 9, 4,
  117454. };
  117455. static static_codebook _huff_book_line_128x17_2sub1 = {
  117456. 1, 18,
  117457. _huff_lengthlist_line_128x17_2sub1,
  117458. 0, 0, 0, 0, 0,
  117459. NULL,
  117460. NULL,
  117461. NULL,
  117462. NULL,
  117463. 0
  117464. };
  117465. static long _huff_lengthlist_line_128x17_2sub2[] = {
  117466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117467. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  117468. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  117469. 13,13,
  117470. };
  117471. static static_codebook _huff_book_line_128x17_2sub2 = {
  117472. 1, 50,
  117473. _huff_lengthlist_line_128x17_2sub2,
  117474. 0, 0, 0, 0, 0,
  117475. NULL,
  117476. NULL,
  117477. NULL,
  117478. NULL,
  117479. 0
  117480. };
  117481. static long _huff_lengthlist_line_128x17_2sub3[] = {
  117482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117485. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117486. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  117487. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117488. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117489. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117490. };
  117491. static static_codebook _huff_book_line_128x17_2sub3 = {
  117492. 1, 128,
  117493. _huff_lengthlist_line_128x17_2sub3,
  117494. 0, 0, 0, 0, 0,
  117495. NULL,
  117496. NULL,
  117497. NULL,
  117498. NULL,
  117499. 0
  117500. };
  117501. static long _huff_lengthlist_line_128x17_3sub1[] = {
  117502. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  117503. 6, 4,
  117504. };
  117505. static static_codebook _huff_book_line_128x17_3sub1 = {
  117506. 1, 18,
  117507. _huff_lengthlist_line_128x17_3sub1,
  117508. 0, 0, 0, 0, 0,
  117509. NULL,
  117510. NULL,
  117511. NULL,
  117512. NULL,
  117513. 0
  117514. };
  117515. static long _huff_lengthlist_line_128x17_3sub2[] = {
  117516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117517. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117518. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  117519. 10, 8,
  117520. };
  117521. static static_codebook _huff_book_line_128x17_3sub2 = {
  117522. 1, 50,
  117523. _huff_lengthlist_line_128x17_3sub2,
  117524. 0, 0, 0, 0, 0,
  117525. NULL,
  117526. NULL,
  117527. NULL,
  117528. NULL,
  117529. 0
  117530. };
  117531. static long _huff_lengthlist_line_128x17_3sub3[] = {
  117532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117535. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  117536. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  117537. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117540. };
  117541. static static_codebook _huff_book_line_128x17_3sub3 = {
  117542. 1, 128,
  117543. _huff_lengthlist_line_128x17_3sub3,
  117544. 0, 0, 0, 0, 0,
  117545. NULL,
  117546. NULL,
  117547. NULL,
  117548. NULL,
  117549. 0
  117550. };
  117551. static long _huff_lengthlist_line_1024x27_class1[] = {
  117552. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  117553. };
  117554. static static_codebook _huff_book_line_1024x27_class1 = {
  117555. 1, 16,
  117556. _huff_lengthlist_line_1024x27_class1,
  117557. 0, 0, 0, 0, 0,
  117558. NULL,
  117559. NULL,
  117560. NULL,
  117561. NULL,
  117562. 0
  117563. };
  117564. static long _huff_lengthlist_line_1024x27_class2[] = {
  117565. 1, 4, 2, 6, 3, 7, 5, 7,
  117566. };
  117567. static static_codebook _huff_book_line_1024x27_class2 = {
  117568. 1, 8,
  117569. _huff_lengthlist_line_1024x27_class2,
  117570. 0, 0, 0, 0, 0,
  117571. NULL,
  117572. NULL,
  117573. NULL,
  117574. NULL,
  117575. 0
  117576. };
  117577. static long _huff_lengthlist_line_1024x27_class3[] = {
  117578. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  117579. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  117580. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  117581. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  117582. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  117583. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  117584. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  117585. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  117586. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  117587. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  117588. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  117589. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117590. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  117591. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  117592. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  117593. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117594. };
  117595. static static_codebook _huff_book_line_1024x27_class3 = {
  117596. 1, 256,
  117597. _huff_lengthlist_line_1024x27_class3,
  117598. 0, 0, 0, 0, 0,
  117599. NULL,
  117600. NULL,
  117601. NULL,
  117602. NULL,
  117603. 0
  117604. };
  117605. static long _huff_lengthlist_line_1024x27_class4[] = {
  117606. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  117607. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  117608. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  117609. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  117610. };
  117611. static static_codebook _huff_book_line_1024x27_class4 = {
  117612. 1, 64,
  117613. _huff_lengthlist_line_1024x27_class4,
  117614. 0, 0, 0, 0, 0,
  117615. NULL,
  117616. NULL,
  117617. NULL,
  117618. NULL,
  117619. 0
  117620. };
  117621. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  117622. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117623. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  117624. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  117625. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  117626. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  117627. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  117628. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  117629. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  117630. };
  117631. static static_codebook _huff_book_line_1024x27_0sub0 = {
  117632. 1, 128,
  117633. _huff_lengthlist_line_1024x27_0sub0,
  117634. 0, 0, 0, 0, 0,
  117635. NULL,
  117636. NULL,
  117637. NULL,
  117638. NULL,
  117639. 0
  117640. };
  117641. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  117642. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  117643. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  117644. };
  117645. static static_codebook _huff_book_line_1024x27_1sub0 = {
  117646. 1, 32,
  117647. _huff_lengthlist_line_1024x27_1sub0,
  117648. 0, 0, 0, 0, 0,
  117649. NULL,
  117650. NULL,
  117651. NULL,
  117652. NULL,
  117653. 0
  117654. };
  117655. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  117656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117658. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  117659. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  117660. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  117661. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  117662. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  117663. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  117664. };
  117665. static static_codebook _huff_book_line_1024x27_1sub1 = {
  117666. 1, 128,
  117667. _huff_lengthlist_line_1024x27_1sub1,
  117668. 0, 0, 0, 0, 0,
  117669. NULL,
  117670. NULL,
  117671. NULL,
  117672. NULL,
  117673. 0
  117674. };
  117675. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  117676. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117677. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  117678. };
  117679. static static_codebook _huff_book_line_1024x27_2sub0 = {
  117680. 1, 32,
  117681. _huff_lengthlist_line_1024x27_2sub0,
  117682. 0, 0, 0, 0, 0,
  117683. NULL,
  117684. NULL,
  117685. NULL,
  117686. NULL,
  117687. 0
  117688. };
  117689. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  117690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117692. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  117693. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  117694. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  117695. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  117696. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  117697. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  117698. };
  117699. static static_codebook _huff_book_line_1024x27_2sub1 = {
  117700. 1, 128,
  117701. _huff_lengthlist_line_1024x27_2sub1,
  117702. 0, 0, 0, 0, 0,
  117703. NULL,
  117704. NULL,
  117705. NULL,
  117706. NULL,
  117707. 0
  117708. };
  117709. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  117710. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  117711. 5, 5,
  117712. };
  117713. static static_codebook _huff_book_line_1024x27_3sub1 = {
  117714. 1, 18,
  117715. _huff_lengthlist_line_1024x27_3sub1,
  117716. 0, 0, 0, 0, 0,
  117717. NULL,
  117718. NULL,
  117719. NULL,
  117720. NULL,
  117721. 0
  117722. };
  117723. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  117724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117725. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  117726. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  117727. 9,11,
  117728. };
  117729. static static_codebook _huff_book_line_1024x27_3sub2 = {
  117730. 1, 50,
  117731. _huff_lengthlist_line_1024x27_3sub2,
  117732. 0, 0, 0, 0, 0,
  117733. NULL,
  117734. NULL,
  117735. NULL,
  117736. NULL,
  117737. 0
  117738. };
  117739. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  117740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117743. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  117744. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  117745. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117746. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117747. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117748. };
  117749. static static_codebook _huff_book_line_1024x27_3sub3 = {
  117750. 1, 128,
  117751. _huff_lengthlist_line_1024x27_3sub3,
  117752. 0, 0, 0, 0, 0,
  117753. NULL,
  117754. NULL,
  117755. NULL,
  117756. NULL,
  117757. 0
  117758. };
  117759. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  117760. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  117761. 5, 4,
  117762. };
  117763. static static_codebook _huff_book_line_1024x27_4sub1 = {
  117764. 1, 18,
  117765. _huff_lengthlist_line_1024x27_4sub1,
  117766. 0, 0, 0, 0, 0,
  117767. NULL,
  117768. NULL,
  117769. NULL,
  117770. NULL,
  117771. 0
  117772. };
  117773. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  117774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117775. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  117776. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  117777. 9,12,
  117778. };
  117779. static static_codebook _huff_book_line_1024x27_4sub2 = {
  117780. 1, 50,
  117781. _huff_lengthlist_line_1024x27_4sub2,
  117782. 0, 0, 0, 0, 0,
  117783. NULL,
  117784. NULL,
  117785. NULL,
  117786. NULL,
  117787. 0
  117788. };
  117789. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  117790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117793. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  117794. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  117795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117797. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  117798. };
  117799. static static_codebook _huff_book_line_1024x27_4sub3 = {
  117800. 1, 128,
  117801. _huff_lengthlist_line_1024x27_4sub3,
  117802. 0, 0, 0, 0, 0,
  117803. NULL,
  117804. NULL,
  117805. NULL,
  117806. NULL,
  117807. 0
  117808. };
  117809. static long _huff_lengthlist_line_2048x27_class1[] = {
  117810. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  117811. };
  117812. static static_codebook _huff_book_line_2048x27_class1 = {
  117813. 1, 16,
  117814. _huff_lengthlist_line_2048x27_class1,
  117815. 0, 0, 0, 0, 0,
  117816. NULL,
  117817. NULL,
  117818. NULL,
  117819. NULL,
  117820. 0
  117821. };
  117822. static long _huff_lengthlist_line_2048x27_class2[] = {
  117823. 1, 2, 3, 6, 4, 7, 5, 7,
  117824. };
  117825. static static_codebook _huff_book_line_2048x27_class2 = {
  117826. 1, 8,
  117827. _huff_lengthlist_line_2048x27_class2,
  117828. 0, 0, 0, 0, 0,
  117829. NULL,
  117830. NULL,
  117831. NULL,
  117832. NULL,
  117833. 0
  117834. };
  117835. static long _huff_lengthlist_line_2048x27_class3[] = {
  117836. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  117837. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  117838. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  117839. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  117840. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  117841. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  117842. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  117843. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  117844. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  117845. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  117846. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  117847. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117848. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  117849. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  117850. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117851. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117852. };
  117853. static static_codebook _huff_book_line_2048x27_class3 = {
  117854. 1, 256,
  117855. _huff_lengthlist_line_2048x27_class3,
  117856. 0, 0, 0, 0, 0,
  117857. NULL,
  117858. NULL,
  117859. NULL,
  117860. NULL,
  117861. 0
  117862. };
  117863. static long _huff_lengthlist_line_2048x27_class4[] = {
  117864. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  117865. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  117866. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  117867. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  117868. };
  117869. static static_codebook _huff_book_line_2048x27_class4 = {
  117870. 1, 64,
  117871. _huff_lengthlist_line_2048x27_class4,
  117872. 0, 0, 0, 0, 0,
  117873. NULL,
  117874. NULL,
  117875. NULL,
  117876. NULL,
  117877. 0
  117878. };
  117879. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  117880. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117881. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  117882. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  117883. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  117884. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  117885. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  117886. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  117887. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  117888. };
  117889. static static_codebook _huff_book_line_2048x27_0sub0 = {
  117890. 1, 128,
  117891. _huff_lengthlist_line_2048x27_0sub0,
  117892. 0, 0, 0, 0, 0,
  117893. NULL,
  117894. NULL,
  117895. NULL,
  117896. NULL,
  117897. 0
  117898. };
  117899. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  117900. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117901. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  117902. };
  117903. static static_codebook _huff_book_line_2048x27_1sub0 = {
  117904. 1, 32,
  117905. _huff_lengthlist_line_2048x27_1sub0,
  117906. 0, 0, 0, 0, 0,
  117907. NULL,
  117908. NULL,
  117909. NULL,
  117910. NULL,
  117911. 0
  117912. };
  117913. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  117914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117916. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  117917. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  117918. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  117919. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  117920. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  117921. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  117922. };
  117923. static static_codebook _huff_book_line_2048x27_1sub1 = {
  117924. 1, 128,
  117925. _huff_lengthlist_line_2048x27_1sub1,
  117926. 0, 0, 0, 0, 0,
  117927. NULL,
  117928. NULL,
  117929. NULL,
  117930. NULL,
  117931. 0
  117932. };
  117933. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  117934. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117935. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  117936. };
  117937. static static_codebook _huff_book_line_2048x27_2sub0 = {
  117938. 1, 32,
  117939. _huff_lengthlist_line_2048x27_2sub0,
  117940. 0, 0, 0, 0, 0,
  117941. NULL,
  117942. NULL,
  117943. NULL,
  117944. NULL,
  117945. 0
  117946. };
  117947. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  117948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117950. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  117951. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  117952. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  117953. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  117954. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  117955. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117956. };
  117957. static static_codebook _huff_book_line_2048x27_2sub1 = {
  117958. 1, 128,
  117959. _huff_lengthlist_line_2048x27_2sub1,
  117960. 0, 0, 0, 0, 0,
  117961. NULL,
  117962. NULL,
  117963. NULL,
  117964. NULL,
  117965. 0
  117966. };
  117967. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  117968. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  117969. 5, 5,
  117970. };
  117971. static static_codebook _huff_book_line_2048x27_3sub1 = {
  117972. 1, 18,
  117973. _huff_lengthlist_line_2048x27_3sub1,
  117974. 0, 0, 0, 0, 0,
  117975. NULL,
  117976. NULL,
  117977. NULL,
  117978. NULL,
  117979. 0
  117980. };
  117981. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  117982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117983. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  117984. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  117985. 10,12,
  117986. };
  117987. static static_codebook _huff_book_line_2048x27_3sub2 = {
  117988. 1, 50,
  117989. _huff_lengthlist_line_2048x27_3sub2,
  117990. 0, 0, 0, 0, 0,
  117991. NULL,
  117992. NULL,
  117993. NULL,
  117994. NULL,
  117995. 0
  117996. };
  117997. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  117998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118001. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  118002. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118003. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118004. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118005. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118006. };
  118007. static static_codebook _huff_book_line_2048x27_3sub3 = {
  118008. 1, 128,
  118009. _huff_lengthlist_line_2048x27_3sub3,
  118010. 0, 0, 0, 0, 0,
  118011. NULL,
  118012. NULL,
  118013. NULL,
  118014. NULL,
  118015. 0
  118016. };
  118017. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  118018. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  118019. 4, 5,
  118020. };
  118021. static static_codebook _huff_book_line_2048x27_4sub1 = {
  118022. 1, 18,
  118023. _huff_lengthlist_line_2048x27_4sub1,
  118024. 0, 0, 0, 0, 0,
  118025. NULL,
  118026. NULL,
  118027. NULL,
  118028. NULL,
  118029. 0
  118030. };
  118031. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  118032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118033. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  118034. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  118035. 10,10,
  118036. };
  118037. static static_codebook _huff_book_line_2048x27_4sub2 = {
  118038. 1, 50,
  118039. _huff_lengthlist_line_2048x27_4sub2,
  118040. 0, 0, 0, 0, 0,
  118041. NULL,
  118042. NULL,
  118043. NULL,
  118044. NULL,
  118045. 0
  118046. };
  118047. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  118048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118051. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  118052. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  118053. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118054. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118055. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  118056. };
  118057. static static_codebook _huff_book_line_2048x27_4sub3 = {
  118058. 1, 128,
  118059. _huff_lengthlist_line_2048x27_4sub3,
  118060. 0, 0, 0, 0, 0,
  118061. NULL,
  118062. NULL,
  118063. NULL,
  118064. NULL,
  118065. 0
  118066. };
  118067. static long _huff_lengthlist_line_256x4low_class0[] = {
  118068. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  118069. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  118070. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  118071. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  118072. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  118073. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  118074. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  118075. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  118076. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  118077. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  118078. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  118079. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  118080. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  118081. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  118082. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  118083. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  118084. };
  118085. static static_codebook _huff_book_line_256x4low_class0 = {
  118086. 1, 256,
  118087. _huff_lengthlist_line_256x4low_class0,
  118088. 0, 0, 0, 0, 0,
  118089. NULL,
  118090. NULL,
  118091. NULL,
  118092. NULL,
  118093. 0
  118094. };
  118095. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  118096. 1, 3, 2, 3,
  118097. };
  118098. static static_codebook _huff_book_line_256x4low_0sub0 = {
  118099. 1, 4,
  118100. _huff_lengthlist_line_256x4low_0sub0,
  118101. 0, 0, 0, 0, 0,
  118102. NULL,
  118103. NULL,
  118104. NULL,
  118105. NULL,
  118106. 0
  118107. };
  118108. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  118109. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  118110. };
  118111. static static_codebook _huff_book_line_256x4low_0sub1 = {
  118112. 1, 10,
  118113. _huff_lengthlist_line_256x4low_0sub1,
  118114. 0, 0, 0, 0, 0,
  118115. NULL,
  118116. NULL,
  118117. NULL,
  118118. NULL,
  118119. 0
  118120. };
  118121. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  118122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  118123. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  118124. };
  118125. static static_codebook _huff_book_line_256x4low_0sub2 = {
  118126. 1, 25,
  118127. _huff_lengthlist_line_256x4low_0sub2,
  118128. 0, 0, 0, 0, 0,
  118129. NULL,
  118130. NULL,
  118131. NULL,
  118132. NULL,
  118133. 0
  118134. };
  118135. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  118136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  118138. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  118139. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  118140. };
  118141. static static_codebook _huff_book_line_256x4low_0sub3 = {
  118142. 1, 64,
  118143. _huff_lengthlist_line_256x4low_0sub3,
  118144. 0, 0, 0, 0, 0,
  118145. NULL,
  118146. NULL,
  118147. NULL,
  118148. NULL,
  118149. 0
  118150. };
  118151. /********* End of inlined file: floor_books.h *********/
  118152. static static_codebook *_floor_128x4_books[]={
  118153. &_huff_book_line_128x4_class0,
  118154. &_huff_book_line_128x4_0sub0,
  118155. &_huff_book_line_128x4_0sub1,
  118156. &_huff_book_line_128x4_0sub2,
  118157. &_huff_book_line_128x4_0sub3,
  118158. };
  118159. static static_codebook *_floor_256x4_books[]={
  118160. &_huff_book_line_256x4_class0,
  118161. &_huff_book_line_256x4_0sub0,
  118162. &_huff_book_line_256x4_0sub1,
  118163. &_huff_book_line_256x4_0sub2,
  118164. &_huff_book_line_256x4_0sub3,
  118165. };
  118166. static static_codebook *_floor_128x7_books[]={
  118167. &_huff_book_line_128x7_class0,
  118168. &_huff_book_line_128x7_class1,
  118169. &_huff_book_line_128x7_0sub1,
  118170. &_huff_book_line_128x7_0sub2,
  118171. &_huff_book_line_128x7_0sub3,
  118172. &_huff_book_line_128x7_1sub1,
  118173. &_huff_book_line_128x7_1sub2,
  118174. &_huff_book_line_128x7_1sub3,
  118175. };
  118176. static static_codebook *_floor_256x7_books[]={
  118177. &_huff_book_line_256x7_class0,
  118178. &_huff_book_line_256x7_class1,
  118179. &_huff_book_line_256x7_0sub1,
  118180. &_huff_book_line_256x7_0sub2,
  118181. &_huff_book_line_256x7_0sub3,
  118182. &_huff_book_line_256x7_1sub1,
  118183. &_huff_book_line_256x7_1sub2,
  118184. &_huff_book_line_256x7_1sub3,
  118185. };
  118186. static static_codebook *_floor_128x11_books[]={
  118187. &_huff_book_line_128x11_class1,
  118188. &_huff_book_line_128x11_class2,
  118189. &_huff_book_line_128x11_class3,
  118190. &_huff_book_line_128x11_0sub0,
  118191. &_huff_book_line_128x11_1sub0,
  118192. &_huff_book_line_128x11_1sub1,
  118193. &_huff_book_line_128x11_2sub1,
  118194. &_huff_book_line_128x11_2sub2,
  118195. &_huff_book_line_128x11_2sub3,
  118196. &_huff_book_line_128x11_3sub1,
  118197. &_huff_book_line_128x11_3sub2,
  118198. &_huff_book_line_128x11_3sub3,
  118199. };
  118200. static static_codebook *_floor_128x17_books[]={
  118201. &_huff_book_line_128x17_class1,
  118202. &_huff_book_line_128x17_class2,
  118203. &_huff_book_line_128x17_class3,
  118204. &_huff_book_line_128x17_0sub0,
  118205. &_huff_book_line_128x17_1sub0,
  118206. &_huff_book_line_128x17_1sub1,
  118207. &_huff_book_line_128x17_2sub1,
  118208. &_huff_book_line_128x17_2sub2,
  118209. &_huff_book_line_128x17_2sub3,
  118210. &_huff_book_line_128x17_3sub1,
  118211. &_huff_book_line_128x17_3sub2,
  118212. &_huff_book_line_128x17_3sub3,
  118213. };
  118214. static static_codebook *_floor_256x4low_books[]={
  118215. &_huff_book_line_256x4low_class0,
  118216. &_huff_book_line_256x4low_0sub0,
  118217. &_huff_book_line_256x4low_0sub1,
  118218. &_huff_book_line_256x4low_0sub2,
  118219. &_huff_book_line_256x4low_0sub3,
  118220. };
  118221. static static_codebook *_floor_1024x27_books[]={
  118222. &_huff_book_line_1024x27_class1,
  118223. &_huff_book_line_1024x27_class2,
  118224. &_huff_book_line_1024x27_class3,
  118225. &_huff_book_line_1024x27_class4,
  118226. &_huff_book_line_1024x27_0sub0,
  118227. &_huff_book_line_1024x27_1sub0,
  118228. &_huff_book_line_1024x27_1sub1,
  118229. &_huff_book_line_1024x27_2sub0,
  118230. &_huff_book_line_1024x27_2sub1,
  118231. &_huff_book_line_1024x27_3sub1,
  118232. &_huff_book_line_1024x27_3sub2,
  118233. &_huff_book_line_1024x27_3sub3,
  118234. &_huff_book_line_1024x27_4sub1,
  118235. &_huff_book_line_1024x27_4sub2,
  118236. &_huff_book_line_1024x27_4sub3,
  118237. };
  118238. static static_codebook *_floor_2048x27_books[]={
  118239. &_huff_book_line_2048x27_class1,
  118240. &_huff_book_line_2048x27_class2,
  118241. &_huff_book_line_2048x27_class3,
  118242. &_huff_book_line_2048x27_class4,
  118243. &_huff_book_line_2048x27_0sub0,
  118244. &_huff_book_line_2048x27_1sub0,
  118245. &_huff_book_line_2048x27_1sub1,
  118246. &_huff_book_line_2048x27_2sub0,
  118247. &_huff_book_line_2048x27_2sub1,
  118248. &_huff_book_line_2048x27_3sub1,
  118249. &_huff_book_line_2048x27_3sub2,
  118250. &_huff_book_line_2048x27_3sub3,
  118251. &_huff_book_line_2048x27_4sub1,
  118252. &_huff_book_line_2048x27_4sub2,
  118253. &_huff_book_line_2048x27_4sub3,
  118254. };
  118255. static static_codebook *_floor_512x17_books[]={
  118256. &_huff_book_line_512x17_class1,
  118257. &_huff_book_line_512x17_class2,
  118258. &_huff_book_line_512x17_class3,
  118259. &_huff_book_line_512x17_0sub0,
  118260. &_huff_book_line_512x17_1sub0,
  118261. &_huff_book_line_512x17_1sub1,
  118262. &_huff_book_line_512x17_2sub1,
  118263. &_huff_book_line_512x17_2sub2,
  118264. &_huff_book_line_512x17_2sub3,
  118265. &_huff_book_line_512x17_3sub1,
  118266. &_huff_book_line_512x17_3sub2,
  118267. &_huff_book_line_512x17_3sub3,
  118268. };
  118269. static static_codebook **_floor_books[10]={
  118270. _floor_128x4_books,
  118271. _floor_256x4_books,
  118272. _floor_128x7_books,
  118273. _floor_256x7_books,
  118274. _floor_128x11_books,
  118275. _floor_128x17_books,
  118276. _floor_256x4low_books,
  118277. _floor_1024x27_books,
  118278. _floor_2048x27_books,
  118279. _floor_512x17_books,
  118280. };
  118281. static vorbis_info_floor1 _floor[10]={
  118282. /* 128 x 4 */
  118283. {
  118284. 1,{0},{4},{2},{0},
  118285. {{1,2,3,4}},
  118286. 4,{0,128, 33,8,16,70},
  118287. 60,30,500, 1.,18., -1
  118288. },
  118289. /* 256 x 4 */
  118290. {
  118291. 1,{0},{4},{2},{0},
  118292. {{1,2,3,4}},
  118293. 4,{0,256, 66,16,32,140},
  118294. 60,30,500, 1.,18., -1
  118295. },
  118296. /* 128 x 7 */
  118297. {
  118298. 2,{0,1},{3,4},{2,2},{0,1},
  118299. {{-1,2,3,4},{-1,5,6,7}},
  118300. 4,{0,128, 14,4,58, 2,8,28,90},
  118301. 60,30,500, 1.,18., -1
  118302. },
  118303. /* 256 x 7 */
  118304. {
  118305. 2,{0,1},{3,4},{2,2},{0,1},
  118306. {{-1,2,3,4},{-1,5,6,7}},
  118307. 4,{0,256, 28,8,116, 4,16,56,180},
  118308. 60,30,500, 1.,18., -1
  118309. },
  118310. /* 128 x 11 */
  118311. {
  118312. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118313. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118314. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  118315. 60,30,500, 1,18., -1
  118316. },
  118317. /* 128 x 17 */
  118318. {
  118319. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118320. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118321. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  118322. 60,30,500, 1,18., -1
  118323. },
  118324. /* 256 x 4 (low bitrate version) */
  118325. {
  118326. 1,{0},{4},{2},{0},
  118327. {{1,2,3,4}},
  118328. 4,{0,256, 66,16,32,140},
  118329. 60,30,500, 1.,18., -1
  118330. },
  118331. /* 1024 x 27 */
  118332. {
  118333. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118334. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118335. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  118336. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  118337. 60,30,500, 3,18., -1 /* lowpass */
  118338. },
  118339. /* 2048 x 27 */
  118340. {
  118341. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118342. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118343. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  118344. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  118345. 60,30,500, 3,18., -1 /* lowpass */
  118346. },
  118347. /* 512 x 17 */
  118348. {
  118349. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118350. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118351. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  118352. 7,23,39, 55,79,110, 156,232,360},
  118353. 60,30,500, 1,18., -1 /* lowpass! */
  118354. },
  118355. };
  118356. /********* End of inlined file: floor_all.h *********/
  118357. /********* Start of inlined file: residue_44.h *********/
  118358. /********* Start of inlined file: res_books_stereo.h *********/
  118359. static long _vq_quantlist__16c0_s_p1_0[] = {
  118360. 1,
  118361. 0,
  118362. 2,
  118363. };
  118364. static long _vq_lengthlist__16c0_s_p1_0[] = {
  118365. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  118366. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  118369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118370. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  118371. 0, 0, 0, 7, 9,10, 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, 0, 0, 0, 0, 0, 0,
  118374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118375. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118376. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0,
  118379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  118411. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  118416. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  118421. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  118457. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  118462. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  118467. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  118776. };
  118777. static float _vq_quantthresh__16c0_s_p1_0[] = {
  118778. -0.5, 0.5,
  118779. };
  118780. static long _vq_quantmap__16c0_s_p1_0[] = {
  118781. 1, 0, 2,
  118782. };
  118783. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  118784. _vq_quantthresh__16c0_s_p1_0,
  118785. _vq_quantmap__16c0_s_p1_0,
  118786. 3,
  118787. 3
  118788. };
  118789. static static_codebook _16c0_s_p1_0 = {
  118790. 8, 6561,
  118791. _vq_lengthlist__16c0_s_p1_0,
  118792. 1, -535822336, 1611661312, 2, 0,
  118793. _vq_quantlist__16c0_s_p1_0,
  118794. NULL,
  118795. &_vq_auxt__16c0_s_p1_0,
  118796. NULL,
  118797. 0
  118798. };
  118799. static long _vq_quantlist__16c0_s_p2_0[] = {
  118800. 2,
  118801. 1,
  118802. 3,
  118803. 0,
  118804. 4,
  118805. };
  118806. static long _vq_lengthlist__16c0_s_p2_0[] = {
  118807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  118847. };
  118848. static float _vq_quantthresh__16c0_s_p2_0[] = {
  118849. -1.5, -0.5, 0.5, 1.5,
  118850. };
  118851. static long _vq_quantmap__16c0_s_p2_0[] = {
  118852. 3, 1, 0, 2, 4,
  118853. };
  118854. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  118855. _vq_quantthresh__16c0_s_p2_0,
  118856. _vq_quantmap__16c0_s_p2_0,
  118857. 5,
  118858. 5
  118859. };
  118860. static static_codebook _16c0_s_p2_0 = {
  118861. 4, 625,
  118862. _vq_lengthlist__16c0_s_p2_0,
  118863. 1, -533725184, 1611661312, 3, 0,
  118864. _vq_quantlist__16c0_s_p2_0,
  118865. NULL,
  118866. &_vq_auxt__16c0_s_p2_0,
  118867. NULL,
  118868. 0
  118869. };
  118870. static long _vq_quantlist__16c0_s_p3_0[] = {
  118871. 2,
  118872. 1,
  118873. 3,
  118874. 0,
  118875. 4,
  118876. };
  118877. static long _vq_lengthlist__16c0_s_p3_0[] = {
  118878. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  118880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118881. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  118883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118884. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118917. 0,
  118918. };
  118919. static float _vq_quantthresh__16c0_s_p3_0[] = {
  118920. -1.5, -0.5, 0.5, 1.5,
  118921. };
  118922. static long _vq_quantmap__16c0_s_p3_0[] = {
  118923. 3, 1, 0, 2, 4,
  118924. };
  118925. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  118926. _vq_quantthresh__16c0_s_p3_0,
  118927. _vq_quantmap__16c0_s_p3_0,
  118928. 5,
  118929. 5
  118930. };
  118931. static static_codebook _16c0_s_p3_0 = {
  118932. 4, 625,
  118933. _vq_lengthlist__16c0_s_p3_0,
  118934. 1, -533725184, 1611661312, 3, 0,
  118935. _vq_quantlist__16c0_s_p3_0,
  118936. NULL,
  118937. &_vq_auxt__16c0_s_p3_0,
  118938. NULL,
  118939. 0
  118940. };
  118941. static long _vq_quantlist__16c0_s_p4_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_p4_0[] = {
  118953. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118954. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118955. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118956. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  118957. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118958. 0,
  118959. };
  118960. static float _vq_quantthresh__16c0_s_p4_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_p4_0[] = {
  118964. 7, 5, 3, 1, 0, 2, 4, 6,
  118965. 8,
  118966. };
  118967. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  118968. _vq_quantthresh__16c0_s_p4_0,
  118969. _vq_quantmap__16c0_s_p4_0,
  118970. 9,
  118971. 9
  118972. };
  118973. static static_codebook _16c0_s_p4_0 = {
  118974. 2, 81,
  118975. _vq_lengthlist__16c0_s_p4_0,
  118976. 1, -531628032, 1611661312, 4, 0,
  118977. _vq_quantlist__16c0_s_p4_0,
  118978. NULL,
  118979. &_vq_auxt__16c0_s_p4_0,
  118980. NULL,
  118981. 0
  118982. };
  118983. static long _vq_quantlist__16c0_s_p5_0[] = {
  118984. 4,
  118985. 3,
  118986. 5,
  118987. 2,
  118988. 6,
  118989. 1,
  118990. 7,
  118991. 0,
  118992. 8,
  118993. };
  118994. static long _vq_lengthlist__16c0_s_p5_0[] = {
  118995. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118996. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  118997. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  118998. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  118999. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119000. 10,
  119001. };
  119002. static float _vq_quantthresh__16c0_s_p5_0[] = {
  119003. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119004. };
  119005. static long _vq_quantmap__16c0_s_p5_0[] = {
  119006. 7, 5, 3, 1, 0, 2, 4, 6,
  119007. 8,
  119008. };
  119009. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  119010. _vq_quantthresh__16c0_s_p5_0,
  119011. _vq_quantmap__16c0_s_p5_0,
  119012. 9,
  119013. 9
  119014. };
  119015. static static_codebook _16c0_s_p5_0 = {
  119016. 2, 81,
  119017. _vq_lengthlist__16c0_s_p5_0,
  119018. 1, -531628032, 1611661312, 4, 0,
  119019. _vq_quantlist__16c0_s_p5_0,
  119020. NULL,
  119021. &_vq_auxt__16c0_s_p5_0,
  119022. NULL,
  119023. 0
  119024. };
  119025. static long _vq_quantlist__16c0_s_p6_0[] = {
  119026. 8,
  119027. 7,
  119028. 9,
  119029. 6,
  119030. 10,
  119031. 5,
  119032. 11,
  119033. 4,
  119034. 12,
  119035. 3,
  119036. 13,
  119037. 2,
  119038. 14,
  119039. 1,
  119040. 15,
  119041. 0,
  119042. 16,
  119043. };
  119044. static long _vq_lengthlist__16c0_s_p6_0[] = {
  119045. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  119046. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  119047. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  119048. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  119049. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  119050. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119051. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119052. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119053. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  119054. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119055. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  119056. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  119057. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  119058. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  119059. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  119060. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  119061. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  119062. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  119063. 14,
  119064. };
  119065. static float _vq_quantthresh__16c0_s_p6_0[] = {
  119066. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119067. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119068. };
  119069. static long _vq_quantmap__16c0_s_p6_0[] = {
  119070. 15, 13, 11, 9, 7, 5, 3, 1,
  119071. 0, 2, 4, 6, 8, 10, 12, 14,
  119072. 16,
  119073. };
  119074. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  119075. _vq_quantthresh__16c0_s_p6_0,
  119076. _vq_quantmap__16c0_s_p6_0,
  119077. 17,
  119078. 17
  119079. };
  119080. static static_codebook _16c0_s_p6_0 = {
  119081. 2, 289,
  119082. _vq_lengthlist__16c0_s_p6_0,
  119083. 1, -529530880, 1611661312, 5, 0,
  119084. _vq_quantlist__16c0_s_p6_0,
  119085. NULL,
  119086. &_vq_auxt__16c0_s_p6_0,
  119087. NULL,
  119088. 0
  119089. };
  119090. static long _vq_quantlist__16c0_s_p7_0[] = {
  119091. 1,
  119092. 0,
  119093. 2,
  119094. };
  119095. static long _vq_lengthlist__16c0_s_p7_0[] = {
  119096. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  119097. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  119098. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  119099. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  119100. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  119101. 13,
  119102. };
  119103. static float _vq_quantthresh__16c0_s_p7_0[] = {
  119104. -5.5, 5.5,
  119105. };
  119106. static long _vq_quantmap__16c0_s_p7_0[] = {
  119107. 1, 0, 2,
  119108. };
  119109. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  119110. _vq_quantthresh__16c0_s_p7_0,
  119111. _vq_quantmap__16c0_s_p7_0,
  119112. 3,
  119113. 3
  119114. };
  119115. static static_codebook _16c0_s_p7_0 = {
  119116. 4, 81,
  119117. _vq_lengthlist__16c0_s_p7_0,
  119118. 1, -529137664, 1618345984, 2, 0,
  119119. _vq_quantlist__16c0_s_p7_0,
  119120. NULL,
  119121. &_vq_auxt__16c0_s_p7_0,
  119122. NULL,
  119123. 0
  119124. };
  119125. static long _vq_quantlist__16c0_s_p7_1[] = {
  119126. 5,
  119127. 4,
  119128. 6,
  119129. 3,
  119130. 7,
  119131. 2,
  119132. 8,
  119133. 1,
  119134. 9,
  119135. 0,
  119136. 10,
  119137. };
  119138. static long _vq_lengthlist__16c0_s_p7_1[] = {
  119139. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  119140. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  119141. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  119142. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  119143. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  119144. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  119145. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  119146. 11,11,11, 9, 9, 9, 9,10,10,
  119147. };
  119148. static float _vq_quantthresh__16c0_s_p7_1[] = {
  119149. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119150. 3.5, 4.5,
  119151. };
  119152. static long _vq_quantmap__16c0_s_p7_1[] = {
  119153. 9, 7, 5, 3, 1, 0, 2, 4,
  119154. 6, 8, 10,
  119155. };
  119156. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  119157. _vq_quantthresh__16c0_s_p7_1,
  119158. _vq_quantmap__16c0_s_p7_1,
  119159. 11,
  119160. 11
  119161. };
  119162. static static_codebook _16c0_s_p7_1 = {
  119163. 2, 121,
  119164. _vq_lengthlist__16c0_s_p7_1,
  119165. 1, -531365888, 1611661312, 4, 0,
  119166. _vq_quantlist__16c0_s_p7_1,
  119167. NULL,
  119168. &_vq_auxt__16c0_s_p7_1,
  119169. NULL,
  119170. 0
  119171. };
  119172. static long _vq_quantlist__16c0_s_p8_0[] = {
  119173. 6,
  119174. 5,
  119175. 7,
  119176. 4,
  119177. 8,
  119178. 3,
  119179. 9,
  119180. 2,
  119181. 10,
  119182. 1,
  119183. 11,
  119184. 0,
  119185. 12,
  119186. };
  119187. static long _vq_lengthlist__16c0_s_p8_0[] = {
  119188. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  119189. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  119190. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  119191. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  119192. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  119193. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  119194. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  119195. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  119196. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  119197. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  119198. 0,12,13,13,12,13,14,14,14,
  119199. };
  119200. static float _vq_quantthresh__16c0_s_p8_0[] = {
  119201. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119202. 12.5, 17.5, 22.5, 27.5,
  119203. };
  119204. static long _vq_quantmap__16c0_s_p8_0[] = {
  119205. 11, 9, 7, 5, 3, 1, 0, 2,
  119206. 4, 6, 8, 10, 12,
  119207. };
  119208. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  119209. _vq_quantthresh__16c0_s_p8_0,
  119210. _vq_quantmap__16c0_s_p8_0,
  119211. 13,
  119212. 13
  119213. };
  119214. static static_codebook _16c0_s_p8_0 = {
  119215. 2, 169,
  119216. _vq_lengthlist__16c0_s_p8_0,
  119217. 1, -526516224, 1616117760, 4, 0,
  119218. _vq_quantlist__16c0_s_p8_0,
  119219. NULL,
  119220. &_vq_auxt__16c0_s_p8_0,
  119221. NULL,
  119222. 0
  119223. };
  119224. static long _vq_quantlist__16c0_s_p8_1[] = {
  119225. 2,
  119226. 1,
  119227. 3,
  119228. 0,
  119229. 4,
  119230. };
  119231. static long _vq_lengthlist__16c0_s_p8_1[] = {
  119232. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  119233. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119234. };
  119235. static float _vq_quantthresh__16c0_s_p8_1[] = {
  119236. -1.5, -0.5, 0.5, 1.5,
  119237. };
  119238. static long _vq_quantmap__16c0_s_p8_1[] = {
  119239. 3, 1, 0, 2, 4,
  119240. };
  119241. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  119242. _vq_quantthresh__16c0_s_p8_1,
  119243. _vq_quantmap__16c0_s_p8_1,
  119244. 5,
  119245. 5
  119246. };
  119247. static static_codebook _16c0_s_p8_1 = {
  119248. 2, 25,
  119249. _vq_lengthlist__16c0_s_p8_1,
  119250. 1, -533725184, 1611661312, 3, 0,
  119251. _vq_quantlist__16c0_s_p8_1,
  119252. NULL,
  119253. &_vq_auxt__16c0_s_p8_1,
  119254. NULL,
  119255. 0
  119256. };
  119257. static long _vq_quantlist__16c0_s_p9_0[] = {
  119258. 1,
  119259. 0,
  119260. 2,
  119261. };
  119262. static long _vq_lengthlist__16c0_s_p9_0[] = {
  119263. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119264. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119265. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119266. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119267. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119268. 7,
  119269. };
  119270. static float _vq_quantthresh__16c0_s_p9_0[] = {
  119271. -157.5, 157.5,
  119272. };
  119273. static long _vq_quantmap__16c0_s_p9_0[] = {
  119274. 1, 0, 2,
  119275. };
  119276. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  119277. _vq_quantthresh__16c0_s_p9_0,
  119278. _vq_quantmap__16c0_s_p9_0,
  119279. 3,
  119280. 3
  119281. };
  119282. static static_codebook _16c0_s_p9_0 = {
  119283. 4, 81,
  119284. _vq_lengthlist__16c0_s_p9_0,
  119285. 1, -518803456, 1628680192, 2, 0,
  119286. _vq_quantlist__16c0_s_p9_0,
  119287. NULL,
  119288. &_vq_auxt__16c0_s_p9_0,
  119289. NULL,
  119290. 0
  119291. };
  119292. static long _vq_quantlist__16c0_s_p9_1[] = {
  119293. 7,
  119294. 6,
  119295. 8,
  119296. 5,
  119297. 9,
  119298. 4,
  119299. 10,
  119300. 3,
  119301. 11,
  119302. 2,
  119303. 12,
  119304. 1,
  119305. 13,
  119306. 0,
  119307. 14,
  119308. };
  119309. static long _vq_lengthlist__16c0_s_p9_1[] = {
  119310. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  119311. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  119312. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  119313. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  119314. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119315. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119316. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119317. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119318. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119319. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119320. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119321. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119322. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119323. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119324. 10,
  119325. };
  119326. static float _vq_quantthresh__16c0_s_p9_1[] = {
  119327. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119328. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119329. };
  119330. static long _vq_quantmap__16c0_s_p9_1[] = {
  119331. 13, 11, 9, 7, 5, 3, 1, 0,
  119332. 2, 4, 6, 8, 10, 12, 14,
  119333. };
  119334. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  119335. _vq_quantthresh__16c0_s_p9_1,
  119336. _vq_quantmap__16c0_s_p9_1,
  119337. 15,
  119338. 15
  119339. };
  119340. static static_codebook _16c0_s_p9_1 = {
  119341. 2, 225,
  119342. _vq_lengthlist__16c0_s_p9_1,
  119343. 1, -520986624, 1620377600, 4, 0,
  119344. _vq_quantlist__16c0_s_p9_1,
  119345. NULL,
  119346. &_vq_auxt__16c0_s_p9_1,
  119347. NULL,
  119348. 0
  119349. };
  119350. static long _vq_quantlist__16c0_s_p9_2[] = {
  119351. 10,
  119352. 9,
  119353. 11,
  119354. 8,
  119355. 12,
  119356. 7,
  119357. 13,
  119358. 6,
  119359. 14,
  119360. 5,
  119361. 15,
  119362. 4,
  119363. 16,
  119364. 3,
  119365. 17,
  119366. 2,
  119367. 18,
  119368. 1,
  119369. 19,
  119370. 0,
  119371. 20,
  119372. };
  119373. static long _vq_lengthlist__16c0_s_p9_2[] = {
  119374. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  119375. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  119376. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  119377. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  119378. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  119379. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  119380. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  119381. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  119382. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  119383. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  119384. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  119385. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  119386. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  119387. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  119388. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  119389. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  119390. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  119391. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  119392. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  119393. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  119394. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  119395. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  119396. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  119397. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  119398. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  119399. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  119400. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  119401. 10,11,10,10,11, 9,10,10,10,
  119402. };
  119403. static float _vq_quantthresh__16c0_s_p9_2[] = {
  119404. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119405. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119406. 6.5, 7.5, 8.5, 9.5,
  119407. };
  119408. static long _vq_quantmap__16c0_s_p9_2[] = {
  119409. 19, 17, 15, 13, 11, 9, 7, 5,
  119410. 3, 1, 0, 2, 4, 6, 8, 10,
  119411. 12, 14, 16, 18, 20,
  119412. };
  119413. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  119414. _vq_quantthresh__16c0_s_p9_2,
  119415. _vq_quantmap__16c0_s_p9_2,
  119416. 21,
  119417. 21
  119418. };
  119419. static static_codebook _16c0_s_p9_2 = {
  119420. 2, 441,
  119421. _vq_lengthlist__16c0_s_p9_2,
  119422. 1, -529268736, 1611661312, 5, 0,
  119423. _vq_quantlist__16c0_s_p9_2,
  119424. NULL,
  119425. &_vq_auxt__16c0_s_p9_2,
  119426. NULL,
  119427. 0
  119428. };
  119429. static long _huff_lengthlist__16c0_s_single[] = {
  119430. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  119431. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  119432. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  119433. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  119434. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  119435. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  119436. 16,16,18,18,
  119437. };
  119438. static static_codebook _huff_book__16c0_s_single = {
  119439. 2, 100,
  119440. _huff_lengthlist__16c0_s_single,
  119441. 0, 0, 0, 0, 0,
  119442. NULL,
  119443. NULL,
  119444. NULL,
  119445. NULL,
  119446. 0
  119447. };
  119448. static long _huff_lengthlist__16c1_s_long[] = {
  119449. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  119450. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  119451. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  119452. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  119453. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  119454. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  119455. 12,11,11,13,
  119456. };
  119457. static static_codebook _huff_book__16c1_s_long = {
  119458. 2, 100,
  119459. _huff_lengthlist__16c1_s_long,
  119460. 0, 0, 0, 0, 0,
  119461. NULL,
  119462. NULL,
  119463. NULL,
  119464. NULL,
  119465. 0
  119466. };
  119467. static long _vq_quantlist__16c1_s_p1_0[] = {
  119468. 1,
  119469. 0,
  119470. 2,
  119471. };
  119472. static long _vq_lengthlist__16c1_s_p1_0[] = {
  119473. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119474. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  119477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119478. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  119479. 0, 0, 0, 7, 8, 9, 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, 0, 0, 0, 0, 0, 0,
  119482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119483. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  119484. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0,
  119487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  119519. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  119524. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119529. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119565. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  119570. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  119575. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  119884. };
  119885. static float _vq_quantthresh__16c1_s_p1_0[] = {
  119886. -0.5, 0.5,
  119887. };
  119888. static long _vq_quantmap__16c1_s_p1_0[] = {
  119889. 1, 0, 2,
  119890. };
  119891. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  119892. _vq_quantthresh__16c1_s_p1_0,
  119893. _vq_quantmap__16c1_s_p1_0,
  119894. 3,
  119895. 3
  119896. };
  119897. static static_codebook _16c1_s_p1_0 = {
  119898. 8, 6561,
  119899. _vq_lengthlist__16c1_s_p1_0,
  119900. 1, -535822336, 1611661312, 2, 0,
  119901. _vq_quantlist__16c1_s_p1_0,
  119902. NULL,
  119903. &_vq_auxt__16c1_s_p1_0,
  119904. NULL,
  119905. 0
  119906. };
  119907. static long _vq_quantlist__16c1_s_p2_0[] = {
  119908. 2,
  119909. 1,
  119910. 3,
  119911. 0,
  119912. 4,
  119913. };
  119914. static long _vq_lengthlist__16c1_s_p2_0[] = {
  119915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  119955. };
  119956. static float _vq_quantthresh__16c1_s_p2_0[] = {
  119957. -1.5, -0.5, 0.5, 1.5,
  119958. };
  119959. static long _vq_quantmap__16c1_s_p2_0[] = {
  119960. 3, 1, 0, 2, 4,
  119961. };
  119962. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  119963. _vq_quantthresh__16c1_s_p2_0,
  119964. _vq_quantmap__16c1_s_p2_0,
  119965. 5,
  119966. 5
  119967. };
  119968. static static_codebook _16c1_s_p2_0 = {
  119969. 4, 625,
  119970. _vq_lengthlist__16c1_s_p2_0,
  119971. 1, -533725184, 1611661312, 3, 0,
  119972. _vq_quantlist__16c1_s_p2_0,
  119973. NULL,
  119974. &_vq_auxt__16c1_s_p2_0,
  119975. NULL,
  119976. 0
  119977. };
  119978. static long _vq_quantlist__16c1_s_p3_0[] = {
  119979. 2,
  119980. 1,
  119981. 3,
  119982. 0,
  119983. 4,
  119984. };
  119985. static long _vq_lengthlist__16c1_s_p3_0[] = {
  119986. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  119988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119989. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  119991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119992. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  119993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120025. 0,
  120026. };
  120027. static float _vq_quantthresh__16c1_s_p3_0[] = {
  120028. -1.5, -0.5, 0.5, 1.5,
  120029. };
  120030. static long _vq_quantmap__16c1_s_p3_0[] = {
  120031. 3, 1, 0, 2, 4,
  120032. };
  120033. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  120034. _vq_quantthresh__16c1_s_p3_0,
  120035. _vq_quantmap__16c1_s_p3_0,
  120036. 5,
  120037. 5
  120038. };
  120039. static static_codebook _16c1_s_p3_0 = {
  120040. 4, 625,
  120041. _vq_lengthlist__16c1_s_p3_0,
  120042. 1, -533725184, 1611661312, 3, 0,
  120043. _vq_quantlist__16c1_s_p3_0,
  120044. NULL,
  120045. &_vq_auxt__16c1_s_p3_0,
  120046. NULL,
  120047. 0
  120048. };
  120049. static long _vq_quantlist__16c1_s_p4_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_p4_0[] = {
  120061. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120062. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120063. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120064. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  120065. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120066. 0,
  120067. };
  120068. static float _vq_quantthresh__16c1_s_p4_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_p4_0[] = {
  120072. 7, 5, 3, 1, 0, 2, 4, 6,
  120073. 8,
  120074. };
  120075. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  120076. _vq_quantthresh__16c1_s_p4_0,
  120077. _vq_quantmap__16c1_s_p4_0,
  120078. 9,
  120079. 9
  120080. };
  120081. static static_codebook _16c1_s_p4_0 = {
  120082. 2, 81,
  120083. _vq_lengthlist__16c1_s_p4_0,
  120084. 1, -531628032, 1611661312, 4, 0,
  120085. _vq_quantlist__16c1_s_p4_0,
  120086. NULL,
  120087. &_vq_auxt__16c1_s_p4_0,
  120088. NULL,
  120089. 0
  120090. };
  120091. static long _vq_quantlist__16c1_s_p5_0[] = {
  120092. 4,
  120093. 3,
  120094. 5,
  120095. 2,
  120096. 6,
  120097. 1,
  120098. 7,
  120099. 0,
  120100. 8,
  120101. };
  120102. static long _vq_lengthlist__16c1_s_p5_0[] = {
  120103. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120104. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  120105. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  120106. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  120107. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120108. 10,
  120109. };
  120110. static float _vq_quantthresh__16c1_s_p5_0[] = {
  120111. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120112. };
  120113. static long _vq_quantmap__16c1_s_p5_0[] = {
  120114. 7, 5, 3, 1, 0, 2, 4, 6,
  120115. 8,
  120116. };
  120117. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  120118. _vq_quantthresh__16c1_s_p5_0,
  120119. _vq_quantmap__16c1_s_p5_0,
  120120. 9,
  120121. 9
  120122. };
  120123. static static_codebook _16c1_s_p5_0 = {
  120124. 2, 81,
  120125. _vq_lengthlist__16c1_s_p5_0,
  120126. 1, -531628032, 1611661312, 4, 0,
  120127. _vq_quantlist__16c1_s_p5_0,
  120128. NULL,
  120129. &_vq_auxt__16c1_s_p5_0,
  120130. NULL,
  120131. 0
  120132. };
  120133. static long _vq_quantlist__16c1_s_p6_0[] = {
  120134. 8,
  120135. 7,
  120136. 9,
  120137. 6,
  120138. 10,
  120139. 5,
  120140. 11,
  120141. 4,
  120142. 12,
  120143. 3,
  120144. 13,
  120145. 2,
  120146. 14,
  120147. 1,
  120148. 15,
  120149. 0,
  120150. 16,
  120151. };
  120152. static long _vq_lengthlist__16c1_s_p6_0[] = {
  120153. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  120154. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120155. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  120156. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  120157. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  120158. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  120159. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  120160. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  120161. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  120162. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120163. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  120164. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  120165. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  120166. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  120167. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  120168. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  120169. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  120170. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  120171. 14,
  120172. };
  120173. static float _vq_quantthresh__16c1_s_p6_0[] = {
  120174. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120175. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120176. };
  120177. static long _vq_quantmap__16c1_s_p6_0[] = {
  120178. 15, 13, 11, 9, 7, 5, 3, 1,
  120179. 0, 2, 4, 6, 8, 10, 12, 14,
  120180. 16,
  120181. };
  120182. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  120183. _vq_quantthresh__16c1_s_p6_0,
  120184. _vq_quantmap__16c1_s_p6_0,
  120185. 17,
  120186. 17
  120187. };
  120188. static static_codebook _16c1_s_p6_0 = {
  120189. 2, 289,
  120190. _vq_lengthlist__16c1_s_p6_0,
  120191. 1, -529530880, 1611661312, 5, 0,
  120192. _vq_quantlist__16c1_s_p6_0,
  120193. NULL,
  120194. &_vq_auxt__16c1_s_p6_0,
  120195. NULL,
  120196. 0
  120197. };
  120198. static long _vq_quantlist__16c1_s_p7_0[] = {
  120199. 1,
  120200. 0,
  120201. 2,
  120202. };
  120203. static long _vq_lengthlist__16c1_s_p7_0[] = {
  120204. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  120205. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120206. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  120207. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  120208. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  120209. 11,
  120210. };
  120211. static float _vq_quantthresh__16c1_s_p7_0[] = {
  120212. -5.5, 5.5,
  120213. };
  120214. static long _vq_quantmap__16c1_s_p7_0[] = {
  120215. 1, 0, 2,
  120216. };
  120217. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  120218. _vq_quantthresh__16c1_s_p7_0,
  120219. _vq_quantmap__16c1_s_p7_0,
  120220. 3,
  120221. 3
  120222. };
  120223. static static_codebook _16c1_s_p7_0 = {
  120224. 4, 81,
  120225. _vq_lengthlist__16c1_s_p7_0,
  120226. 1, -529137664, 1618345984, 2, 0,
  120227. _vq_quantlist__16c1_s_p7_0,
  120228. NULL,
  120229. &_vq_auxt__16c1_s_p7_0,
  120230. NULL,
  120231. 0
  120232. };
  120233. static long _vq_quantlist__16c1_s_p7_1[] = {
  120234. 5,
  120235. 4,
  120236. 6,
  120237. 3,
  120238. 7,
  120239. 2,
  120240. 8,
  120241. 1,
  120242. 9,
  120243. 0,
  120244. 10,
  120245. };
  120246. static long _vq_lengthlist__16c1_s_p7_1[] = {
  120247. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  120248. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  120249. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120250. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  120251. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  120252. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  120253. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  120254. 10,10,10, 8, 8, 8, 8, 9, 9,
  120255. };
  120256. static float _vq_quantthresh__16c1_s_p7_1[] = {
  120257. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120258. 3.5, 4.5,
  120259. };
  120260. static long _vq_quantmap__16c1_s_p7_1[] = {
  120261. 9, 7, 5, 3, 1, 0, 2, 4,
  120262. 6, 8, 10,
  120263. };
  120264. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  120265. _vq_quantthresh__16c1_s_p7_1,
  120266. _vq_quantmap__16c1_s_p7_1,
  120267. 11,
  120268. 11
  120269. };
  120270. static static_codebook _16c1_s_p7_1 = {
  120271. 2, 121,
  120272. _vq_lengthlist__16c1_s_p7_1,
  120273. 1, -531365888, 1611661312, 4, 0,
  120274. _vq_quantlist__16c1_s_p7_1,
  120275. NULL,
  120276. &_vq_auxt__16c1_s_p7_1,
  120277. NULL,
  120278. 0
  120279. };
  120280. static long _vq_quantlist__16c1_s_p8_0[] = {
  120281. 6,
  120282. 5,
  120283. 7,
  120284. 4,
  120285. 8,
  120286. 3,
  120287. 9,
  120288. 2,
  120289. 10,
  120290. 1,
  120291. 11,
  120292. 0,
  120293. 12,
  120294. };
  120295. static long _vq_lengthlist__16c1_s_p8_0[] = {
  120296. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  120297. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  120298. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  120299. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  120300. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  120301. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  120302. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  120303. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  120304. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  120305. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  120306. 0,12,12,12,12,13,13,14,15,
  120307. };
  120308. static float _vq_quantthresh__16c1_s_p8_0[] = {
  120309. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120310. 12.5, 17.5, 22.5, 27.5,
  120311. };
  120312. static long _vq_quantmap__16c1_s_p8_0[] = {
  120313. 11, 9, 7, 5, 3, 1, 0, 2,
  120314. 4, 6, 8, 10, 12,
  120315. };
  120316. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  120317. _vq_quantthresh__16c1_s_p8_0,
  120318. _vq_quantmap__16c1_s_p8_0,
  120319. 13,
  120320. 13
  120321. };
  120322. static static_codebook _16c1_s_p8_0 = {
  120323. 2, 169,
  120324. _vq_lengthlist__16c1_s_p8_0,
  120325. 1, -526516224, 1616117760, 4, 0,
  120326. _vq_quantlist__16c1_s_p8_0,
  120327. NULL,
  120328. &_vq_auxt__16c1_s_p8_0,
  120329. NULL,
  120330. 0
  120331. };
  120332. static long _vq_quantlist__16c1_s_p8_1[] = {
  120333. 2,
  120334. 1,
  120335. 3,
  120336. 0,
  120337. 4,
  120338. };
  120339. static long _vq_lengthlist__16c1_s_p8_1[] = {
  120340. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120341. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120342. };
  120343. static float _vq_quantthresh__16c1_s_p8_1[] = {
  120344. -1.5, -0.5, 0.5, 1.5,
  120345. };
  120346. static long _vq_quantmap__16c1_s_p8_1[] = {
  120347. 3, 1, 0, 2, 4,
  120348. };
  120349. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  120350. _vq_quantthresh__16c1_s_p8_1,
  120351. _vq_quantmap__16c1_s_p8_1,
  120352. 5,
  120353. 5
  120354. };
  120355. static static_codebook _16c1_s_p8_1 = {
  120356. 2, 25,
  120357. _vq_lengthlist__16c1_s_p8_1,
  120358. 1, -533725184, 1611661312, 3, 0,
  120359. _vq_quantlist__16c1_s_p8_1,
  120360. NULL,
  120361. &_vq_auxt__16c1_s_p8_1,
  120362. NULL,
  120363. 0
  120364. };
  120365. static long _vq_quantlist__16c1_s_p9_0[] = {
  120366. 6,
  120367. 5,
  120368. 7,
  120369. 4,
  120370. 8,
  120371. 3,
  120372. 9,
  120373. 2,
  120374. 10,
  120375. 1,
  120376. 11,
  120377. 0,
  120378. 12,
  120379. };
  120380. static long _vq_lengthlist__16c1_s_p9_0[] = {
  120381. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120382. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120383. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120384. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120385. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120386. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120387. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120388. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120389. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120390. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120391. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120392. };
  120393. static float _vq_quantthresh__16c1_s_p9_0[] = {
  120394. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  120395. 787.5, 1102.5, 1417.5, 1732.5,
  120396. };
  120397. static long _vq_quantmap__16c1_s_p9_0[] = {
  120398. 11, 9, 7, 5, 3, 1, 0, 2,
  120399. 4, 6, 8, 10, 12,
  120400. };
  120401. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  120402. _vq_quantthresh__16c1_s_p9_0,
  120403. _vq_quantmap__16c1_s_p9_0,
  120404. 13,
  120405. 13
  120406. };
  120407. static static_codebook _16c1_s_p9_0 = {
  120408. 2, 169,
  120409. _vq_lengthlist__16c1_s_p9_0,
  120410. 1, -513964032, 1628680192, 4, 0,
  120411. _vq_quantlist__16c1_s_p9_0,
  120412. NULL,
  120413. &_vq_auxt__16c1_s_p9_0,
  120414. NULL,
  120415. 0
  120416. };
  120417. static long _vq_quantlist__16c1_s_p9_1[] = {
  120418. 7,
  120419. 6,
  120420. 8,
  120421. 5,
  120422. 9,
  120423. 4,
  120424. 10,
  120425. 3,
  120426. 11,
  120427. 2,
  120428. 12,
  120429. 1,
  120430. 13,
  120431. 0,
  120432. 14,
  120433. };
  120434. static long _vq_lengthlist__16c1_s_p9_1[] = {
  120435. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  120436. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  120437. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  120438. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  120439. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  120440. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  120441. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  120442. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120443. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120444. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120445. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120446. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120447. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  120448. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120449. 13,
  120450. };
  120451. static float _vq_quantthresh__16c1_s_p9_1[] = {
  120452. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120453. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120454. };
  120455. static long _vq_quantmap__16c1_s_p9_1[] = {
  120456. 13, 11, 9, 7, 5, 3, 1, 0,
  120457. 2, 4, 6, 8, 10, 12, 14,
  120458. };
  120459. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  120460. _vq_quantthresh__16c1_s_p9_1,
  120461. _vq_quantmap__16c1_s_p9_1,
  120462. 15,
  120463. 15
  120464. };
  120465. static static_codebook _16c1_s_p9_1 = {
  120466. 2, 225,
  120467. _vq_lengthlist__16c1_s_p9_1,
  120468. 1, -520986624, 1620377600, 4, 0,
  120469. _vq_quantlist__16c1_s_p9_1,
  120470. NULL,
  120471. &_vq_auxt__16c1_s_p9_1,
  120472. NULL,
  120473. 0
  120474. };
  120475. static long _vq_quantlist__16c1_s_p9_2[] = {
  120476. 10,
  120477. 9,
  120478. 11,
  120479. 8,
  120480. 12,
  120481. 7,
  120482. 13,
  120483. 6,
  120484. 14,
  120485. 5,
  120486. 15,
  120487. 4,
  120488. 16,
  120489. 3,
  120490. 17,
  120491. 2,
  120492. 18,
  120493. 1,
  120494. 19,
  120495. 0,
  120496. 20,
  120497. };
  120498. static long _vq_lengthlist__16c1_s_p9_2[] = {
  120499. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  120500. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  120501. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  120502. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  120503. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  120504. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  120505. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  120506. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  120507. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  120508. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  120509. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  120510. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  120511. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  120512. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  120513. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  120514. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  120515. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  120516. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  120517. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  120518. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  120519. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  120520. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  120521. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  120522. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  120523. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  120524. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  120525. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  120526. 11,11,11,11,12,11,11,12,11,
  120527. };
  120528. static float _vq_quantthresh__16c1_s_p9_2[] = {
  120529. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120530. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120531. 6.5, 7.5, 8.5, 9.5,
  120532. };
  120533. static long _vq_quantmap__16c1_s_p9_2[] = {
  120534. 19, 17, 15, 13, 11, 9, 7, 5,
  120535. 3, 1, 0, 2, 4, 6, 8, 10,
  120536. 12, 14, 16, 18, 20,
  120537. };
  120538. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  120539. _vq_quantthresh__16c1_s_p9_2,
  120540. _vq_quantmap__16c1_s_p9_2,
  120541. 21,
  120542. 21
  120543. };
  120544. static static_codebook _16c1_s_p9_2 = {
  120545. 2, 441,
  120546. _vq_lengthlist__16c1_s_p9_2,
  120547. 1, -529268736, 1611661312, 5, 0,
  120548. _vq_quantlist__16c1_s_p9_2,
  120549. NULL,
  120550. &_vq_auxt__16c1_s_p9_2,
  120551. NULL,
  120552. 0
  120553. };
  120554. static long _huff_lengthlist__16c1_s_short[] = {
  120555. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  120556. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  120557. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  120558. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  120559. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  120560. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  120561. 9, 9,10,13,
  120562. };
  120563. static static_codebook _huff_book__16c1_s_short = {
  120564. 2, 100,
  120565. _huff_lengthlist__16c1_s_short,
  120566. 0, 0, 0, 0, 0,
  120567. NULL,
  120568. NULL,
  120569. NULL,
  120570. NULL,
  120571. 0
  120572. };
  120573. static long _huff_lengthlist__16c2_s_long[] = {
  120574. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  120575. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  120576. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  120577. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  120578. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  120579. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  120580. 14,14,16,18,
  120581. };
  120582. static static_codebook _huff_book__16c2_s_long = {
  120583. 2, 100,
  120584. _huff_lengthlist__16c2_s_long,
  120585. 0, 0, 0, 0, 0,
  120586. NULL,
  120587. NULL,
  120588. NULL,
  120589. NULL,
  120590. 0
  120591. };
  120592. static long _vq_quantlist__16c2_s_p1_0[] = {
  120593. 1,
  120594. 0,
  120595. 2,
  120596. };
  120597. static long _vq_lengthlist__16c2_s_p1_0[] = {
  120598. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  120599. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  120604. };
  120605. static float _vq_quantthresh__16c2_s_p1_0[] = {
  120606. -0.5, 0.5,
  120607. };
  120608. static long _vq_quantmap__16c2_s_p1_0[] = {
  120609. 1, 0, 2,
  120610. };
  120611. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  120612. _vq_quantthresh__16c2_s_p1_0,
  120613. _vq_quantmap__16c2_s_p1_0,
  120614. 3,
  120615. 3
  120616. };
  120617. static static_codebook _16c2_s_p1_0 = {
  120618. 4, 81,
  120619. _vq_lengthlist__16c2_s_p1_0,
  120620. 1, -535822336, 1611661312, 2, 0,
  120621. _vq_quantlist__16c2_s_p1_0,
  120622. NULL,
  120623. &_vq_auxt__16c2_s_p1_0,
  120624. NULL,
  120625. 0
  120626. };
  120627. static long _vq_quantlist__16c2_s_p2_0[] = {
  120628. 2,
  120629. 1,
  120630. 3,
  120631. 0,
  120632. 4,
  120633. };
  120634. static long _vq_lengthlist__16c2_s_p2_0[] = {
  120635. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  120636. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  120637. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  120638. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  120639. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  120640. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  120641. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  120642. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  120643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120647. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  120648. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  120649. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  120650. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  120651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120655. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  120656. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  120657. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  120658. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120663. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  120664. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  120665. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  120666. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  120671. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  120672. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  120673. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  120674. 13,
  120675. };
  120676. static float _vq_quantthresh__16c2_s_p2_0[] = {
  120677. -1.5, -0.5, 0.5, 1.5,
  120678. };
  120679. static long _vq_quantmap__16c2_s_p2_0[] = {
  120680. 3, 1, 0, 2, 4,
  120681. };
  120682. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  120683. _vq_quantthresh__16c2_s_p2_0,
  120684. _vq_quantmap__16c2_s_p2_0,
  120685. 5,
  120686. 5
  120687. };
  120688. static static_codebook _16c2_s_p2_0 = {
  120689. 4, 625,
  120690. _vq_lengthlist__16c2_s_p2_0,
  120691. 1, -533725184, 1611661312, 3, 0,
  120692. _vq_quantlist__16c2_s_p2_0,
  120693. NULL,
  120694. &_vq_auxt__16c2_s_p2_0,
  120695. NULL,
  120696. 0
  120697. };
  120698. static long _vq_quantlist__16c2_s_p3_0[] = {
  120699. 4,
  120700. 3,
  120701. 5,
  120702. 2,
  120703. 6,
  120704. 1,
  120705. 7,
  120706. 0,
  120707. 8,
  120708. };
  120709. static long _vq_lengthlist__16c2_s_p3_0[] = {
  120710. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  120711. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  120712. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  120713. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  120714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120715. 0,
  120716. };
  120717. static float _vq_quantthresh__16c2_s_p3_0[] = {
  120718. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120719. };
  120720. static long _vq_quantmap__16c2_s_p3_0[] = {
  120721. 7, 5, 3, 1, 0, 2, 4, 6,
  120722. 8,
  120723. };
  120724. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  120725. _vq_quantthresh__16c2_s_p3_0,
  120726. _vq_quantmap__16c2_s_p3_0,
  120727. 9,
  120728. 9
  120729. };
  120730. static static_codebook _16c2_s_p3_0 = {
  120731. 2, 81,
  120732. _vq_lengthlist__16c2_s_p3_0,
  120733. 1, -531628032, 1611661312, 4, 0,
  120734. _vq_quantlist__16c2_s_p3_0,
  120735. NULL,
  120736. &_vq_auxt__16c2_s_p3_0,
  120737. NULL,
  120738. 0
  120739. };
  120740. static long _vq_quantlist__16c2_s_p4_0[] = {
  120741. 8,
  120742. 7,
  120743. 9,
  120744. 6,
  120745. 10,
  120746. 5,
  120747. 11,
  120748. 4,
  120749. 12,
  120750. 3,
  120751. 13,
  120752. 2,
  120753. 14,
  120754. 1,
  120755. 15,
  120756. 0,
  120757. 16,
  120758. };
  120759. static long _vq_lengthlist__16c2_s_p4_0[] = {
  120760. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  120761. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  120762. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  120763. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  120764. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  120765. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  120766. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  120767. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  120768. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  120769. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  120770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120778. 0,
  120779. };
  120780. static float _vq_quantthresh__16c2_s_p4_0[] = {
  120781. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120782. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120783. };
  120784. static long _vq_quantmap__16c2_s_p4_0[] = {
  120785. 15, 13, 11, 9, 7, 5, 3, 1,
  120786. 0, 2, 4, 6, 8, 10, 12, 14,
  120787. 16,
  120788. };
  120789. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  120790. _vq_quantthresh__16c2_s_p4_0,
  120791. _vq_quantmap__16c2_s_p4_0,
  120792. 17,
  120793. 17
  120794. };
  120795. static static_codebook _16c2_s_p4_0 = {
  120796. 2, 289,
  120797. _vq_lengthlist__16c2_s_p4_0,
  120798. 1, -529530880, 1611661312, 5, 0,
  120799. _vq_quantlist__16c2_s_p4_0,
  120800. NULL,
  120801. &_vq_auxt__16c2_s_p4_0,
  120802. NULL,
  120803. 0
  120804. };
  120805. static long _vq_quantlist__16c2_s_p5_0[] = {
  120806. 1,
  120807. 0,
  120808. 2,
  120809. };
  120810. static long _vq_lengthlist__16c2_s_p5_0[] = {
  120811. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  120812. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  120813. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  120814. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  120815. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  120816. 12,
  120817. };
  120818. static float _vq_quantthresh__16c2_s_p5_0[] = {
  120819. -5.5, 5.5,
  120820. };
  120821. static long _vq_quantmap__16c2_s_p5_0[] = {
  120822. 1, 0, 2,
  120823. };
  120824. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  120825. _vq_quantthresh__16c2_s_p5_0,
  120826. _vq_quantmap__16c2_s_p5_0,
  120827. 3,
  120828. 3
  120829. };
  120830. static static_codebook _16c2_s_p5_0 = {
  120831. 4, 81,
  120832. _vq_lengthlist__16c2_s_p5_0,
  120833. 1, -529137664, 1618345984, 2, 0,
  120834. _vq_quantlist__16c2_s_p5_0,
  120835. NULL,
  120836. &_vq_auxt__16c2_s_p5_0,
  120837. NULL,
  120838. 0
  120839. };
  120840. static long _vq_quantlist__16c2_s_p5_1[] = {
  120841. 5,
  120842. 4,
  120843. 6,
  120844. 3,
  120845. 7,
  120846. 2,
  120847. 8,
  120848. 1,
  120849. 9,
  120850. 0,
  120851. 10,
  120852. };
  120853. static long _vq_lengthlist__16c2_s_p5_1[] = {
  120854. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  120855. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  120856. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  120857. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  120858. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  120859. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  120860. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  120861. 11,11,11, 7, 7, 8, 8, 8, 8,
  120862. };
  120863. static float _vq_quantthresh__16c2_s_p5_1[] = {
  120864. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120865. 3.5, 4.5,
  120866. };
  120867. static long _vq_quantmap__16c2_s_p5_1[] = {
  120868. 9, 7, 5, 3, 1, 0, 2, 4,
  120869. 6, 8, 10,
  120870. };
  120871. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  120872. _vq_quantthresh__16c2_s_p5_1,
  120873. _vq_quantmap__16c2_s_p5_1,
  120874. 11,
  120875. 11
  120876. };
  120877. static static_codebook _16c2_s_p5_1 = {
  120878. 2, 121,
  120879. _vq_lengthlist__16c2_s_p5_1,
  120880. 1, -531365888, 1611661312, 4, 0,
  120881. _vq_quantlist__16c2_s_p5_1,
  120882. NULL,
  120883. &_vq_auxt__16c2_s_p5_1,
  120884. NULL,
  120885. 0
  120886. };
  120887. static long _vq_quantlist__16c2_s_p6_0[] = {
  120888. 6,
  120889. 5,
  120890. 7,
  120891. 4,
  120892. 8,
  120893. 3,
  120894. 9,
  120895. 2,
  120896. 10,
  120897. 1,
  120898. 11,
  120899. 0,
  120900. 12,
  120901. };
  120902. static long _vq_lengthlist__16c2_s_p6_0[] = {
  120903. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120904. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  120905. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  120906. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  120907. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  120908. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. };
  120915. static float _vq_quantthresh__16c2_s_p6_0[] = {
  120916. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120917. 12.5, 17.5, 22.5, 27.5,
  120918. };
  120919. static long _vq_quantmap__16c2_s_p6_0[] = {
  120920. 11, 9, 7, 5, 3, 1, 0, 2,
  120921. 4, 6, 8, 10, 12,
  120922. };
  120923. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  120924. _vq_quantthresh__16c2_s_p6_0,
  120925. _vq_quantmap__16c2_s_p6_0,
  120926. 13,
  120927. 13
  120928. };
  120929. static static_codebook _16c2_s_p6_0 = {
  120930. 2, 169,
  120931. _vq_lengthlist__16c2_s_p6_0,
  120932. 1, -526516224, 1616117760, 4, 0,
  120933. _vq_quantlist__16c2_s_p6_0,
  120934. NULL,
  120935. &_vq_auxt__16c2_s_p6_0,
  120936. NULL,
  120937. 0
  120938. };
  120939. static long _vq_quantlist__16c2_s_p6_1[] = {
  120940. 2,
  120941. 1,
  120942. 3,
  120943. 0,
  120944. 4,
  120945. };
  120946. static long _vq_lengthlist__16c2_s_p6_1[] = {
  120947. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120948. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120949. };
  120950. static float _vq_quantthresh__16c2_s_p6_1[] = {
  120951. -1.5, -0.5, 0.5, 1.5,
  120952. };
  120953. static long _vq_quantmap__16c2_s_p6_1[] = {
  120954. 3, 1, 0, 2, 4,
  120955. };
  120956. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  120957. _vq_quantthresh__16c2_s_p6_1,
  120958. _vq_quantmap__16c2_s_p6_1,
  120959. 5,
  120960. 5
  120961. };
  120962. static static_codebook _16c2_s_p6_1 = {
  120963. 2, 25,
  120964. _vq_lengthlist__16c2_s_p6_1,
  120965. 1, -533725184, 1611661312, 3, 0,
  120966. _vq_quantlist__16c2_s_p6_1,
  120967. NULL,
  120968. &_vq_auxt__16c2_s_p6_1,
  120969. NULL,
  120970. 0
  120971. };
  120972. static long _vq_quantlist__16c2_s_p7_0[] = {
  120973. 6,
  120974. 5,
  120975. 7,
  120976. 4,
  120977. 8,
  120978. 3,
  120979. 9,
  120980. 2,
  120981. 10,
  120982. 1,
  120983. 11,
  120984. 0,
  120985. 12,
  120986. };
  120987. static long _vq_lengthlist__16c2_s_p7_0[] = {
  120988. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120989. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  120990. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  120991. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  120992. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  120993. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  120994. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  120995. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  120996. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  120997. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  120998. 18,13,14,13,13,14,13,15,14,
  120999. };
  121000. static float _vq_quantthresh__16c2_s_p7_0[] = {
  121001. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  121002. 27.5, 38.5, 49.5, 60.5,
  121003. };
  121004. static long _vq_quantmap__16c2_s_p7_0[] = {
  121005. 11, 9, 7, 5, 3, 1, 0, 2,
  121006. 4, 6, 8, 10, 12,
  121007. };
  121008. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  121009. _vq_quantthresh__16c2_s_p7_0,
  121010. _vq_quantmap__16c2_s_p7_0,
  121011. 13,
  121012. 13
  121013. };
  121014. static static_codebook _16c2_s_p7_0 = {
  121015. 2, 169,
  121016. _vq_lengthlist__16c2_s_p7_0,
  121017. 1, -523206656, 1618345984, 4, 0,
  121018. _vq_quantlist__16c2_s_p7_0,
  121019. NULL,
  121020. &_vq_auxt__16c2_s_p7_0,
  121021. NULL,
  121022. 0
  121023. };
  121024. static long _vq_quantlist__16c2_s_p7_1[] = {
  121025. 5,
  121026. 4,
  121027. 6,
  121028. 3,
  121029. 7,
  121030. 2,
  121031. 8,
  121032. 1,
  121033. 9,
  121034. 0,
  121035. 10,
  121036. };
  121037. static long _vq_lengthlist__16c2_s_p7_1[] = {
  121038. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  121039. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  121040. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  121041. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121042. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  121043. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  121044. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  121045. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  121046. };
  121047. static float _vq_quantthresh__16c2_s_p7_1[] = {
  121048. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121049. 3.5, 4.5,
  121050. };
  121051. static long _vq_quantmap__16c2_s_p7_1[] = {
  121052. 9, 7, 5, 3, 1, 0, 2, 4,
  121053. 6, 8, 10,
  121054. };
  121055. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  121056. _vq_quantthresh__16c2_s_p7_1,
  121057. _vq_quantmap__16c2_s_p7_1,
  121058. 11,
  121059. 11
  121060. };
  121061. static static_codebook _16c2_s_p7_1 = {
  121062. 2, 121,
  121063. _vq_lengthlist__16c2_s_p7_1,
  121064. 1, -531365888, 1611661312, 4, 0,
  121065. _vq_quantlist__16c2_s_p7_1,
  121066. NULL,
  121067. &_vq_auxt__16c2_s_p7_1,
  121068. NULL,
  121069. 0
  121070. };
  121071. static long _vq_quantlist__16c2_s_p8_0[] = {
  121072. 7,
  121073. 6,
  121074. 8,
  121075. 5,
  121076. 9,
  121077. 4,
  121078. 10,
  121079. 3,
  121080. 11,
  121081. 2,
  121082. 12,
  121083. 1,
  121084. 13,
  121085. 0,
  121086. 14,
  121087. };
  121088. static long _vq_lengthlist__16c2_s_p8_0[] = {
  121089. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  121090. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  121091. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  121092. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  121093. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  121094. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  121095. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  121096. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  121097. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  121098. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  121099. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  121100. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  121101. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  121102. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  121103. 13,
  121104. };
  121105. static float _vq_quantthresh__16c2_s_p8_0[] = {
  121106. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121107. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121108. };
  121109. static long _vq_quantmap__16c2_s_p8_0[] = {
  121110. 13, 11, 9, 7, 5, 3, 1, 0,
  121111. 2, 4, 6, 8, 10, 12, 14,
  121112. };
  121113. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  121114. _vq_quantthresh__16c2_s_p8_0,
  121115. _vq_quantmap__16c2_s_p8_0,
  121116. 15,
  121117. 15
  121118. };
  121119. static static_codebook _16c2_s_p8_0 = {
  121120. 2, 225,
  121121. _vq_lengthlist__16c2_s_p8_0,
  121122. 1, -520986624, 1620377600, 4, 0,
  121123. _vq_quantlist__16c2_s_p8_0,
  121124. NULL,
  121125. &_vq_auxt__16c2_s_p8_0,
  121126. NULL,
  121127. 0
  121128. };
  121129. static long _vq_quantlist__16c2_s_p8_1[] = {
  121130. 10,
  121131. 9,
  121132. 11,
  121133. 8,
  121134. 12,
  121135. 7,
  121136. 13,
  121137. 6,
  121138. 14,
  121139. 5,
  121140. 15,
  121141. 4,
  121142. 16,
  121143. 3,
  121144. 17,
  121145. 2,
  121146. 18,
  121147. 1,
  121148. 19,
  121149. 0,
  121150. 20,
  121151. };
  121152. static long _vq_lengthlist__16c2_s_p8_1[] = {
  121153. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  121154. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  121155. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  121156. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  121157. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  121158. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  121159. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  121160. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  121161. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  121162. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  121163. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  121164. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  121165. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  121166. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  121167. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  121168. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  121169. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  121170. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  121171. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  121172. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  121173. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  121174. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  121175. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  121176. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  121177. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  121178. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  121179. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  121180. 10,11,10,10,10,10,10,10,10,
  121181. };
  121182. static float _vq_quantthresh__16c2_s_p8_1[] = {
  121183. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121184. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121185. 6.5, 7.5, 8.5, 9.5,
  121186. };
  121187. static long _vq_quantmap__16c2_s_p8_1[] = {
  121188. 19, 17, 15, 13, 11, 9, 7, 5,
  121189. 3, 1, 0, 2, 4, 6, 8, 10,
  121190. 12, 14, 16, 18, 20,
  121191. };
  121192. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  121193. _vq_quantthresh__16c2_s_p8_1,
  121194. _vq_quantmap__16c2_s_p8_1,
  121195. 21,
  121196. 21
  121197. };
  121198. static static_codebook _16c2_s_p8_1 = {
  121199. 2, 441,
  121200. _vq_lengthlist__16c2_s_p8_1,
  121201. 1, -529268736, 1611661312, 5, 0,
  121202. _vq_quantlist__16c2_s_p8_1,
  121203. NULL,
  121204. &_vq_auxt__16c2_s_p8_1,
  121205. NULL,
  121206. 0
  121207. };
  121208. static long _vq_quantlist__16c2_s_p9_0[] = {
  121209. 6,
  121210. 5,
  121211. 7,
  121212. 4,
  121213. 8,
  121214. 3,
  121215. 9,
  121216. 2,
  121217. 10,
  121218. 1,
  121219. 11,
  121220. 0,
  121221. 12,
  121222. };
  121223. static long _vq_lengthlist__16c2_s_p9_0[] = {
  121224. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121225. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121226. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121227. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121228. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121229. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121230. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121231. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121232. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121233. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121234. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121235. };
  121236. static float _vq_quantthresh__16c2_s_p9_0[] = {
  121237. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  121238. 2327.5, 3258.5, 4189.5, 5120.5,
  121239. };
  121240. static long _vq_quantmap__16c2_s_p9_0[] = {
  121241. 11, 9, 7, 5, 3, 1, 0, 2,
  121242. 4, 6, 8, 10, 12,
  121243. };
  121244. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  121245. _vq_quantthresh__16c2_s_p9_0,
  121246. _vq_quantmap__16c2_s_p9_0,
  121247. 13,
  121248. 13
  121249. };
  121250. static static_codebook _16c2_s_p9_0 = {
  121251. 2, 169,
  121252. _vq_lengthlist__16c2_s_p9_0,
  121253. 1, -510275072, 1631393792, 4, 0,
  121254. _vq_quantlist__16c2_s_p9_0,
  121255. NULL,
  121256. &_vq_auxt__16c2_s_p9_0,
  121257. NULL,
  121258. 0
  121259. };
  121260. static long _vq_quantlist__16c2_s_p9_1[] = {
  121261. 8,
  121262. 7,
  121263. 9,
  121264. 6,
  121265. 10,
  121266. 5,
  121267. 11,
  121268. 4,
  121269. 12,
  121270. 3,
  121271. 13,
  121272. 2,
  121273. 14,
  121274. 1,
  121275. 15,
  121276. 0,
  121277. 16,
  121278. };
  121279. static long _vq_lengthlist__16c2_s_p9_1[] = {
  121280. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  121281. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  121282. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  121283. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  121284. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  121285. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  121286. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  121287. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  121288. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  121289. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  121290. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121291. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121292. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121293. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121294. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121295. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  121296. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  121297. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121298. 10,
  121299. };
  121300. static float _vq_quantthresh__16c2_s_p9_1[] = {
  121301. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  121302. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  121303. };
  121304. static long _vq_quantmap__16c2_s_p9_1[] = {
  121305. 15, 13, 11, 9, 7, 5, 3, 1,
  121306. 0, 2, 4, 6, 8, 10, 12, 14,
  121307. 16,
  121308. };
  121309. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  121310. _vq_quantthresh__16c2_s_p9_1,
  121311. _vq_quantmap__16c2_s_p9_1,
  121312. 17,
  121313. 17
  121314. };
  121315. static static_codebook _16c2_s_p9_1 = {
  121316. 2, 289,
  121317. _vq_lengthlist__16c2_s_p9_1,
  121318. 1, -518488064, 1622704128, 5, 0,
  121319. _vq_quantlist__16c2_s_p9_1,
  121320. NULL,
  121321. &_vq_auxt__16c2_s_p9_1,
  121322. NULL,
  121323. 0
  121324. };
  121325. static long _vq_quantlist__16c2_s_p9_2[] = {
  121326. 13,
  121327. 12,
  121328. 14,
  121329. 11,
  121330. 15,
  121331. 10,
  121332. 16,
  121333. 9,
  121334. 17,
  121335. 8,
  121336. 18,
  121337. 7,
  121338. 19,
  121339. 6,
  121340. 20,
  121341. 5,
  121342. 21,
  121343. 4,
  121344. 22,
  121345. 3,
  121346. 23,
  121347. 2,
  121348. 24,
  121349. 1,
  121350. 25,
  121351. 0,
  121352. 26,
  121353. };
  121354. static long _vq_lengthlist__16c2_s_p9_2[] = {
  121355. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  121356. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  121357. };
  121358. static float _vq_quantthresh__16c2_s_p9_2[] = {
  121359. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  121360. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121361. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  121362. 11.5, 12.5,
  121363. };
  121364. static long _vq_quantmap__16c2_s_p9_2[] = {
  121365. 25, 23, 21, 19, 17, 15, 13, 11,
  121366. 9, 7, 5, 3, 1, 0, 2, 4,
  121367. 6, 8, 10, 12, 14, 16, 18, 20,
  121368. 22, 24, 26,
  121369. };
  121370. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  121371. _vq_quantthresh__16c2_s_p9_2,
  121372. _vq_quantmap__16c2_s_p9_2,
  121373. 27,
  121374. 27
  121375. };
  121376. static static_codebook _16c2_s_p9_2 = {
  121377. 1, 27,
  121378. _vq_lengthlist__16c2_s_p9_2,
  121379. 1, -528875520, 1611661312, 5, 0,
  121380. _vq_quantlist__16c2_s_p9_2,
  121381. NULL,
  121382. &_vq_auxt__16c2_s_p9_2,
  121383. NULL,
  121384. 0
  121385. };
  121386. static long _huff_lengthlist__16c2_s_short[] = {
  121387. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  121388. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  121389. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  121390. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  121391. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  121392. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  121393. 15,12,14,14,
  121394. };
  121395. static static_codebook _huff_book__16c2_s_short = {
  121396. 2, 100,
  121397. _huff_lengthlist__16c2_s_short,
  121398. 0, 0, 0, 0, 0,
  121399. NULL,
  121400. NULL,
  121401. NULL,
  121402. NULL,
  121403. 0
  121404. };
  121405. static long _vq_quantlist__8c0_s_p1_0[] = {
  121406. 1,
  121407. 0,
  121408. 2,
  121409. };
  121410. static long _vq_lengthlist__8c0_s_p1_0[] = {
  121411. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121412. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  121415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121416. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  121417. 0, 0, 0, 7, 8, 9, 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, 0, 0, 0, 0, 0, 0,
  121420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121421. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121422. 0, 0, 0, 0, 7, 9, 8, 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, 0, 0, 0, 0, 0,
  121425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  121457. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  121462. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  121467. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121503. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  121508. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  121513. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  121822. };
  121823. static float _vq_quantthresh__8c0_s_p1_0[] = {
  121824. -0.5, 0.5,
  121825. };
  121826. static long _vq_quantmap__8c0_s_p1_0[] = {
  121827. 1, 0, 2,
  121828. };
  121829. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  121830. _vq_quantthresh__8c0_s_p1_0,
  121831. _vq_quantmap__8c0_s_p1_0,
  121832. 3,
  121833. 3
  121834. };
  121835. static static_codebook _8c0_s_p1_0 = {
  121836. 8, 6561,
  121837. _vq_lengthlist__8c0_s_p1_0,
  121838. 1, -535822336, 1611661312, 2, 0,
  121839. _vq_quantlist__8c0_s_p1_0,
  121840. NULL,
  121841. &_vq_auxt__8c0_s_p1_0,
  121842. NULL,
  121843. 0
  121844. };
  121845. static long _vq_quantlist__8c0_s_p2_0[] = {
  121846. 2,
  121847. 1,
  121848. 3,
  121849. 0,
  121850. 4,
  121851. };
  121852. static long _vq_lengthlist__8c0_s_p2_0[] = {
  121853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  121893. };
  121894. static float _vq_quantthresh__8c0_s_p2_0[] = {
  121895. -1.5, -0.5, 0.5, 1.5,
  121896. };
  121897. static long _vq_quantmap__8c0_s_p2_0[] = {
  121898. 3, 1, 0, 2, 4,
  121899. };
  121900. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  121901. _vq_quantthresh__8c0_s_p2_0,
  121902. _vq_quantmap__8c0_s_p2_0,
  121903. 5,
  121904. 5
  121905. };
  121906. static static_codebook _8c0_s_p2_0 = {
  121907. 4, 625,
  121908. _vq_lengthlist__8c0_s_p2_0,
  121909. 1, -533725184, 1611661312, 3, 0,
  121910. _vq_quantlist__8c0_s_p2_0,
  121911. NULL,
  121912. &_vq_auxt__8c0_s_p2_0,
  121913. NULL,
  121914. 0
  121915. };
  121916. static long _vq_quantlist__8c0_s_p3_0[] = {
  121917. 2,
  121918. 1,
  121919. 3,
  121920. 0,
  121921. 4,
  121922. };
  121923. static long _vq_lengthlist__8c0_s_p3_0[] = {
  121924. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  121929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121930. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  121931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0,
  121964. };
  121965. static float _vq_quantthresh__8c0_s_p3_0[] = {
  121966. -1.5, -0.5, 0.5, 1.5,
  121967. };
  121968. static long _vq_quantmap__8c0_s_p3_0[] = {
  121969. 3, 1, 0, 2, 4,
  121970. };
  121971. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  121972. _vq_quantthresh__8c0_s_p3_0,
  121973. _vq_quantmap__8c0_s_p3_0,
  121974. 5,
  121975. 5
  121976. };
  121977. static static_codebook _8c0_s_p3_0 = {
  121978. 4, 625,
  121979. _vq_lengthlist__8c0_s_p3_0,
  121980. 1, -533725184, 1611661312, 3, 0,
  121981. _vq_quantlist__8c0_s_p3_0,
  121982. NULL,
  121983. &_vq_auxt__8c0_s_p3_0,
  121984. NULL,
  121985. 0
  121986. };
  121987. static long _vq_quantlist__8c0_s_p4_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_p4_0[] = {
  121999. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122000. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122001. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122002. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  122003. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122004. 0,
  122005. };
  122006. static float _vq_quantthresh__8c0_s_p4_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_p4_0[] = {
  122010. 7, 5, 3, 1, 0, 2, 4, 6,
  122011. 8,
  122012. };
  122013. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  122014. _vq_quantthresh__8c0_s_p4_0,
  122015. _vq_quantmap__8c0_s_p4_0,
  122016. 9,
  122017. 9
  122018. };
  122019. static static_codebook _8c0_s_p4_0 = {
  122020. 2, 81,
  122021. _vq_lengthlist__8c0_s_p4_0,
  122022. 1, -531628032, 1611661312, 4, 0,
  122023. _vq_quantlist__8c0_s_p4_0,
  122024. NULL,
  122025. &_vq_auxt__8c0_s_p4_0,
  122026. NULL,
  122027. 0
  122028. };
  122029. static long _vq_quantlist__8c0_s_p5_0[] = {
  122030. 4,
  122031. 3,
  122032. 5,
  122033. 2,
  122034. 6,
  122035. 1,
  122036. 7,
  122037. 0,
  122038. 8,
  122039. };
  122040. static long _vq_lengthlist__8c0_s_p5_0[] = {
  122041. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122042. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  122043. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  122044. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  122045. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122046. 10,
  122047. };
  122048. static float _vq_quantthresh__8c0_s_p5_0[] = {
  122049. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122050. };
  122051. static long _vq_quantmap__8c0_s_p5_0[] = {
  122052. 7, 5, 3, 1, 0, 2, 4, 6,
  122053. 8,
  122054. };
  122055. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  122056. _vq_quantthresh__8c0_s_p5_0,
  122057. _vq_quantmap__8c0_s_p5_0,
  122058. 9,
  122059. 9
  122060. };
  122061. static static_codebook _8c0_s_p5_0 = {
  122062. 2, 81,
  122063. _vq_lengthlist__8c0_s_p5_0,
  122064. 1, -531628032, 1611661312, 4, 0,
  122065. _vq_quantlist__8c0_s_p5_0,
  122066. NULL,
  122067. &_vq_auxt__8c0_s_p5_0,
  122068. NULL,
  122069. 0
  122070. };
  122071. static long _vq_quantlist__8c0_s_p6_0[] = {
  122072. 8,
  122073. 7,
  122074. 9,
  122075. 6,
  122076. 10,
  122077. 5,
  122078. 11,
  122079. 4,
  122080. 12,
  122081. 3,
  122082. 13,
  122083. 2,
  122084. 14,
  122085. 1,
  122086. 15,
  122087. 0,
  122088. 16,
  122089. };
  122090. static long _vq_lengthlist__8c0_s_p6_0[] = {
  122091. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  122092. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122093. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  122094. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  122095. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  122096. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  122097. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  122098. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  122099. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  122100. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122101. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  122102. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  122103. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  122104. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  122105. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  122106. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  122107. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  122109. 14,
  122110. };
  122111. static float _vq_quantthresh__8c0_s_p6_0[] = {
  122112. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122113. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122114. };
  122115. static long _vq_quantmap__8c0_s_p6_0[] = {
  122116. 15, 13, 11, 9, 7, 5, 3, 1,
  122117. 0, 2, 4, 6, 8, 10, 12, 14,
  122118. 16,
  122119. };
  122120. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  122121. _vq_quantthresh__8c0_s_p6_0,
  122122. _vq_quantmap__8c0_s_p6_0,
  122123. 17,
  122124. 17
  122125. };
  122126. static static_codebook _8c0_s_p6_0 = {
  122127. 2, 289,
  122128. _vq_lengthlist__8c0_s_p6_0,
  122129. 1, -529530880, 1611661312, 5, 0,
  122130. _vq_quantlist__8c0_s_p6_0,
  122131. NULL,
  122132. &_vq_auxt__8c0_s_p6_0,
  122133. NULL,
  122134. 0
  122135. };
  122136. static long _vq_quantlist__8c0_s_p7_0[] = {
  122137. 1,
  122138. 0,
  122139. 2,
  122140. };
  122141. static long _vq_lengthlist__8c0_s_p7_0[] = {
  122142. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  122143. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  122144. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  122145. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  122146. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  122147. 10,
  122148. };
  122149. static float _vq_quantthresh__8c0_s_p7_0[] = {
  122150. -5.5, 5.5,
  122151. };
  122152. static long _vq_quantmap__8c0_s_p7_0[] = {
  122153. 1, 0, 2,
  122154. };
  122155. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  122156. _vq_quantthresh__8c0_s_p7_0,
  122157. _vq_quantmap__8c0_s_p7_0,
  122158. 3,
  122159. 3
  122160. };
  122161. static static_codebook _8c0_s_p7_0 = {
  122162. 4, 81,
  122163. _vq_lengthlist__8c0_s_p7_0,
  122164. 1, -529137664, 1618345984, 2, 0,
  122165. _vq_quantlist__8c0_s_p7_0,
  122166. NULL,
  122167. &_vq_auxt__8c0_s_p7_0,
  122168. NULL,
  122169. 0
  122170. };
  122171. static long _vq_quantlist__8c0_s_p7_1[] = {
  122172. 5,
  122173. 4,
  122174. 6,
  122175. 3,
  122176. 7,
  122177. 2,
  122178. 8,
  122179. 1,
  122180. 9,
  122181. 0,
  122182. 10,
  122183. };
  122184. static long _vq_lengthlist__8c0_s_p7_1[] = {
  122185. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  122186. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  122187. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  122188. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  122189. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  122190. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  122191. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  122192. 10,10,10, 9, 9, 9,10,10,10,
  122193. };
  122194. static float _vq_quantthresh__8c0_s_p7_1[] = {
  122195. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122196. 3.5, 4.5,
  122197. };
  122198. static long _vq_quantmap__8c0_s_p7_1[] = {
  122199. 9, 7, 5, 3, 1, 0, 2, 4,
  122200. 6, 8, 10,
  122201. };
  122202. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  122203. _vq_quantthresh__8c0_s_p7_1,
  122204. _vq_quantmap__8c0_s_p7_1,
  122205. 11,
  122206. 11
  122207. };
  122208. static static_codebook _8c0_s_p7_1 = {
  122209. 2, 121,
  122210. _vq_lengthlist__8c0_s_p7_1,
  122211. 1, -531365888, 1611661312, 4, 0,
  122212. _vq_quantlist__8c0_s_p7_1,
  122213. NULL,
  122214. &_vq_auxt__8c0_s_p7_1,
  122215. NULL,
  122216. 0
  122217. };
  122218. static long _vq_quantlist__8c0_s_p8_0[] = {
  122219. 6,
  122220. 5,
  122221. 7,
  122222. 4,
  122223. 8,
  122224. 3,
  122225. 9,
  122226. 2,
  122227. 10,
  122228. 1,
  122229. 11,
  122230. 0,
  122231. 12,
  122232. };
  122233. static long _vq_lengthlist__8c0_s_p8_0[] = {
  122234. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  122235. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  122236. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  122237. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  122238. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  122239. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  122240. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  122241. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  122242. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  122243. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  122244. 0, 0,13,13,11,13,13,11,12,
  122245. };
  122246. static float _vq_quantthresh__8c0_s_p8_0[] = {
  122247. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122248. 12.5, 17.5, 22.5, 27.5,
  122249. };
  122250. static long _vq_quantmap__8c0_s_p8_0[] = {
  122251. 11, 9, 7, 5, 3, 1, 0, 2,
  122252. 4, 6, 8, 10, 12,
  122253. };
  122254. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  122255. _vq_quantthresh__8c0_s_p8_0,
  122256. _vq_quantmap__8c0_s_p8_0,
  122257. 13,
  122258. 13
  122259. };
  122260. static static_codebook _8c0_s_p8_0 = {
  122261. 2, 169,
  122262. _vq_lengthlist__8c0_s_p8_0,
  122263. 1, -526516224, 1616117760, 4, 0,
  122264. _vq_quantlist__8c0_s_p8_0,
  122265. NULL,
  122266. &_vq_auxt__8c0_s_p8_0,
  122267. NULL,
  122268. 0
  122269. };
  122270. static long _vq_quantlist__8c0_s_p8_1[] = {
  122271. 2,
  122272. 1,
  122273. 3,
  122274. 0,
  122275. 4,
  122276. };
  122277. static long _vq_lengthlist__8c0_s_p8_1[] = {
  122278. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  122279. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122280. };
  122281. static float _vq_quantthresh__8c0_s_p8_1[] = {
  122282. -1.5, -0.5, 0.5, 1.5,
  122283. };
  122284. static long _vq_quantmap__8c0_s_p8_1[] = {
  122285. 3, 1, 0, 2, 4,
  122286. };
  122287. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  122288. _vq_quantthresh__8c0_s_p8_1,
  122289. _vq_quantmap__8c0_s_p8_1,
  122290. 5,
  122291. 5
  122292. };
  122293. static static_codebook _8c0_s_p8_1 = {
  122294. 2, 25,
  122295. _vq_lengthlist__8c0_s_p8_1,
  122296. 1, -533725184, 1611661312, 3, 0,
  122297. _vq_quantlist__8c0_s_p8_1,
  122298. NULL,
  122299. &_vq_auxt__8c0_s_p8_1,
  122300. NULL,
  122301. 0
  122302. };
  122303. static long _vq_quantlist__8c0_s_p9_0[] = {
  122304. 1,
  122305. 0,
  122306. 2,
  122307. };
  122308. static long _vq_lengthlist__8c0_s_p9_0[] = {
  122309. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122310. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122311. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122312. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122313. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122314. 7,
  122315. };
  122316. static float _vq_quantthresh__8c0_s_p9_0[] = {
  122317. -157.5, 157.5,
  122318. };
  122319. static long _vq_quantmap__8c0_s_p9_0[] = {
  122320. 1, 0, 2,
  122321. };
  122322. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  122323. _vq_quantthresh__8c0_s_p9_0,
  122324. _vq_quantmap__8c0_s_p9_0,
  122325. 3,
  122326. 3
  122327. };
  122328. static static_codebook _8c0_s_p9_0 = {
  122329. 4, 81,
  122330. _vq_lengthlist__8c0_s_p9_0,
  122331. 1, -518803456, 1628680192, 2, 0,
  122332. _vq_quantlist__8c0_s_p9_0,
  122333. NULL,
  122334. &_vq_auxt__8c0_s_p9_0,
  122335. NULL,
  122336. 0
  122337. };
  122338. static long _vq_quantlist__8c0_s_p9_1[] = {
  122339. 7,
  122340. 6,
  122341. 8,
  122342. 5,
  122343. 9,
  122344. 4,
  122345. 10,
  122346. 3,
  122347. 11,
  122348. 2,
  122349. 12,
  122350. 1,
  122351. 13,
  122352. 0,
  122353. 14,
  122354. };
  122355. static long _vq_lengthlist__8c0_s_p9_1[] = {
  122356. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  122357. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  122358. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  122359. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  122360. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122361. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122363. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122370. 11,
  122371. };
  122372. static float _vq_quantthresh__8c0_s_p9_1[] = {
  122373. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122374. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122375. };
  122376. static long _vq_quantmap__8c0_s_p9_1[] = {
  122377. 13, 11, 9, 7, 5, 3, 1, 0,
  122378. 2, 4, 6, 8, 10, 12, 14,
  122379. };
  122380. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  122381. _vq_quantthresh__8c0_s_p9_1,
  122382. _vq_quantmap__8c0_s_p9_1,
  122383. 15,
  122384. 15
  122385. };
  122386. static static_codebook _8c0_s_p9_1 = {
  122387. 2, 225,
  122388. _vq_lengthlist__8c0_s_p9_1,
  122389. 1, -520986624, 1620377600, 4, 0,
  122390. _vq_quantlist__8c0_s_p9_1,
  122391. NULL,
  122392. &_vq_auxt__8c0_s_p9_1,
  122393. NULL,
  122394. 0
  122395. };
  122396. static long _vq_quantlist__8c0_s_p9_2[] = {
  122397. 10,
  122398. 9,
  122399. 11,
  122400. 8,
  122401. 12,
  122402. 7,
  122403. 13,
  122404. 6,
  122405. 14,
  122406. 5,
  122407. 15,
  122408. 4,
  122409. 16,
  122410. 3,
  122411. 17,
  122412. 2,
  122413. 18,
  122414. 1,
  122415. 19,
  122416. 0,
  122417. 20,
  122418. };
  122419. static long _vq_lengthlist__8c0_s_p9_2[] = {
  122420. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  122421. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  122422. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  122423. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  122424. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  122425. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  122426. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  122427. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  122428. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  122429. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  122430. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  122431. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  122432. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  122433. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  122434. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  122435. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  122436. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  122437. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  122438. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  122439. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  122440. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  122441. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  122442. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  122443. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  122444. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  122445. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  122446. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  122447. 10,11, 9,11,10, 9,10, 9,10,
  122448. };
  122449. static float _vq_quantthresh__8c0_s_p9_2[] = {
  122450. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122451. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122452. 6.5, 7.5, 8.5, 9.5,
  122453. };
  122454. static long _vq_quantmap__8c0_s_p9_2[] = {
  122455. 19, 17, 15, 13, 11, 9, 7, 5,
  122456. 3, 1, 0, 2, 4, 6, 8, 10,
  122457. 12, 14, 16, 18, 20,
  122458. };
  122459. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  122460. _vq_quantthresh__8c0_s_p9_2,
  122461. _vq_quantmap__8c0_s_p9_2,
  122462. 21,
  122463. 21
  122464. };
  122465. static static_codebook _8c0_s_p9_2 = {
  122466. 2, 441,
  122467. _vq_lengthlist__8c0_s_p9_2,
  122468. 1, -529268736, 1611661312, 5, 0,
  122469. _vq_quantlist__8c0_s_p9_2,
  122470. NULL,
  122471. &_vq_auxt__8c0_s_p9_2,
  122472. NULL,
  122473. 0
  122474. };
  122475. static long _huff_lengthlist__8c0_s_single[] = {
  122476. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  122477. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  122478. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  122479. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  122480. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  122481. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  122482. 17,16,17,17,
  122483. };
  122484. static static_codebook _huff_book__8c0_s_single = {
  122485. 2, 100,
  122486. _huff_lengthlist__8c0_s_single,
  122487. 0, 0, 0, 0, 0,
  122488. NULL,
  122489. NULL,
  122490. NULL,
  122491. NULL,
  122492. 0
  122493. };
  122494. static long _vq_quantlist__8c1_s_p1_0[] = {
  122495. 1,
  122496. 0,
  122497. 2,
  122498. };
  122499. static long _vq_lengthlist__8c1_s_p1_0[] = {
  122500. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122501. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122506. 0, 0, 0, 7, 8, 9, 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, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122511. 0, 0, 0, 0, 7, 9, 8, 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, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  122546. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122551. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122556. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122592. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  122597. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  122602. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122911. };
  122912. static float _vq_quantthresh__8c1_s_p1_0[] = {
  122913. -0.5, 0.5,
  122914. };
  122915. static long _vq_quantmap__8c1_s_p1_0[] = {
  122916. 1, 0, 2,
  122917. };
  122918. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  122919. _vq_quantthresh__8c1_s_p1_0,
  122920. _vq_quantmap__8c1_s_p1_0,
  122921. 3,
  122922. 3
  122923. };
  122924. static static_codebook _8c1_s_p1_0 = {
  122925. 8, 6561,
  122926. _vq_lengthlist__8c1_s_p1_0,
  122927. 1, -535822336, 1611661312, 2, 0,
  122928. _vq_quantlist__8c1_s_p1_0,
  122929. NULL,
  122930. &_vq_auxt__8c1_s_p1_0,
  122931. NULL,
  122932. 0
  122933. };
  122934. static long _vq_quantlist__8c1_s_p2_0[] = {
  122935. 2,
  122936. 1,
  122937. 3,
  122938. 0,
  122939. 4,
  122940. };
  122941. static long _vq_lengthlist__8c1_s_p2_0[] = {
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122982. };
  122983. static float _vq_quantthresh__8c1_s_p2_0[] = {
  122984. -1.5, -0.5, 0.5, 1.5,
  122985. };
  122986. static long _vq_quantmap__8c1_s_p2_0[] = {
  122987. 3, 1, 0, 2, 4,
  122988. };
  122989. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  122990. _vq_quantthresh__8c1_s_p2_0,
  122991. _vq_quantmap__8c1_s_p2_0,
  122992. 5,
  122993. 5
  122994. };
  122995. static static_codebook _8c1_s_p2_0 = {
  122996. 4, 625,
  122997. _vq_lengthlist__8c1_s_p2_0,
  122998. 1, -533725184, 1611661312, 3, 0,
  122999. _vq_quantlist__8c1_s_p2_0,
  123000. NULL,
  123001. &_vq_auxt__8c1_s_p2_0,
  123002. NULL,
  123003. 0
  123004. };
  123005. static long _vq_quantlist__8c1_s_p3_0[] = {
  123006. 2,
  123007. 1,
  123008. 3,
  123009. 0,
  123010. 4,
  123011. };
  123012. static long _vq_lengthlist__8c1_s_p3_0[] = {
  123013. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0,
  123053. };
  123054. static float _vq_quantthresh__8c1_s_p3_0[] = {
  123055. -1.5, -0.5, 0.5, 1.5,
  123056. };
  123057. static long _vq_quantmap__8c1_s_p3_0[] = {
  123058. 3, 1, 0, 2, 4,
  123059. };
  123060. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  123061. _vq_quantthresh__8c1_s_p3_0,
  123062. _vq_quantmap__8c1_s_p3_0,
  123063. 5,
  123064. 5
  123065. };
  123066. static static_codebook _8c1_s_p3_0 = {
  123067. 4, 625,
  123068. _vq_lengthlist__8c1_s_p3_0,
  123069. 1, -533725184, 1611661312, 3, 0,
  123070. _vq_quantlist__8c1_s_p3_0,
  123071. NULL,
  123072. &_vq_auxt__8c1_s_p3_0,
  123073. NULL,
  123074. 0
  123075. };
  123076. static long _vq_quantlist__8c1_s_p4_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_p4_0[] = {
  123088. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123089. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123090. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123091. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  123092. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0,
  123094. };
  123095. static float _vq_quantthresh__8c1_s_p4_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_p4_0[] = {
  123099. 7, 5, 3, 1, 0, 2, 4, 6,
  123100. 8,
  123101. };
  123102. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  123103. _vq_quantthresh__8c1_s_p4_0,
  123104. _vq_quantmap__8c1_s_p4_0,
  123105. 9,
  123106. 9
  123107. };
  123108. static static_codebook _8c1_s_p4_0 = {
  123109. 2, 81,
  123110. _vq_lengthlist__8c1_s_p4_0,
  123111. 1, -531628032, 1611661312, 4, 0,
  123112. _vq_quantlist__8c1_s_p4_0,
  123113. NULL,
  123114. &_vq_auxt__8c1_s_p4_0,
  123115. NULL,
  123116. 0
  123117. };
  123118. static long _vq_quantlist__8c1_s_p5_0[] = {
  123119. 4,
  123120. 3,
  123121. 5,
  123122. 2,
  123123. 6,
  123124. 1,
  123125. 7,
  123126. 0,
  123127. 8,
  123128. };
  123129. static long _vq_lengthlist__8c1_s_p5_0[] = {
  123130. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  123131. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  123132. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  123133. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  123134. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123135. 10,
  123136. };
  123137. static float _vq_quantthresh__8c1_s_p5_0[] = {
  123138. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123139. };
  123140. static long _vq_quantmap__8c1_s_p5_0[] = {
  123141. 7, 5, 3, 1, 0, 2, 4, 6,
  123142. 8,
  123143. };
  123144. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  123145. _vq_quantthresh__8c1_s_p5_0,
  123146. _vq_quantmap__8c1_s_p5_0,
  123147. 9,
  123148. 9
  123149. };
  123150. static static_codebook _8c1_s_p5_0 = {
  123151. 2, 81,
  123152. _vq_lengthlist__8c1_s_p5_0,
  123153. 1, -531628032, 1611661312, 4, 0,
  123154. _vq_quantlist__8c1_s_p5_0,
  123155. NULL,
  123156. &_vq_auxt__8c1_s_p5_0,
  123157. NULL,
  123158. 0
  123159. };
  123160. static long _vq_quantlist__8c1_s_p6_0[] = {
  123161. 8,
  123162. 7,
  123163. 9,
  123164. 6,
  123165. 10,
  123166. 5,
  123167. 11,
  123168. 4,
  123169. 12,
  123170. 3,
  123171. 13,
  123172. 2,
  123173. 14,
  123174. 1,
  123175. 15,
  123176. 0,
  123177. 16,
  123178. };
  123179. static long _vq_lengthlist__8c1_s_p6_0[] = {
  123180. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  123181. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123182. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123183. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  123184. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  123185. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  123186. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  123187. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  123188. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123189. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123190. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123191. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  123192. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  123193. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123194. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123195. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  123196. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123198. 14,
  123199. };
  123200. static float _vq_quantthresh__8c1_s_p6_0[] = {
  123201. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123202. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123203. };
  123204. static long _vq_quantmap__8c1_s_p6_0[] = {
  123205. 15, 13, 11, 9, 7, 5, 3, 1,
  123206. 0, 2, 4, 6, 8, 10, 12, 14,
  123207. 16,
  123208. };
  123209. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  123210. _vq_quantthresh__8c1_s_p6_0,
  123211. _vq_quantmap__8c1_s_p6_0,
  123212. 17,
  123213. 17
  123214. };
  123215. static static_codebook _8c1_s_p6_0 = {
  123216. 2, 289,
  123217. _vq_lengthlist__8c1_s_p6_0,
  123218. 1, -529530880, 1611661312, 5, 0,
  123219. _vq_quantlist__8c1_s_p6_0,
  123220. NULL,
  123221. &_vq_auxt__8c1_s_p6_0,
  123222. NULL,
  123223. 0
  123224. };
  123225. static long _vq_quantlist__8c1_s_p7_0[] = {
  123226. 1,
  123227. 0,
  123228. 2,
  123229. };
  123230. static long _vq_lengthlist__8c1_s_p7_0[] = {
  123231. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  123232. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  123233. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  123234. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  123235. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  123236. 9,
  123237. };
  123238. static float _vq_quantthresh__8c1_s_p7_0[] = {
  123239. -5.5, 5.5,
  123240. };
  123241. static long _vq_quantmap__8c1_s_p7_0[] = {
  123242. 1, 0, 2,
  123243. };
  123244. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  123245. _vq_quantthresh__8c1_s_p7_0,
  123246. _vq_quantmap__8c1_s_p7_0,
  123247. 3,
  123248. 3
  123249. };
  123250. static static_codebook _8c1_s_p7_0 = {
  123251. 4, 81,
  123252. _vq_lengthlist__8c1_s_p7_0,
  123253. 1, -529137664, 1618345984, 2, 0,
  123254. _vq_quantlist__8c1_s_p7_0,
  123255. NULL,
  123256. &_vq_auxt__8c1_s_p7_0,
  123257. NULL,
  123258. 0
  123259. };
  123260. static long _vq_quantlist__8c1_s_p7_1[] = {
  123261. 5,
  123262. 4,
  123263. 6,
  123264. 3,
  123265. 7,
  123266. 2,
  123267. 8,
  123268. 1,
  123269. 9,
  123270. 0,
  123271. 10,
  123272. };
  123273. static long _vq_lengthlist__8c1_s_p7_1[] = {
  123274. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  123275. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  123276. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123277. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123278. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123279. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123280. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  123281. 10,10,10, 8, 8, 8, 8, 8, 8,
  123282. };
  123283. static float _vq_quantthresh__8c1_s_p7_1[] = {
  123284. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123285. 3.5, 4.5,
  123286. };
  123287. static long _vq_quantmap__8c1_s_p7_1[] = {
  123288. 9, 7, 5, 3, 1, 0, 2, 4,
  123289. 6, 8, 10,
  123290. };
  123291. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  123292. _vq_quantthresh__8c1_s_p7_1,
  123293. _vq_quantmap__8c1_s_p7_1,
  123294. 11,
  123295. 11
  123296. };
  123297. static static_codebook _8c1_s_p7_1 = {
  123298. 2, 121,
  123299. _vq_lengthlist__8c1_s_p7_1,
  123300. 1, -531365888, 1611661312, 4, 0,
  123301. _vq_quantlist__8c1_s_p7_1,
  123302. NULL,
  123303. &_vq_auxt__8c1_s_p7_1,
  123304. NULL,
  123305. 0
  123306. };
  123307. static long _vq_quantlist__8c1_s_p8_0[] = {
  123308. 6,
  123309. 5,
  123310. 7,
  123311. 4,
  123312. 8,
  123313. 3,
  123314. 9,
  123315. 2,
  123316. 10,
  123317. 1,
  123318. 11,
  123319. 0,
  123320. 12,
  123321. };
  123322. static long _vq_lengthlist__8c1_s_p8_0[] = {
  123323. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  123324. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  123325. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123326. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123327. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  123328. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  123329. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  123330. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  123331. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  123332. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  123333. 0,12,12,11,10,12,11,13,12,
  123334. };
  123335. static float _vq_quantthresh__8c1_s_p8_0[] = {
  123336. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123337. 12.5, 17.5, 22.5, 27.5,
  123338. };
  123339. static long _vq_quantmap__8c1_s_p8_0[] = {
  123340. 11, 9, 7, 5, 3, 1, 0, 2,
  123341. 4, 6, 8, 10, 12,
  123342. };
  123343. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  123344. _vq_quantthresh__8c1_s_p8_0,
  123345. _vq_quantmap__8c1_s_p8_0,
  123346. 13,
  123347. 13
  123348. };
  123349. static static_codebook _8c1_s_p8_0 = {
  123350. 2, 169,
  123351. _vq_lengthlist__8c1_s_p8_0,
  123352. 1, -526516224, 1616117760, 4, 0,
  123353. _vq_quantlist__8c1_s_p8_0,
  123354. NULL,
  123355. &_vq_auxt__8c1_s_p8_0,
  123356. NULL,
  123357. 0
  123358. };
  123359. static long _vq_quantlist__8c1_s_p8_1[] = {
  123360. 2,
  123361. 1,
  123362. 3,
  123363. 0,
  123364. 4,
  123365. };
  123366. static long _vq_lengthlist__8c1_s_p8_1[] = {
  123367. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123368. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123369. };
  123370. static float _vq_quantthresh__8c1_s_p8_1[] = {
  123371. -1.5, -0.5, 0.5, 1.5,
  123372. };
  123373. static long _vq_quantmap__8c1_s_p8_1[] = {
  123374. 3, 1, 0, 2, 4,
  123375. };
  123376. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  123377. _vq_quantthresh__8c1_s_p8_1,
  123378. _vq_quantmap__8c1_s_p8_1,
  123379. 5,
  123380. 5
  123381. };
  123382. static static_codebook _8c1_s_p8_1 = {
  123383. 2, 25,
  123384. _vq_lengthlist__8c1_s_p8_1,
  123385. 1, -533725184, 1611661312, 3, 0,
  123386. _vq_quantlist__8c1_s_p8_1,
  123387. NULL,
  123388. &_vq_auxt__8c1_s_p8_1,
  123389. NULL,
  123390. 0
  123391. };
  123392. static long _vq_quantlist__8c1_s_p9_0[] = {
  123393. 6,
  123394. 5,
  123395. 7,
  123396. 4,
  123397. 8,
  123398. 3,
  123399. 9,
  123400. 2,
  123401. 10,
  123402. 1,
  123403. 11,
  123404. 0,
  123405. 12,
  123406. };
  123407. static long _vq_lengthlist__8c1_s_p9_0[] = {
  123408. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  123409. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  123410. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123411. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123412. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123413. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123415. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123417. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123418. 10,10,10,10,10, 9, 9, 9, 9,
  123419. };
  123420. static float _vq_quantthresh__8c1_s_p9_0[] = {
  123421. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123422. 787.5, 1102.5, 1417.5, 1732.5,
  123423. };
  123424. static long _vq_quantmap__8c1_s_p9_0[] = {
  123425. 11, 9, 7, 5, 3, 1, 0, 2,
  123426. 4, 6, 8, 10, 12,
  123427. };
  123428. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  123429. _vq_quantthresh__8c1_s_p9_0,
  123430. _vq_quantmap__8c1_s_p9_0,
  123431. 13,
  123432. 13
  123433. };
  123434. static static_codebook _8c1_s_p9_0 = {
  123435. 2, 169,
  123436. _vq_lengthlist__8c1_s_p9_0,
  123437. 1, -513964032, 1628680192, 4, 0,
  123438. _vq_quantlist__8c1_s_p9_0,
  123439. NULL,
  123440. &_vq_auxt__8c1_s_p9_0,
  123441. NULL,
  123442. 0
  123443. };
  123444. static long _vq_quantlist__8c1_s_p9_1[] = {
  123445. 7,
  123446. 6,
  123447. 8,
  123448. 5,
  123449. 9,
  123450. 4,
  123451. 10,
  123452. 3,
  123453. 11,
  123454. 2,
  123455. 12,
  123456. 1,
  123457. 13,
  123458. 0,
  123459. 14,
  123460. };
  123461. static long _vq_lengthlist__8c1_s_p9_1[] = {
  123462. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  123463. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  123464. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  123465. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  123466. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  123467. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  123468. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  123469. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  123470. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  123471. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  123472. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  123473. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  123474. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  123475. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  123476. 15,
  123477. };
  123478. static float _vq_quantthresh__8c1_s_p9_1[] = {
  123479. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123480. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123481. };
  123482. static long _vq_quantmap__8c1_s_p9_1[] = {
  123483. 13, 11, 9, 7, 5, 3, 1, 0,
  123484. 2, 4, 6, 8, 10, 12, 14,
  123485. };
  123486. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  123487. _vq_quantthresh__8c1_s_p9_1,
  123488. _vq_quantmap__8c1_s_p9_1,
  123489. 15,
  123490. 15
  123491. };
  123492. static static_codebook _8c1_s_p9_1 = {
  123493. 2, 225,
  123494. _vq_lengthlist__8c1_s_p9_1,
  123495. 1, -520986624, 1620377600, 4, 0,
  123496. _vq_quantlist__8c1_s_p9_1,
  123497. NULL,
  123498. &_vq_auxt__8c1_s_p9_1,
  123499. NULL,
  123500. 0
  123501. };
  123502. static long _vq_quantlist__8c1_s_p9_2[] = {
  123503. 10,
  123504. 9,
  123505. 11,
  123506. 8,
  123507. 12,
  123508. 7,
  123509. 13,
  123510. 6,
  123511. 14,
  123512. 5,
  123513. 15,
  123514. 4,
  123515. 16,
  123516. 3,
  123517. 17,
  123518. 2,
  123519. 18,
  123520. 1,
  123521. 19,
  123522. 0,
  123523. 20,
  123524. };
  123525. static long _vq_lengthlist__8c1_s_p9_2[] = {
  123526. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  123527. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  123528. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  123529. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  123530. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123531. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  123532. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  123533. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  123534. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  123535. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  123536. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  123537. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  123538. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  123539. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  123540. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  123541. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  123542. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123543. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  123544. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  123545. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  123546. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123547. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  123548. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  123549. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  123550. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  123551. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  123552. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  123553. 10,10,10,10,10,10,10,10,10,
  123554. };
  123555. static float _vq_quantthresh__8c1_s_p9_2[] = {
  123556. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123557. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123558. 6.5, 7.5, 8.5, 9.5,
  123559. };
  123560. static long _vq_quantmap__8c1_s_p9_2[] = {
  123561. 19, 17, 15, 13, 11, 9, 7, 5,
  123562. 3, 1, 0, 2, 4, 6, 8, 10,
  123563. 12, 14, 16, 18, 20,
  123564. };
  123565. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  123566. _vq_quantthresh__8c1_s_p9_2,
  123567. _vq_quantmap__8c1_s_p9_2,
  123568. 21,
  123569. 21
  123570. };
  123571. static static_codebook _8c1_s_p9_2 = {
  123572. 2, 441,
  123573. _vq_lengthlist__8c1_s_p9_2,
  123574. 1, -529268736, 1611661312, 5, 0,
  123575. _vq_quantlist__8c1_s_p9_2,
  123576. NULL,
  123577. &_vq_auxt__8c1_s_p9_2,
  123578. NULL,
  123579. 0
  123580. };
  123581. static long _huff_lengthlist__8c1_s_single[] = {
  123582. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  123583. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  123584. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  123585. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  123586. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  123587. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  123588. 9, 7, 7, 8,
  123589. };
  123590. static static_codebook _huff_book__8c1_s_single = {
  123591. 2, 100,
  123592. _huff_lengthlist__8c1_s_single,
  123593. 0, 0, 0, 0, 0,
  123594. NULL,
  123595. NULL,
  123596. NULL,
  123597. NULL,
  123598. 0
  123599. };
  123600. static long _huff_lengthlist__44c2_s_long[] = {
  123601. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  123602. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  123603. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  123604. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  123605. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  123606. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  123607. 10, 8, 8, 9,
  123608. };
  123609. static static_codebook _huff_book__44c2_s_long = {
  123610. 2, 100,
  123611. _huff_lengthlist__44c2_s_long,
  123612. 0, 0, 0, 0, 0,
  123613. NULL,
  123614. NULL,
  123615. NULL,
  123616. NULL,
  123617. 0
  123618. };
  123619. static long _vq_quantlist__44c2_s_p1_0[] = {
  123620. 1,
  123621. 0,
  123622. 2,
  123623. };
  123624. static long _vq_lengthlist__44c2_s_p1_0[] = {
  123625. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123626. 0, 0, 5, 6, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123631. 0, 0, 0, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123636. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  123671. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123676. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  123681. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123717. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123722. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123727. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0,
  124036. };
  124037. static float _vq_quantthresh__44c2_s_p1_0[] = {
  124038. -0.5, 0.5,
  124039. };
  124040. static long _vq_quantmap__44c2_s_p1_0[] = {
  124041. 1, 0, 2,
  124042. };
  124043. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  124044. _vq_quantthresh__44c2_s_p1_0,
  124045. _vq_quantmap__44c2_s_p1_0,
  124046. 3,
  124047. 3
  124048. };
  124049. static static_codebook _44c2_s_p1_0 = {
  124050. 8, 6561,
  124051. _vq_lengthlist__44c2_s_p1_0,
  124052. 1, -535822336, 1611661312, 2, 0,
  124053. _vq_quantlist__44c2_s_p1_0,
  124054. NULL,
  124055. &_vq_auxt__44c2_s_p1_0,
  124056. NULL,
  124057. 0
  124058. };
  124059. static long _vq_quantlist__44c2_s_p2_0[] = {
  124060. 2,
  124061. 1,
  124062. 3,
  124063. 0,
  124064. 4,
  124065. };
  124066. static long _vq_lengthlist__44c2_s_p2_0[] = {
  124067. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  124068. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  124069. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  124070. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  124071. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  124077. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  124078. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  124079. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  124085. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  124086. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  124093. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  124094. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  124107. };
  124108. static float _vq_quantthresh__44c2_s_p2_0[] = {
  124109. -1.5, -0.5, 0.5, 1.5,
  124110. };
  124111. static long _vq_quantmap__44c2_s_p2_0[] = {
  124112. 3, 1, 0, 2, 4,
  124113. };
  124114. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  124115. _vq_quantthresh__44c2_s_p2_0,
  124116. _vq_quantmap__44c2_s_p2_0,
  124117. 5,
  124118. 5
  124119. };
  124120. static static_codebook _44c2_s_p2_0 = {
  124121. 4, 625,
  124122. _vq_lengthlist__44c2_s_p2_0,
  124123. 1, -533725184, 1611661312, 3, 0,
  124124. _vq_quantlist__44c2_s_p2_0,
  124125. NULL,
  124126. &_vq_auxt__44c2_s_p2_0,
  124127. NULL,
  124128. 0
  124129. };
  124130. static long _vq_quantlist__44c2_s_p3_0[] = {
  124131. 2,
  124132. 1,
  124133. 3,
  124134. 0,
  124135. 4,
  124136. };
  124137. static long _vq_lengthlist__44c2_s_p3_0[] = {
  124138. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0,
  124178. };
  124179. static float _vq_quantthresh__44c2_s_p3_0[] = {
  124180. -1.5, -0.5, 0.5, 1.5,
  124181. };
  124182. static long _vq_quantmap__44c2_s_p3_0[] = {
  124183. 3, 1, 0, 2, 4,
  124184. };
  124185. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  124186. _vq_quantthresh__44c2_s_p3_0,
  124187. _vq_quantmap__44c2_s_p3_0,
  124188. 5,
  124189. 5
  124190. };
  124191. static static_codebook _44c2_s_p3_0 = {
  124192. 4, 625,
  124193. _vq_lengthlist__44c2_s_p3_0,
  124194. 1, -533725184, 1611661312, 3, 0,
  124195. _vq_quantlist__44c2_s_p3_0,
  124196. NULL,
  124197. &_vq_auxt__44c2_s_p3_0,
  124198. NULL,
  124199. 0
  124200. };
  124201. static long _vq_quantlist__44c2_s_p4_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_p4_0[] = {
  124213. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  124214. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  124215. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  124216. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  124217. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0,
  124219. };
  124220. static float _vq_quantthresh__44c2_s_p4_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_p4_0[] = {
  124224. 7, 5, 3, 1, 0, 2, 4, 6,
  124225. 8,
  124226. };
  124227. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  124228. _vq_quantthresh__44c2_s_p4_0,
  124229. _vq_quantmap__44c2_s_p4_0,
  124230. 9,
  124231. 9
  124232. };
  124233. static static_codebook _44c2_s_p4_0 = {
  124234. 2, 81,
  124235. _vq_lengthlist__44c2_s_p4_0,
  124236. 1, -531628032, 1611661312, 4, 0,
  124237. _vq_quantlist__44c2_s_p4_0,
  124238. NULL,
  124239. &_vq_auxt__44c2_s_p4_0,
  124240. NULL,
  124241. 0
  124242. };
  124243. static long _vq_quantlist__44c2_s_p5_0[] = {
  124244. 4,
  124245. 3,
  124246. 5,
  124247. 2,
  124248. 6,
  124249. 1,
  124250. 7,
  124251. 0,
  124252. 8,
  124253. };
  124254. static long _vq_lengthlist__44c2_s_p5_0[] = {
  124255. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  124256. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  124257. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124258. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124259. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  124260. 11,
  124261. };
  124262. static float _vq_quantthresh__44c2_s_p5_0[] = {
  124263. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124264. };
  124265. static long _vq_quantmap__44c2_s_p5_0[] = {
  124266. 7, 5, 3, 1, 0, 2, 4, 6,
  124267. 8,
  124268. };
  124269. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  124270. _vq_quantthresh__44c2_s_p5_0,
  124271. _vq_quantmap__44c2_s_p5_0,
  124272. 9,
  124273. 9
  124274. };
  124275. static static_codebook _44c2_s_p5_0 = {
  124276. 2, 81,
  124277. _vq_lengthlist__44c2_s_p5_0,
  124278. 1, -531628032, 1611661312, 4, 0,
  124279. _vq_quantlist__44c2_s_p5_0,
  124280. NULL,
  124281. &_vq_auxt__44c2_s_p5_0,
  124282. NULL,
  124283. 0
  124284. };
  124285. static long _vq_quantlist__44c2_s_p6_0[] = {
  124286. 8,
  124287. 7,
  124288. 9,
  124289. 6,
  124290. 10,
  124291. 5,
  124292. 11,
  124293. 4,
  124294. 12,
  124295. 3,
  124296. 13,
  124297. 2,
  124298. 14,
  124299. 1,
  124300. 15,
  124301. 0,
  124302. 16,
  124303. };
  124304. static long _vq_lengthlist__44c2_s_p6_0[] = {
  124305. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  124306. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124307. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124308. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  124309. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  124310. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124311. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124312. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124313. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124314. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124315. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124316. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124317. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  124318. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124319. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  124320. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  124321. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124323. 14,
  124324. };
  124325. static float _vq_quantthresh__44c2_s_p6_0[] = {
  124326. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124327. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124328. };
  124329. static long _vq_quantmap__44c2_s_p6_0[] = {
  124330. 15, 13, 11, 9, 7, 5, 3, 1,
  124331. 0, 2, 4, 6, 8, 10, 12, 14,
  124332. 16,
  124333. };
  124334. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  124335. _vq_quantthresh__44c2_s_p6_0,
  124336. _vq_quantmap__44c2_s_p6_0,
  124337. 17,
  124338. 17
  124339. };
  124340. static static_codebook _44c2_s_p6_0 = {
  124341. 2, 289,
  124342. _vq_lengthlist__44c2_s_p6_0,
  124343. 1, -529530880, 1611661312, 5, 0,
  124344. _vq_quantlist__44c2_s_p6_0,
  124345. NULL,
  124346. &_vq_auxt__44c2_s_p6_0,
  124347. NULL,
  124348. 0
  124349. };
  124350. static long _vq_quantlist__44c2_s_p7_0[] = {
  124351. 1,
  124352. 0,
  124353. 2,
  124354. };
  124355. static long _vq_lengthlist__44c2_s_p7_0[] = {
  124356. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124357. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  124358. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124359. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  124360. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  124361. 11,
  124362. };
  124363. static float _vq_quantthresh__44c2_s_p7_0[] = {
  124364. -5.5, 5.5,
  124365. };
  124366. static long _vq_quantmap__44c2_s_p7_0[] = {
  124367. 1, 0, 2,
  124368. };
  124369. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  124370. _vq_quantthresh__44c2_s_p7_0,
  124371. _vq_quantmap__44c2_s_p7_0,
  124372. 3,
  124373. 3
  124374. };
  124375. static static_codebook _44c2_s_p7_0 = {
  124376. 4, 81,
  124377. _vq_lengthlist__44c2_s_p7_0,
  124378. 1, -529137664, 1618345984, 2, 0,
  124379. _vq_quantlist__44c2_s_p7_0,
  124380. NULL,
  124381. &_vq_auxt__44c2_s_p7_0,
  124382. NULL,
  124383. 0
  124384. };
  124385. static long _vq_quantlist__44c2_s_p7_1[] = {
  124386. 5,
  124387. 4,
  124388. 6,
  124389. 3,
  124390. 7,
  124391. 2,
  124392. 8,
  124393. 1,
  124394. 9,
  124395. 0,
  124396. 10,
  124397. };
  124398. static long _vq_lengthlist__44c2_s_p7_1[] = {
  124399. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  124400. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  124401. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124402. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124403. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124404. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124405. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  124406. 10,10,10, 8, 8, 8, 8, 8, 8,
  124407. };
  124408. static float _vq_quantthresh__44c2_s_p7_1[] = {
  124409. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124410. 3.5, 4.5,
  124411. };
  124412. static long _vq_quantmap__44c2_s_p7_1[] = {
  124413. 9, 7, 5, 3, 1, 0, 2, 4,
  124414. 6, 8, 10,
  124415. };
  124416. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  124417. _vq_quantthresh__44c2_s_p7_1,
  124418. _vq_quantmap__44c2_s_p7_1,
  124419. 11,
  124420. 11
  124421. };
  124422. static static_codebook _44c2_s_p7_1 = {
  124423. 2, 121,
  124424. _vq_lengthlist__44c2_s_p7_1,
  124425. 1, -531365888, 1611661312, 4, 0,
  124426. _vq_quantlist__44c2_s_p7_1,
  124427. NULL,
  124428. &_vq_auxt__44c2_s_p7_1,
  124429. NULL,
  124430. 0
  124431. };
  124432. static long _vq_quantlist__44c2_s_p8_0[] = {
  124433. 6,
  124434. 5,
  124435. 7,
  124436. 4,
  124437. 8,
  124438. 3,
  124439. 9,
  124440. 2,
  124441. 10,
  124442. 1,
  124443. 11,
  124444. 0,
  124445. 12,
  124446. };
  124447. static long _vq_lengthlist__44c2_s_p8_0[] = {
  124448. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124449. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  124450. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124451. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124452. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  124453. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124454. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  124455. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  124456. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  124457. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  124458. 0,12,12,12,12,13,12,14,14,
  124459. };
  124460. static float _vq_quantthresh__44c2_s_p8_0[] = {
  124461. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124462. 12.5, 17.5, 22.5, 27.5,
  124463. };
  124464. static long _vq_quantmap__44c2_s_p8_0[] = {
  124465. 11, 9, 7, 5, 3, 1, 0, 2,
  124466. 4, 6, 8, 10, 12,
  124467. };
  124468. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  124469. _vq_quantthresh__44c2_s_p8_0,
  124470. _vq_quantmap__44c2_s_p8_0,
  124471. 13,
  124472. 13
  124473. };
  124474. static static_codebook _44c2_s_p8_0 = {
  124475. 2, 169,
  124476. _vq_lengthlist__44c2_s_p8_0,
  124477. 1, -526516224, 1616117760, 4, 0,
  124478. _vq_quantlist__44c2_s_p8_0,
  124479. NULL,
  124480. &_vq_auxt__44c2_s_p8_0,
  124481. NULL,
  124482. 0
  124483. };
  124484. static long _vq_quantlist__44c2_s_p8_1[] = {
  124485. 2,
  124486. 1,
  124487. 3,
  124488. 0,
  124489. 4,
  124490. };
  124491. static long _vq_lengthlist__44c2_s_p8_1[] = {
  124492. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  124493. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124494. };
  124495. static float _vq_quantthresh__44c2_s_p8_1[] = {
  124496. -1.5, -0.5, 0.5, 1.5,
  124497. };
  124498. static long _vq_quantmap__44c2_s_p8_1[] = {
  124499. 3, 1, 0, 2, 4,
  124500. };
  124501. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  124502. _vq_quantthresh__44c2_s_p8_1,
  124503. _vq_quantmap__44c2_s_p8_1,
  124504. 5,
  124505. 5
  124506. };
  124507. static static_codebook _44c2_s_p8_1 = {
  124508. 2, 25,
  124509. _vq_lengthlist__44c2_s_p8_1,
  124510. 1, -533725184, 1611661312, 3, 0,
  124511. _vq_quantlist__44c2_s_p8_1,
  124512. NULL,
  124513. &_vq_auxt__44c2_s_p8_1,
  124514. NULL,
  124515. 0
  124516. };
  124517. static long _vq_quantlist__44c2_s_p9_0[] = {
  124518. 6,
  124519. 5,
  124520. 7,
  124521. 4,
  124522. 8,
  124523. 3,
  124524. 9,
  124525. 2,
  124526. 10,
  124527. 1,
  124528. 11,
  124529. 0,
  124530. 12,
  124531. };
  124532. static long _vq_lengthlist__44c2_s_p9_0[] = {
  124533. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  124534. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  124535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124536. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  124537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124543. 11,11,11,11,11,11,11,11,11,
  124544. };
  124545. static float _vq_quantthresh__44c2_s_p9_0[] = {
  124546. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  124547. 552.5, 773.5, 994.5, 1215.5,
  124548. };
  124549. static long _vq_quantmap__44c2_s_p9_0[] = {
  124550. 11, 9, 7, 5, 3, 1, 0, 2,
  124551. 4, 6, 8, 10, 12,
  124552. };
  124553. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  124554. _vq_quantthresh__44c2_s_p9_0,
  124555. _vq_quantmap__44c2_s_p9_0,
  124556. 13,
  124557. 13
  124558. };
  124559. static static_codebook _44c2_s_p9_0 = {
  124560. 2, 169,
  124561. _vq_lengthlist__44c2_s_p9_0,
  124562. 1, -514541568, 1627103232, 4, 0,
  124563. _vq_quantlist__44c2_s_p9_0,
  124564. NULL,
  124565. &_vq_auxt__44c2_s_p9_0,
  124566. NULL,
  124567. 0
  124568. };
  124569. static long _vq_quantlist__44c2_s_p9_1[] = {
  124570. 6,
  124571. 5,
  124572. 7,
  124573. 4,
  124574. 8,
  124575. 3,
  124576. 9,
  124577. 2,
  124578. 10,
  124579. 1,
  124580. 11,
  124581. 0,
  124582. 12,
  124583. };
  124584. static long _vq_lengthlist__44c2_s_p9_1[] = {
  124585. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  124586. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  124587. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  124588. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  124589. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  124590. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  124591. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  124592. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  124593. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  124594. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  124595. 17,13,12,12,10,13,11,14,14,
  124596. };
  124597. static float _vq_quantthresh__44c2_s_p9_1[] = {
  124598. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  124599. 42.5, 59.5, 76.5, 93.5,
  124600. };
  124601. static long _vq_quantmap__44c2_s_p9_1[] = {
  124602. 11, 9, 7, 5, 3, 1, 0, 2,
  124603. 4, 6, 8, 10, 12,
  124604. };
  124605. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  124606. _vq_quantthresh__44c2_s_p9_1,
  124607. _vq_quantmap__44c2_s_p9_1,
  124608. 13,
  124609. 13
  124610. };
  124611. static static_codebook _44c2_s_p9_1 = {
  124612. 2, 169,
  124613. _vq_lengthlist__44c2_s_p9_1,
  124614. 1, -522616832, 1620115456, 4, 0,
  124615. _vq_quantlist__44c2_s_p9_1,
  124616. NULL,
  124617. &_vq_auxt__44c2_s_p9_1,
  124618. NULL,
  124619. 0
  124620. };
  124621. static long _vq_quantlist__44c2_s_p9_2[] = {
  124622. 8,
  124623. 7,
  124624. 9,
  124625. 6,
  124626. 10,
  124627. 5,
  124628. 11,
  124629. 4,
  124630. 12,
  124631. 3,
  124632. 13,
  124633. 2,
  124634. 14,
  124635. 1,
  124636. 15,
  124637. 0,
  124638. 16,
  124639. };
  124640. static long _vq_lengthlist__44c2_s_p9_2[] = {
  124641. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124642. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124643. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  124644. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  124645. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  124646. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124647. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  124648. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  124649. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  124650. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  124651. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  124652. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  124653. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  124654. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  124655. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  124656. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  124657. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  124658. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  124659. 10,
  124660. };
  124661. static float _vq_quantthresh__44c2_s_p9_2[] = {
  124662. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124663. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124664. };
  124665. static long _vq_quantmap__44c2_s_p9_2[] = {
  124666. 15, 13, 11, 9, 7, 5, 3, 1,
  124667. 0, 2, 4, 6, 8, 10, 12, 14,
  124668. 16,
  124669. };
  124670. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  124671. _vq_quantthresh__44c2_s_p9_2,
  124672. _vq_quantmap__44c2_s_p9_2,
  124673. 17,
  124674. 17
  124675. };
  124676. static static_codebook _44c2_s_p9_2 = {
  124677. 2, 289,
  124678. _vq_lengthlist__44c2_s_p9_2,
  124679. 1, -529530880, 1611661312, 5, 0,
  124680. _vq_quantlist__44c2_s_p9_2,
  124681. NULL,
  124682. &_vq_auxt__44c2_s_p9_2,
  124683. NULL,
  124684. 0
  124685. };
  124686. static long _huff_lengthlist__44c2_s_short[] = {
  124687. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  124688. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  124689. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  124690. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  124691. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  124692. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  124693. 6, 8, 9,12,
  124694. };
  124695. static static_codebook _huff_book__44c2_s_short = {
  124696. 2, 100,
  124697. _huff_lengthlist__44c2_s_short,
  124698. 0, 0, 0, 0, 0,
  124699. NULL,
  124700. NULL,
  124701. NULL,
  124702. NULL,
  124703. 0
  124704. };
  124705. static long _huff_lengthlist__44c3_s_long[] = {
  124706. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  124707. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  124708. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  124709. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  124710. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  124711. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  124712. 9, 8, 8, 8,
  124713. };
  124714. static static_codebook _huff_book__44c3_s_long = {
  124715. 2, 100,
  124716. _huff_lengthlist__44c3_s_long,
  124717. 0, 0, 0, 0, 0,
  124718. NULL,
  124719. NULL,
  124720. NULL,
  124721. NULL,
  124722. 0
  124723. };
  124724. static long _vq_quantlist__44c3_s_p1_0[] = {
  124725. 1,
  124726. 0,
  124727. 2,
  124728. };
  124729. static long _vq_lengthlist__44c3_s_p1_0[] = {
  124730. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124731. 0, 0, 5, 6, 6, 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, 0, 0, 0, 0, 0, 0, 0,
  124734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124735. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124736. 0, 0, 0, 6, 7, 8, 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, 0, 0, 0, 0, 0, 0,
  124739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124740. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124741. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0,
  124744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  124776. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124781. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124786. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124822. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124827. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124832. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0,
  125141. };
  125142. static float _vq_quantthresh__44c3_s_p1_0[] = {
  125143. -0.5, 0.5,
  125144. };
  125145. static long _vq_quantmap__44c3_s_p1_0[] = {
  125146. 1, 0, 2,
  125147. };
  125148. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  125149. _vq_quantthresh__44c3_s_p1_0,
  125150. _vq_quantmap__44c3_s_p1_0,
  125151. 3,
  125152. 3
  125153. };
  125154. static static_codebook _44c3_s_p1_0 = {
  125155. 8, 6561,
  125156. _vq_lengthlist__44c3_s_p1_0,
  125157. 1, -535822336, 1611661312, 2, 0,
  125158. _vq_quantlist__44c3_s_p1_0,
  125159. NULL,
  125160. &_vq_auxt__44c3_s_p1_0,
  125161. NULL,
  125162. 0
  125163. };
  125164. static long _vq_quantlist__44c3_s_p2_0[] = {
  125165. 2,
  125166. 1,
  125167. 3,
  125168. 0,
  125169. 4,
  125170. };
  125171. static long _vq_lengthlist__44c3_s_p2_0[] = {
  125172. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125173. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  125174. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125175. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  125176. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125181. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  125182. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  125183. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  125184. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  125190. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  125191. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125197. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125198. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125199. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  125212. };
  125213. static float _vq_quantthresh__44c3_s_p2_0[] = {
  125214. -1.5, -0.5, 0.5, 1.5,
  125215. };
  125216. static long _vq_quantmap__44c3_s_p2_0[] = {
  125217. 3, 1, 0, 2, 4,
  125218. };
  125219. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  125220. _vq_quantthresh__44c3_s_p2_0,
  125221. _vq_quantmap__44c3_s_p2_0,
  125222. 5,
  125223. 5
  125224. };
  125225. static static_codebook _44c3_s_p2_0 = {
  125226. 4, 625,
  125227. _vq_lengthlist__44c3_s_p2_0,
  125228. 1, -533725184, 1611661312, 3, 0,
  125229. _vq_quantlist__44c3_s_p2_0,
  125230. NULL,
  125231. &_vq_auxt__44c3_s_p2_0,
  125232. NULL,
  125233. 0
  125234. };
  125235. static long _vq_quantlist__44c3_s_p3_0[] = {
  125236. 2,
  125237. 1,
  125238. 3,
  125239. 0,
  125240. 4,
  125241. };
  125242. static long _vq_lengthlist__44c3_s_p3_0[] = {
  125243. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125246. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0,
  125283. };
  125284. static float _vq_quantthresh__44c3_s_p3_0[] = {
  125285. -1.5, -0.5, 0.5, 1.5,
  125286. };
  125287. static long _vq_quantmap__44c3_s_p3_0[] = {
  125288. 3, 1, 0, 2, 4,
  125289. };
  125290. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  125291. _vq_quantthresh__44c3_s_p3_0,
  125292. _vq_quantmap__44c3_s_p3_0,
  125293. 5,
  125294. 5
  125295. };
  125296. static static_codebook _44c3_s_p3_0 = {
  125297. 4, 625,
  125298. _vq_lengthlist__44c3_s_p3_0,
  125299. 1, -533725184, 1611661312, 3, 0,
  125300. _vq_quantlist__44c3_s_p3_0,
  125301. NULL,
  125302. &_vq_auxt__44c3_s_p3_0,
  125303. NULL,
  125304. 0
  125305. };
  125306. static long _vq_quantlist__44c3_s_p4_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_p4_0[] = {
  125318. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125319. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125320. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125321. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  125322. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0,
  125324. };
  125325. static float _vq_quantthresh__44c3_s_p4_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_p4_0[] = {
  125329. 7, 5, 3, 1, 0, 2, 4, 6,
  125330. 8,
  125331. };
  125332. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  125333. _vq_quantthresh__44c3_s_p4_0,
  125334. _vq_quantmap__44c3_s_p4_0,
  125335. 9,
  125336. 9
  125337. };
  125338. static static_codebook _44c3_s_p4_0 = {
  125339. 2, 81,
  125340. _vq_lengthlist__44c3_s_p4_0,
  125341. 1, -531628032, 1611661312, 4, 0,
  125342. _vq_quantlist__44c3_s_p4_0,
  125343. NULL,
  125344. &_vq_auxt__44c3_s_p4_0,
  125345. NULL,
  125346. 0
  125347. };
  125348. static long _vq_quantlist__44c3_s_p5_0[] = {
  125349. 4,
  125350. 3,
  125351. 5,
  125352. 2,
  125353. 6,
  125354. 1,
  125355. 7,
  125356. 0,
  125357. 8,
  125358. };
  125359. static long _vq_lengthlist__44c3_s_p5_0[] = {
  125360. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  125361. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  125362. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  125363. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  125364. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  125365. 11,
  125366. };
  125367. static float _vq_quantthresh__44c3_s_p5_0[] = {
  125368. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125369. };
  125370. static long _vq_quantmap__44c3_s_p5_0[] = {
  125371. 7, 5, 3, 1, 0, 2, 4, 6,
  125372. 8,
  125373. };
  125374. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  125375. _vq_quantthresh__44c3_s_p5_0,
  125376. _vq_quantmap__44c3_s_p5_0,
  125377. 9,
  125378. 9
  125379. };
  125380. static static_codebook _44c3_s_p5_0 = {
  125381. 2, 81,
  125382. _vq_lengthlist__44c3_s_p5_0,
  125383. 1, -531628032, 1611661312, 4, 0,
  125384. _vq_quantlist__44c3_s_p5_0,
  125385. NULL,
  125386. &_vq_auxt__44c3_s_p5_0,
  125387. NULL,
  125388. 0
  125389. };
  125390. static long _vq_quantlist__44c3_s_p6_0[] = {
  125391. 8,
  125392. 7,
  125393. 9,
  125394. 6,
  125395. 10,
  125396. 5,
  125397. 11,
  125398. 4,
  125399. 12,
  125400. 3,
  125401. 13,
  125402. 2,
  125403. 14,
  125404. 1,
  125405. 15,
  125406. 0,
  125407. 16,
  125408. };
  125409. static long _vq_lengthlist__44c3_s_p6_0[] = {
  125410. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  125411. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  125412. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  125413. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125414. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125415. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125416. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  125417. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125418. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125419. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  125420. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  125421. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  125422. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  125423. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  125424. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  125425. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125426. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125428. 13,
  125429. };
  125430. static float _vq_quantthresh__44c3_s_p6_0[] = {
  125431. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125432. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125433. };
  125434. static long _vq_quantmap__44c3_s_p6_0[] = {
  125435. 15, 13, 11, 9, 7, 5, 3, 1,
  125436. 0, 2, 4, 6, 8, 10, 12, 14,
  125437. 16,
  125438. };
  125439. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  125440. _vq_quantthresh__44c3_s_p6_0,
  125441. _vq_quantmap__44c3_s_p6_0,
  125442. 17,
  125443. 17
  125444. };
  125445. static static_codebook _44c3_s_p6_0 = {
  125446. 2, 289,
  125447. _vq_lengthlist__44c3_s_p6_0,
  125448. 1, -529530880, 1611661312, 5, 0,
  125449. _vq_quantlist__44c3_s_p6_0,
  125450. NULL,
  125451. &_vq_auxt__44c3_s_p6_0,
  125452. NULL,
  125453. 0
  125454. };
  125455. static long _vq_quantlist__44c3_s_p7_0[] = {
  125456. 1,
  125457. 0,
  125458. 2,
  125459. };
  125460. static long _vq_lengthlist__44c3_s_p7_0[] = {
  125461. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125462. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125463. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125464. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  125465. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125466. 10,
  125467. };
  125468. static float _vq_quantthresh__44c3_s_p7_0[] = {
  125469. -5.5, 5.5,
  125470. };
  125471. static long _vq_quantmap__44c3_s_p7_0[] = {
  125472. 1, 0, 2,
  125473. };
  125474. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  125475. _vq_quantthresh__44c3_s_p7_0,
  125476. _vq_quantmap__44c3_s_p7_0,
  125477. 3,
  125478. 3
  125479. };
  125480. static static_codebook _44c3_s_p7_0 = {
  125481. 4, 81,
  125482. _vq_lengthlist__44c3_s_p7_0,
  125483. 1, -529137664, 1618345984, 2, 0,
  125484. _vq_quantlist__44c3_s_p7_0,
  125485. NULL,
  125486. &_vq_auxt__44c3_s_p7_0,
  125487. NULL,
  125488. 0
  125489. };
  125490. static long _vq_quantlist__44c3_s_p7_1[] = {
  125491. 5,
  125492. 4,
  125493. 6,
  125494. 3,
  125495. 7,
  125496. 2,
  125497. 8,
  125498. 1,
  125499. 9,
  125500. 0,
  125501. 10,
  125502. };
  125503. static long _vq_lengthlist__44c3_s_p7_1[] = {
  125504. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  125505. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125506. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125507. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  125508. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125509. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125510. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  125511. 10,10,10, 8, 8, 8, 8, 8, 8,
  125512. };
  125513. static float _vq_quantthresh__44c3_s_p7_1[] = {
  125514. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125515. 3.5, 4.5,
  125516. };
  125517. static long _vq_quantmap__44c3_s_p7_1[] = {
  125518. 9, 7, 5, 3, 1, 0, 2, 4,
  125519. 6, 8, 10,
  125520. };
  125521. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  125522. _vq_quantthresh__44c3_s_p7_1,
  125523. _vq_quantmap__44c3_s_p7_1,
  125524. 11,
  125525. 11
  125526. };
  125527. static static_codebook _44c3_s_p7_1 = {
  125528. 2, 121,
  125529. _vq_lengthlist__44c3_s_p7_1,
  125530. 1, -531365888, 1611661312, 4, 0,
  125531. _vq_quantlist__44c3_s_p7_1,
  125532. NULL,
  125533. &_vq_auxt__44c3_s_p7_1,
  125534. NULL,
  125535. 0
  125536. };
  125537. static long _vq_quantlist__44c3_s_p8_0[] = {
  125538. 6,
  125539. 5,
  125540. 7,
  125541. 4,
  125542. 8,
  125543. 3,
  125544. 9,
  125545. 2,
  125546. 10,
  125547. 1,
  125548. 11,
  125549. 0,
  125550. 12,
  125551. };
  125552. static long _vq_lengthlist__44c3_s_p8_0[] = {
  125553. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125554. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  125555. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125556. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125557. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  125558. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125559. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  125560. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125561. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  125562. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  125563. 0,13,13,12,12,13,12,14,13,
  125564. };
  125565. static float _vq_quantthresh__44c3_s_p8_0[] = {
  125566. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125567. 12.5, 17.5, 22.5, 27.5,
  125568. };
  125569. static long _vq_quantmap__44c3_s_p8_0[] = {
  125570. 11, 9, 7, 5, 3, 1, 0, 2,
  125571. 4, 6, 8, 10, 12,
  125572. };
  125573. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  125574. _vq_quantthresh__44c3_s_p8_0,
  125575. _vq_quantmap__44c3_s_p8_0,
  125576. 13,
  125577. 13
  125578. };
  125579. static static_codebook _44c3_s_p8_0 = {
  125580. 2, 169,
  125581. _vq_lengthlist__44c3_s_p8_0,
  125582. 1, -526516224, 1616117760, 4, 0,
  125583. _vq_quantlist__44c3_s_p8_0,
  125584. NULL,
  125585. &_vq_auxt__44c3_s_p8_0,
  125586. NULL,
  125587. 0
  125588. };
  125589. static long _vq_quantlist__44c3_s_p8_1[] = {
  125590. 2,
  125591. 1,
  125592. 3,
  125593. 0,
  125594. 4,
  125595. };
  125596. static long _vq_lengthlist__44c3_s_p8_1[] = {
  125597. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  125598. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125599. };
  125600. static float _vq_quantthresh__44c3_s_p8_1[] = {
  125601. -1.5, -0.5, 0.5, 1.5,
  125602. };
  125603. static long _vq_quantmap__44c3_s_p8_1[] = {
  125604. 3, 1, 0, 2, 4,
  125605. };
  125606. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  125607. _vq_quantthresh__44c3_s_p8_1,
  125608. _vq_quantmap__44c3_s_p8_1,
  125609. 5,
  125610. 5
  125611. };
  125612. static static_codebook _44c3_s_p8_1 = {
  125613. 2, 25,
  125614. _vq_lengthlist__44c3_s_p8_1,
  125615. 1, -533725184, 1611661312, 3, 0,
  125616. _vq_quantlist__44c3_s_p8_1,
  125617. NULL,
  125618. &_vq_auxt__44c3_s_p8_1,
  125619. NULL,
  125620. 0
  125621. };
  125622. static long _vq_quantlist__44c3_s_p9_0[] = {
  125623. 6,
  125624. 5,
  125625. 7,
  125626. 4,
  125627. 8,
  125628. 3,
  125629. 9,
  125630. 2,
  125631. 10,
  125632. 1,
  125633. 11,
  125634. 0,
  125635. 12,
  125636. };
  125637. static long _vq_lengthlist__44c3_s_p9_0[] = {
  125638. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125639. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  125640. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125641. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  125642. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125643. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125644. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125645. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125646. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  125647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125648. 11,11,11,11,11,11,11,11,11,
  125649. };
  125650. static float _vq_quantthresh__44c3_s_p9_0[] = {
  125651. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  125652. 637.5, 892.5, 1147.5, 1402.5,
  125653. };
  125654. static long _vq_quantmap__44c3_s_p9_0[] = {
  125655. 11, 9, 7, 5, 3, 1, 0, 2,
  125656. 4, 6, 8, 10, 12,
  125657. };
  125658. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  125659. _vq_quantthresh__44c3_s_p9_0,
  125660. _vq_quantmap__44c3_s_p9_0,
  125661. 13,
  125662. 13
  125663. };
  125664. static static_codebook _44c3_s_p9_0 = {
  125665. 2, 169,
  125666. _vq_lengthlist__44c3_s_p9_0,
  125667. 1, -514332672, 1627381760, 4, 0,
  125668. _vq_quantlist__44c3_s_p9_0,
  125669. NULL,
  125670. &_vq_auxt__44c3_s_p9_0,
  125671. NULL,
  125672. 0
  125673. };
  125674. static long _vq_quantlist__44c3_s_p9_1[] = {
  125675. 7,
  125676. 6,
  125677. 8,
  125678. 5,
  125679. 9,
  125680. 4,
  125681. 10,
  125682. 3,
  125683. 11,
  125684. 2,
  125685. 12,
  125686. 1,
  125687. 13,
  125688. 0,
  125689. 14,
  125690. };
  125691. static long _vq_lengthlist__44c3_s_p9_1[] = {
  125692. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  125693. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  125694. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  125695. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  125696. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  125697. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  125698. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  125699. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  125700. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  125701. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  125702. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  125703. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  125704. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  125705. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  125706. 15,
  125707. };
  125708. static float _vq_quantthresh__44c3_s_p9_1[] = {
  125709. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  125710. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  125711. };
  125712. static long _vq_quantmap__44c3_s_p9_1[] = {
  125713. 13, 11, 9, 7, 5, 3, 1, 0,
  125714. 2, 4, 6, 8, 10, 12, 14,
  125715. };
  125716. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  125717. _vq_quantthresh__44c3_s_p9_1,
  125718. _vq_quantmap__44c3_s_p9_1,
  125719. 15,
  125720. 15
  125721. };
  125722. static static_codebook _44c3_s_p9_1 = {
  125723. 2, 225,
  125724. _vq_lengthlist__44c3_s_p9_1,
  125725. 1, -522338304, 1620115456, 4, 0,
  125726. _vq_quantlist__44c3_s_p9_1,
  125727. NULL,
  125728. &_vq_auxt__44c3_s_p9_1,
  125729. NULL,
  125730. 0
  125731. };
  125732. static long _vq_quantlist__44c3_s_p9_2[] = {
  125733. 8,
  125734. 7,
  125735. 9,
  125736. 6,
  125737. 10,
  125738. 5,
  125739. 11,
  125740. 4,
  125741. 12,
  125742. 3,
  125743. 13,
  125744. 2,
  125745. 14,
  125746. 1,
  125747. 15,
  125748. 0,
  125749. 16,
  125750. };
  125751. static long _vq_lengthlist__44c3_s_p9_2[] = {
  125752. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125753. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  125754. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  125755. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125756. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  125757. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125758. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  125759. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  125760. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  125761. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  125762. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  125763. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  125764. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  125765. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  125766. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  125767. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  125768. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  125769. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  125770. 10,
  125771. };
  125772. static float _vq_quantthresh__44c3_s_p9_2[] = {
  125773. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125774. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125775. };
  125776. static long _vq_quantmap__44c3_s_p9_2[] = {
  125777. 15, 13, 11, 9, 7, 5, 3, 1,
  125778. 0, 2, 4, 6, 8, 10, 12, 14,
  125779. 16,
  125780. };
  125781. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  125782. _vq_quantthresh__44c3_s_p9_2,
  125783. _vq_quantmap__44c3_s_p9_2,
  125784. 17,
  125785. 17
  125786. };
  125787. static static_codebook _44c3_s_p9_2 = {
  125788. 2, 289,
  125789. _vq_lengthlist__44c3_s_p9_2,
  125790. 1, -529530880, 1611661312, 5, 0,
  125791. _vq_quantlist__44c3_s_p9_2,
  125792. NULL,
  125793. &_vq_auxt__44c3_s_p9_2,
  125794. NULL,
  125795. 0
  125796. };
  125797. static long _huff_lengthlist__44c3_s_short[] = {
  125798. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  125799. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  125800. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  125801. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  125802. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  125803. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  125804. 6, 8, 9,11,
  125805. };
  125806. static static_codebook _huff_book__44c3_s_short = {
  125807. 2, 100,
  125808. _huff_lengthlist__44c3_s_short,
  125809. 0, 0, 0, 0, 0,
  125810. NULL,
  125811. NULL,
  125812. NULL,
  125813. NULL,
  125814. 0
  125815. };
  125816. static long _huff_lengthlist__44c4_s_long[] = {
  125817. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  125818. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  125819. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  125820. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  125821. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  125822. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  125823. 9, 8, 7, 7,
  125824. };
  125825. static static_codebook _huff_book__44c4_s_long = {
  125826. 2, 100,
  125827. _huff_lengthlist__44c4_s_long,
  125828. 0, 0, 0, 0, 0,
  125829. NULL,
  125830. NULL,
  125831. NULL,
  125832. NULL,
  125833. 0
  125834. };
  125835. static long _vq_quantlist__44c4_s_p1_0[] = {
  125836. 1,
  125837. 0,
  125838. 2,
  125839. };
  125840. static long _vq_lengthlist__44c4_s_p1_0[] = {
  125841. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125842. 0, 0, 5, 6, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125847. 0, 0, 0, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125852. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  125887. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125892. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  125897. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125933. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125938. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125943. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0,
  126252. };
  126253. static float _vq_quantthresh__44c4_s_p1_0[] = {
  126254. -0.5, 0.5,
  126255. };
  126256. static long _vq_quantmap__44c4_s_p1_0[] = {
  126257. 1, 0, 2,
  126258. };
  126259. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  126260. _vq_quantthresh__44c4_s_p1_0,
  126261. _vq_quantmap__44c4_s_p1_0,
  126262. 3,
  126263. 3
  126264. };
  126265. static static_codebook _44c4_s_p1_0 = {
  126266. 8, 6561,
  126267. _vq_lengthlist__44c4_s_p1_0,
  126268. 1, -535822336, 1611661312, 2, 0,
  126269. _vq_quantlist__44c4_s_p1_0,
  126270. NULL,
  126271. &_vq_auxt__44c4_s_p1_0,
  126272. NULL,
  126273. 0
  126274. };
  126275. static long _vq_quantlist__44c4_s_p2_0[] = {
  126276. 2,
  126277. 1,
  126278. 3,
  126279. 0,
  126280. 4,
  126281. };
  126282. static long _vq_lengthlist__44c4_s_p2_0[] = {
  126283. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126284. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  126285. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126286. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  126287. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  126293. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  126294. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  126295. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  126301. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  126302. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  126309. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  126310. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  126323. };
  126324. static float _vq_quantthresh__44c4_s_p2_0[] = {
  126325. -1.5, -0.5, 0.5, 1.5,
  126326. };
  126327. static long _vq_quantmap__44c4_s_p2_0[] = {
  126328. 3, 1, 0, 2, 4,
  126329. };
  126330. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  126331. _vq_quantthresh__44c4_s_p2_0,
  126332. _vq_quantmap__44c4_s_p2_0,
  126333. 5,
  126334. 5
  126335. };
  126336. static static_codebook _44c4_s_p2_0 = {
  126337. 4, 625,
  126338. _vq_lengthlist__44c4_s_p2_0,
  126339. 1, -533725184, 1611661312, 3, 0,
  126340. _vq_quantlist__44c4_s_p2_0,
  126341. NULL,
  126342. &_vq_auxt__44c4_s_p2_0,
  126343. NULL,
  126344. 0
  126345. };
  126346. static long _vq_quantlist__44c4_s_p3_0[] = {
  126347. 2,
  126348. 1,
  126349. 3,
  126350. 0,
  126351. 4,
  126352. };
  126353. static long _vq_lengthlist__44c4_s_p3_0[] = {
  126354. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0,
  126394. };
  126395. static float _vq_quantthresh__44c4_s_p3_0[] = {
  126396. -1.5, -0.5, 0.5, 1.5,
  126397. };
  126398. static long _vq_quantmap__44c4_s_p3_0[] = {
  126399. 3, 1, 0, 2, 4,
  126400. };
  126401. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  126402. _vq_quantthresh__44c4_s_p3_0,
  126403. _vq_quantmap__44c4_s_p3_0,
  126404. 5,
  126405. 5
  126406. };
  126407. static static_codebook _44c4_s_p3_0 = {
  126408. 4, 625,
  126409. _vq_lengthlist__44c4_s_p3_0,
  126410. 1, -533725184, 1611661312, 3, 0,
  126411. _vq_quantlist__44c4_s_p3_0,
  126412. NULL,
  126413. &_vq_auxt__44c4_s_p3_0,
  126414. NULL,
  126415. 0
  126416. };
  126417. static long _vq_quantlist__44c4_s_p4_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_p4_0[] = {
  126429. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126430. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126431. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126432. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126433. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0,
  126435. };
  126436. static float _vq_quantthresh__44c4_s_p4_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_p4_0[] = {
  126440. 7, 5, 3, 1, 0, 2, 4, 6,
  126441. 8,
  126442. };
  126443. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  126444. _vq_quantthresh__44c4_s_p4_0,
  126445. _vq_quantmap__44c4_s_p4_0,
  126446. 9,
  126447. 9
  126448. };
  126449. static static_codebook _44c4_s_p4_0 = {
  126450. 2, 81,
  126451. _vq_lengthlist__44c4_s_p4_0,
  126452. 1, -531628032, 1611661312, 4, 0,
  126453. _vq_quantlist__44c4_s_p4_0,
  126454. NULL,
  126455. &_vq_auxt__44c4_s_p4_0,
  126456. NULL,
  126457. 0
  126458. };
  126459. static long _vq_quantlist__44c4_s_p5_0[] = {
  126460. 4,
  126461. 3,
  126462. 5,
  126463. 2,
  126464. 6,
  126465. 1,
  126466. 7,
  126467. 0,
  126468. 8,
  126469. };
  126470. static long _vq_lengthlist__44c4_s_p5_0[] = {
  126471. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126472. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  126473. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  126474. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  126475. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  126476. 10,
  126477. };
  126478. static float _vq_quantthresh__44c4_s_p5_0[] = {
  126479. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126480. };
  126481. static long _vq_quantmap__44c4_s_p5_0[] = {
  126482. 7, 5, 3, 1, 0, 2, 4, 6,
  126483. 8,
  126484. };
  126485. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  126486. _vq_quantthresh__44c4_s_p5_0,
  126487. _vq_quantmap__44c4_s_p5_0,
  126488. 9,
  126489. 9
  126490. };
  126491. static static_codebook _44c4_s_p5_0 = {
  126492. 2, 81,
  126493. _vq_lengthlist__44c4_s_p5_0,
  126494. 1, -531628032, 1611661312, 4, 0,
  126495. _vq_quantlist__44c4_s_p5_0,
  126496. NULL,
  126497. &_vq_auxt__44c4_s_p5_0,
  126498. NULL,
  126499. 0
  126500. };
  126501. static long _vq_quantlist__44c4_s_p6_0[] = {
  126502. 8,
  126503. 7,
  126504. 9,
  126505. 6,
  126506. 10,
  126507. 5,
  126508. 11,
  126509. 4,
  126510. 12,
  126511. 3,
  126512. 13,
  126513. 2,
  126514. 14,
  126515. 1,
  126516. 15,
  126517. 0,
  126518. 16,
  126519. };
  126520. static long _vq_lengthlist__44c4_s_p6_0[] = {
  126521. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  126522. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126523. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  126524. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126525. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126526. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126527. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126528. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126529. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126530. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  126531. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  126532. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  126533. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  126534. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  126535. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126536. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126537. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  126539. 13,
  126540. };
  126541. static float _vq_quantthresh__44c4_s_p6_0[] = {
  126542. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126543. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126544. };
  126545. static long _vq_quantmap__44c4_s_p6_0[] = {
  126546. 15, 13, 11, 9, 7, 5, 3, 1,
  126547. 0, 2, 4, 6, 8, 10, 12, 14,
  126548. 16,
  126549. };
  126550. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  126551. _vq_quantthresh__44c4_s_p6_0,
  126552. _vq_quantmap__44c4_s_p6_0,
  126553. 17,
  126554. 17
  126555. };
  126556. static static_codebook _44c4_s_p6_0 = {
  126557. 2, 289,
  126558. _vq_lengthlist__44c4_s_p6_0,
  126559. 1, -529530880, 1611661312, 5, 0,
  126560. _vq_quantlist__44c4_s_p6_0,
  126561. NULL,
  126562. &_vq_auxt__44c4_s_p6_0,
  126563. NULL,
  126564. 0
  126565. };
  126566. static long _vq_quantlist__44c4_s_p7_0[] = {
  126567. 1,
  126568. 0,
  126569. 2,
  126570. };
  126571. static long _vq_lengthlist__44c4_s_p7_0[] = {
  126572. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126573. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126574. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126575. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  126576. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126577. 10,
  126578. };
  126579. static float _vq_quantthresh__44c4_s_p7_0[] = {
  126580. -5.5, 5.5,
  126581. };
  126582. static long _vq_quantmap__44c4_s_p7_0[] = {
  126583. 1, 0, 2,
  126584. };
  126585. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  126586. _vq_quantthresh__44c4_s_p7_0,
  126587. _vq_quantmap__44c4_s_p7_0,
  126588. 3,
  126589. 3
  126590. };
  126591. static static_codebook _44c4_s_p7_0 = {
  126592. 4, 81,
  126593. _vq_lengthlist__44c4_s_p7_0,
  126594. 1, -529137664, 1618345984, 2, 0,
  126595. _vq_quantlist__44c4_s_p7_0,
  126596. NULL,
  126597. &_vq_auxt__44c4_s_p7_0,
  126598. NULL,
  126599. 0
  126600. };
  126601. static long _vq_quantlist__44c4_s_p7_1[] = {
  126602. 5,
  126603. 4,
  126604. 6,
  126605. 3,
  126606. 7,
  126607. 2,
  126608. 8,
  126609. 1,
  126610. 9,
  126611. 0,
  126612. 10,
  126613. };
  126614. static long _vq_lengthlist__44c4_s_p7_1[] = {
  126615. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126616. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126617. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126618. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  126619. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126620. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126621. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126622. 10,10,10, 8, 8, 8, 8, 9, 9,
  126623. };
  126624. static float _vq_quantthresh__44c4_s_p7_1[] = {
  126625. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126626. 3.5, 4.5,
  126627. };
  126628. static long _vq_quantmap__44c4_s_p7_1[] = {
  126629. 9, 7, 5, 3, 1, 0, 2, 4,
  126630. 6, 8, 10,
  126631. };
  126632. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  126633. _vq_quantthresh__44c4_s_p7_1,
  126634. _vq_quantmap__44c4_s_p7_1,
  126635. 11,
  126636. 11
  126637. };
  126638. static static_codebook _44c4_s_p7_1 = {
  126639. 2, 121,
  126640. _vq_lengthlist__44c4_s_p7_1,
  126641. 1, -531365888, 1611661312, 4, 0,
  126642. _vq_quantlist__44c4_s_p7_1,
  126643. NULL,
  126644. &_vq_auxt__44c4_s_p7_1,
  126645. NULL,
  126646. 0
  126647. };
  126648. static long _vq_quantlist__44c4_s_p8_0[] = {
  126649. 6,
  126650. 5,
  126651. 7,
  126652. 4,
  126653. 8,
  126654. 3,
  126655. 9,
  126656. 2,
  126657. 10,
  126658. 1,
  126659. 11,
  126660. 0,
  126661. 12,
  126662. };
  126663. static long _vq_lengthlist__44c4_s_p8_0[] = {
  126664. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126665. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126666. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126667. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126668. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  126669. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  126670. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  126671. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126672. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  126673. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126674. 0,13,12,12,12,12,12,13,13,
  126675. };
  126676. static float _vq_quantthresh__44c4_s_p8_0[] = {
  126677. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126678. 12.5, 17.5, 22.5, 27.5,
  126679. };
  126680. static long _vq_quantmap__44c4_s_p8_0[] = {
  126681. 11, 9, 7, 5, 3, 1, 0, 2,
  126682. 4, 6, 8, 10, 12,
  126683. };
  126684. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  126685. _vq_quantthresh__44c4_s_p8_0,
  126686. _vq_quantmap__44c4_s_p8_0,
  126687. 13,
  126688. 13
  126689. };
  126690. static static_codebook _44c4_s_p8_0 = {
  126691. 2, 169,
  126692. _vq_lengthlist__44c4_s_p8_0,
  126693. 1, -526516224, 1616117760, 4, 0,
  126694. _vq_quantlist__44c4_s_p8_0,
  126695. NULL,
  126696. &_vq_auxt__44c4_s_p8_0,
  126697. NULL,
  126698. 0
  126699. };
  126700. static long _vq_quantlist__44c4_s_p8_1[] = {
  126701. 2,
  126702. 1,
  126703. 3,
  126704. 0,
  126705. 4,
  126706. };
  126707. static long _vq_lengthlist__44c4_s_p8_1[] = {
  126708. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  126709. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126710. };
  126711. static float _vq_quantthresh__44c4_s_p8_1[] = {
  126712. -1.5, -0.5, 0.5, 1.5,
  126713. };
  126714. static long _vq_quantmap__44c4_s_p8_1[] = {
  126715. 3, 1, 0, 2, 4,
  126716. };
  126717. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  126718. _vq_quantthresh__44c4_s_p8_1,
  126719. _vq_quantmap__44c4_s_p8_1,
  126720. 5,
  126721. 5
  126722. };
  126723. static static_codebook _44c4_s_p8_1 = {
  126724. 2, 25,
  126725. _vq_lengthlist__44c4_s_p8_1,
  126726. 1, -533725184, 1611661312, 3, 0,
  126727. _vq_quantlist__44c4_s_p8_1,
  126728. NULL,
  126729. &_vq_auxt__44c4_s_p8_1,
  126730. NULL,
  126731. 0
  126732. };
  126733. static long _vq_quantlist__44c4_s_p9_0[] = {
  126734. 6,
  126735. 5,
  126736. 7,
  126737. 4,
  126738. 8,
  126739. 3,
  126740. 9,
  126741. 2,
  126742. 10,
  126743. 1,
  126744. 11,
  126745. 0,
  126746. 12,
  126747. };
  126748. static long _vq_lengthlist__44c4_s_p9_0[] = {
  126749. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  126750. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  126751. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126752. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126753. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126754. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126755. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126756. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126757. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126758. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126759. 12,12,12,12,12,12,12,12,12,
  126760. };
  126761. static float _vq_quantthresh__44c4_s_p9_0[] = {
  126762. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126763. 787.5, 1102.5, 1417.5, 1732.5,
  126764. };
  126765. static long _vq_quantmap__44c4_s_p9_0[] = {
  126766. 11, 9, 7, 5, 3, 1, 0, 2,
  126767. 4, 6, 8, 10, 12,
  126768. };
  126769. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  126770. _vq_quantthresh__44c4_s_p9_0,
  126771. _vq_quantmap__44c4_s_p9_0,
  126772. 13,
  126773. 13
  126774. };
  126775. static static_codebook _44c4_s_p9_0 = {
  126776. 2, 169,
  126777. _vq_lengthlist__44c4_s_p9_0,
  126778. 1, -513964032, 1628680192, 4, 0,
  126779. _vq_quantlist__44c4_s_p9_0,
  126780. NULL,
  126781. &_vq_auxt__44c4_s_p9_0,
  126782. NULL,
  126783. 0
  126784. };
  126785. static long _vq_quantlist__44c4_s_p9_1[] = {
  126786. 7,
  126787. 6,
  126788. 8,
  126789. 5,
  126790. 9,
  126791. 4,
  126792. 10,
  126793. 3,
  126794. 11,
  126795. 2,
  126796. 12,
  126797. 1,
  126798. 13,
  126799. 0,
  126800. 14,
  126801. };
  126802. static long _vq_lengthlist__44c4_s_p9_1[] = {
  126803. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  126804. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  126805. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  126806. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  126807. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  126808. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  126809. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  126810. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  126811. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  126812. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  126813. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  126814. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  126815. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  126816. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  126817. 15,
  126818. };
  126819. static float _vq_quantthresh__44c4_s_p9_1[] = {
  126820. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126821. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126822. };
  126823. static long _vq_quantmap__44c4_s_p9_1[] = {
  126824. 13, 11, 9, 7, 5, 3, 1, 0,
  126825. 2, 4, 6, 8, 10, 12, 14,
  126826. };
  126827. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  126828. _vq_quantthresh__44c4_s_p9_1,
  126829. _vq_quantmap__44c4_s_p9_1,
  126830. 15,
  126831. 15
  126832. };
  126833. static static_codebook _44c4_s_p9_1 = {
  126834. 2, 225,
  126835. _vq_lengthlist__44c4_s_p9_1,
  126836. 1, -520986624, 1620377600, 4, 0,
  126837. _vq_quantlist__44c4_s_p9_1,
  126838. NULL,
  126839. &_vq_auxt__44c4_s_p9_1,
  126840. NULL,
  126841. 0
  126842. };
  126843. static long _vq_quantlist__44c4_s_p9_2[] = {
  126844. 10,
  126845. 9,
  126846. 11,
  126847. 8,
  126848. 12,
  126849. 7,
  126850. 13,
  126851. 6,
  126852. 14,
  126853. 5,
  126854. 15,
  126855. 4,
  126856. 16,
  126857. 3,
  126858. 17,
  126859. 2,
  126860. 18,
  126861. 1,
  126862. 19,
  126863. 0,
  126864. 20,
  126865. };
  126866. static long _vq_lengthlist__44c4_s_p9_2[] = {
  126867. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126868. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  126869. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  126870. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  126871. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  126872. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  126873. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  126874. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  126875. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  126876. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  126877. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126878. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126879. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126880. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126881. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  126882. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  126883. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  126884. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126885. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  126886. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  126887. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126888. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126889. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  126890. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  126891. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  126892. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  126893. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  126894. 10,10,10,10,10,10,10,10,10,
  126895. };
  126896. static float _vq_quantthresh__44c4_s_p9_2[] = {
  126897. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126898. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126899. 6.5, 7.5, 8.5, 9.5,
  126900. };
  126901. static long _vq_quantmap__44c4_s_p9_2[] = {
  126902. 19, 17, 15, 13, 11, 9, 7, 5,
  126903. 3, 1, 0, 2, 4, 6, 8, 10,
  126904. 12, 14, 16, 18, 20,
  126905. };
  126906. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  126907. _vq_quantthresh__44c4_s_p9_2,
  126908. _vq_quantmap__44c4_s_p9_2,
  126909. 21,
  126910. 21
  126911. };
  126912. static static_codebook _44c4_s_p9_2 = {
  126913. 2, 441,
  126914. _vq_lengthlist__44c4_s_p9_2,
  126915. 1, -529268736, 1611661312, 5, 0,
  126916. _vq_quantlist__44c4_s_p9_2,
  126917. NULL,
  126918. &_vq_auxt__44c4_s_p9_2,
  126919. NULL,
  126920. 0
  126921. };
  126922. static long _huff_lengthlist__44c4_s_short[] = {
  126923. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  126924. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  126925. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  126926. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  126927. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  126928. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  126929. 7, 9,12,17,
  126930. };
  126931. static static_codebook _huff_book__44c4_s_short = {
  126932. 2, 100,
  126933. _huff_lengthlist__44c4_s_short,
  126934. 0, 0, 0, 0, 0,
  126935. NULL,
  126936. NULL,
  126937. NULL,
  126938. NULL,
  126939. 0
  126940. };
  126941. static long _huff_lengthlist__44c5_s_long[] = {
  126942. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  126943. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  126944. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  126945. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  126946. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  126947. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  126948. 9, 8, 7, 7,
  126949. };
  126950. static static_codebook _huff_book__44c5_s_long = {
  126951. 2, 100,
  126952. _huff_lengthlist__44c5_s_long,
  126953. 0, 0, 0, 0, 0,
  126954. NULL,
  126955. NULL,
  126956. NULL,
  126957. NULL,
  126958. 0
  126959. };
  126960. static long _vq_quantlist__44c5_s_p1_0[] = {
  126961. 1,
  126962. 0,
  126963. 2,
  126964. };
  126965. static long _vq_lengthlist__44c5_s_p1_0[] = {
  126966. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126967. 0, 0, 4, 6, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126972. 0, 0, 0, 7, 8, 9, 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, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126977. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0,
  127012. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  127017. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127022. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127058. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  127063. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127068. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0,
  127377. };
  127378. static float _vq_quantthresh__44c5_s_p1_0[] = {
  127379. -0.5, 0.5,
  127380. };
  127381. static long _vq_quantmap__44c5_s_p1_0[] = {
  127382. 1, 0, 2,
  127383. };
  127384. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  127385. _vq_quantthresh__44c5_s_p1_0,
  127386. _vq_quantmap__44c5_s_p1_0,
  127387. 3,
  127388. 3
  127389. };
  127390. static static_codebook _44c5_s_p1_0 = {
  127391. 8, 6561,
  127392. _vq_lengthlist__44c5_s_p1_0,
  127393. 1, -535822336, 1611661312, 2, 0,
  127394. _vq_quantlist__44c5_s_p1_0,
  127395. NULL,
  127396. &_vq_auxt__44c5_s_p1_0,
  127397. NULL,
  127398. 0
  127399. };
  127400. static long _vq_quantlist__44c5_s_p2_0[] = {
  127401. 2,
  127402. 1,
  127403. 3,
  127404. 0,
  127405. 4,
  127406. };
  127407. static long _vq_lengthlist__44c5_s_p2_0[] = {
  127408. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  127409. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127410. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127411. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  127412. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  127418. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  127419. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  127420. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  127426. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  127427. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  127434. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  127435. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127448. };
  127449. static float _vq_quantthresh__44c5_s_p2_0[] = {
  127450. -1.5, -0.5, 0.5, 1.5,
  127451. };
  127452. static long _vq_quantmap__44c5_s_p2_0[] = {
  127453. 3, 1, 0, 2, 4,
  127454. };
  127455. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  127456. _vq_quantthresh__44c5_s_p2_0,
  127457. _vq_quantmap__44c5_s_p2_0,
  127458. 5,
  127459. 5
  127460. };
  127461. static static_codebook _44c5_s_p2_0 = {
  127462. 4, 625,
  127463. _vq_lengthlist__44c5_s_p2_0,
  127464. 1, -533725184, 1611661312, 3, 0,
  127465. _vq_quantlist__44c5_s_p2_0,
  127466. NULL,
  127467. &_vq_auxt__44c5_s_p2_0,
  127468. NULL,
  127469. 0
  127470. };
  127471. static long _vq_quantlist__44c5_s_p3_0[] = {
  127472. 2,
  127473. 1,
  127474. 3,
  127475. 0,
  127476. 4,
  127477. };
  127478. static long _vq_lengthlist__44c5_s_p3_0[] = {
  127479. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0,
  127519. };
  127520. static float _vq_quantthresh__44c5_s_p3_0[] = {
  127521. -1.5, -0.5, 0.5, 1.5,
  127522. };
  127523. static long _vq_quantmap__44c5_s_p3_0[] = {
  127524. 3, 1, 0, 2, 4,
  127525. };
  127526. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  127527. _vq_quantthresh__44c5_s_p3_0,
  127528. _vq_quantmap__44c5_s_p3_0,
  127529. 5,
  127530. 5
  127531. };
  127532. static static_codebook _44c5_s_p3_0 = {
  127533. 4, 625,
  127534. _vq_lengthlist__44c5_s_p3_0,
  127535. 1, -533725184, 1611661312, 3, 0,
  127536. _vq_quantlist__44c5_s_p3_0,
  127537. NULL,
  127538. &_vq_auxt__44c5_s_p3_0,
  127539. NULL,
  127540. 0
  127541. };
  127542. static long _vq_quantlist__44c5_s_p4_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_p4_0[] = {
  127554. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127555. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127556. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127557. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  127558. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0,
  127560. };
  127561. static float _vq_quantthresh__44c5_s_p4_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_p4_0[] = {
  127565. 7, 5, 3, 1, 0, 2, 4, 6,
  127566. 8,
  127567. };
  127568. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  127569. _vq_quantthresh__44c5_s_p4_0,
  127570. _vq_quantmap__44c5_s_p4_0,
  127571. 9,
  127572. 9
  127573. };
  127574. static static_codebook _44c5_s_p4_0 = {
  127575. 2, 81,
  127576. _vq_lengthlist__44c5_s_p4_0,
  127577. 1, -531628032, 1611661312, 4, 0,
  127578. _vq_quantlist__44c5_s_p4_0,
  127579. NULL,
  127580. &_vq_auxt__44c5_s_p4_0,
  127581. NULL,
  127582. 0
  127583. };
  127584. static long _vq_quantlist__44c5_s_p5_0[] = {
  127585. 4,
  127586. 3,
  127587. 5,
  127588. 2,
  127589. 6,
  127590. 1,
  127591. 7,
  127592. 0,
  127593. 8,
  127594. };
  127595. static long _vq_lengthlist__44c5_s_p5_0[] = {
  127596. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127597. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127598. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  127599. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127600. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127601. 10,
  127602. };
  127603. static float _vq_quantthresh__44c5_s_p5_0[] = {
  127604. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127605. };
  127606. static long _vq_quantmap__44c5_s_p5_0[] = {
  127607. 7, 5, 3, 1, 0, 2, 4, 6,
  127608. 8,
  127609. };
  127610. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  127611. _vq_quantthresh__44c5_s_p5_0,
  127612. _vq_quantmap__44c5_s_p5_0,
  127613. 9,
  127614. 9
  127615. };
  127616. static static_codebook _44c5_s_p5_0 = {
  127617. 2, 81,
  127618. _vq_lengthlist__44c5_s_p5_0,
  127619. 1, -531628032, 1611661312, 4, 0,
  127620. _vq_quantlist__44c5_s_p5_0,
  127621. NULL,
  127622. &_vq_auxt__44c5_s_p5_0,
  127623. NULL,
  127624. 0
  127625. };
  127626. static long _vq_quantlist__44c5_s_p6_0[] = {
  127627. 8,
  127628. 7,
  127629. 9,
  127630. 6,
  127631. 10,
  127632. 5,
  127633. 11,
  127634. 4,
  127635. 12,
  127636. 3,
  127637. 13,
  127638. 2,
  127639. 14,
  127640. 1,
  127641. 15,
  127642. 0,
  127643. 16,
  127644. };
  127645. static long _vq_lengthlist__44c5_s_p6_0[] = {
  127646. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  127647. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127648. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127649. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127650. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127651. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  127652. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  127653. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  127654. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127655. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  127656. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  127657. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  127658. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  127659. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  127660. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  127661. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127662. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  127664. 13,
  127665. };
  127666. static float _vq_quantthresh__44c5_s_p6_0[] = {
  127667. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127668. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127669. };
  127670. static long _vq_quantmap__44c5_s_p6_0[] = {
  127671. 15, 13, 11, 9, 7, 5, 3, 1,
  127672. 0, 2, 4, 6, 8, 10, 12, 14,
  127673. 16,
  127674. };
  127675. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  127676. _vq_quantthresh__44c5_s_p6_0,
  127677. _vq_quantmap__44c5_s_p6_0,
  127678. 17,
  127679. 17
  127680. };
  127681. static static_codebook _44c5_s_p6_0 = {
  127682. 2, 289,
  127683. _vq_lengthlist__44c5_s_p6_0,
  127684. 1, -529530880, 1611661312, 5, 0,
  127685. _vq_quantlist__44c5_s_p6_0,
  127686. NULL,
  127687. &_vq_auxt__44c5_s_p6_0,
  127688. NULL,
  127689. 0
  127690. };
  127691. static long _vq_quantlist__44c5_s_p7_0[] = {
  127692. 1,
  127693. 0,
  127694. 2,
  127695. };
  127696. static long _vq_lengthlist__44c5_s_p7_0[] = {
  127697. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127698. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127699. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127700. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127701. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127702. 10,
  127703. };
  127704. static float _vq_quantthresh__44c5_s_p7_0[] = {
  127705. -5.5, 5.5,
  127706. };
  127707. static long _vq_quantmap__44c5_s_p7_0[] = {
  127708. 1, 0, 2,
  127709. };
  127710. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  127711. _vq_quantthresh__44c5_s_p7_0,
  127712. _vq_quantmap__44c5_s_p7_0,
  127713. 3,
  127714. 3
  127715. };
  127716. static static_codebook _44c5_s_p7_0 = {
  127717. 4, 81,
  127718. _vq_lengthlist__44c5_s_p7_0,
  127719. 1, -529137664, 1618345984, 2, 0,
  127720. _vq_quantlist__44c5_s_p7_0,
  127721. NULL,
  127722. &_vq_auxt__44c5_s_p7_0,
  127723. NULL,
  127724. 0
  127725. };
  127726. static long _vq_quantlist__44c5_s_p7_1[] = {
  127727. 5,
  127728. 4,
  127729. 6,
  127730. 3,
  127731. 7,
  127732. 2,
  127733. 8,
  127734. 1,
  127735. 9,
  127736. 0,
  127737. 10,
  127738. };
  127739. static long _vq_lengthlist__44c5_s_p7_1[] = {
  127740. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  127741. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127742. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127743. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127744. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127745. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  127746. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127747. 10,10,10, 8, 8, 8, 8, 8, 8,
  127748. };
  127749. static float _vq_quantthresh__44c5_s_p7_1[] = {
  127750. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127751. 3.5, 4.5,
  127752. };
  127753. static long _vq_quantmap__44c5_s_p7_1[] = {
  127754. 9, 7, 5, 3, 1, 0, 2, 4,
  127755. 6, 8, 10,
  127756. };
  127757. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  127758. _vq_quantthresh__44c5_s_p7_1,
  127759. _vq_quantmap__44c5_s_p7_1,
  127760. 11,
  127761. 11
  127762. };
  127763. static static_codebook _44c5_s_p7_1 = {
  127764. 2, 121,
  127765. _vq_lengthlist__44c5_s_p7_1,
  127766. 1, -531365888, 1611661312, 4, 0,
  127767. _vq_quantlist__44c5_s_p7_1,
  127768. NULL,
  127769. &_vq_auxt__44c5_s_p7_1,
  127770. NULL,
  127771. 0
  127772. };
  127773. static long _vq_quantlist__44c5_s_p8_0[] = {
  127774. 6,
  127775. 5,
  127776. 7,
  127777. 4,
  127778. 8,
  127779. 3,
  127780. 9,
  127781. 2,
  127782. 10,
  127783. 1,
  127784. 11,
  127785. 0,
  127786. 12,
  127787. };
  127788. static long _vq_lengthlist__44c5_s_p8_0[] = {
  127789. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127790. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  127791. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127792. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127793. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  127794. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  127795. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  127796. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127797. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  127798. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127799. 0,12,12,12,12,12,12,13,13,
  127800. };
  127801. static float _vq_quantthresh__44c5_s_p8_0[] = {
  127802. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127803. 12.5, 17.5, 22.5, 27.5,
  127804. };
  127805. static long _vq_quantmap__44c5_s_p8_0[] = {
  127806. 11, 9, 7, 5, 3, 1, 0, 2,
  127807. 4, 6, 8, 10, 12,
  127808. };
  127809. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  127810. _vq_quantthresh__44c5_s_p8_0,
  127811. _vq_quantmap__44c5_s_p8_0,
  127812. 13,
  127813. 13
  127814. };
  127815. static static_codebook _44c5_s_p8_0 = {
  127816. 2, 169,
  127817. _vq_lengthlist__44c5_s_p8_0,
  127818. 1, -526516224, 1616117760, 4, 0,
  127819. _vq_quantlist__44c5_s_p8_0,
  127820. NULL,
  127821. &_vq_auxt__44c5_s_p8_0,
  127822. NULL,
  127823. 0
  127824. };
  127825. static long _vq_quantlist__44c5_s_p8_1[] = {
  127826. 2,
  127827. 1,
  127828. 3,
  127829. 0,
  127830. 4,
  127831. };
  127832. static long _vq_lengthlist__44c5_s_p8_1[] = {
  127833. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  127834. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127835. };
  127836. static float _vq_quantthresh__44c5_s_p8_1[] = {
  127837. -1.5, -0.5, 0.5, 1.5,
  127838. };
  127839. static long _vq_quantmap__44c5_s_p8_1[] = {
  127840. 3, 1, 0, 2, 4,
  127841. };
  127842. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  127843. _vq_quantthresh__44c5_s_p8_1,
  127844. _vq_quantmap__44c5_s_p8_1,
  127845. 5,
  127846. 5
  127847. };
  127848. static static_codebook _44c5_s_p8_1 = {
  127849. 2, 25,
  127850. _vq_lengthlist__44c5_s_p8_1,
  127851. 1, -533725184, 1611661312, 3, 0,
  127852. _vq_quantlist__44c5_s_p8_1,
  127853. NULL,
  127854. &_vq_auxt__44c5_s_p8_1,
  127855. NULL,
  127856. 0
  127857. };
  127858. static long _vq_quantlist__44c5_s_p9_0[] = {
  127859. 7,
  127860. 6,
  127861. 8,
  127862. 5,
  127863. 9,
  127864. 4,
  127865. 10,
  127866. 3,
  127867. 11,
  127868. 2,
  127869. 12,
  127870. 1,
  127871. 13,
  127872. 0,
  127873. 14,
  127874. };
  127875. static long _vq_lengthlist__44c5_s_p9_0[] = {
  127876. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  127877. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  127878. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127879. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127880. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127881. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127882. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127883. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127884. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127885. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127886. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127887. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127888. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127889. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  127890. 12,
  127891. };
  127892. static float _vq_quantthresh__44c5_s_p9_0[] = {
  127893. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  127894. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  127895. };
  127896. static long _vq_quantmap__44c5_s_p9_0[] = {
  127897. 13, 11, 9, 7, 5, 3, 1, 0,
  127898. 2, 4, 6, 8, 10, 12, 14,
  127899. };
  127900. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  127901. _vq_quantthresh__44c5_s_p9_0,
  127902. _vq_quantmap__44c5_s_p9_0,
  127903. 15,
  127904. 15
  127905. };
  127906. static static_codebook _44c5_s_p9_0 = {
  127907. 2, 225,
  127908. _vq_lengthlist__44c5_s_p9_0,
  127909. 1, -512522752, 1628852224, 4, 0,
  127910. _vq_quantlist__44c5_s_p9_0,
  127911. NULL,
  127912. &_vq_auxt__44c5_s_p9_0,
  127913. NULL,
  127914. 0
  127915. };
  127916. static long _vq_quantlist__44c5_s_p9_1[] = {
  127917. 8,
  127918. 7,
  127919. 9,
  127920. 6,
  127921. 10,
  127922. 5,
  127923. 11,
  127924. 4,
  127925. 12,
  127926. 3,
  127927. 13,
  127928. 2,
  127929. 14,
  127930. 1,
  127931. 15,
  127932. 0,
  127933. 16,
  127934. };
  127935. static long _vq_lengthlist__44c5_s_p9_1[] = {
  127936. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  127937. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  127938. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  127939. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  127940. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  127941. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  127942. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  127943. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  127944. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  127945. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  127946. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  127947. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  127948. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  127949. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  127950. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  127951. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  127952. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  127953. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  127954. 15,
  127955. };
  127956. static float _vq_quantthresh__44c5_s_p9_1[] = {
  127957. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  127958. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  127959. };
  127960. static long _vq_quantmap__44c5_s_p9_1[] = {
  127961. 15, 13, 11, 9, 7, 5, 3, 1,
  127962. 0, 2, 4, 6, 8, 10, 12, 14,
  127963. 16,
  127964. };
  127965. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  127966. _vq_quantthresh__44c5_s_p9_1,
  127967. _vq_quantmap__44c5_s_p9_1,
  127968. 17,
  127969. 17
  127970. };
  127971. static static_codebook _44c5_s_p9_1 = {
  127972. 2, 289,
  127973. _vq_lengthlist__44c5_s_p9_1,
  127974. 1, -520814592, 1620377600, 5, 0,
  127975. _vq_quantlist__44c5_s_p9_1,
  127976. NULL,
  127977. &_vq_auxt__44c5_s_p9_1,
  127978. NULL,
  127979. 0
  127980. };
  127981. static long _vq_quantlist__44c5_s_p9_2[] = {
  127982. 10,
  127983. 9,
  127984. 11,
  127985. 8,
  127986. 12,
  127987. 7,
  127988. 13,
  127989. 6,
  127990. 14,
  127991. 5,
  127992. 15,
  127993. 4,
  127994. 16,
  127995. 3,
  127996. 17,
  127997. 2,
  127998. 18,
  127999. 1,
  128000. 19,
  128001. 0,
  128002. 20,
  128003. };
  128004. static long _vq_lengthlist__44c5_s_p9_2[] = {
  128005. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  128006. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  128007. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  128008. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  128009. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  128010. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128011. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  128012. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  128013. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  128014. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128015. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  128016. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  128017. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  128018. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  128019. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  128020. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  128021. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  128022. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128023. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  128024. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  128025. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128026. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128027. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  128028. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128029. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  128030. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  128031. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  128032. 10,10,10,10,10,10,10,10,10,
  128033. };
  128034. static float _vq_quantthresh__44c5_s_p9_2[] = {
  128035. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128036. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128037. 6.5, 7.5, 8.5, 9.5,
  128038. };
  128039. static long _vq_quantmap__44c5_s_p9_2[] = {
  128040. 19, 17, 15, 13, 11, 9, 7, 5,
  128041. 3, 1, 0, 2, 4, 6, 8, 10,
  128042. 12, 14, 16, 18, 20,
  128043. };
  128044. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  128045. _vq_quantthresh__44c5_s_p9_2,
  128046. _vq_quantmap__44c5_s_p9_2,
  128047. 21,
  128048. 21
  128049. };
  128050. static static_codebook _44c5_s_p9_2 = {
  128051. 2, 441,
  128052. _vq_lengthlist__44c5_s_p9_2,
  128053. 1, -529268736, 1611661312, 5, 0,
  128054. _vq_quantlist__44c5_s_p9_2,
  128055. NULL,
  128056. &_vq_auxt__44c5_s_p9_2,
  128057. NULL,
  128058. 0
  128059. };
  128060. static long _huff_lengthlist__44c5_s_short[] = {
  128061. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  128062. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  128063. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  128064. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  128065. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  128066. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  128067. 6, 8,11,16,
  128068. };
  128069. static static_codebook _huff_book__44c5_s_short = {
  128070. 2, 100,
  128071. _huff_lengthlist__44c5_s_short,
  128072. 0, 0, 0, 0, 0,
  128073. NULL,
  128074. NULL,
  128075. NULL,
  128076. NULL,
  128077. 0
  128078. };
  128079. static long _huff_lengthlist__44c6_s_long[] = {
  128080. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  128081. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  128082. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  128083. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  128084. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  128085. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  128086. 11,10,10,12,
  128087. };
  128088. static static_codebook _huff_book__44c6_s_long = {
  128089. 2, 100,
  128090. _huff_lengthlist__44c6_s_long,
  128091. 0, 0, 0, 0, 0,
  128092. NULL,
  128093. NULL,
  128094. NULL,
  128095. NULL,
  128096. 0
  128097. };
  128098. static long _vq_quantlist__44c6_s_p1_0[] = {
  128099. 1,
  128100. 0,
  128101. 2,
  128102. };
  128103. static long _vq_lengthlist__44c6_s_p1_0[] = {
  128104. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128105. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128107. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128108. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  128109. 8,
  128110. };
  128111. static float _vq_quantthresh__44c6_s_p1_0[] = {
  128112. -0.5, 0.5,
  128113. };
  128114. static long _vq_quantmap__44c6_s_p1_0[] = {
  128115. 1, 0, 2,
  128116. };
  128117. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  128118. _vq_quantthresh__44c6_s_p1_0,
  128119. _vq_quantmap__44c6_s_p1_0,
  128120. 3,
  128121. 3
  128122. };
  128123. static static_codebook _44c6_s_p1_0 = {
  128124. 4, 81,
  128125. _vq_lengthlist__44c6_s_p1_0,
  128126. 1, -535822336, 1611661312, 2, 0,
  128127. _vq_quantlist__44c6_s_p1_0,
  128128. NULL,
  128129. &_vq_auxt__44c6_s_p1_0,
  128130. NULL,
  128131. 0
  128132. };
  128133. static long _vq_quantlist__44c6_s_p2_0[] = {
  128134. 2,
  128135. 1,
  128136. 3,
  128137. 0,
  128138. 4,
  128139. };
  128140. static long _vq_lengthlist__44c6_s_p2_0[] = {
  128141. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128142. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128143. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128144. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128145. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  128146. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128147. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  128148. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128151. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128152. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128153. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128154. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128155. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  128156. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128159. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  128160. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  128161. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  128162. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  128163. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128164. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  128167. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128168. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128169. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  128170. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128171. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  128172. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128177. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  128178. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  128179. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128180. 13,
  128181. };
  128182. static float _vq_quantthresh__44c6_s_p2_0[] = {
  128183. -1.5, -0.5, 0.5, 1.5,
  128184. };
  128185. static long _vq_quantmap__44c6_s_p2_0[] = {
  128186. 3, 1, 0, 2, 4,
  128187. };
  128188. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  128189. _vq_quantthresh__44c6_s_p2_0,
  128190. _vq_quantmap__44c6_s_p2_0,
  128191. 5,
  128192. 5
  128193. };
  128194. static static_codebook _44c6_s_p2_0 = {
  128195. 4, 625,
  128196. _vq_lengthlist__44c6_s_p2_0,
  128197. 1, -533725184, 1611661312, 3, 0,
  128198. _vq_quantlist__44c6_s_p2_0,
  128199. NULL,
  128200. &_vq_auxt__44c6_s_p2_0,
  128201. NULL,
  128202. 0
  128203. };
  128204. static long _vq_quantlist__44c6_s_p3_0[] = {
  128205. 4,
  128206. 3,
  128207. 5,
  128208. 2,
  128209. 6,
  128210. 1,
  128211. 7,
  128212. 0,
  128213. 8,
  128214. };
  128215. static long _vq_lengthlist__44c6_s_p3_0[] = {
  128216. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128217. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  128218. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  128219. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0,
  128222. };
  128223. static float _vq_quantthresh__44c6_s_p3_0[] = {
  128224. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128225. };
  128226. static long _vq_quantmap__44c6_s_p3_0[] = {
  128227. 7, 5, 3, 1, 0, 2, 4, 6,
  128228. 8,
  128229. };
  128230. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  128231. _vq_quantthresh__44c6_s_p3_0,
  128232. _vq_quantmap__44c6_s_p3_0,
  128233. 9,
  128234. 9
  128235. };
  128236. static static_codebook _44c6_s_p3_0 = {
  128237. 2, 81,
  128238. _vq_lengthlist__44c6_s_p3_0,
  128239. 1, -531628032, 1611661312, 4, 0,
  128240. _vq_quantlist__44c6_s_p3_0,
  128241. NULL,
  128242. &_vq_auxt__44c6_s_p3_0,
  128243. NULL,
  128244. 0
  128245. };
  128246. static long _vq_quantlist__44c6_s_p4_0[] = {
  128247. 8,
  128248. 7,
  128249. 9,
  128250. 6,
  128251. 10,
  128252. 5,
  128253. 11,
  128254. 4,
  128255. 12,
  128256. 3,
  128257. 13,
  128258. 2,
  128259. 14,
  128260. 1,
  128261. 15,
  128262. 0,
  128263. 16,
  128264. };
  128265. static long _vq_lengthlist__44c6_s_p4_0[] = {
  128266. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  128267. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128268. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  128269. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128270. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128271. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128272. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  128273. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128274. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  128275. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0,
  128285. };
  128286. static float _vq_quantthresh__44c6_s_p4_0[] = {
  128287. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128288. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128289. };
  128290. static long _vq_quantmap__44c6_s_p4_0[] = {
  128291. 15, 13, 11, 9, 7, 5, 3, 1,
  128292. 0, 2, 4, 6, 8, 10, 12, 14,
  128293. 16,
  128294. };
  128295. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  128296. _vq_quantthresh__44c6_s_p4_0,
  128297. _vq_quantmap__44c6_s_p4_0,
  128298. 17,
  128299. 17
  128300. };
  128301. static static_codebook _44c6_s_p4_0 = {
  128302. 2, 289,
  128303. _vq_lengthlist__44c6_s_p4_0,
  128304. 1, -529530880, 1611661312, 5, 0,
  128305. _vq_quantlist__44c6_s_p4_0,
  128306. NULL,
  128307. &_vq_auxt__44c6_s_p4_0,
  128308. NULL,
  128309. 0
  128310. };
  128311. static long _vq_quantlist__44c6_s_p5_0[] = {
  128312. 1,
  128313. 0,
  128314. 2,
  128315. };
  128316. static long _vq_lengthlist__44c6_s_p5_0[] = {
  128317. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  128318. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  128319. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  128320. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128321. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  128322. 12,
  128323. };
  128324. static float _vq_quantthresh__44c6_s_p5_0[] = {
  128325. -5.5, 5.5,
  128326. };
  128327. static long _vq_quantmap__44c6_s_p5_0[] = {
  128328. 1, 0, 2,
  128329. };
  128330. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  128331. _vq_quantthresh__44c6_s_p5_0,
  128332. _vq_quantmap__44c6_s_p5_0,
  128333. 3,
  128334. 3
  128335. };
  128336. static static_codebook _44c6_s_p5_0 = {
  128337. 4, 81,
  128338. _vq_lengthlist__44c6_s_p5_0,
  128339. 1, -529137664, 1618345984, 2, 0,
  128340. _vq_quantlist__44c6_s_p5_0,
  128341. NULL,
  128342. &_vq_auxt__44c6_s_p5_0,
  128343. NULL,
  128344. 0
  128345. };
  128346. static long _vq_quantlist__44c6_s_p5_1[] = {
  128347. 5,
  128348. 4,
  128349. 6,
  128350. 3,
  128351. 7,
  128352. 2,
  128353. 8,
  128354. 1,
  128355. 9,
  128356. 0,
  128357. 10,
  128358. };
  128359. static long _vq_lengthlist__44c6_s_p5_1[] = {
  128360. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  128361. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  128362. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  128363. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  128364. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  128365. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  128366. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  128367. 11,10,10, 7, 7, 8, 8, 8, 8,
  128368. };
  128369. static float _vq_quantthresh__44c6_s_p5_1[] = {
  128370. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128371. 3.5, 4.5,
  128372. };
  128373. static long _vq_quantmap__44c6_s_p5_1[] = {
  128374. 9, 7, 5, 3, 1, 0, 2, 4,
  128375. 6, 8, 10,
  128376. };
  128377. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  128378. _vq_quantthresh__44c6_s_p5_1,
  128379. _vq_quantmap__44c6_s_p5_1,
  128380. 11,
  128381. 11
  128382. };
  128383. static static_codebook _44c6_s_p5_1 = {
  128384. 2, 121,
  128385. _vq_lengthlist__44c6_s_p5_1,
  128386. 1, -531365888, 1611661312, 4, 0,
  128387. _vq_quantlist__44c6_s_p5_1,
  128388. NULL,
  128389. &_vq_auxt__44c6_s_p5_1,
  128390. NULL,
  128391. 0
  128392. };
  128393. static long _vq_quantlist__44c6_s_p6_0[] = {
  128394. 6,
  128395. 5,
  128396. 7,
  128397. 4,
  128398. 8,
  128399. 3,
  128400. 9,
  128401. 2,
  128402. 10,
  128403. 1,
  128404. 11,
  128405. 0,
  128406. 12,
  128407. };
  128408. static long _vq_lengthlist__44c6_s_p6_0[] = {
  128409. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  128410. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  128411. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  128412. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128413. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  128414. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. };
  128421. static float _vq_quantthresh__44c6_s_p6_0[] = {
  128422. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128423. 12.5, 17.5, 22.5, 27.5,
  128424. };
  128425. static long _vq_quantmap__44c6_s_p6_0[] = {
  128426. 11, 9, 7, 5, 3, 1, 0, 2,
  128427. 4, 6, 8, 10, 12,
  128428. };
  128429. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  128430. _vq_quantthresh__44c6_s_p6_0,
  128431. _vq_quantmap__44c6_s_p6_0,
  128432. 13,
  128433. 13
  128434. };
  128435. static static_codebook _44c6_s_p6_0 = {
  128436. 2, 169,
  128437. _vq_lengthlist__44c6_s_p6_0,
  128438. 1, -526516224, 1616117760, 4, 0,
  128439. _vq_quantlist__44c6_s_p6_0,
  128440. NULL,
  128441. &_vq_auxt__44c6_s_p6_0,
  128442. NULL,
  128443. 0
  128444. };
  128445. static long _vq_quantlist__44c6_s_p6_1[] = {
  128446. 2,
  128447. 1,
  128448. 3,
  128449. 0,
  128450. 4,
  128451. };
  128452. static long _vq_lengthlist__44c6_s_p6_1[] = {
  128453. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128454. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128455. };
  128456. static float _vq_quantthresh__44c6_s_p6_1[] = {
  128457. -1.5, -0.5, 0.5, 1.5,
  128458. };
  128459. static long _vq_quantmap__44c6_s_p6_1[] = {
  128460. 3, 1, 0, 2, 4,
  128461. };
  128462. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  128463. _vq_quantthresh__44c6_s_p6_1,
  128464. _vq_quantmap__44c6_s_p6_1,
  128465. 5,
  128466. 5
  128467. };
  128468. static static_codebook _44c6_s_p6_1 = {
  128469. 2, 25,
  128470. _vq_lengthlist__44c6_s_p6_1,
  128471. 1, -533725184, 1611661312, 3, 0,
  128472. _vq_quantlist__44c6_s_p6_1,
  128473. NULL,
  128474. &_vq_auxt__44c6_s_p6_1,
  128475. NULL,
  128476. 0
  128477. };
  128478. static long _vq_quantlist__44c6_s_p7_0[] = {
  128479. 6,
  128480. 5,
  128481. 7,
  128482. 4,
  128483. 8,
  128484. 3,
  128485. 9,
  128486. 2,
  128487. 10,
  128488. 1,
  128489. 11,
  128490. 0,
  128491. 12,
  128492. };
  128493. static long _vq_lengthlist__44c6_s_p7_0[] = {
  128494. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  128495. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  128496. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  128497. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128498. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  128499. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  128500. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  128501. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  128502. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  128503. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  128504. 20,13,13,13,13,13,13,14,14,
  128505. };
  128506. static float _vq_quantthresh__44c6_s_p7_0[] = {
  128507. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128508. 27.5, 38.5, 49.5, 60.5,
  128509. };
  128510. static long _vq_quantmap__44c6_s_p7_0[] = {
  128511. 11, 9, 7, 5, 3, 1, 0, 2,
  128512. 4, 6, 8, 10, 12,
  128513. };
  128514. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  128515. _vq_quantthresh__44c6_s_p7_0,
  128516. _vq_quantmap__44c6_s_p7_0,
  128517. 13,
  128518. 13
  128519. };
  128520. static static_codebook _44c6_s_p7_0 = {
  128521. 2, 169,
  128522. _vq_lengthlist__44c6_s_p7_0,
  128523. 1, -523206656, 1618345984, 4, 0,
  128524. _vq_quantlist__44c6_s_p7_0,
  128525. NULL,
  128526. &_vq_auxt__44c6_s_p7_0,
  128527. NULL,
  128528. 0
  128529. };
  128530. static long _vq_quantlist__44c6_s_p7_1[] = {
  128531. 5,
  128532. 4,
  128533. 6,
  128534. 3,
  128535. 7,
  128536. 2,
  128537. 8,
  128538. 1,
  128539. 9,
  128540. 0,
  128541. 10,
  128542. };
  128543. static long _vq_lengthlist__44c6_s_p7_1[] = {
  128544. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  128545. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  128546. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  128547. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  128548. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  128549. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  128550. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  128551. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  128552. };
  128553. static float _vq_quantthresh__44c6_s_p7_1[] = {
  128554. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128555. 3.5, 4.5,
  128556. };
  128557. static long _vq_quantmap__44c6_s_p7_1[] = {
  128558. 9, 7, 5, 3, 1, 0, 2, 4,
  128559. 6, 8, 10,
  128560. };
  128561. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  128562. _vq_quantthresh__44c6_s_p7_1,
  128563. _vq_quantmap__44c6_s_p7_1,
  128564. 11,
  128565. 11
  128566. };
  128567. static static_codebook _44c6_s_p7_1 = {
  128568. 2, 121,
  128569. _vq_lengthlist__44c6_s_p7_1,
  128570. 1, -531365888, 1611661312, 4, 0,
  128571. _vq_quantlist__44c6_s_p7_1,
  128572. NULL,
  128573. &_vq_auxt__44c6_s_p7_1,
  128574. NULL,
  128575. 0
  128576. };
  128577. static long _vq_quantlist__44c6_s_p8_0[] = {
  128578. 7,
  128579. 6,
  128580. 8,
  128581. 5,
  128582. 9,
  128583. 4,
  128584. 10,
  128585. 3,
  128586. 11,
  128587. 2,
  128588. 12,
  128589. 1,
  128590. 13,
  128591. 0,
  128592. 14,
  128593. };
  128594. static long _vq_lengthlist__44c6_s_p8_0[] = {
  128595. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  128596. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  128597. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  128598. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  128599. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  128600. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  128601. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  128602. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  128603. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  128604. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  128605. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  128606. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  128607. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  128608. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  128609. 14,
  128610. };
  128611. static float _vq_quantthresh__44c6_s_p8_0[] = {
  128612. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128613. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128614. };
  128615. static long _vq_quantmap__44c6_s_p8_0[] = {
  128616. 13, 11, 9, 7, 5, 3, 1, 0,
  128617. 2, 4, 6, 8, 10, 12, 14,
  128618. };
  128619. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  128620. _vq_quantthresh__44c6_s_p8_0,
  128621. _vq_quantmap__44c6_s_p8_0,
  128622. 15,
  128623. 15
  128624. };
  128625. static static_codebook _44c6_s_p8_0 = {
  128626. 2, 225,
  128627. _vq_lengthlist__44c6_s_p8_0,
  128628. 1, -520986624, 1620377600, 4, 0,
  128629. _vq_quantlist__44c6_s_p8_0,
  128630. NULL,
  128631. &_vq_auxt__44c6_s_p8_0,
  128632. NULL,
  128633. 0
  128634. };
  128635. static long _vq_quantlist__44c6_s_p8_1[] = {
  128636. 10,
  128637. 9,
  128638. 11,
  128639. 8,
  128640. 12,
  128641. 7,
  128642. 13,
  128643. 6,
  128644. 14,
  128645. 5,
  128646. 15,
  128647. 4,
  128648. 16,
  128649. 3,
  128650. 17,
  128651. 2,
  128652. 18,
  128653. 1,
  128654. 19,
  128655. 0,
  128656. 20,
  128657. };
  128658. static long _vq_lengthlist__44c6_s_p8_1[] = {
  128659. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  128660. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  128661. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128662. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128663. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128664. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  128665. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  128666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  128667. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128668. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128669. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  128670. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  128671. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  128672. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  128673. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  128674. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  128675. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  128676. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  128677. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  128678. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  128679. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  128680. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128681. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  128682. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128683. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  128684. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  128685. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  128686. 10,10,10,10,10,10,10,10,10,
  128687. };
  128688. static float _vq_quantthresh__44c6_s_p8_1[] = {
  128689. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128690. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128691. 6.5, 7.5, 8.5, 9.5,
  128692. };
  128693. static long _vq_quantmap__44c6_s_p8_1[] = {
  128694. 19, 17, 15, 13, 11, 9, 7, 5,
  128695. 3, 1, 0, 2, 4, 6, 8, 10,
  128696. 12, 14, 16, 18, 20,
  128697. };
  128698. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  128699. _vq_quantthresh__44c6_s_p8_1,
  128700. _vq_quantmap__44c6_s_p8_1,
  128701. 21,
  128702. 21
  128703. };
  128704. static static_codebook _44c6_s_p8_1 = {
  128705. 2, 441,
  128706. _vq_lengthlist__44c6_s_p8_1,
  128707. 1, -529268736, 1611661312, 5, 0,
  128708. _vq_quantlist__44c6_s_p8_1,
  128709. NULL,
  128710. &_vq_auxt__44c6_s_p8_1,
  128711. NULL,
  128712. 0
  128713. };
  128714. static long _vq_quantlist__44c6_s_p9_0[] = {
  128715. 6,
  128716. 5,
  128717. 7,
  128718. 4,
  128719. 8,
  128720. 3,
  128721. 9,
  128722. 2,
  128723. 10,
  128724. 1,
  128725. 11,
  128726. 0,
  128727. 12,
  128728. };
  128729. static long _vq_lengthlist__44c6_s_p9_0[] = {
  128730. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  128731. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  128732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128733. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  128734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128735. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128736. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128737. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128738. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128739. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128740. 10,10,10,10,10,10,10,10,10,
  128741. };
  128742. static float _vq_quantthresh__44c6_s_p9_0[] = {
  128743. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  128744. 1592.5, 2229.5, 2866.5, 3503.5,
  128745. };
  128746. static long _vq_quantmap__44c6_s_p9_0[] = {
  128747. 11, 9, 7, 5, 3, 1, 0, 2,
  128748. 4, 6, 8, 10, 12,
  128749. };
  128750. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  128751. _vq_quantthresh__44c6_s_p9_0,
  128752. _vq_quantmap__44c6_s_p9_0,
  128753. 13,
  128754. 13
  128755. };
  128756. static static_codebook _44c6_s_p9_0 = {
  128757. 2, 169,
  128758. _vq_lengthlist__44c6_s_p9_0,
  128759. 1, -511845376, 1630791680, 4, 0,
  128760. _vq_quantlist__44c6_s_p9_0,
  128761. NULL,
  128762. &_vq_auxt__44c6_s_p9_0,
  128763. NULL,
  128764. 0
  128765. };
  128766. static long _vq_quantlist__44c6_s_p9_1[] = {
  128767. 6,
  128768. 5,
  128769. 7,
  128770. 4,
  128771. 8,
  128772. 3,
  128773. 9,
  128774. 2,
  128775. 10,
  128776. 1,
  128777. 11,
  128778. 0,
  128779. 12,
  128780. };
  128781. static long _vq_lengthlist__44c6_s_p9_1[] = {
  128782. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128783. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  128784. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  128785. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  128786. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  128787. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  128788. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  128789. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  128790. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  128791. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  128792. 15,12,10,11,11,13,11,12,13,
  128793. };
  128794. static float _vq_quantthresh__44c6_s_p9_1[] = {
  128795. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128796. 122.5, 171.5, 220.5, 269.5,
  128797. };
  128798. static long _vq_quantmap__44c6_s_p9_1[] = {
  128799. 11, 9, 7, 5, 3, 1, 0, 2,
  128800. 4, 6, 8, 10, 12,
  128801. };
  128802. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  128803. _vq_quantthresh__44c6_s_p9_1,
  128804. _vq_quantmap__44c6_s_p9_1,
  128805. 13,
  128806. 13
  128807. };
  128808. static static_codebook _44c6_s_p9_1 = {
  128809. 2, 169,
  128810. _vq_lengthlist__44c6_s_p9_1,
  128811. 1, -518889472, 1622704128, 4, 0,
  128812. _vq_quantlist__44c6_s_p9_1,
  128813. NULL,
  128814. &_vq_auxt__44c6_s_p9_1,
  128815. NULL,
  128816. 0
  128817. };
  128818. static long _vq_quantlist__44c6_s_p9_2[] = {
  128819. 24,
  128820. 23,
  128821. 25,
  128822. 22,
  128823. 26,
  128824. 21,
  128825. 27,
  128826. 20,
  128827. 28,
  128828. 19,
  128829. 29,
  128830. 18,
  128831. 30,
  128832. 17,
  128833. 31,
  128834. 16,
  128835. 32,
  128836. 15,
  128837. 33,
  128838. 14,
  128839. 34,
  128840. 13,
  128841. 35,
  128842. 12,
  128843. 36,
  128844. 11,
  128845. 37,
  128846. 10,
  128847. 38,
  128848. 9,
  128849. 39,
  128850. 8,
  128851. 40,
  128852. 7,
  128853. 41,
  128854. 6,
  128855. 42,
  128856. 5,
  128857. 43,
  128858. 4,
  128859. 44,
  128860. 3,
  128861. 45,
  128862. 2,
  128863. 46,
  128864. 1,
  128865. 47,
  128866. 0,
  128867. 48,
  128868. };
  128869. static long _vq_lengthlist__44c6_s_p9_2[] = {
  128870. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128871. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128872. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128873. 7,
  128874. };
  128875. static float _vq_quantthresh__44c6_s_p9_2[] = {
  128876. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128877. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128878. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128879. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128880. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128881. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128882. };
  128883. static long _vq_quantmap__44c6_s_p9_2[] = {
  128884. 47, 45, 43, 41, 39, 37, 35, 33,
  128885. 31, 29, 27, 25, 23, 21, 19, 17,
  128886. 15, 13, 11, 9, 7, 5, 3, 1,
  128887. 0, 2, 4, 6, 8, 10, 12, 14,
  128888. 16, 18, 20, 22, 24, 26, 28, 30,
  128889. 32, 34, 36, 38, 40, 42, 44, 46,
  128890. 48,
  128891. };
  128892. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  128893. _vq_quantthresh__44c6_s_p9_2,
  128894. _vq_quantmap__44c6_s_p9_2,
  128895. 49,
  128896. 49
  128897. };
  128898. static static_codebook _44c6_s_p9_2 = {
  128899. 1, 49,
  128900. _vq_lengthlist__44c6_s_p9_2,
  128901. 1, -526909440, 1611661312, 6, 0,
  128902. _vq_quantlist__44c6_s_p9_2,
  128903. NULL,
  128904. &_vq_auxt__44c6_s_p9_2,
  128905. NULL,
  128906. 0
  128907. };
  128908. static long _huff_lengthlist__44c6_s_short[] = {
  128909. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  128910. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  128911. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  128912. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  128913. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  128914. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  128915. 9,10,17,18,
  128916. };
  128917. static static_codebook _huff_book__44c6_s_short = {
  128918. 2, 100,
  128919. _huff_lengthlist__44c6_s_short,
  128920. 0, 0, 0, 0, 0,
  128921. NULL,
  128922. NULL,
  128923. NULL,
  128924. NULL,
  128925. 0
  128926. };
  128927. static long _huff_lengthlist__44c7_s_long[] = {
  128928. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  128929. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  128930. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  128931. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  128932. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  128933. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  128934. 11,10,10,12,
  128935. };
  128936. static static_codebook _huff_book__44c7_s_long = {
  128937. 2, 100,
  128938. _huff_lengthlist__44c7_s_long,
  128939. 0, 0, 0, 0, 0,
  128940. NULL,
  128941. NULL,
  128942. NULL,
  128943. NULL,
  128944. 0
  128945. };
  128946. static long _vq_quantlist__44c7_s_p1_0[] = {
  128947. 1,
  128948. 0,
  128949. 2,
  128950. };
  128951. static long _vq_lengthlist__44c7_s_p1_0[] = {
  128952. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128953. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128955. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128956. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128957. 8,
  128958. };
  128959. static float _vq_quantthresh__44c7_s_p1_0[] = {
  128960. -0.5, 0.5,
  128961. };
  128962. static long _vq_quantmap__44c7_s_p1_0[] = {
  128963. 1, 0, 2,
  128964. };
  128965. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  128966. _vq_quantthresh__44c7_s_p1_0,
  128967. _vq_quantmap__44c7_s_p1_0,
  128968. 3,
  128969. 3
  128970. };
  128971. static static_codebook _44c7_s_p1_0 = {
  128972. 4, 81,
  128973. _vq_lengthlist__44c7_s_p1_0,
  128974. 1, -535822336, 1611661312, 2, 0,
  128975. _vq_quantlist__44c7_s_p1_0,
  128976. NULL,
  128977. &_vq_auxt__44c7_s_p1_0,
  128978. NULL,
  128979. 0
  128980. };
  128981. static long _vq_quantlist__44c7_s_p2_0[] = {
  128982. 2,
  128983. 1,
  128984. 3,
  128985. 0,
  128986. 4,
  128987. };
  128988. static long _vq_lengthlist__44c7_s_p2_0[] = {
  128989. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128990. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128991. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128992. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128993. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128994. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128995. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  128996. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128999. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  129000. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129001. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  129002. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  129003. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  129004. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  129007. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  129008. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  129009. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  129010. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  129011. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  129012. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129015. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  129016. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129017. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  129018. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  129019. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  129020. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129025. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  129026. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129027. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  129028. 13,
  129029. };
  129030. static float _vq_quantthresh__44c7_s_p2_0[] = {
  129031. -1.5, -0.5, 0.5, 1.5,
  129032. };
  129033. static long _vq_quantmap__44c7_s_p2_0[] = {
  129034. 3, 1, 0, 2, 4,
  129035. };
  129036. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  129037. _vq_quantthresh__44c7_s_p2_0,
  129038. _vq_quantmap__44c7_s_p2_0,
  129039. 5,
  129040. 5
  129041. };
  129042. static static_codebook _44c7_s_p2_0 = {
  129043. 4, 625,
  129044. _vq_lengthlist__44c7_s_p2_0,
  129045. 1, -533725184, 1611661312, 3, 0,
  129046. _vq_quantlist__44c7_s_p2_0,
  129047. NULL,
  129048. &_vq_auxt__44c7_s_p2_0,
  129049. NULL,
  129050. 0
  129051. };
  129052. static long _vq_quantlist__44c7_s_p3_0[] = {
  129053. 4,
  129054. 3,
  129055. 5,
  129056. 2,
  129057. 6,
  129058. 1,
  129059. 7,
  129060. 0,
  129061. 8,
  129062. };
  129063. static long _vq_lengthlist__44c7_s_p3_0[] = {
  129064. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129065. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129066. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129067. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0,
  129070. };
  129071. static float _vq_quantthresh__44c7_s_p3_0[] = {
  129072. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129073. };
  129074. static long _vq_quantmap__44c7_s_p3_0[] = {
  129075. 7, 5, 3, 1, 0, 2, 4, 6,
  129076. 8,
  129077. };
  129078. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  129079. _vq_quantthresh__44c7_s_p3_0,
  129080. _vq_quantmap__44c7_s_p3_0,
  129081. 9,
  129082. 9
  129083. };
  129084. static static_codebook _44c7_s_p3_0 = {
  129085. 2, 81,
  129086. _vq_lengthlist__44c7_s_p3_0,
  129087. 1, -531628032, 1611661312, 4, 0,
  129088. _vq_quantlist__44c7_s_p3_0,
  129089. NULL,
  129090. &_vq_auxt__44c7_s_p3_0,
  129091. NULL,
  129092. 0
  129093. };
  129094. static long _vq_quantlist__44c7_s_p4_0[] = {
  129095. 8,
  129096. 7,
  129097. 9,
  129098. 6,
  129099. 10,
  129100. 5,
  129101. 11,
  129102. 4,
  129103. 12,
  129104. 3,
  129105. 13,
  129106. 2,
  129107. 14,
  129108. 1,
  129109. 15,
  129110. 0,
  129111. 16,
  129112. };
  129113. static long _vq_lengthlist__44c7_s_p4_0[] = {
  129114. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129115. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  129116. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129117. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  129118. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  129119. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129120. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129121. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129122. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129123. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0,
  129133. };
  129134. static float _vq_quantthresh__44c7_s_p4_0[] = {
  129135. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129136. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129137. };
  129138. static long _vq_quantmap__44c7_s_p4_0[] = {
  129139. 15, 13, 11, 9, 7, 5, 3, 1,
  129140. 0, 2, 4, 6, 8, 10, 12, 14,
  129141. 16,
  129142. };
  129143. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  129144. _vq_quantthresh__44c7_s_p4_0,
  129145. _vq_quantmap__44c7_s_p4_0,
  129146. 17,
  129147. 17
  129148. };
  129149. static static_codebook _44c7_s_p4_0 = {
  129150. 2, 289,
  129151. _vq_lengthlist__44c7_s_p4_0,
  129152. 1, -529530880, 1611661312, 5, 0,
  129153. _vq_quantlist__44c7_s_p4_0,
  129154. NULL,
  129155. &_vq_auxt__44c7_s_p4_0,
  129156. NULL,
  129157. 0
  129158. };
  129159. static long _vq_quantlist__44c7_s_p5_0[] = {
  129160. 1,
  129161. 0,
  129162. 2,
  129163. };
  129164. static long _vq_lengthlist__44c7_s_p5_0[] = {
  129165. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  129166. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129167. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129168. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  129169. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  129170. 12,
  129171. };
  129172. static float _vq_quantthresh__44c7_s_p5_0[] = {
  129173. -5.5, 5.5,
  129174. };
  129175. static long _vq_quantmap__44c7_s_p5_0[] = {
  129176. 1, 0, 2,
  129177. };
  129178. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  129179. _vq_quantthresh__44c7_s_p5_0,
  129180. _vq_quantmap__44c7_s_p5_0,
  129181. 3,
  129182. 3
  129183. };
  129184. static static_codebook _44c7_s_p5_0 = {
  129185. 4, 81,
  129186. _vq_lengthlist__44c7_s_p5_0,
  129187. 1, -529137664, 1618345984, 2, 0,
  129188. _vq_quantlist__44c7_s_p5_0,
  129189. NULL,
  129190. &_vq_auxt__44c7_s_p5_0,
  129191. NULL,
  129192. 0
  129193. };
  129194. static long _vq_quantlist__44c7_s_p5_1[] = {
  129195. 5,
  129196. 4,
  129197. 6,
  129198. 3,
  129199. 7,
  129200. 2,
  129201. 8,
  129202. 1,
  129203. 9,
  129204. 0,
  129205. 10,
  129206. };
  129207. static long _vq_lengthlist__44c7_s_p5_1[] = {
  129208. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129209. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  129210. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  129211. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  129212. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  129213. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  129214. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  129215. 11,11,11, 7, 7, 8, 8, 8, 8,
  129216. };
  129217. static float _vq_quantthresh__44c7_s_p5_1[] = {
  129218. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129219. 3.5, 4.5,
  129220. };
  129221. static long _vq_quantmap__44c7_s_p5_1[] = {
  129222. 9, 7, 5, 3, 1, 0, 2, 4,
  129223. 6, 8, 10,
  129224. };
  129225. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  129226. _vq_quantthresh__44c7_s_p5_1,
  129227. _vq_quantmap__44c7_s_p5_1,
  129228. 11,
  129229. 11
  129230. };
  129231. static static_codebook _44c7_s_p5_1 = {
  129232. 2, 121,
  129233. _vq_lengthlist__44c7_s_p5_1,
  129234. 1, -531365888, 1611661312, 4, 0,
  129235. _vq_quantlist__44c7_s_p5_1,
  129236. NULL,
  129237. &_vq_auxt__44c7_s_p5_1,
  129238. NULL,
  129239. 0
  129240. };
  129241. static long _vq_quantlist__44c7_s_p6_0[] = {
  129242. 6,
  129243. 5,
  129244. 7,
  129245. 4,
  129246. 8,
  129247. 3,
  129248. 9,
  129249. 2,
  129250. 10,
  129251. 1,
  129252. 11,
  129253. 0,
  129254. 12,
  129255. };
  129256. static long _vq_lengthlist__44c7_s_p6_0[] = {
  129257. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  129258. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129259. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  129260. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  129261. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  129262. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. };
  129269. static float _vq_quantthresh__44c7_s_p6_0[] = {
  129270. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129271. 12.5, 17.5, 22.5, 27.5,
  129272. };
  129273. static long _vq_quantmap__44c7_s_p6_0[] = {
  129274. 11, 9, 7, 5, 3, 1, 0, 2,
  129275. 4, 6, 8, 10, 12,
  129276. };
  129277. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  129278. _vq_quantthresh__44c7_s_p6_0,
  129279. _vq_quantmap__44c7_s_p6_0,
  129280. 13,
  129281. 13
  129282. };
  129283. static static_codebook _44c7_s_p6_0 = {
  129284. 2, 169,
  129285. _vq_lengthlist__44c7_s_p6_0,
  129286. 1, -526516224, 1616117760, 4, 0,
  129287. _vq_quantlist__44c7_s_p6_0,
  129288. NULL,
  129289. &_vq_auxt__44c7_s_p6_0,
  129290. NULL,
  129291. 0
  129292. };
  129293. static long _vq_quantlist__44c7_s_p6_1[] = {
  129294. 2,
  129295. 1,
  129296. 3,
  129297. 0,
  129298. 4,
  129299. };
  129300. static long _vq_lengthlist__44c7_s_p6_1[] = {
  129301. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129302. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129303. };
  129304. static float _vq_quantthresh__44c7_s_p6_1[] = {
  129305. -1.5, -0.5, 0.5, 1.5,
  129306. };
  129307. static long _vq_quantmap__44c7_s_p6_1[] = {
  129308. 3, 1, 0, 2, 4,
  129309. };
  129310. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  129311. _vq_quantthresh__44c7_s_p6_1,
  129312. _vq_quantmap__44c7_s_p6_1,
  129313. 5,
  129314. 5
  129315. };
  129316. static static_codebook _44c7_s_p6_1 = {
  129317. 2, 25,
  129318. _vq_lengthlist__44c7_s_p6_1,
  129319. 1, -533725184, 1611661312, 3, 0,
  129320. _vq_quantlist__44c7_s_p6_1,
  129321. NULL,
  129322. &_vq_auxt__44c7_s_p6_1,
  129323. NULL,
  129324. 0
  129325. };
  129326. static long _vq_quantlist__44c7_s_p7_0[] = {
  129327. 6,
  129328. 5,
  129329. 7,
  129330. 4,
  129331. 8,
  129332. 3,
  129333. 9,
  129334. 2,
  129335. 10,
  129336. 1,
  129337. 11,
  129338. 0,
  129339. 12,
  129340. };
  129341. static long _vq_lengthlist__44c7_s_p7_0[] = {
  129342. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  129343. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  129344. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  129345. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  129346. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  129347. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  129348. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  129349. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  129350. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  129351. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  129352. 19,13,13,13,13,14,14,15,15,
  129353. };
  129354. static float _vq_quantthresh__44c7_s_p7_0[] = {
  129355. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129356. 27.5, 38.5, 49.5, 60.5,
  129357. };
  129358. static long _vq_quantmap__44c7_s_p7_0[] = {
  129359. 11, 9, 7, 5, 3, 1, 0, 2,
  129360. 4, 6, 8, 10, 12,
  129361. };
  129362. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  129363. _vq_quantthresh__44c7_s_p7_0,
  129364. _vq_quantmap__44c7_s_p7_0,
  129365. 13,
  129366. 13
  129367. };
  129368. static static_codebook _44c7_s_p7_0 = {
  129369. 2, 169,
  129370. _vq_lengthlist__44c7_s_p7_0,
  129371. 1, -523206656, 1618345984, 4, 0,
  129372. _vq_quantlist__44c7_s_p7_0,
  129373. NULL,
  129374. &_vq_auxt__44c7_s_p7_0,
  129375. NULL,
  129376. 0
  129377. };
  129378. static long _vq_quantlist__44c7_s_p7_1[] = {
  129379. 5,
  129380. 4,
  129381. 6,
  129382. 3,
  129383. 7,
  129384. 2,
  129385. 8,
  129386. 1,
  129387. 9,
  129388. 0,
  129389. 10,
  129390. };
  129391. static long _vq_lengthlist__44c7_s_p7_1[] = {
  129392. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  129393. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  129394. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  129395. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129396. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129397. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129398. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129399. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129400. };
  129401. static float _vq_quantthresh__44c7_s_p7_1[] = {
  129402. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129403. 3.5, 4.5,
  129404. };
  129405. static long _vq_quantmap__44c7_s_p7_1[] = {
  129406. 9, 7, 5, 3, 1, 0, 2, 4,
  129407. 6, 8, 10,
  129408. };
  129409. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  129410. _vq_quantthresh__44c7_s_p7_1,
  129411. _vq_quantmap__44c7_s_p7_1,
  129412. 11,
  129413. 11
  129414. };
  129415. static static_codebook _44c7_s_p7_1 = {
  129416. 2, 121,
  129417. _vq_lengthlist__44c7_s_p7_1,
  129418. 1, -531365888, 1611661312, 4, 0,
  129419. _vq_quantlist__44c7_s_p7_1,
  129420. NULL,
  129421. &_vq_auxt__44c7_s_p7_1,
  129422. NULL,
  129423. 0
  129424. };
  129425. static long _vq_quantlist__44c7_s_p8_0[] = {
  129426. 7,
  129427. 6,
  129428. 8,
  129429. 5,
  129430. 9,
  129431. 4,
  129432. 10,
  129433. 3,
  129434. 11,
  129435. 2,
  129436. 12,
  129437. 1,
  129438. 13,
  129439. 0,
  129440. 14,
  129441. };
  129442. static long _vq_lengthlist__44c7_s_p8_0[] = {
  129443. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  129444. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  129445. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  129446. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  129447. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  129448. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  129449. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  129450. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  129451. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  129452. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  129453. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  129454. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  129455. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  129456. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  129457. 14,
  129458. };
  129459. static float _vq_quantthresh__44c7_s_p8_0[] = {
  129460. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129461. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129462. };
  129463. static long _vq_quantmap__44c7_s_p8_0[] = {
  129464. 13, 11, 9, 7, 5, 3, 1, 0,
  129465. 2, 4, 6, 8, 10, 12, 14,
  129466. };
  129467. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  129468. _vq_quantthresh__44c7_s_p8_0,
  129469. _vq_quantmap__44c7_s_p8_0,
  129470. 15,
  129471. 15
  129472. };
  129473. static static_codebook _44c7_s_p8_0 = {
  129474. 2, 225,
  129475. _vq_lengthlist__44c7_s_p8_0,
  129476. 1, -520986624, 1620377600, 4, 0,
  129477. _vq_quantlist__44c7_s_p8_0,
  129478. NULL,
  129479. &_vq_auxt__44c7_s_p8_0,
  129480. NULL,
  129481. 0
  129482. };
  129483. static long _vq_quantlist__44c7_s_p8_1[] = {
  129484. 10,
  129485. 9,
  129486. 11,
  129487. 8,
  129488. 12,
  129489. 7,
  129490. 13,
  129491. 6,
  129492. 14,
  129493. 5,
  129494. 15,
  129495. 4,
  129496. 16,
  129497. 3,
  129498. 17,
  129499. 2,
  129500. 18,
  129501. 1,
  129502. 19,
  129503. 0,
  129504. 20,
  129505. };
  129506. static long _vq_lengthlist__44c7_s_p8_1[] = {
  129507. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129508. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129509. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129510. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129511. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129512. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129513. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  129514. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129515. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129516. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129517. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  129518. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  129519. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  129520. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  129521. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  129522. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  129523. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  129524. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  129525. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  129526. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  129527. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  129528. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  129529. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  129530. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  129531. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  129532. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  129533. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  129534. 10,10,10,10,10,10,10,10,10,
  129535. };
  129536. static float _vq_quantthresh__44c7_s_p8_1[] = {
  129537. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129538. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129539. 6.5, 7.5, 8.5, 9.5,
  129540. };
  129541. static long _vq_quantmap__44c7_s_p8_1[] = {
  129542. 19, 17, 15, 13, 11, 9, 7, 5,
  129543. 3, 1, 0, 2, 4, 6, 8, 10,
  129544. 12, 14, 16, 18, 20,
  129545. };
  129546. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  129547. _vq_quantthresh__44c7_s_p8_1,
  129548. _vq_quantmap__44c7_s_p8_1,
  129549. 21,
  129550. 21
  129551. };
  129552. static static_codebook _44c7_s_p8_1 = {
  129553. 2, 441,
  129554. _vq_lengthlist__44c7_s_p8_1,
  129555. 1, -529268736, 1611661312, 5, 0,
  129556. _vq_quantlist__44c7_s_p8_1,
  129557. NULL,
  129558. &_vq_auxt__44c7_s_p8_1,
  129559. NULL,
  129560. 0
  129561. };
  129562. static long _vq_quantlist__44c7_s_p9_0[] = {
  129563. 6,
  129564. 5,
  129565. 7,
  129566. 4,
  129567. 8,
  129568. 3,
  129569. 9,
  129570. 2,
  129571. 10,
  129572. 1,
  129573. 11,
  129574. 0,
  129575. 12,
  129576. };
  129577. static long _vq_lengthlist__44c7_s_p9_0[] = {
  129578. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  129579. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  129580. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129581. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129582. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129583. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129584. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129585. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129586. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129587. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129588. 11,11,11,11,11,11,11,11,11,
  129589. };
  129590. static float _vq_quantthresh__44c7_s_p9_0[] = {
  129591. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  129592. 1592.5, 2229.5, 2866.5, 3503.5,
  129593. };
  129594. static long _vq_quantmap__44c7_s_p9_0[] = {
  129595. 11, 9, 7, 5, 3, 1, 0, 2,
  129596. 4, 6, 8, 10, 12,
  129597. };
  129598. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  129599. _vq_quantthresh__44c7_s_p9_0,
  129600. _vq_quantmap__44c7_s_p9_0,
  129601. 13,
  129602. 13
  129603. };
  129604. static static_codebook _44c7_s_p9_0 = {
  129605. 2, 169,
  129606. _vq_lengthlist__44c7_s_p9_0,
  129607. 1, -511845376, 1630791680, 4, 0,
  129608. _vq_quantlist__44c7_s_p9_0,
  129609. NULL,
  129610. &_vq_auxt__44c7_s_p9_0,
  129611. NULL,
  129612. 0
  129613. };
  129614. static long _vq_quantlist__44c7_s_p9_1[] = {
  129615. 6,
  129616. 5,
  129617. 7,
  129618. 4,
  129619. 8,
  129620. 3,
  129621. 9,
  129622. 2,
  129623. 10,
  129624. 1,
  129625. 11,
  129626. 0,
  129627. 12,
  129628. };
  129629. static long _vq_lengthlist__44c7_s_p9_1[] = {
  129630. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  129631. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  129632. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  129633. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  129634. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  129635. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  129636. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  129637. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  129638. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  129639. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  129640. 15,11,11,10,10,12,12,12,12,
  129641. };
  129642. static float _vq_quantthresh__44c7_s_p9_1[] = {
  129643. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  129644. 122.5, 171.5, 220.5, 269.5,
  129645. };
  129646. static long _vq_quantmap__44c7_s_p9_1[] = {
  129647. 11, 9, 7, 5, 3, 1, 0, 2,
  129648. 4, 6, 8, 10, 12,
  129649. };
  129650. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  129651. _vq_quantthresh__44c7_s_p9_1,
  129652. _vq_quantmap__44c7_s_p9_1,
  129653. 13,
  129654. 13
  129655. };
  129656. static static_codebook _44c7_s_p9_1 = {
  129657. 2, 169,
  129658. _vq_lengthlist__44c7_s_p9_1,
  129659. 1, -518889472, 1622704128, 4, 0,
  129660. _vq_quantlist__44c7_s_p9_1,
  129661. NULL,
  129662. &_vq_auxt__44c7_s_p9_1,
  129663. NULL,
  129664. 0
  129665. };
  129666. static long _vq_quantlist__44c7_s_p9_2[] = {
  129667. 24,
  129668. 23,
  129669. 25,
  129670. 22,
  129671. 26,
  129672. 21,
  129673. 27,
  129674. 20,
  129675. 28,
  129676. 19,
  129677. 29,
  129678. 18,
  129679. 30,
  129680. 17,
  129681. 31,
  129682. 16,
  129683. 32,
  129684. 15,
  129685. 33,
  129686. 14,
  129687. 34,
  129688. 13,
  129689. 35,
  129690. 12,
  129691. 36,
  129692. 11,
  129693. 37,
  129694. 10,
  129695. 38,
  129696. 9,
  129697. 39,
  129698. 8,
  129699. 40,
  129700. 7,
  129701. 41,
  129702. 6,
  129703. 42,
  129704. 5,
  129705. 43,
  129706. 4,
  129707. 44,
  129708. 3,
  129709. 45,
  129710. 2,
  129711. 46,
  129712. 1,
  129713. 47,
  129714. 0,
  129715. 48,
  129716. };
  129717. static long _vq_lengthlist__44c7_s_p9_2[] = {
  129718. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  129719. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129720. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129721. 7,
  129722. };
  129723. static float _vq_quantthresh__44c7_s_p9_2[] = {
  129724. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129725. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129726. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129727. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129728. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129729. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129730. };
  129731. static long _vq_quantmap__44c7_s_p9_2[] = {
  129732. 47, 45, 43, 41, 39, 37, 35, 33,
  129733. 31, 29, 27, 25, 23, 21, 19, 17,
  129734. 15, 13, 11, 9, 7, 5, 3, 1,
  129735. 0, 2, 4, 6, 8, 10, 12, 14,
  129736. 16, 18, 20, 22, 24, 26, 28, 30,
  129737. 32, 34, 36, 38, 40, 42, 44, 46,
  129738. 48,
  129739. };
  129740. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  129741. _vq_quantthresh__44c7_s_p9_2,
  129742. _vq_quantmap__44c7_s_p9_2,
  129743. 49,
  129744. 49
  129745. };
  129746. static static_codebook _44c7_s_p9_2 = {
  129747. 1, 49,
  129748. _vq_lengthlist__44c7_s_p9_2,
  129749. 1, -526909440, 1611661312, 6, 0,
  129750. _vq_quantlist__44c7_s_p9_2,
  129751. NULL,
  129752. &_vq_auxt__44c7_s_p9_2,
  129753. NULL,
  129754. 0
  129755. };
  129756. static long _huff_lengthlist__44c7_s_short[] = {
  129757. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  129758. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  129759. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  129760. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  129761. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  129762. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  129763. 10, 9,11,14,
  129764. };
  129765. static static_codebook _huff_book__44c7_s_short = {
  129766. 2, 100,
  129767. _huff_lengthlist__44c7_s_short,
  129768. 0, 0, 0, 0, 0,
  129769. NULL,
  129770. NULL,
  129771. NULL,
  129772. NULL,
  129773. 0
  129774. };
  129775. static long _huff_lengthlist__44c8_s_long[] = {
  129776. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  129777. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  129778. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  129779. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  129780. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  129781. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  129782. 11, 9, 9,10,
  129783. };
  129784. static static_codebook _huff_book__44c8_s_long = {
  129785. 2, 100,
  129786. _huff_lengthlist__44c8_s_long,
  129787. 0, 0, 0, 0, 0,
  129788. NULL,
  129789. NULL,
  129790. NULL,
  129791. NULL,
  129792. 0
  129793. };
  129794. static long _vq_quantlist__44c8_s_p1_0[] = {
  129795. 1,
  129796. 0,
  129797. 2,
  129798. };
  129799. static long _vq_lengthlist__44c8_s_p1_0[] = {
  129800. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  129801. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129803. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129804. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  129805. 8,
  129806. };
  129807. static float _vq_quantthresh__44c8_s_p1_0[] = {
  129808. -0.5, 0.5,
  129809. };
  129810. static long _vq_quantmap__44c8_s_p1_0[] = {
  129811. 1, 0, 2,
  129812. };
  129813. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  129814. _vq_quantthresh__44c8_s_p1_0,
  129815. _vq_quantmap__44c8_s_p1_0,
  129816. 3,
  129817. 3
  129818. };
  129819. static static_codebook _44c8_s_p1_0 = {
  129820. 4, 81,
  129821. _vq_lengthlist__44c8_s_p1_0,
  129822. 1, -535822336, 1611661312, 2, 0,
  129823. _vq_quantlist__44c8_s_p1_0,
  129824. NULL,
  129825. &_vq_auxt__44c8_s_p1_0,
  129826. NULL,
  129827. 0
  129828. };
  129829. static long _vq_quantlist__44c8_s_p2_0[] = {
  129830. 2,
  129831. 1,
  129832. 3,
  129833. 0,
  129834. 4,
  129835. };
  129836. static long _vq_lengthlist__44c8_s_p2_0[] = {
  129837. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129838. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129839. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129840. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  129841. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  129842. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  129843. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  129844. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129847. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  129848. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129849. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  129850. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  129851. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  129852. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  129855. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  129856. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  129857. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  129858. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  129859. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  129860. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129863. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  129864. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129865. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  129866. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  129867. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  129868. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129873. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  129874. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129875. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  129876. 13,
  129877. };
  129878. static float _vq_quantthresh__44c8_s_p2_0[] = {
  129879. -1.5, -0.5, 0.5, 1.5,
  129880. };
  129881. static long _vq_quantmap__44c8_s_p2_0[] = {
  129882. 3, 1, 0, 2, 4,
  129883. };
  129884. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  129885. _vq_quantthresh__44c8_s_p2_0,
  129886. _vq_quantmap__44c8_s_p2_0,
  129887. 5,
  129888. 5
  129889. };
  129890. static static_codebook _44c8_s_p2_0 = {
  129891. 4, 625,
  129892. _vq_lengthlist__44c8_s_p2_0,
  129893. 1, -533725184, 1611661312, 3, 0,
  129894. _vq_quantlist__44c8_s_p2_0,
  129895. NULL,
  129896. &_vq_auxt__44c8_s_p2_0,
  129897. NULL,
  129898. 0
  129899. };
  129900. static long _vq_quantlist__44c8_s_p3_0[] = {
  129901. 4,
  129902. 3,
  129903. 5,
  129904. 2,
  129905. 6,
  129906. 1,
  129907. 7,
  129908. 0,
  129909. 8,
  129910. };
  129911. static long _vq_lengthlist__44c8_s_p3_0[] = {
  129912. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129913. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129914. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129915. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0,
  129918. };
  129919. static float _vq_quantthresh__44c8_s_p3_0[] = {
  129920. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129921. };
  129922. static long _vq_quantmap__44c8_s_p3_0[] = {
  129923. 7, 5, 3, 1, 0, 2, 4, 6,
  129924. 8,
  129925. };
  129926. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  129927. _vq_quantthresh__44c8_s_p3_0,
  129928. _vq_quantmap__44c8_s_p3_0,
  129929. 9,
  129930. 9
  129931. };
  129932. static static_codebook _44c8_s_p3_0 = {
  129933. 2, 81,
  129934. _vq_lengthlist__44c8_s_p3_0,
  129935. 1, -531628032, 1611661312, 4, 0,
  129936. _vq_quantlist__44c8_s_p3_0,
  129937. NULL,
  129938. &_vq_auxt__44c8_s_p3_0,
  129939. NULL,
  129940. 0
  129941. };
  129942. static long _vq_quantlist__44c8_s_p4_0[] = {
  129943. 8,
  129944. 7,
  129945. 9,
  129946. 6,
  129947. 10,
  129948. 5,
  129949. 11,
  129950. 4,
  129951. 12,
  129952. 3,
  129953. 13,
  129954. 2,
  129955. 14,
  129956. 1,
  129957. 15,
  129958. 0,
  129959. 16,
  129960. };
  129961. static long _vq_lengthlist__44c8_s_p4_0[] = {
  129962. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129963. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  129964. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129965. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  129966. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  129967. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129968. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129969. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129970. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129971. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0,
  129981. };
  129982. static float _vq_quantthresh__44c8_s_p4_0[] = {
  129983. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129984. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129985. };
  129986. static long _vq_quantmap__44c8_s_p4_0[] = {
  129987. 15, 13, 11, 9, 7, 5, 3, 1,
  129988. 0, 2, 4, 6, 8, 10, 12, 14,
  129989. 16,
  129990. };
  129991. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  129992. _vq_quantthresh__44c8_s_p4_0,
  129993. _vq_quantmap__44c8_s_p4_0,
  129994. 17,
  129995. 17
  129996. };
  129997. static static_codebook _44c8_s_p4_0 = {
  129998. 2, 289,
  129999. _vq_lengthlist__44c8_s_p4_0,
  130000. 1, -529530880, 1611661312, 5, 0,
  130001. _vq_quantlist__44c8_s_p4_0,
  130002. NULL,
  130003. &_vq_auxt__44c8_s_p4_0,
  130004. NULL,
  130005. 0
  130006. };
  130007. static long _vq_quantlist__44c8_s_p5_0[] = {
  130008. 1,
  130009. 0,
  130010. 2,
  130011. };
  130012. static long _vq_lengthlist__44c8_s_p5_0[] = {
  130013. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  130014. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  130015. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  130016. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  130017. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  130018. 12,
  130019. };
  130020. static float _vq_quantthresh__44c8_s_p5_0[] = {
  130021. -5.5, 5.5,
  130022. };
  130023. static long _vq_quantmap__44c8_s_p5_0[] = {
  130024. 1, 0, 2,
  130025. };
  130026. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  130027. _vq_quantthresh__44c8_s_p5_0,
  130028. _vq_quantmap__44c8_s_p5_0,
  130029. 3,
  130030. 3
  130031. };
  130032. static static_codebook _44c8_s_p5_0 = {
  130033. 4, 81,
  130034. _vq_lengthlist__44c8_s_p5_0,
  130035. 1, -529137664, 1618345984, 2, 0,
  130036. _vq_quantlist__44c8_s_p5_0,
  130037. NULL,
  130038. &_vq_auxt__44c8_s_p5_0,
  130039. NULL,
  130040. 0
  130041. };
  130042. static long _vq_quantlist__44c8_s_p5_1[] = {
  130043. 5,
  130044. 4,
  130045. 6,
  130046. 3,
  130047. 7,
  130048. 2,
  130049. 8,
  130050. 1,
  130051. 9,
  130052. 0,
  130053. 10,
  130054. };
  130055. static long _vq_lengthlist__44c8_s_p5_1[] = {
  130056. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  130057. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130058. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  130059. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  130060. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  130061. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  130062. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  130063. 11,11,11, 7, 7, 7, 7, 8, 8,
  130064. };
  130065. static float _vq_quantthresh__44c8_s_p5_1[] = {
  130066. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130067. 3.5, 4.5,
  130068. };
  130069. static long _vq_quantmap__44c8_s_p5_1[] = {
  130070. 9, 7, 5, 3, 1, 0, 2, 4,
  130071. 6, 8, 10,
  130072. };
  130073. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  130074. _vq_quantthresh__44c8_s_p5_1,
  130075. _vq_quantmap__44c8_s_p5_1,
  130076. 11,
  130077. 11
  130078. };
  130079. static static_codebook _44c8_s_p5_1 = {
  130080. 2, 121,
  130081. _vq_lengthlist__44c8_s_p5_1,
  130082. 1, -531365888, 1611661312, 4, 0,
  130083. _vq_quantlist__44c8_s_p5_1,
  130084. NULL,
  130085. &_vq_auxt__44c8_s_p5_1,
  130086. NULL,
  130087. 0
  130088. };
  130089. static long _vq_quantlist__44c8_s_p6_0[] = {
  130090. 6,
  130091. 5,
  130092. 7,
  130093. 4,
  130094. 8,
  130095. 3,
  130096. 9,
  130097. 2,
  130098. 10,
  130099. 1,
  130100. 11,
  130101. 0,
  130102. 12,
  130103. };
  130104. static long _vq_lengthlist__44c8_s_p6_0[] = {
  130105. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130106. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  130107. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  130108. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  130109. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  130110. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. };
  130117. static float _vq_quantthresh__44c8_s_p6_0[] = {
  130118. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130119. 12.5, 17.5, 22.5, 27.5,
  130120. };
  130121. static long _vq_quantmap__44c8_s_p6_0[] = {
  130122. 11, 9, 7, 5, 3, 1, 0, 2,
  130123. 4, 6, 8, 10, 12,
  130124. };
  130125. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  130126. _vq_quantthresh__44c8_s_p6_0,
  130127. _vq_quantmap__44c8_s_p6_0,
  130128. 13,
  130129. 13
  130130. };
  130131. static static_codebook _44c8_s_p6_0 = {
  130132. 2, 169,
  130133. _vq_lengthlist__44c8_s_p6_0,
  130134. 1, -526516224, 1616117760, 4, 0,
  130135. _vq_quantlist__44c8_s_p6_0,
  130136. NULL,
  130137. &_vq_auxt__44c8_s_p6_0,
  130138. NULL,
  130139. 0
  130140. };
  130141. static long _vq_quantlist__44c8_s_p6_1[] = {
  130142. 2,
  130143. 1,
  130144. 3,
  130145. 0,
  130146. 4,
  130147. };
  130148. static long _vq_lengthlist__44c8_s_p6_1[] = {
  130149. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  130150. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130151. };
  130152. static float _vq_quantthresh__44c8_s_p6_1[] = {
  130153. -1.5, -0.5, 0.5, 1.5,
  130154. };
  130155. static long _vq_quantmap__44c8_s_p6_1[] = {
  130156. 3, 1, 0, 2, 4,
  130157. };
  130158. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  130159. _vq_quantthresh__44c8_s_p6_1,
  130160. _vq_quantmap__44c8_s_p6_1,
  130161. 5,
  130162. 5
  130163. };
  130164. static static_codebook _44c8_s_p6_1 = {
  130165. 2, 25,
  130166. _vq_lengthlist__44c8_s_p6_1,
  130167. 1, -533725184, 1611661312, 3, 0,
  130168. _vq_quantlist__44c8_s_p6_1,
  130169. NULL,
  130170. &_vq_auxt__44c8_s_p6_1,
  130171. NULL,
  130172. 0
  130173. };
  130174. static long _vq_quantlist__44c8_s_p7_0[] = {
  130175. 6,
  130176. 5,
  130177. 7,
  130178. 4,
  130179. 8,
  130180. 3,
  130181. 9,
  130182. 2,
  130183. 10,
  130184. 1,
  130185. 11,
  130186. 0,
  130187. 12,
  130188. };
  130189. static long _vq_lengthlist__44c8_s_p7_0[] = {
  130190. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  130191. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130192. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  130193. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  130194. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  130195. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  130196. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  130197. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  130198. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  130199. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  130200. 20,13,13,13,13,14,13,15,15,
  130201. };
  130202. static float _vq_quantthresh__44c8_s_p7_0[] = {
  130203. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130204. 27.5, 38.5, 49.5, 60.5,
  130205. };
  130206. static long _vq_quantmap__44c8_s_p7_0[] = {
  130207. 11, 9, 7, 5, 3, 1, 0, 2,
  130208. 4, 6, 8, 10, 12,
  130209. };
  130210. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  130211. _vq_quantthresh__44c8_s_p7_0,
  130212. _vq_quantmap__44c8_s_p7_0,
  130213. 13,
  130214. 13
  130215. };
  130216. static static_codebook _44c8_s_p7_0 = {
  130217. 2, 169,
  130218. _vq_lengthlist__44c8_s_p7_0,
  130219. 1, -523206656, 1618345984, 4, 0,
  130220. _vq_quantlist__44c8_s_p7_0,
  130221. NULL,
  130222. &_vq_auxt__44c8_s_p7_0,
  130223. NULL,
  130224. 0
  130225. };
  130226. static long _vq_quantlist__44c8_s_p7_1[] = {
  130227. 5,
  130228. 4,
  130229. 6,
  130230. 3,
  130231. 7,
  130232. 2,
  130233. 8,
  130234. 1,
  130235. 9,
  130236. 0,
  130237. 10,
  130238. };
  130239. static long _vq_lengthlist__44c8_s_p7_1[] = {
  130240. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  130241. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130242. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130243. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130244. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130245. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130246. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130247. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130248. };
  130249. static float _vq_quantthresh__44c8_s_p7_1[] = {
  130250. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130251. 3.5, 4.5,
  130252. };
  130253. static long _vq_quantmap__44c8_s_p7_1[] = {
  130254. 9, 7, 5, 3, 1, 0, 2, 4,
  130255. 6, 8, 10,
  130256. };
  130257. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  130258. _vq_quantthresh__44c8_s_p7_1,
  130259. _vq_quantmap__44c8_s_p7_1,
  130260. 11,
  130261. 11
  130262. };
  130263. static static_codebook _44c8_s_p7_1 = {
  130264. 2, 121,
  130265. _vq_lengthlist__44c8_s_p7_1,
  130266. 1, -531365888, 1611661312, 4, 0,
  130267. _vq_quantlist__44c8_s_p7_1,
  130268. NULL,
  130269. &_vq_auxt__44c8_s_p7_1,
  130270. NULL,
  130271. 0
  130272. };
  130273. static long _vq_quantlist__44c8_s_p8_0[] = {
  130274. 7,
  130275. 6,
  130276. 8,
  130277. 5,
  130278. 9,
  130279. 4,
  130280. 10,
  130281. 3,
  130282. 11,
  130283. 2,
  130284. 12,
  130285. 1,
  130286. 13,
  130287. 0,
  130288. 14,
  130289. };
  130290. static long _vq_lengthlist__44c8_s_p8_0[] = {
  130291. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  130292. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  130293. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  130294. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  130295. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  130296. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  130297. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  130298. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  130299. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  130300. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  130301. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  130302. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130303. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  130304. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  130305. 15,
  130306. };
  130307. static float _vq_quantthresh__44c8_s_p8_0[] = {
  130308. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130309. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130310. };
  130311. static long _vq_quantmap__44c8_s_p8_0[] = {
  130312. 13, 11, 9, 7, 5, 3, 1, 0,
  130313. 2, 4, 6, 8, 10, 12, 14,
  130314. };
  130315. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  130316. _vq_quantthresh__44c8_s_p8_0,
  130317. _vq_quantmap__44c8_s_p8_0,
  130318. 15,
  130319. 15
  130320. };
  130321. static static_codebook _44c8_s_p8_0 = {
  130322. 2, 225,
  130323. _vq_lengthlist__44c8_s_p8_0,
  130324. 1, -520986624, 1620377600, 4, 0,
  130325. _vq_quantlist__44c8_s_p8_0,
  130326. NULL,
  130327. &_vq_auxt__44c8_s_p8_0,
  130328. NULL,
  130329. 0
  130330. };
  130331. static long _vq_quantlist__44c8_s_p8_1[] = {
  130332. 10,
  130333. 9,
  130334. 11,
  130335. 8,
  130336. 12,
  130337. 7,
  130338. 13,
  130339. 6,
  130340. 14,
  130341. 5,
  130342. 15,
  130343. 4,
  130344. 16,
  130345. 3,
  130346. 17,
  130347. 2,
  130348. 18,
  130349. 1,
  130350. 19,
  130351. 0,
  130352. 20,
  130353. };
  130354. static long _vq_lengthlist__44c8_s_p8_1[] = {
  130355. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130356. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130357. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130358. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130359. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130360. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130361. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130362. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130363. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130364. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130365. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  130366. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130367. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  130368. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130369. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  130370. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  130371. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  130372. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  130373. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  130374. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  130375. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  130376. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  130377. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130378. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  130379. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  130380. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  130381. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130382. 10, 9, 9,10,10, 9,10, 9, 9,
  130383. };
  130384. static float _vq_quantthresh__44c8_s_p8_1[] = {
  130385. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130386. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130387. 6.5, 7.5, 8.5, 9.5,
  130388. };
  130389. static long _vq_quantmap__44c8_s_p8_1[] = {
  130390. 19, 17, 15, 13, 11, 9, 7, 5,
  130391. 3, 1, 0, 2, 4, 6, 8, 10,
  130392. 12, 14, 16, 18, 20,
  130393. };
  130394. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  130395. _vq_quantthresh__44c8_s_p8_1,
  130396. _vq_quantmap__44c8_s_p8_1,
  130397. 21,
  130398. 21
  130399. };
  130400. static static_codebook _44c8_s_p8_1 = {
  130401. 2, 441,
  130402. _vq_lengthlist__44c8_s_p8_1,
  130403. 1, -529268736, 1611661312, 5, 0,
  130404. _vq_quantlist__44c8_s_p8_1,
  130405. NULL,
  130406. &_vq_auxt__44c8_s_p8_1,
  130407. NULL,
  130408. 0
  130409. };
  130410. static long _vq_quantlist__44c8_s_p9_0[] = {
  130411. 8,
  130412. 7,
  130413. 9,
  130414. 6,
  130415. 10,
  130416. 5,
  130417. 11,
  130418. 4,
  130419. 12,
  130420. 3,
  130421. 13,
  130422. 2,
  130423. 14,
  130424. 1,
  130425. 15,
  130426. 0,
  130427. 16,
  130428. };
  130429. static long _vq_lengthlist__44c8_s_p9_0[] = {
  130430. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130431. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  130432. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  130433. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130434. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130435. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130436. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130437. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130438. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130439. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130440. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130441. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130442. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130443. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130444. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130445. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130446. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130447. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130448. 10,
  130449. };
  130450. static float _vq_quantthresh__44c8_s_p9_0[] = {
  130451. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  130452. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  130453. };
  130454. static long _vq_quantmap__44c8_s_p9_0[] = {
  130455. 15, 13, 11, 9, 7, 5, 3, 1,
  130456. 0, 2, 4, 6, 8, 10, 12, 14,
  130457. 16,
  130458. };
  130459. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  130460. _vq_quantthresh__44c8_s_p9_0,
  130461. _vq_quantmap__44c8_s_p9_0,
  130462. 17,
  130463. 17
  130464. };
  130465. static static_codebook _44c8_s_p9_0 = {
  130466. 2, 289,
  130467. _vq_lengthlist__44c8_s_p9_0,
  130468. 1, -509798400, 1631393792, 5, 0,
  130469. _vq_quantlist__44c8_s_p9_0,
  130470. NULL,
  130471. &_vq_auxt__44c8_s_p9_0,
  130472. NULL,
  130473. 0
  130474. };
  130475. static long _vq_quantlist__44c8_s_p9_1[] = {
  130476. 9,
  130477. 8,
  130478. 10,
  130479. 7,
  130480. 11,
  130481. 6,
  130482. 12,
  130483. 5,
  130484. 13,
  130485. 4,
  130486. 14,
  130487. 3,
  130488. 15,
  130489. 2,
  130490. 16,
  130491. 1,
  130492. 17,
  130493. 0,
  130494. 18,
  130495. };
  130496. static long _vq_lengthlist__44c8_s_p9_1[] = {
  130497. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  130498. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  130499. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  130500. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  130501. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  130502. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  130503. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  130504. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  130505. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  130506. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  130507. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  130508. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  130509. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  130510. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  130511. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  130512. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  130513. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  130514. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  130515. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  130516. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  130517. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  130518. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  130519. 14,13,13,14,14,15,14,15,14,
  130520. };
  130521. static float _vq_quantthresh__44c8_s_p9_1[] = {
  130522. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  130523. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  130524. 367.5, 416.5,
  130525. };
  130526. static long _vq_quantmap__44c8_s_p9_1[] = {
  130527. 17, 15, 13, 11, 9, 7, 5, 3,
  130528. 1, 0, 2, 4, 6, 8, 10, 12,
  130529. 14, 16, 18,
  130530. };
  130531. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  130532. _vq_quantthresh__44c8_s_p9_1,
  130533. _vq_quantmap__44c8_s_p9_1,
  130534. 19,
  130535. 19
  130536. };
  130537. static static_codebook _44c8_s_p9_1 = {
  130538. 2, 361,
  130539. _vq_lengthlist__44c8_s_p9_1,
  130540. 1, -518287360, 1622704128, 5, 0,
  130541. _vq_quantlist__44c8_s_p9_1,
  130542. NULL,
  130543. &_vq_auxt__44c8_s_p9_1,
  130544. NULL,
  130545. 0
  130546. };
  130547. static long _vq_quantlist__44c8_s_p9_2[] = {
  130548. 24,
  130549. 23,
  130550. 25,
  130551. 22,
  130552. 26,
  130553. 21,
  130554. 27,
  130555. 20,
  130556. 28,
  130557. 19,
  130558. 29,
  130559. 18,
  130560. 30,
  130561. 17,
  130562. 31,
  130563. 16,
  130564. 32,
  130565. 15,
  130566. 33,
  130567. 14,
  130568. 34,
  130569. 13,
  130570. 35,
  130571. 12,
  130572. 36,
  130573. 11,
  130574. 37,
  130575. 10,
  130576. 38,
  130577. 9,
  130578. 39,
  130579. 8,
  130580. 40,
  130581. 7,
  130582. 41,
  130583. 6,
  130584. 42,
  130585. 5,
  130586. 43,
  130587. 4,
  130588. 44,
  130589. 3,
  130590. 45,
  130591. 2,
  130592. 46,
  130593. 1,
  130594. 47,
  130595. 0,
  130596. 48,
  130597. };
  130598. static long _vq_lengthlist__44c8_s_p9_2[] = {
  130599. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  130600. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130601. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130602. 7,
  130603. };
  130604. static float _vq_quantthresh__44c8_s_p9_2[] = {
  130605. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130606. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130607. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130608. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130609. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130610. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130611. };
  130612. static long _vq_quantmap__44c8_s_p9_2[] = {
  130613. 47, 45, 43, 41, 39, 37, 35, 33,
  130614. 31, 29, 27, 25, 23, 21, 19, 17,
  130615. 15, 13, 11, 9, 7, 5, 3, 1,
  130616. 0, 2, 4, 6, 8, 10, 12, 14,
  130617. 16, 18, 20, 22, 24, 26, 28, 30,
  130618. 32, 34, 36, 38, 40, 42, 44, 46,
  130619. 48,
  130620. };
  130621. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  130622. _vq_quantthresh__44c8_s_p9_2,
  130623. _vq_quantmap__44c8_s_p9_2,
  130624. 49,
  130625. 49
  130626. };
  130627. static static_codebook _44c8_s_p9_2 = {
  130628. 1, 49,
  130629. _vq_lengthlist__44c8_s_p9_2,
  130630. 1, -526909440, 1611661312, 6, 0,
  130631. _vq_quantlist__44c8_s_p9_2,
  130632. NULL,
  130633. &_vq_auxt__44c8_s_p9_2,
  130634. NULL,
  130635. 0
  130636. };
  130637. static long _huff_lengthlist__44c8_s_short[] = {
  130638. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  130639. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  130640. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  130641. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  130642. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  130643. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  130644. 10, 9,11,14,
  130645. };
  130646. static static_codebook _huff_book__44c8_s_short = {
  130647. 2, 100,
  130648. _huff_lengthlist__44c8_s_short,
  130649. 0, 0, 0, 0, 0,
  130650. NULL,
  130651. NULL,
  130652. NULL,
  130653. NULL,
  130654. 0
  130655. };
  130656. static long _huff_lengthlist__44c9_s_long[] = {
  130657. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  130658. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  130659. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  130660. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  130661. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  130662. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  130663. 10, 9, 8, 9,
  130664. };
  130665. static static_codebook _huff_book__44c9_s_long = {
  130666. 2, 100,
  130667. _huff_lengthlist__44c9_s_long,
  130668. 0, 0, 0, 0, 0,
  130669. NULL,
  130670. NULL,
  130671. NULL,
  130672. NULL,
  130673. 0
  130674. };
  130675. static long _vq_quantlist__44c9_s_p1_0[] = {
  130676. 1,
  130677. 0,
  130678. 2,
  130679. };
  130680. static long _vq_lengthlist__44c9_s_p1_0[] = {
  130681. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  130682. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  130684. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130685. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  130686. 7,
  130687. };
  130688. static float _vq_quantthresh__44c9_s_p1_0[] = {
  130689. -0.5, 0.5,
  130690. };
  130691. static long _vq_quantmap__44c9_s_p1_0[] = {
  130692. 1, 0, 2,
  130693. };
  130694. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  130695. _vq_quantthresh__44c9_s_p1_0,
  130696. _vq_quantmap__44c9_s_p1_0,
  130697. 3,
  130698. 3
  130699. };
  130700. static static_codebook _44c9_s_p1_0 = {
  130701. 4, 81,
  130702. _vq_lengthlist__44c9_s_p1_0,
  130703. 1, -535822336, 1611661312, 2, 0,
  130704. _vq_quantlist__44c9_s_p1_0,
  130705. NULL,
  130706. &_vq_auxt__44c9_s_p1_0,
  130707. NULL,
  130708. 0
  130709. };
  130710. static long _vq_quantlist__44c9_s_p2_0[] = {
  130711. 2,
  130712. 1,
  130713. 3,
  130714. 0,
  130715. 4,
  130716. };
  130717. static long _vq_lengthlist__44c9_s_p2_0[] = {
  130718. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130719. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  130720. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  130721. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  130722. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  130723. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  130724. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  130725. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  130728. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  130729. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  130730. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  130731. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  130732. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  130733. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  130736. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  130737. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  130738. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  130739. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  130740. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  130741. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  130744. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  130745. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  130746. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  130747. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  130748. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  130749. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  130754. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  130755. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  130756. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  130757. 12,
  130758. };
  130759. static float _vq_quantthresh__44c9_s_p2_0[] = {
  130760. -1.5, -0.5, 0.5, 1.5,
  130761. };
  130762. static long _vq_quantmap__44c9_s_p2_0[] = {
  130763. 3, 1, 0, 2, 4,
  130764. };
  130765. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  130766. _vq_quantthresh__44c9_s_p2_0,
  130767. _vq_quantmap__44c9_s_p2_0,
  130768. 5,
  130769. 5
  130770. };
  130771. static static_codebook _44c9_s_p2_0 = {
  130772. 4, 625,
  130773. _vq_lengthlist__44c9_s_p2_0,
  130774. 1, -533725184, 1611661312, 3, 0,
  130775. _vq_quantlist__44c9_s_p2_0,
  130776. NULL,
  130777. &_vq_auxt__44c9_s_p2_0,
  130778. NULL,
  130779. 0
  130780. };
  130781. static long _vq_quantlist__44c9_s_p3_0[] = {
  130782. 4,
  130783. 3,
  130784. 5,
  130785. 2,
  130786. 6,
  130787. 1,
  130788. 7,
  130789. 0,
  130790. 8,
  130791. };
  130792. static long _vq_lengthlist__44c9_s_p3_0[] = {
  130793. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  130794. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  130795. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  130796. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0,
  130799. };
  130800. static float _vq_quantthresh__44c9_s_p3_0[] = {
  130801. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130802. };
  130803. static long _vq_quantmap__44c9_s_p3_0[] = {
  130804. 7, 5, 3, 1, 0, 2, 4, 6,
  130805. 8,
  130806. };
  130807. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  130808. _vq_quantthresh__44c9_s_p3_0,
  130809. _vq_quantmap__44c9_s_p3_0,
  130810. 9,
  130811. 9
  130812. };
  130813. static static_codebook _44c9_s_p3_0 = {
  130814. 2, 81,
  130815. _vq_lengthlist__44c9_s_p3_0,
  130816. 1, -531628032, 1611661312, 4, 0,
  130817. _vq_quantlist__44c9_s_p3_0,
  130818. NULL,
  130819. &_vq_auxt__44c9_s_p3_0,
  130820. NULL,
  130821. 0
  130822. };
  130823. static long _vq_quantlist__44c9_s_p4_0[] = {
  130824. 8,
  130825. 7,
  130826. 9,
  130827. 6,
  130828. 10,
  130829. 5,
  130830. 11,
  130831. 4,
  130832. 12,
  130833. 3,
  130834. 13,
  130835. 2,
  130836. 14,
  130837. 1,
  130838. 15,
  130839. 0,
  130840. 16,
  130841. };
  130842. static long _vq_lengthlist__44c9_s_p4_0[] = {
  130843. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  130844. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  130845. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  130846. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  130847. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  130848. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  130849. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  130850. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130851. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130852. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0,
  130862. };
  130863. static float _vq_quantthresh__44c9_s_p4_0[] = {
  130864. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130865. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130866. };
  130867. static long _vq_quantmap__44c9_s_p4_0[] = {
  130868. 15, 13, 11, 9, 7, 5, 3, 1,
  130869. 0, 2, 4, 6, 8, 10, 12, 14,
  130870. 16,
  130871. };
  130872. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  130873. _vq_quantthresh__44c9_s_p4_0,
  130874. _vq_quantmap__44c9_s_p4_0,
  130875. 17,
  130876. 17
  130877. };
  130878. static static_codebook _44c9_s_p4_0 = {
  130879. 2, 289,
  130880. _vq_lengthlist__44c9_s_p4_0,
  130881. 1, -529530880, 1611661312, 5, 0,
  130882. _vq_quantlist__44c9_s_p4_0,
  130883. NULL,
  130884. &_vq_auxt__44c9_s_p4_0,
  130885. NULL,
  130886. 0
  130887. };
  130888. static long _vq_quantlist__44c9_s_p5_0[] = {
  130889. 1,
  130890. 0,
  130891. 2,
  130892. };
  130893. static long _vq_lengthlist__44c9_s_p5_0[] = {
  130894. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  130895. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  130896. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  130897. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  130898. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  130899. 12,
  130900. };
  130901. static float _vq_quantthresh__44c9_s_p5_0[] = {
  130902. -5.5, 5.5,
  130903. };
  130904. static long _vq_quantmap__44c9_s_p5_0[] = {
  130905. 1, 0, 2,
  130906. };
  130907. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  130908. _vq_quantthresh__44c9_s_p5_0,
  130909. _vq_quantmap__44c9_s_p5_0,
  130910. 3,
  130911. 3
  130912. };
  130913. static static_codebook _44c9_s_p5_0 = {
  130914. 4, 81,
  130915. _vq_lengthlist__44c9_s_p5_0,
  130916. 1, -529137664, 1618345984, 2, 0,
  130917. _vq_quantlist__44c9_s_p5_0,
  130918. NULL,
  130919. &_vq_auxt__44c9_s_p5_0,
  130920. NULL,
  130921. 0
  130922. };
  130923. static long _vq_quantlist__44c9_s_p5_1[] = {
  130924. 5,
  130925. 4,
  130926. 6,
  130927. 3,
  130928. 7,
  130929. 2,
  130930. 8,
  130931. 1,
  130932. 9,
  130933. 0,
  130934. 10,
  130935. };
  130936. static long _vq_lengthlist__44c9_s_p5_1[] = {
  130937. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  130938. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  130939. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  130940. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  130941. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  130942. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  130943. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  130944. 11,11,11, 7, 7, 7, 7, 7, 7,
  130945. };
  130946. static float _vq_quantthresh__44c9_s_p5_1[] = {
  130947. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130948. 3.5, 4.5,
  130949. };
  130950. static long _vq_quantmap__44c9_s_p5_1[] = {
  130951. 9, 7, 5, 3, 1, 0, 2, 4,
  130952. 6, 8, 10,
  130953. };
  130954. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  130955. _vq_quantthresh__44c9_s_p5_1,
  130956. _vq_quantmap__44c9_s_p5_1,
  130957. 11,
  130958. 11
  130959. };
  130960. static static_codebook _44c9_s_p5_1 = {
  130961. 2, 121,
  130962. _vq_lengthlist__44c9_s_p5_1,
  130963. 1, -531365888, 1611661312, 4, 0,
  130964. _vq_quantlist__44c9_s_p5_1,
  130965. NULL,
  130966. &_vq_auxt__44c9_s_p5_1,
  130967. NULL,
  130968. 0
  130969. };
  130970. static long _vq_quantlist__44c9_s_p6_0[] = {
  130971. 6,
  130972. 5,
  130973. 7,
  130974. 4,
  130975. 8,
  130976. 3,
  130977. 9,
  130978. 2,
  130979. 10,
  130980. 1,
  130981. 11,
  130982. 0,
  130983. 12,
  130984. };
  130985. static long _vq_lengthlist__44c9_s_p6_0[] = {
  130986. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  130987. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  130988. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  130989. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130990. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  130991. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. };
  130998. static float _vq_quantthresh__44c9_s_p6_0[] = {
  130999. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131000. 12.5, 17.5, 22.5, 27.5,
  131001. };
  131002. static long _vq_quantmap__44c9_s_p6_0[] = {
  131003. 11, 9, 7, 5, 3, 1, 0, 2,
  131004. 4, 6, 8, 10, 12,
  131005. };
  131006. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  131007. _vq_quantthresh__44c9_s_p6_0,
  131008. _vq_quantmap__44c9_s_p6_0,
  131009. 13,
  131010. 13
  131011. };
  131012. static static_codebook _44c9_s_p6_0 = {
  131013. 2, 169,
  131014. _vq_lengthlist__44c9_s_p6_0,
  131015. 1, -526516224, 1616117760, 4, 0,
  131016. _vq_quantlist__44c9_s_p6_0,
  131017. NULL,
  131018. &_vq_auxt__44c9_s_p6_0,
  131019. NULL,
  131020. 0
  131021. };
  131022. static long _vq_quantlist__44c9_s_p6_1[] = {
  131023. 2,
  131024. 1,
  131025. 3,
  131026. 0,
  131027. 4,
  131028. };
  131029. static long _vq_lengthlist__44c9_s_p6_1[] = {
  131030. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  131031. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  131032. };
  131033. static float _vq_quantthresh__44c9_s_p6_1[] = {
  131034. -1.5, -0.5, 0.5, 1.5,
  131035. };
  131036. static long _vq_quantmap__44c9_s_p6_1[] = {
  131037. 3, 1, 0, 2, 4,
  131038. };
  131039. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  131040. _vq_quantthresh__44c9_s_p6_1,
  131041. _vq_quantmap__44c9_s_p6_1,
  131042. 5,
  131043. 5
  131044. };
  131045. static static_codebook _44c9_s_p6_1 = {
  131046. 2, 25,
  131047. _vq_lengthlist__44c9_s_p6_1,
  131048. 1, -533725184, 1611661312, 3, 0,
  131049. _vq_quantlist__44c9_s_p6_1,
  131050. NULL,
  131051. &_vq_auxt__44c9_s_p6_1,
  131052. NULL,
  131053. 0
  131054. };
  131055. static long _vq_quantlist__44c9_s_p7_0[] = {
  131056. 6,
  131057. 5,
  131058. 7,
  131059. 4,
  131060. 8,
  131061. 3,
  131062. 9,
  131063. 2,
  131064. 10,
  131065. 1,
  131066. 11,
  131067. 0,
  131068. 12,
  131069. };
  131070. static long _vq_lengthlist__44c9_s_p7_0[] = {
  131071. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  131072. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  131073. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  131074. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  131075. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  131076. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  131077. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  131078. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  131079. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  131080. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  131081. 19,12,12,12,12,13,13,14,14,
  131082. };
  131083. static float _vq_quantthresh__44c9_s_p7_0[] = {
  131084. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131085. 27.5, 38.5, 49.5, 60.5,
  131086. };
  131087. static long _vq_quantmap__44c9_s_p7_0[] = {
  131088. 11, 9, 7, 5, 3, 1, 0, 2,
  131089. 4, 6, 8, 10, 12,
  131090. };
  131091. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  131092. _vq_quantthresh__44c9_s_p7_0,
  131093. _vq_quantmap__44c9_s_p7_0,
  131094. 13,
  131095. 13
  131096. };
  131097. static static_codebook _44c9_s_p7_0 = {
  131098. 2, 169,
  131099. _vq_lengthlist__44c9_s_p7_0,
  131100. 1, -523206656, 1618345984, 4, 0,
  131101. _vq_quantlist__44c9_s_p7_0,
  131102. NULL,
  131103. &_vq_auxt__44c9_s_p7_0,
  131104. NULL,
  131105. 0
  131106. };
  131107. static long _vq_quantlist__44c9_s_p7_1[] = {
  131108. 5,
  131109. 4,
  131110. 6,
  131111. 3,
  131112. 7,
  131113. 2,
  131114. 8,
  131115. 1,
  131116. 9,
  131117. 0,
  131118. 10,
  131119. };
  131120. static long _vq_lengthlist__44c9_s_p7_1[] = {
  131121. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  131122. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131123. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  131124. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131125. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  131126. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  131127. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  131128. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  131129. };
  131130. static float _vq_quantthresh__44c9_s_p7_1[] = {
  131131. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131132. 3.5, 4.5,
  131133. };
  131134. static long _vq_quantmap__44c9_s_p7_1[] = {
  131135. 9, 7, 5, 3, 1, 0, 2, 4,
  131136. 6, 8, 10,
  131137. };
  131138. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  131139. _vq_quantthresh__44c9_s_p7_1,
  131140. _vq_quantmap__44c9_s_p7_1,
  131141. 11,
  131142. 11
  131143. };
  131144. static static_codebook _44c9_s_p7_1 = {
  131145. 2, 121,
  131146. _vq_lengthlist__44c9_s_p7_1,
  131147. 1, -531365888, 1611661312, 4, 0,
  131148. _vq_quantlist__44c9_s_p7_1,
  131149. NULL,
  131150. &_vq_auxt__44c9_s_p7_1,
  131151. NULL,
  131152. 0
  131153. };
  131154. static long _vq_quantlist__44c9_s_p8_0[] = {
  131155. 7,
  131156. 6,
  131157. 8,
  131158. 5,
  131159. 9,
  131160. 4,
  131161. 10,
  131162. 3,
  131163. 11,
  131164. 2,
  131165. 12,
  131166. 1,
  131167. 13,
  131168. 0,
  131169. 14,
  131170. };
  131171. static long _vq_lengthlist__44c9_s_p8_0[] = {
  131172. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  131173. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  131174. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  131175. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  131176. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  131177. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  131178. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  131179. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  131180. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  131181. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  131182. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  131183. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  131184. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  131185. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  131186. 14,
  131187. };
  131188. static float _vq_quantthresh__44c9_s_p8_0[] = {
  131189. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131190. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131191. };
  131192. static long _vq_quantmap__44c9_s_p8_0[] = {
  131193. 13, 11, 9, 7, 5, 3, 1, 0,
  131194. 2, 4, 6, 8, 10, 12, 14,
  131195. };
  131196. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  131197. _vq_quantthresh__44c9_s_p8_0,
  131198. _vq_quantmap__44c9_s_p8_0,
  131199. 15,
  131200. 15
  131201. };
  131202. static static_codebook _44c9_s_p8_0 = {
  131203. 2, 225,
  131204. _vq_lengthlist__44c9_s_p8_0,
  131205. 1, -520986624, 1620377600, 4, 0,
  131206. _vq_quantlist__44c9_s_p8_0,
  131207. NULL,
  131208. &_vq_auxt__44c9_s_p8_0,
  131209. NULL,
  131210. 0
  131211. };
  131212. static long _vq_quantlist__44c9_s_p8_1[] = {
  131213. 10,
  131214. 9,
  131215. 11,
  131216. 8,
  131217. 12,
  131218. 7,
  131219. 13,
  131220. 6,
  131221. 14,
  131222. 5,
  131223. 15,
  131224. 4,
  131225. 16,
  131226. 3,
  131227. 17,
  131228. 2,
  131229. 18,
  131230. 1,
  131231. 19,
  131232. 0,
  131233. 20,
  131234. };
  131235. static long _vq_lengthlist__44c9_s_p8_1[] = {
  131236. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131237. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131238. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131239. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131240. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131241. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131242. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  131243. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131244. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131245. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131246. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131247. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131248. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131249. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131250. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131251. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  131252. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  131253. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  131254. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  131255. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131256. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131257. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  131258. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131259. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131260. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  131261. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  131262. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  131263. 9, 9, 9,10, 9, 9, 9, 9, 9,
  131264. };
  131265. static float _vq_quantthresh__44c9_s_p8_1[] = {
  131266. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131267. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131268. 6.5, 7.5, 8.5, 9.5,
  131269. };
  131270. static long _vq_quantmap__44c9_s_p8_1[] = {
  131271. 19, 17, 15, 13, 11, 9, 7, 5,
  131272. 3, 1, 0, 2, 4, 6, 8, 10,
  131273. 12, 14, 16, 18, 20,
  131274. };
  131275. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  131276. _vq_quantthresh__44c9_s_p8_1,
  131277. _vq_quantmap__44c9_s_p8_1,
  131278. 21,
  131279. 21
  131280. };
  131281. static static_codebook _44c9_s_p8_1 = {
  131282. 2, 441,
  131283. _vq_lengthlist__44c9_s_p8_1,
  131284. 1, -529268736, 1611661312, 5, 0,
  131285. _vq_quantlist__44c9_s_p8_1,
  131286. NULL,
  131287. &_vq_auxt__44c9_s_p8_1,
  131288. NULL,
  131289. 0
  131290. };
  131291. static long _vq_quantlist__44c9_s_p9_0[] = {
  131292. 9,
  131293. 8,
  131294. 10,
  131295. 7,
  131296. 11,
  131297. 6,
  131298. 12,
  131299. 5,
  131300. 13,
  131301. 4,
  131302. 14,
  131303. 3,
  131304. 15,
  131305. 2,
  131306. 16,
  131307. 1,
  131308. 17,
  131309. 0,
  131310. 18,
  131311. };
  131312. static long _vq_lengthlist__44c9_s_p9_0[] = {
  131313. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131314. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  131315. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  131316. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  131317. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131318. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131319. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131320. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131321. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131322. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131323. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131324. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131325. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131326. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131327. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131328. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131329. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  131330. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131331. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131332. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131333. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131334. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131335. 11,11,11,11,11,11,11,11,11,
  131336. };
  131337. static float _vq_quantthresh__44c9_s_p9_0[] = {
  131338. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  131339. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  131340. 6982.5, 7913.5,
  131341. };
  131342. static long _vq_quantmap__44c9_s_p9_0[] = {
  131343. 17, 15, 13, 11, 9, 7, 5, 3,
  131344. 1, 0, 2, 4, 6, 8, 10, 12,
  131345. 14, 16, 18,
  131346. };
  131347. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  131348. _vq_quantthresh__44c9_s_p9_0,
  131349. _vq_quantmap__44c9_s_p9_0,
  131350. 19,
  131351. 19
  131352. };
  131353. static static_codebook _44c9_s_p9_0 = {
  131354. 2, 361,
  131355. _vq_lengthlist__44c9_s_p9_0,
  131356. 1, -508535424, 1631393792, 5, 0,
  131357. _vq_quantlist__44c9_s_p9_0,
  131358. NULL,
  131359. &_vq_auxt__44c9_s_p9_0,
  131360. NULL,
  131361. 0
  131362. };
  131363. static long _vq_quantlist__44c9_s_p9_1[] = {
  131364. 9,
  131365. 8,
  131366. 10,
  131367. 7,
  131368. 11,
  131369. 6,
  131370. 12,
  131371. 5,
  131372. 13,
  131373. 4,
  131374. 14,
  131375. 3,
  131376. 15,
  131377. 2,
  131378. 16,
  131379. 1,
  131380. 17,
  131381. 0,
  131382. 18,
  131383. };
  131384. static long _vq_lengthlist__44c9_s_p9_1[] = {
  131385. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  131386. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  131387. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  131388. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  131389. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  131390. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  131391. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  131392. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  131393. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  131394. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  131395. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  131396. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  131397. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  131398. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  131399. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  131400. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  131401. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  131402. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  131403. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  131404. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  131405. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  131406. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  131407. 13,13,13,14,13,14,15,15,15,
  131408. };
  131409. static float _vq_quantthresh__44c9_s_p9_1[] = {
  131410. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131411. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131412. 367.5, 416.5,
  131413. };
  131414. static long _vq_quantmap__44c9_s_p9_1[] = {
  131415. 17, 15, 13, 11, 9, 7, 5, 3,
  131416. 1, 0, 2, 4, 6, 8, 10, 12,
  131417. 14, 16, 18,
  131418. };
  131419. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  131420. _vq_quantthresh__44c9_s_p9_1,
  131421. _vq_quantmap__44c9_s_p9_1,
  131422. 19,
  131423. 19
  131424. };
  131425. static static_codebook _44c9_s_p9_1 = {
  131426. 2, 361,
  131427. _vq_lengthlist__44c9_s_p9_1,
  131428. 1, -518287360, 1622704128, 5, 0,
  131429. _vq_quantlist__44c9_s_p9_1,
  131430. NULL,
  131431. &_vq_auxt__44c9_s_p9_1,
  131432. NULL,
  131433. 0
  131434. };
  131435. static long _vq_quantlist__44c9_s_p9_2[] = {
  131436. 24,
  131437. 23,
  131438. 25,
  131439. 22,
  131440. 26,
  131441. 21,
  131442. 27,
  131443. 20,
  131444. 28,
  131445. 19,
  131446. 29,
  131447. 18,
  131448. 30,
  131449. 17,
  131450. 31,
  131451. 16,
  131452. 32,
  131453. 15,
  131454. 33,
  131455. 14,
  131456. 34,
  131457. 13,
  131458. 35,
  131459. 12,
  131460. 36,
  131461. 11,
  131462. 37,
  131463. 10,
  131464. 38,
  131465. 9,
  131466. 39,
  131467. 8,
  131468. 40,
  131469. 7,
  131470. 41,
  131471. 6,
  131472. 42,
  131473. 5,
  131474. 43,
  131475. 4,
  131476. 44,
  131477. 3,
  131478. 45,
  131479. 2,
  131480. 46,
  131481. 1,
  131482. 47,
  131483. 0,
  131484. 48,
  131485. };
  131486. static long _vq_lengthlist__44c9_s_p9_2[] = {
  131487. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131488. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131489. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131490. 7,
  131491. };
  131492. static float _vq_quantthresh__44c9_s_p9_2[] = {
  131493. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131494. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131495. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131496. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131497. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131498. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131499. };
  131500. static long _vq_quantmap__44c9_s_p9_2[] = {
  131501. 47, 45, 43, 41, 39, 37, 35, 33,
  131502. 31, 29, 27, 25, 23, 21, 19, 17,
  131503. 15, 13, 11, 9, 7, 5, 3, 1,
  131504. 0, 2, 4, 6, 8, 10, 12, 14,
  131505. 16, 18, 20, 22, 24, 26, 28, 30,
  131506. 32, 34, 36, 38, 40, 42, 44, 46,
  131507. 48,
  131508. };
  131509. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  131510. _vq_quantthresh__44c9_s_p9_2,
  131511. _vq_quantmap__44c9_s_p9_2,
  131512. 49,
  131513. 49
  131514. };
  131515. static static_codebook _44c9_s_p9_2 = {
  131516. 1, 49,
  131517. _vq_lengthlist__44c9_s_p9_2,
  131518. 1, -526909440, 1611661312, 6, 0,
  131519. _vq_quantlist__44c9_s_p9_2,
  131520. NULL,
  131521. &_vq_auxt__44c9_s_p9_2,
  131522. NULL,
  131523. 0
  131524. };
  131525. static long _huff_lengthlist__44c9_s_short[] = {
  131526. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  131527. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  131528. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  131529. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  131530. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  131531. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  131532. 9, 8,10,13,
  131533. };
  131534. static static_codebook _huff_book__44c9_s_short = {
  131535. 2, 100,
  131536. _huff_lengthlist__44c9_s_short,
  131537. 0, 0, 0, 0, 0,
  131538. NULL,
  131539. NULL,
  131540. NULL,
  131541. NULL,
  131542. 0
  131543. };
  131544. static long _huff_lengthlist__44c0_s_long[] = {
  131545. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  131546. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  131547. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  131548. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  131549. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  131550. 12,
  131551. };
  131552. static static_codebook _huff_book__44c0_s_long = {
  131553. 2, 81,
  131554. _huff_lengthlist__44c0_s_long,
  131555. 0, 0, 0, 0, 0,
  131556. NULL,
  131557. NULL,
  131558. NULL,
  131559. NULL,
  131560. 0
  131561. };
  131562. static long _vq_quantlist__44c0_s_p1_0[] = {
  131563. 1,
  131564. 0,
  131565. 2,
  131566. };
  131567. static long _vq_lengthlist__44c0_s_p1_0[] = {
  131568. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131569. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131574. 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131579. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  131614. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131619. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131624. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131660. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131665. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  131670. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131979. };
  131980. static float _vq_quantthresh__44c0_s_p1_0[] = {
  131981. -0.5, 0.5,
  131982. };
  131983. static long _vq_quantmap__44c0_s_p1_0[] = {
  131984. 1, 0, 2,
  131985. };
  131986. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  131987. _vq_quantthresh__44c0_s_p1_0,
  131988. _vq_quantmap__44c0_s_p1_0,
  131989. 3,
  131990. 3
  131991. };
  131992. static static_codebook _44c0_s_p1_0 = {
  131993. 8, 6561,
  131994. _vq_lengthlist__44c0_s_p1_0,
  131995. 1, -535822336, 1611661312, 2, 0,
  131996. _vq_quantlist__44c0_s_p1_0,
  131997. NULL,
  131998. &_vq_auxt__44c0_s_p1_0,
  131999. NULL,
  132000. 0
  132001. };
  132002. static long _vq_quantlist__44c0_s_p2_0[] = {
  132003. 2,
  132004. 1,
  132005. 3,
  132006. 0,
  132007. 4,
  132008. };
  132009. static long _vq_lengthlist__44c0_s_p2_0[] = {
  132010. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  132012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132013. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  132015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132016. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132049. 0,
  132050. };
  132051. static float _vq_quantthresh__44c0_s_p2_0[] = {
  132052. -1.5, -0.5, 0.5, 1.5,
  132053. };
  132054. static long _vq_quantmap__44c0_s_p2_0[] = {
  132055. 3, 1, 0, 2, 4,
  132056. };
  132057. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  132058. _vq_quantthresh__44c0_s_p2_0,
  132059. _vq_quantmap__44c0_s_p2_0,
  132060. 5,
  132061. 5
  132062. };
  132063. static static_codebook _44c0_s_p2_0 = {
  132064. 4, 625,
  132065. _vq_lengthlist__44c0_s_p2_0,
  132066. 1, -533725184, 1611661312, 3, 0,
  132067. _vq_quantlist__44c0_s_p2_0,
  132068. NULL,
  132069. &_vq_auxt__44c0_s_p2_0,
  132070. NULL,
  132071. 0
  132072. };
  132073. static long _vq_quantlist__44c0_s_p3_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_p3_0[] = {
  132085. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  132086. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  132087. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132088. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132089. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132090. 0,
  132091. };
  132092. static float _vq_quantthresh__44c0_s_p3_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_p3_0[] = {
  132096. 7, 5, 3, 1, 0, 2, 4, 6,
  132097. 8,
  132098. };
  132099. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  132100. _vq_quantthresh__44c0_s_p3_0,
  132101. _vq_quantmap__44c0_s_p3_0,
  132102. 9,
  132103. 9
  132104. };
  132105. static static_codebook _44c0_s_p3_0 = {
  132106. 2, 81,
  132107. _vq_lengthlist__44c0_s_p3_0,
  132108. 1, -531628032, 1611661312, 4, 0,
  132109. _vq_quantlist__44c0_s_p3_0,
  132110. NULL,
  132111. &_vq_auxt__44c0_s_p3_0,
  132112. NULL,
  132113. 0
  132114. };
  132115. static long _vq_quantlist__44c0_s_p4_0[] = {
  132116. 4,
  132117. 3,
  132118. 5,
  132119. 2,
  132120. 6,
  132121. 1,
  132122. 7,
  132123. 0,
  132124. 8,
  132125. };
  132126. static long _vq_lengthlist__44c0_s_p4_0[] = {
  132127. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  132128. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  132129. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  132130. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  132131. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132132. 10,
  132133. };
  132134. static float _vq_quantthresh__44c0_s_p4_0[] = {
  132135. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132136. };
  132137. static long _vq_quantmap__44c0_s_p4_0[] = {
  132138. 7, 5, 3, 1, 0, 2, 4, 6,
  132139. 8,
  132140. };
  132141. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  132142. _vq_quantthresh__44c0_s_p4_0,
  132143. _vq_quantmap__44c0_s_p4_0,
  132144. 9,
  132145. 9
  132146. };
  132147. static static_codebook _44c0_s_p4_0 = {
  132148. 2, 81,
  132149. _vq_lengthlist__44c0_s_p4_0,
  132150. 1, -531628032, 1611661312, 4, 0,
  132151. _vq_quantlist__44c0_s_p4_0,
  132152. NULL,
  132153. &_vq_auxt__44c0_s_p4_0,
  132154. NULL,
  132155. 0
  132156. };
  132157. static long _vq_quantlist__44c0_s_p5_0[] = {
  132158. 8,
  132159. 7,
  132160. 9,
  132161. 6,
  132162. 10,
  132163. 5,
  132164. 11,
  132165. 4,
  132166. 12,
  132167. 3,
  132168. 13,
  132169. 2,
  132170. 14,
  132171. 1,
  132172. 15,
  132173. 0,
  132174. 16,
  132175. };
  132176. static long _vq_lengthlist__44c0_s_p5_0[] = {
  132177. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132178. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  132179. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132180. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132181. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132182. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  132183. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  132184. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132185. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132186. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  132187. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132188. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132189. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132190. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132191. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  132192. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  132193. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  132194. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132195. 14,
  132196. };
  132197. static float _vq_quantthresh__44c0_s_p5_0[] = {
  132198. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132199. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132200. };
  132201. static long _vq_quantmap__44c0_s_p5_0[] = {
  132202. 15, 13, 11, 9, 7, 5, 3, 1,
  132203. 0, 2, 4, 6, 8, 10, 12, 14,
  132204. 16,
  132205. };
  132206. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  132207. _vq_quantthresh__44c0_s_p5_0,
  132208. _vq_quantmap__44c0_s_p5_0,
  132209. 17,
  132210. 17
  132211. };
  132212. static static_codebook _44c0_s_p5_0 = {
  132213. 2, 289,
  132214. _vq_lengthlist__44c0_s_p5_0,
  132215. 1, -529530880, 1611661312, 5, 0,
  132216. _vq_quantlist__44c0_s_p5_0,
  132217. NULL,
  132218. &_vq_auxt__44c0_s_p5_0,
  132219. NULL,
  132220. 0
  132221. };
  132222. static long _vq_quantlist__44c0_s_p6_0[] = {
  132223. 1,
  132224. 0,
  132225. 2,
  132226. };
  132227. static long _vq_lengthlist__44c0_s_p6_0[] = {
  132228. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  132229. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132230. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  132231. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  132232. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132233. 10,
  132234. };
  132235. static float _vq_quantthresh__44c0_s_p6_0[] = {
  132236. -5.5, 5.5,
  132237. };
  132238. static long _vq_quantmap__44c0_s_p6_0[] = {
  132239. 1, 0, 2,
  132240. };
  132241. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  132242. _vq_quantthresh__44c0_s_p6_0,
  132243. _vq_quantmap__44c0_s_p6_0,
  132244. 3,
  132245. 3
  132246. };
  132247. static static_codebook _44c0_s_p6_0 = {
  132248. 4, 81,
  132249. _vq_lengthlist__44c0_s_p6_0,
  132250. 1, -529137664, 1618345984, 2, 0,
  132251. _vq_quantlist__44c0_s_p6_0,
  132252. NULL,
  132253. &_vq_auxt__44c0_s_p6_0,
  132254. NULL,
  132255. 0
  132256. };
  132257. static long _vq_quantlist__44c0_s_p6_1[] = {
  132258. 5,
  132259. 4,
  132260. 6,
  132261. 3,
  132262. 7,
  132263. 2,
  132264. 8,
  132265. 1,
  132266. 9,
  132267. 0,
  132268. 10,
  132269. };
  132270. static long _vq_lengthlist__44c0_s_p6_1[] = {
  132271. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  132272. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132273. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132274. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  132275. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132276. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132277. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132278. 10,10,10, 8, 8, 8, 8, 8, 8,
  132279. };
  132280. static float _vq_quantthresh__44c0_s_p6_1[] = {
  132281. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132282. 3.5, 4.5,
  132283. };
  132284. static long _vq_quantmap__44c0_s_p6_1[] = {
  132285. 9, 7, 5, 3, 1, 0, 2, 4,
  132286. 6, 8, 10,
  132287. };
  132288. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  132289. _vq_quantthresh__44c0_s_p6_1,
  132290. _vq_quantmap__44c0_s_p6_1,
  132291. 11,
  132292. 11
  132293. };
  132294. static static_codebook _44c0_s_p6_1 = {
  132295. 2, 121,
  132296. _vq_lengthlist__44c0_s_p6_1,
  132297. 1, -531365888, 1611661312, 4, 0,
  132298. _vq_quantlist__44c0_s_p6_1,
  132299. NULL,
  132300. &_vq_auxt__44c0_s_p6_1,
  132301. NULL,
  132302. 0
  132303. };
  132304. static long _vq_quantlist__44c0_s_p7_0[] = {
  132305. 6,
  132306. 5,
  132307. 7,
  132308. 4,
  132309. 8,
  132310. 3,
  132311. 9,
  132312. 2,
  132313. 10,
  132314. 1,
  132315. 11,
  132316. 0,
  132317. 12,
  132318. };
  132319. static long _vq_lengthlist__44c0_s_p7_0[] = {
  132320. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  132321. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  132322. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132323. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132324. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  132325. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  132326. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  132327. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132328. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132329. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  132330. 0,12,12,11,11,12,12,13,13,
  132331. };
  132332. static float _vq_quantthresh__44c0_s_p7_0[] = {
  132333. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132334. 12.5, 17.5, 22.5, 27.5,
  132335. };
  132336. static long _vq_quantmap__44c0_s_p7_0[] = {
  132337. 11, 9, 7, 5, 3, 1, 0, 2,
  132338. 4, 6, 8, 10, 12,
  132339. };
  132340. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  132341. _vq_quantthresh__44c0_s_p7_0,
  132342. _vq_quantmap__44c0_s_p7_0,
  132343. 13,
  132344. 13
  132345. };
  132346. static static_codebook _44c0_s_p7_0 = {
  132347. 2, 169,
  132348. _vq_lengthlist__44c0_s_p7_0,
  132349. 1, -526516224, 1616117760, 4, 0,
  132350. _vq_quantlist__44c0_s_p7_0,
  132351. NULL,
  132352. &_vq_auxt__44c0_s_p7_0,
  132353. NULL,
  132354. 0
  132355. };
  132356. static long _vq_quantlist__44c0_s_p7_1[] = {
  132357. 2,
  132358. 1,
  132359. 3,
  132360. 0,
  132361. 4,
  132362. };
  132363. static long _vq_lengthlist__44c0_s_p7_1[] = {
  132364. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132365. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132366. };
  132367. static float _vq_quantthresh__44c0_s_p7_1[] = {
  132368. -1.5, -0.5, 0.5, 1.5,
  132369. };
  132370. static long _vq_quantmap__44c0_s_p7_1[] = {
  132371. 3, 1, 0, 2, 4,
  132372. };
  132373. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  132374. _vq_quantthresh__44c0_s_p7_1,
  132375. _vq_quantmap__44c0_s_p7_1,
  132376. 5,
  132377. 5
  132378. };
  132379. static static_codebook _44c0_s_p7_1 = {
  132380. 2, 25,
  132381. _vq_lengthlist__44c0_s_p7_1,
  132382. 1, -533725184, 1611661312, 3, 0,
  132383. _vq_quantlist__44c0_s_p7_1,
  132384. NULL,
  132385. &_vq_auxt__44c0_s_p7_1,
  132386. NULL,
  132387. 0
  132388. };
  132389. static long _vq_quantlist__44c0_s_p8_0[] = {
  132390. 2,
  132391. 1,
  132392. 3,
  132393. 0,
  132394. 4,
  132395. };
  132396. static long _vq_lengthlist__44c0_s_p8_0[] = {
  132397. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  132398. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132399. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132400. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132401. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132402. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132403. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132404. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  132405. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132406. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132407. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132408. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132409. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  132410. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132411. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132412. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  132413. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132414. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132415. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132416. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132417. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132418. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132419. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132420. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132421. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132422. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132423. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132424. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132425. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132426. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132427. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132428. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132429. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132430. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132431. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132432. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132433. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132434. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132435. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132436. 11,
  132437. };
  132438. static float _vq_quantthresh__44c0_s_p8_0[] = {
  132439. -331.5, -110.5, 110.5, 331.5,
  132440. };
  132441. static long _vq_quantmap__44c0_s_p8_0[] = {
  132442. 3, 1, 0, 2, 4,
  132443. };
  132444. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  132445. _vq_quantthresh__44c0_s_p8_0,
  132446. _vq_quantmap__44c0_s_p8_0,
  132447. 5,
  132448. 5
  132449. };
  132450. static static_codebook _44c0_s_p8_0 = {
  132451. 4, 625,
  132452. _vq_lengthlist__44c0_s_p8_0,
  132453. 1, -518283264, 1627103232, 3, 0,
  132454. _vq_quantlist__44c0_s_p8_0,
  132455. NULL,
  132456. &_vq_auxt__44c0_s_p8_0,
  132457. NULL,
  132458. 0
  132459. };
  132460. static long _vq_quantlist__44c0_s_p8_1[] = {
  132461. 6,
  132462. 5,
  132463. 7,
  132464. 4,
  132465. 8,
  132466. 3,
  132467. 9,
  132468. 2,
  132469. 10,
  132470. 1,
  132471. 11,
  132472. 0,
  132473. 12,
  132474. };
  132475. static long _vq_lengthlist__44c0_s_p8_1[] = {
  132476. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  132477. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  132478. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  132479. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  132480. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  132481. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  132482. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  132483. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  132484. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  132485. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  132486. 16,13,13,12,12,14,14,15,13,
  132487. };
  132488. static float _vq_quantthresh__44c0_s_p8_1[] = {
  132489. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132490. 42.5, 59.5, 76.5, 93.5,
  132491. };
  132492. static long _vq_quantmap__44c0_s_p8_1[] = {
  132493. 11, 9, 7, 5, 3, 1, 0, 2,
  132494. 4, 6, 8, 10, 12,
  132495. };
  132496. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  132497. _vq_quantthresh__44c0_s_p8_1,
  132498. _vq_quantmap__44c0_s_p8_1,
  132499. 13,
  132500. 13
  132501. };
  132502. static static_codebook _44c0_s_p8_1 = {
  132503. 2, 169,
  132504. _vq_lengthlist__44c0_s_p8_1,
  132505. 1, -522616832, 1620115456, 4, 0,
  132506. _vq_quantlist__44c0_s_p8_1,
  132507. NULL,
  132508. &_vq_auxt__44c0_s_p8_1,
  132509. NULL,
  132510. 0
  132511. };
  132512. static long _vq_quantlist__44c0_s_p8_2[] = {
  132513. 8,
  132514. 7,
  132515. 9,
  132516. 6,
  132517. 10,
  132518. 5,
  132519. 11,
  132520. 4,
  132521. 12,
  132522. 3,
  132523. 13,
  132524. 2,
  132525. 14,
  132526. 1,
  132527. 15,
  132528. 0,
  132529. 16,
  132530. };
  132531. static long _vq_lengthlist__44c0_s_p8_2[] = {
  132532. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132533. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  132534. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  132535. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  132536. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132537. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  132538. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  132539. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  132540. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  132541. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  132542. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  132543. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  132544. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  132545. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  132546. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  132547. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  132548. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  132549. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  132550. 10,
  132551. };
  132552. static float _vq_quantthresh__44c0_s_p8_2[] = {
  132553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132555. };
  132556. static long _vq_quantmap__44c0_s_p8_2[] = {
  132557. 15, 13, 11, 9, 7, 5, 3, 1,
  132558. 0, 2, 4, 6, 8, 10, 12, 14,
  132559. 16,
  132560. };
  132561. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  132562. _vq_quantthresh__44c0_s_p8_2,
  132563. _vq_quantmap__44c0_s_p8_2,
  132564. 17,
  132565. 17
  132566. };
  132567. static static_codebook _44c0_s_p8_2 = {
  132568. 2, 289,
  132569. _vq_lengthlist__44c0_s_p8_2,
  132570. 1, -529530880, 1611661312, 5, 0,
  132571. _vq_quantlist__44c0_s_p8_2,
  132572. NULL,
  132573. &_vq_auxt__44c0_s_p8_2,
  132574. NULL,
  132575. 0
  132576. };
  132577. static long _huff_lengthlist__44c0_s_short[] = {
  132578. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  132579. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  132580. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  132581. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  132582. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  132583. 12,
  132584. };
  132585. static static_codebook _huff_book__44c0_s_short = {
  132586. 2, 81,
  132587. _huff_lengthlist__44c0_s_short,
  132588. 0, 0, 0, 0, 0,
  132589. NULL,
  132590. NULL,
  132591. NULL,
  132592. NULL,
  132593. 0
  132594. };
  132595. static long _huff_lengthlist__44c0_sm_long[] = {
  132596. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  132597. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  132598. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  132599. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  132600. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  132601. 13,
  132602. };
  132603. static static_codebook _huff_book__44c0_sm_long = {
  132604. 2, 81,
  132605. _huff_lengthlist__44c0_sm_long,
  132606. 0, 0, 0, 0, 0,
  132607. NULL,
  132608. NULL,
  132609. NULL,
  132610. NULL,
  132611. 0
  132612. };
  132613. static long _vq_quantlist__44c0_sm_p1_0[] = {
  132614. 1,
  132615. 0,
  132616. 2,
  132617. };
  132618. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  132619. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132620. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  132623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132624. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132625. 0, 0, 0, 7, 8, 9, 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, 0, 0, 0, 0, 0, 0,
  132628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132629. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132630. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0,
  132633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  132665. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132670. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132675. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132711. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132716. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132721. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  133030. };
  133031. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  133032. -0.5, 0.5,
  133033. };
  133034. static long _vq_quantmap__44c0_sm_p1_0[] = {
  133035. 1, 0, 2,
  133036. };
  133037. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  133038. _vq_quantthresh__44c0_sm_p1_0,
  133039. _vq_quantmap__44c0_sm_p1_0,
  133040. 3,
  133041. 3
  133042. };
  133043. static static_codebook _44c0_sm_p1_0 = {
  133044. 8, 6561,
  133045. _vq_lengthlist__44c0_sm_p1_0,
  133046. 1, -535822336, 1611661312, 2, 0,
  133047. _vq_quantlist__44c0_sm_p1_0,
  133048. NULL,
  133049. &_vq_auxt__44c0_sm_p1_0,
  133050. NULL,
  133051. 0
  133052. };
  133053. static long _vq_quantlist__44c0_sm_p2_0[] = {
  133054. 2,
  133055. 1,
  133056. 3,
  133057. 0,
  133058. 4,
  133059. };
  133060. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  133061. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  133063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133064. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133100. 0,
  133101. };
  133102. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  133103. -1.5, -0.5, 0.5, 1.5,
  133104. };
  133105. static long _vq_quantmap__44c0_sm_p2_0[] = {
  133106. 3, 1, 0, 2, 4,
  133107. };
  133108. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  133109. _vq_quantthresh__44c0_sm_p2_0,
  133110. _vq_quantmap__44c0_sm_p2_0,
  133111. 5,
  133112. 5
  133113. };
  133114. static static_codebook _44c0_sm_p2_0 = {
  133115. 4, 625,
  133116. _vq_lengthlist__44c0_sm_p2_0,
  133117. 1, -533725184, 1611661312, 3, 0,
  133118. _vq_quantlist__44c0_sm_p2_0,
  133119. NULL,
  133120. &_vq_auxt__44c0_sm_p2_0,
  133121. NULL,
  133122. 0
  133123. };
  133124. static long _vq_quantlist__44c0_sm_p3_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_p3_0[] = {
  133136. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  133137. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  133138. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133139. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  133140. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133141. 0,
  133142. };
  133143. static float _vq_quantthresh__44c0_sm_p3_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_p3_0[] = {
  133147. 7, 5, 3, 1, 0, 2, 4, 6,
  133148. 8,
  133149. };
  133150. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  133151. _vq_quantthresh__44c0_sm_p3_0,
  133152. _vq_quantmap__44c0_sm_p3_0,
  133153. 9,
  133154. 9
  133155. };
  133156. static static_codebook _44c0_sm_p3_0 = {
  133157. 2, 81,
  133158. _vq_lengthlist__44c0_sm_p3_0,
  133159. 1, -531628032, 1611661312, 4, 0,
  133160. _vq_quantlist__44c0_sm_p3_0,
  133161. NULL,
  133162. &_vq_auxt__44c0_sm_p3_0,
  133163. NULL,
  133164. 0
  133165. };
  133166. static long _vq_quantlist__44c0_sm_p4_0[] = {
  133167. 4,
  133168. 3,
  133169. 5,
  133170. 2,
  133171. 6,
  133172. 1,
  133173. 7,
  133174. 0,
  133175. 8,
  133176. };
  133177. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  133178. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  133179. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133180. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133181. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133182. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133183. 11,
  133184. };
  133185. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  133186. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133187. };
  133188. static long _vq_quantmap__44c0_sm_p4_0[] = {
  133189. 7, 5, 3, 1, 0, 2, 4, 6,
  133190. 8,
  133191. };
  133192. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  133193. _vq_quantthresh__44c0_sm_p4_0,
  133194. _vq_quantmap__44c0_sm_p4_0,
  133195. 9,
  133196. 9
  133197. };
  133198. static static_codebook _44c0_sm_p4_0 = {
  133199. 2, 81,
  133200. _vq_lengthlist__44c0_sm_p4_0,
  133201. 1, -531628032, 1611661312, 4, 0,
  133202. _vq_quantlist__44c0_sm_p4_0,
  133203. NULL,
  133204. &_vq_auxt__44c0_sm_p4_0,
  133205. NULL,
  133206. 0
  133207. };
  133208. static long _vq_quantlist__44c0_sm_p5_0[] = {
  133209. 8,
  133210. 7,
  133211. 9,
  133212. 6,
  133213. 10,
  133214. 5,
  133215. 11,
  133216. 4,
  133217. 12,
  133218. 3,
  133219. 13,
  133220. 2,
  133221. 14,
  133222. 1,
  133223. 15,
  133224. 0,
  133225. 16,
  133226. };
  133227. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  133228. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  133229. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  133230. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133231. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  133232. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  133233. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  133234. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  133235. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133236. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  133237. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133238. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133239. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133240. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  133241. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  133242. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  133243. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  133244. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  133245. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133246. 14,
  133247. };
  133248. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  133249. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133250. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133251. };
  133252. static long _vq_quantmap__44c0_sm_p5_0[] = {
  133253. 15, 13, 11, 9, 7, 5, 3, 1,
  133254. 0, 2, 4, 6, 8, 10, 12, 14,
  133255. 16,
  133256. };
  133257. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  133258. _vq_quantthresh__44c0_sm_p5_0,
  133259. _vq_quantmap__44c0_sm_p5_0,
  133260. 17,
  133261. 17
  133262. };
  133263. static static_codebook _44c0_sm_p5_0 = {
  133264. 2, 289,
  133265. _vq_lengthlist__44c0_sm_p5_0,
  133266. 1, -529530880, 1611661312, 5, 0,
  133267. _vq_quantlist__44c0_sm_p5_0,
  133268. NULL,
  133269. &_vq_auxt__44c0_sm_p5_0,
  133270. NULL,
  133271. 0
  133272. };
  133273. static long _vq_quantlist__44c0_sm_p6_0[] = {
  133274. 1,
  133275. 0,
  133276. 2,
  133277. };
  133278. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  133279. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133280. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133281. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133282. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  133283. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  133284. 11,
  133285. };
  133286. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  133287. -5.5, 5.5,
  133288. };
  133289. static long _vq_quantmap__44c0_sm_p6_0[] = {
  133290. 1, 0, 2,
  133291. };
  133292. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  133293. _vq_quantthresh__44c0_sm_p6_0,
  133294. _vq_quantmap__44c0_sm_p6_0,
  133295. 3,
  133296. 3
  133297. };
  133298. static static_codebook _44c0_sm_p6_0 = {
  133299. 4, 81,
  133300. _vq_lengthlist__44c0_sm_p6_0,
  133301. 1, -529137664, 1618345984, 2, 0,
  133302. _vq_quantlist__44c0_sm_p6_0,
  133303. NULL,
  133304. &_vq_auxt__44c0_sm_p6_0,
  133305. NULL,
  133306. 0
  133307. };
  133308. static long _vq_quantlist__44c0_sm_p6_1[] = {
  133309. 5,
  133310. 4,
  133311. 6,
  133312. 3,
  133313. 7,
  133314. 2,
  133315. 8,
  133316. 1,
  133317. 9,
  133318. 0,
  133319. 10,
  133320. };
  133321. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  133322. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  133323. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133324. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133325. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  133326. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  133327. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133328. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133329. 10,10,10, 8, 8, 8, 8, 8, 8,
  133330. };
  133331. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  133332. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133333. 3.5, 4.5,
  133334. };
  133335. static long _vq_quantmap__44c0_sm_p6_1[] = {
  133336. 9, 7, 5, 3, 1, 0, 2, 4,
  133337. 6, 8, 10,
  133338. };
  133339. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  133340. _vq_quantthresh__44c0_sm_p6_1,
  133341. _vq_quantmap__44c0_sm_p6_1,
  133342. 11,
  133343. 11
  133344. };
  133345. static static_codebook _44c0_sm_p6_1 = {
  133346. 2, 121,
  133347. _vq_lengthlist__44c0_sm_p6_1,
  133348. 1, -531365888, 1611661312, 4, 0,
  133349. _vq_quantlist__44c0_sm_p6_1,
  133350. NULL,
  133351. &_vq_auxt__44c0_sm_p6_1,
  133352. NULL,
  133353. 0
  133354. };
  133355. static long _vq_quantlist__44c0_sm_p7_0[] = {
  133356. 6,
  133357. 5,
  133358. 7,
  133359. 4,
  133360. 8,
  133361. 3,
  133362. 9,
  133363. 2,
  133364. 10,
  133365. 1,
  133366. 11,
  133367. 0,
  133368. 12,
  133369. };
  133370. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  133371. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133372. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  133373. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133374. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133375. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133376. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  133377. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133378. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133379. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133380. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  133381. 0,12,12,11,11,13,12,14,14,
  133382. };
  133383. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  133384. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133385. 12.5, 17.5, 22.5, 27.5,
  133386. };
  133387. static long _vq_quantmap__44c0_sm_p7_0[] = {
  133388. 11, 9, 7, 5, 3, 1, 0, 2,
  133389. 4, 6, 8, 10, 12,
  133390. };
  133391. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  133392. _vq_quantthresh__44c0_sm_p7_0,
  133393. _vq_quantmap__44c0_sm_p7_0,
  133394. 13,
  133395. 13
  133396. };
  133397. static static_codebook _44c0_sm_p7_0 = {
  133398. 2, 169,
  133399. _vq_lengthlist__44c0_sm_p7_0,
  133400. 1, -526516224, 1616117760, 4, 0,
  133401. _vq_quantlist__44c0_sm_p7_0,
  133402. NULL,
  133403. &_vq_auxt__44c0_sm_p7_0,
  133404. NULL,
  133405. 0
  133406. };
  133407. static long _vq_quantlist__44c0_sm_p7_1[] = {
  133408. 2,
  133409. 1,
  133410. 3,
  133411. 0,
  133412. 4,
  133413. };
  133414. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  133415. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133416. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133417. };
  133418. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  133419. -1.5, -0.5, 0.5, 1.5,
  133420. };
  133421. static long _vq_quantmap__44c0_sm_p7_1[] = {
  133422. 3, 1, 0, 2, 4,
  133423. };
  133424. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  133425. _vq_quantthresh__44c0_sm_p7_1,
  133426. _vq_quantmap__44c0_sm_p7_1,
  133427. 5,
  133428. 5
  133429. };
  133430. static static_codebook _44c0_sm_p7_1 = {
  133431. 2, 25,
  133432. _vq_lengthlist__44c0_sm_p7_1,
  133433. 1, -533725184, 1611661312, 3, 0,
  133434. _vq_quantlist__44c0_sm_p7_1,
  133435. NULL,
  133436. &_vq_auxt__44c0_sm_p7_1,
  133437. NULL,
  133438. 0
  133439. };
  133440. static long _vq_quantlist__44c0_sm_p8_0[] = {
  133441. 4,
  133442. 3,
  133443. 5,
  133444. 2,
  133445. 6,
  133446. 1,
  133447. 7,
  133448. 0,
  133449. 8,
  133450. };
  133451. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  133452. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  133453. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  133454. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133455. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133456. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133457. 12,
  133458. };
  133459. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  133460. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  133461. };
  133462. static long _vq_quantmap__44c0_sm_p8_0[] = {
  133463. 7, 5, 3, 1, 0, 2, 4, 6,
  133464. 8,
  133465. };
  133466. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  133467. _vq_quantthresh__44c0_sm_p8_0,
  133468. _vq_quantmap__44c0_sm_p8_0,
  133469. 9,
  133470. 9
  133471. };
  133472. static static_codebook _44c0_sm_p8_0 = {
  133473. 2, 81,
  133474. _vq_lengthlist__44c0_sm_p8_0,
  133475. 1, -516186112, 1627103232, 4, 0,
  133476. _vq_quantlist__44c0_sm_p8_0,
  133477. NULL,
  133478. &_vq_auxt__44c0_sm_p8_0,
  133479. NULL,
  133480. 0
  133481. };
  133482. static long _vq_quantlist__44c0_sm_p8_1[] = {
  133483. 6,
  133484. 5,
  133485. 7,
  133486. 4,
  133487. 8,
  133488. 3,
  133489. 9,
  133490. 2,
  133491. 10,
  133492. 1,
  133493. 11,
  133494. 0,
  133495. 12,
  133496. };
  133497. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  133498. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133499. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  133500. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  133501. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  133502. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  133503. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  133504. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  133505. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  133506. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  133507. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  133508. 20,13,13,12,12,16,13,15,13,
  133509. };
  133510. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  133511. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133512. 42.5, 59.5, 76.5, 93.5,
  133513. };
  133514. static long _vq_quantmap__44c0_sm_p8_1[] = {
  133515. 11, 9, 7, 5, 3, 1, 0, 2,
  133516. 4, 6, 8, 10, 12,
  133517. };
  133518. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  133519. _vq_quantthresh__44c0_sm_p8_1,
  133520. _vq_quantmap__44c0_sm_p8_1,
  133521. 13,
  133522. 13
  133523. };
  133524. static static_codebook _44c0_sm_p8_1 = {
  133525. 2, 169,
  133526. _vq_lengthlist__44c0_sm_p8_1,
  133527. 1, -522616832, 1620115456, 4, 0,
  133528. _vq_quantlist__44c0_sm_p8_1,
  133529. NULL,
  133530. &_vq_auxt__44c0_sm_p8_1,
  133531. NULL,
  133532. 0
  133533. };
  133534. static long _vq_quantlist__44c0_sm_p8_2[] = {
  133535. 8,
  133536. 7,
  133537. 9,
  133538. 6,
  133539. 10,
  133540. 5,
  133541. 11,
  133542. 4,
  133543. 12,
  133544. 3,
  133545. 13,
  133546. 2,
  133547. 14,
  133548. 1,
  133549. 15,
  133550. 0,
  133551. 16,
  133552. };
  133553. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  133554. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133555. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133556. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  133557. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133558. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133559. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133560. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133561. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133562. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  133563. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  133564. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  133565. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133566. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  133567. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  133568. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133569. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  133570. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  133571. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  133572. 9,
  133573. };
  133574. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  133575. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133576. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133577. };
  133578. static long _vq_quantmap__44c0_sm_p8_2[] = {
  133579. 15, 13, 11, 9, 7, 5, 3, 1,
  133580. 0, 2, 4, 6, 8, 10, 12, 14,
  133581. 16,
  133582. };
  133583. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  133584. _vq_quantthresh__44c0_sm_p8_2,
  133585. _vq_quantmap__44c0_sm_p8_2,
  133586. 17,
  133587. 17
  133588. };
  133589. static static_codebook _44c0_sm_p8_2 = {
  133590. 2, 289,
  133591. _vq_lengthlist__44c0_sm_p8_2,
  133592. 1, -529530880, 1611661312, 5, 0,
  133593. _vq_quantlist__44c0_sm_p8_2,
  133594. NULL,
  133595. &_vq_auxt__44c0_sm_p8_2,
  133596. NULL,
  133597. 0
  133598. };
  133599. static long _huff_lengthlist__44c0_sm_short[] = {
  133600. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  133601. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  133602. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  133603. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  133604. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  133605. 12,
  133606. };
  133607. static static_codebook _huff_book__44c0_sm_short = {
  133608. 2, 81,
  133609. _huff_lengthlist__44c0_sm_short,
  133610. 0, 0, 0, 0, 0,
  133611. NULL,
  133612. NULL,
  133613. NULL,
  133614. NULL,
  133615. 0
  133616. };
  133617. static long _huff_lengthlist__44c1_s_long[] = {
  133618. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  133619. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  133620. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  133621. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  133622. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  133623. 11,
  133624. };
  133625. static static_codebook _huff_book__44c1_s_long = {
  133626. 2, 81,
  133627. _huff_lengthlist__44c1_s_long,
  133628. 0, 0, 0, 0, 0,
  133629. NULL,
  133630. NULL,
  133631. NULL,
  133632. NULL,
  133633. 0
  133634. };
  133635. static long _vq_quantlist__44c1_s_p1_0[] = {
  133636. 1,
  133637. 0,
  133638. 2,
  133639. };
  133640. static long _vq_lengthlist__44c1_s_p1_0[] = {
  133641. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  133642. 0, 0, 5, 6, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  133645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133646. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  133647. 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0,
  133650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133651. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133652. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0,
  133655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0,
  133687. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  133692. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  133697. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133733. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  133738. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133743. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  134052. };
  134053. static float _vq_quantthresh__44c1_s_p1_0[] = {
  134054. -0.5, 0.5,
  134055. };
  134056. static long _vq_quantmap__44c1_s_p1_0[] = {
  134057. 1, 0, 2,
  134058. };
  134059. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  134060. _vq_quantthresh__44c1_s_p1_0,
  134061. _vq_quantmap__44c1_s_p1_0,
  134062. 3,
  134063. 3
  134064. };
  134065. static static_codebook _44c1_s_p1_0 = {
  134066. 8, 6561,
  134067. _vq_lengthlist__44c1_s_p1_0,
  134068. 1, -535822336, 1611661312, 2, 0,
  134069. _vq_quantlist__44c1_s_p1_0,
  134070. NULL,
  134071. &_vq_auxt__44c1_s_p1_0,
  134072. NULL,
  134073. 0
  134074. };
  134075. static long _vq_quantlist__44c1_s_p2_0[] = {
  134076. 2,
  134077. 1,
  134078. 3,
  134079. 0,
  134080. 4,
  134081. };
  134082. static long _vq_lengthlist__44c1_s_p2_0[] = {
  134083. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134086. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  134088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134089. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0,
  134123. };
  134124. static float _vq_quantthresh__44c1_s_p2_0[] = {
  134125. -1.5, -0.5, 0.5, 1.5,
  134126. };
  134127. static long _vq_quantmap__44c1_s_p2_0[] = {
  134128. 3, 1, 0, 2, 4,
  134129. };
  134130. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  134131. _vq_quantthresh__44c1_s_p2_0,
  134132. _vq_quantmap__44c1_s_p2_0,
  134133. 5,
  134134. 5
  134135. };
  134136. static static_codebook _44c1_s_p2_0 = {
  134137. 4, 625,
  134138. _vq_lengthlist__44c1_s_p2_0,
  134139. 1, -533725184, 1611661312, 3, 0,
  134140. _vq_quantlist__44c1_s_p2_0,
  134141. NULL,
  134142. &_vq_auxt__44c1_s_p2_0,
  134143. NULL,
  134144. 0
  134145. };
  134146. static long _vq_quantlist__44c1_s_p3_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_p3_0[] = {
  134158. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  134159. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  134160. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134161. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134162. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0,
  134164. };
  134165. static float _vq_quantthresh__44c1_s_p3_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_p3_0[] = {
  134169. 7, 5, 3, 1, 0, 2, 4, 6,
  134170. 8,
  134171. };
  134172. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  134173. _vq_quantthresh__44c1_s_p3_0,
  134174. _vq_quantmap__44c1_s_p3_0,
  134175. 9,
  134176. 9
  134177. };
  134178. static static_codebook _44c1_s_p3_0 = {
  134179. 2, 81,
  134180. _vq_lengthlist__44c1_s_p3_0,
  134181. 1, -531628032, 1611661312, 4, 0,
  134182. _vq_quantlist__44c1_s_p3_0,
  134183. NULL,
  134184. &_vq_auxt__44c1_s_p3_0,
  134185. NULL,
  134186. 0
  134187. };
  134188. static long _vq_quantlist__44c1_s_p4_0[] = {
  134189. 4,
  134190. 3,
  134191. 5,
  134192. 2,
  134193. 6,
  134194. 1,
  134195. 7,
  134196. 0,
  134197. 8,
  134198. };
  134199. static long _vq_lengthlist__44c1_s_p4_0[] = {
  134200. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  134201. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134202. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134203. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  134204. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134205. 11,
  134206. };
  134207. static float _vq_quantthresh__44c1_s_p4_0[] = {
  134208. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134209. };
  134210. static long _vq_quantmap__44c1_s_p4_0[] = {
  134211. 7, 5, 3, 1, 0, 2, 4, 6,
  134212. 8,
  134213. };
  134214. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  134215. _vq_quantthresh__44c1_s_p4_0,
  134216. _vq_quantmap__44c1_s_p4_0,
  134217. 9,
  134218. 9
  134219. };
  134220. static static_codebook _44c1_s_p4_0 = {
  134221. 2, 81,
  134222. _vq_lengthlist__44c1_s_p4_0,
  134223. 1, -531628032, 1611661312, 4, 0,
  134224. _vq_quantlist__44c1_s_p4_0,
  134225. NULL,
  134226. &_vq_auxt__44c1_s_p4_0,
  134227. NULL,
  134228. 0
  134229. };
  134230. static long _vq_quantlist__44c1_s_p5_0[] = {
  134231. 8,
  134232. 7,
  134233. 9,
  134234. 6,
  134235. 10,
  134236. 5,
  134237. 11,
  134238. 4,
  134239. 12,
  134240. 3,
  134241. 13,
  134242. 2,
  134243. 14,
  134244. 1,
  134245. 15,
  134246. 0,
  134247. 16,
  134248. };
  134249. static long _vq_lengthlist__44c1_s_p5_0[] = {
  134250. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134251. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134252. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134253. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134254. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134255. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  134256. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  134257. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134258. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134259. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134260. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134261. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134262. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134263. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134264. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  134265. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134266. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  134267. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134268. 14,
  134269. };
  134270. static float _vq_quantthresh__44c1_s_p5_0[] = {
  134271. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134272. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134273. };
  134274. static long _vq_quantmap__44c1_s_p5_0[] = {
  134275. 15, 13, 11, 9, 7, 5, 3, 1,
  134276. 0, 2, 4, 6, 8, 10, 12, 14,
  134277. 16,
  134278. };
  134279. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  134280. _vq_quantthresh__44c1_s_p5_0,
  134281. _vq_quantmap__44c1_s_p5_0,
  134282. 17,
  134283. 17
  134284. };
  134285. static static_codebook _44c1_s_p5_0 = {
  134286. 2, 289,
  134287. _vq_lengthlist__44c1_s_p5_0,
  134288. 1, -529530880, 1611661312, 5, 0,
  134289. _vq_quantlist__44c1_s_p5_0,
  134290. NULL,
  134291. &_vq_auxt__44c1_s_p5_0,
  134292. NULL,
  134293. 0
  134294. };
  134295. static long _vq_quantlist__44c1_s_p6_0[] = {
  134296. 1,
  134297. 0,
  134298. 2,
  134299. };
  134300. static long _vq_lengthlist__44c1_s_p6_0[] = {
  134301. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134302. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  134303. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  134304. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  134305. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  134306. 11,
  134307. };
  134308. static float _vq_quantthresh__44c1_s_p6_0[] = {
  134309. -5.5, 5.5,
  134310. };
  134311. static long _vq_quantmap__44c1_s_p6_0[] = {
  134312. 1, 0, 2,
  134313. };
  134314. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  134315. _vq_quantthresh__44c1_s_p6_0,
  134316. _vq_quantmap__44c1_s_p6_0,
  134317. 3,
  134318. 3
  134319. };
  134320. static static_codebook _44c1_s_p6_0 = {
  134321. 4, 81,
  134322. _vq_lengthlist__44c1_s_p6_0,
  134323. 1, -529137664, 1618345984, 2, 0,
  134324. _vq_quantlist__44c1_s_p6_0,
  134325. NULL,
  134326. &_vq_auxt__44c1_s_p6_0,
  134327. NULL,
  134328. 0
  134329. };
  134330. static long _vq_quantlist__44c1_s_p6_1[] = {
  134331. 5,
  134332. 4,
  134333. 6,
  134334. 3,
  134335. 7,
  134336. 2,
  134337. 8,
  134338. 1,
  134339. 9,
  134340. 0,
  134341. 10,
  134342. };
  134343. static long _vq_lengthlist__44c1_s_p6_1[] = {
  134344. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  134345. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  134346. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134347. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  134348. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  134349. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134350. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134351. 10,10,10, 8, 8, 8, 8, 8, 8,
  134352. };
  134353. static float _vq_quantthresh__44c1_s_p6_1[] = {
  134354. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134355. 3.5, 4.5,
  134356. };
  134357. static long _vq_quantmap__44c1_s_p6_1[] = {
  134358. 9, 7, 5, 3, 1, 0, 2, 4,
  134359. 6, 8, 10,
  134360. };
  134361. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  134362. _vq_quantthresh__44c1_s_p6_1,
  134363. _vq_quantmap__44c1_s_p6_1,
  134364. 11,
  134365. 11
  134366. };
  134367. static static_codebook _44c1_s_p6_1 = {
  134368. 2, 121,
  134369. _vq_lengthlist__44c1_s_p6_1,
  134370. 1, -531365888, 1611661312, 4, 0,
  134371. _vq_quantlist__44c1_s_p6_1,
  134372. NULL,
  134373. &_vq_auxt__44c1_s_p6_1,
  134374. NULL,
  134375. 0
  134376. };
  134377. static long _vq_quantlist__44c1_s_p7_0[] = {
  134378. 6,
  134379. 5,
  134380. 7,
  134381. 4,
  134382. 8,
  134383. 3,
  134384. 9,
  134385. 2,
  134386. 10,
  134387. 1,
  134388. 11,
  134389. 0,
  134390. 12,
  134391. };
  134392. static long _vq_lengthlist__44c1_s_p7_0[] = {
  134393. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  134394. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  134395. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134396. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134397. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  134398. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  134399. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  134400. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134401. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134402. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  134403. 0,12,11,11,11,13,10,14,13,
  134404. };
  134405. static float _vq_quantthresh__44c1_s_p7_0[] = {
  134406. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134407. 12.5, 17.5, 22.5, 27.5,
  134408. };
  134409. static long _vq_quantmap__44c1_s_p7_0[] = {
  134410. 11, 9, 7, 5, 3, 1, 0, 2,
  134411. 4, 6, 8, 10, 12,
  134412. };
  134413. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  134414. _vq_quantthresh__44c1_s_p7_0,
  134415. _vq_quantmap__44c1_s_p7_0,
  134416. 13,
  134417. 13
  134418. };
  134419. static static_codebook _44c1_s_p7_0 = {
  134420. 2, 169,
  134421. _vq_lengthlist__44c1_s_p7_0,
  134422. 1, -526516224, 1616117760, 4, 0,
  134423. _vq_quantlist__44c1_s_p7_0,
  134424. NULL,
  134425. &_vq_auxt__44c1_s_p7_0,
  134426. NULL,
  134427. 0
  134428. };
  134429. static long _vq_quantlist__44c1_s_p7_1[] = {
  134430. 2,
  134431. 1,
  134432. 3,
  134433. 0,
  134434. 4,
  134435. };
  134436. static long _vq_lengthlist__44c1_s_p7_1[] = {
  134437. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134438. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134439. };
  134440. static float _vq_quantthresh__44c1_s_p7_1[] = {
  134441. -1.5, -0.5, 0.5, 1.5,
  134442. };
  134443. static long _vq_quantmap__44c1_s_p7_1[] = {
  134444. 3, 1, 0, 2, 4,
  134445. };
  134446. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  134447. _vq_quantthresh__44c1_s_p7_1,
  134448. _vq_quantmap__44c1_s_p7_1,
  134449. 5,
  134450. 5
  134451. };
  134452. static static_codebook _44c1_s_p7_1 = {
  134453. 2, 25,
  134454. _vq_lengthlist__44c1_s_p7_1,
  134455. 1, -533725184, 1611661312, 3, 0,
  134456. _vq_quantlist__44c1_s_p7_1,
  134457. NULL,
  134458. &_vq_auxt__44c1_s_p7_1,
  134459. NULL,
  134460. 0
  134461. };
  134462. static long _vq_quantlist__44c1_s_p8_0[] = {
  134463. 6,
  134464. 5,
  134465. 7,
  134466. 4,
  134467. 8,
  134468. 3,
  134469. 9,
  134470. 2,
  134471. 10,
  134472. 1,
  134473. 11,
  134474. 0,
  134475. 12,
  134476. };
  134477. static long _vq_lengthlist__44c1_s_p8_0[] = {
  134478. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  134479. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  134480. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134481. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134482. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134483. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134484. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134485. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134486. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134487. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134488. 10,10,10,10,10,10,10,10,10,
  134489. };
  134490. static float _vq_quantthresh__44c1_s_p8_0[] = {
  134491. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  134492. 552.5, 773.5, 994.5, 1215.5,
  134493. };
  134494. static long _vq_quantmap__44c1_s_p8_0[] = {
  134495. 11, 9, 7, 5, 3, 1, 0, 2,
  134496. 4, 6, 8, 10, 12,
  134497. };
  134498. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  134499. _vq_quantthresh__44c1_s_p8_0,
  134500. _vq_quantmap__44c1_s_p8_0,
  134501. 13,
  134502. 13
  134503. };
  134504. static static_codebook _44c1_s_p8_0 = {
  134505. 2, 169,
  134506. _vq_lengthlist__44c1_s_p8_0,
  134507. 1, -514541568, 1627103232, 4, 0,
  134508. _vq_quantlist__44c1_s_p8_0,
  134509. NULL,
  134510. &_vq_auxt__44c1_s_p8_0,
  134511. NULL,
  134512. 0
  134513. };
  134514. static long _vq_quantlist__44c1_s_p8_1[] = {
  134515. 6,
  134516. 5,
  134517. 7,
  134518. 4,
  134519. 8,
  134520. 3,
  134521. 9,
  134522. 2,
  134523. 10,
  134524. 1,
  134525. 11,
  134526. 0,
  134527. 12,
  134528. };
  134529. static long _vq_lengthlist__44c1_s_p8_1[] = {
  134530. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134531. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134532. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  134533. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  134534. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  134535. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  134536. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  134537. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  134538. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  134539. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  134540. 16,13,12,12,11,14,12,15,13,
  134541. };
  134542. static float _vq_quantthresh__44c1_s_p8_1[] = {
  134543. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134544. 42.5, 59.5, 76.5, 93.5,
  134545. };
  134546. static long _vq_quantmap__44c1_s_p8_1[] = {
  134547. 11, 9, 7, 5, 3, 1, 0, 2,
  134548. 4, 6, 8, 10, 12,
  134549. };
  134550. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  134551. _vq_quantthresh__44c1_s_p8_1,
  134552. _vq_quantmap__44c1_s_p8_1,
  134553. 13,
  134554. 13
  134555. };
  134556. static static_codebook _44c1_s_p8_1 = {
  134557. 2, 169,
  134558. _vq_lengthlist__44c1_s_p8_1,
  134559. 1, -522616832, 1620115456, 4, 0,
  134560. _vq_quantlist__44c1_s_p8_1,
  134561. NULL,
  134562. &_vq_auxt__44c1_s_p8_1,
  134563. NULL,
  134564. 0
  134565. };
  134566. static long _vq_quantlist__44c1_s_p8_2[] = {
  134567. 8,
  134568. 7,
  134569. 9,
  134570. 6,
  134571. 10,
  134572. 5,
  134573. 11,
  134574. 4,
  134575. 12,
  134576. 3,
  134577. 13,
  134578. 2,
  134579. 14,
  134580. 1,
  134581. 15,
  134582. 0,
  134583. 16,
  134584. };
  134585. static long _vq_lengthlist__44c1_s_p8_2[] = {
  134586. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134587. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134588. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134589. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134590. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134591. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134592. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134593. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  134594. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  134595. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  134596. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  134597. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134598. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  134599. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  134600. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134601. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  134602. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  134603. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  134604. 9,
  134605. };
  134606. static float _vq_quantthresh__44c1_s_p8_2[] = {
  134607. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134608. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134609. };
  134610. static long _vq_quantmap__44c1_s_p8_2[] = {
  134611. 15, 13, 11, 9, 7, 5, 3, 1,
  134612. 0, 2, 4, 6, 8, 10, 12, 14,
  134613. 16,
  134614. };
  134615. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  134616. _vq_quantthresh__44c1_s_p8_2,
  134617. _vq_quantmap__44c1_s_p8_2,
  134618. 17,
  134619. 17
  134620. };
  134621. static static_codebook _44c1_s_p8_2 = {
  134622. 2, 289,
  134623. _vq_lengthlist__44c1_s_p8_2,
  134624. 1, -529530880, 1611661312, 5, 0,
  134625. _vq_quantlist__44c1_s_p8_2,
  134626. NULL,
  134627. &_vq_auxt__44c1_s_p8_2,
  134628. NULL,
  134629. 0
  134630. };
  134631. static long _huff_lengthlist__44c1_s_short[] = {
  134632. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  134633. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  134634. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  134635. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  134636. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  134637. 11,
  134638. };
  134639. static static_codebook _huff_book__44c1_s_short = {
  134640. 2, 81,
  134641. _huff_lengthlist__44c1_s_short,
  134642. 0, 0, 0, 0, 0,
  134643. NULL,
  134644. NULL,
  134645. NULL,
  134646. NULL,
  134647. 0
  134648. };
  134649. static long _huff_lengthlist__44c1_sm_long[] = {
  134650. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  134651. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  134652. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  134653. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  134654. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  134655. 11,
  134656. };
  134657. static static_codebook _huff_book__44c1_sm_long = {
  134658. 2, 81,
  134659. _huff_lengthlist__44c1_sm_long,
  134660. 0, 0, 0, 0, 0,
  134661. NULL,
  134662. NULL,
  134663. NULL,
  134664. NULL,
  134665. 0
  134666. };
  134667. static long _vq_quantlist__44c1_sm_p1_0[] = {
  134668. 1,
  134669. 0,
  134670. 2,
  134671. };
  134672. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  134673. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134674. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  134677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134678. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134679. 0, 0, 0, 7, 8, 9, 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, 0, 0, 0, 0, 0, 0,
  134682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134683. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  134684. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0,
  134687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  134719. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134724. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134729. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134765. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134770. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134775. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  135084. };
  135085. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  135086. -0.5, 0.5,
  135087. };
  135088. static long _vq_quantmap__44c1_sm_p1_0[] = {
  135089. 1, 0, 2,
  135090. };
  135091. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  135092. _vq_quantthresh__44c1_sm_p1_0,
  135093. _vq_quantmap__44c1_sm_p1_0,
  135094. 3,
  135095. 3
  135096. };
  135097. static static_codebook _44c1_sm_p1_0 = {
  135098. 8, 6561,
  135099. _vq_lengthlist__44c1_sm_p1_0,
  135100. 1, -535822336, 1611661312, 2, 0,
  135101. _vq_quantlist__44c1_sm_p1_0,
  135102. NULL,
  135103. &_vq_auxt__44c1_sm_p1_0,
  135104. NULL,
  135105. 0
  135106. };
  135107. static long _vq_quantlist__44c1_sm_p2_0[] = {
  135108. 2,
  135109. 1,
  135110. 3,
  135111. 0,
  135112. 4,
  135113. };
  135114. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  135115. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0,
  135155. };
  135156. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  135157. -1.5, -0.5, 0.5, 1.5,
  135158. };
  135159. static long _vq_quantmap__44c1_sm_p2_0[] = {
  135160. 3, 1, 0, 2, 4,
  135161. };
  135162. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  135163. _vq_quantthresh__44c1_sm_p2_0,
  135164. _vq_quantmap__44c1_sm_p2_0,
  135165. 5,
  135166. 5
  135167. };
  135168. static static_codebook _44c1_sm_p2_0 = {
  135169. 4, 625,
  135170. _vq_lengthlist__44c1_sm_p2_0,
  135171. 1, -533725184, 1611661312, 3, 0,
  135172. _vq_quantlist__44c1_sm_p2_0,
  135173. NULL,
  135174. &_vq_auxt__44c1_sm_p2_0,
  135175. NULL,
  135176. 0
  135177. };
  135178. static long _vq_quantlist__44c1_sm_p3_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_p3_0[] = {
  135190. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  135191. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  135192. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135193. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135194. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0,
  135196. };
  135197. static float _vq_quantthresh__44c1_sm_p3_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_p3_0[] = {
  135201. 7, 5, 3, 1, 0, 2, 4, 6,
  135202. 8,
  135203. };
  135204. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  135205. _vq_quantthresh__44c1_sm_p3_0,
  135206. _vq_quantmap__44c1_sm_p3_0,
  135207. 9,
  135208. 9
  135209. };
  135210. static static_codebook _44c1_sm_p3_0 = {
  135211. 2, 81,
  135212. _vq_lengthlist__44c1_sm_p3_0,
  135213. 1, -531628032, 1611661312, 4, 0,
  135214. _vq_quantlist__44c1_sm_p3_0,
  135215. NULL,
  135216. &_vq_auxt__44c1_sm_p3_0,
  135217. NULL,
  135218. 0
  135219. };
  135220. static long _vq_quantlist__44c1_sm_p4_0[] = {
  135221. 4,
  135222. 3,
  135223. 5,
  135224. 2,
  135225. 6,
  135226. 1,
  135227. 7,
  135228. 0,
  135229. 8,
  135230. };
  135231. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  135232. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  135233. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135234. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135235. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  135236. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135237. 11,
  135238. };
  135239. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  135240. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135241. };
  135242. static long _vq_quantmap__44c1_sm_p4_0[] = {
  135243. 7, 5, 3, 1, 0, 2, 4, 6,
  135244. 8,
  135245. };
  135246. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  135247. _vq_quantthresh__44c1_sm_p4_0,
  135248. _vq_quantmap__44c1_sm_p4_0,
  135249. 9,
  135250. 9
  135251. };
  135252. static static_codebook _44c1_sm_p4_0 = {
  135253. 2, 81,
  135254. _vq_lengthlist__44c1_sm_p4_0,
  135255. 1, -531628032, 1611661312, 4, 0,
  135256. _vq_quantlist__44c1_sm_p4_0,
  135257. NULL,
  135258. &_vq_auxt__44c1_sm_p4_0,
  135259. NULL,
  135260. 0
  135261. };
  135262. static long _vq_quantlist__44c1_sm_p5_0[] = {
  135263. 8,
  135264. 7,
  135265. 9,
  135266. 6,
  135267. 10,
  135268. 5,
  135269. 11,
  135270. 4,
  135271. 12,
  135272. 3,
  135273. 13,
  135274. 2,
  135275. 14,
  135276. 1,
  135277. 15,
  135278. 0,
  135279. 16,
  135280. };
  135281. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  135282. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135283. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135284. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  135285. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135286. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135287. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  135288. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  135289. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135290. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135291. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  135292. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135293. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135294. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  135295. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135296. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  135297. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  135298. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135300. 14,
  135301. };
  135302. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  135303. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135304. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135305. };
  135306. static long _vq_quantmap__44c1_sm_p5_0[] = {
  135307. 15, 13, 11, 9, 7, 5, 3, 1,
  135308. 0, 2, 4, 6, 8, 10, 12, 14,
  135309. 16,
  135310. };
  135311. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  135312. _vq_quantthresh__44c1_sm_p5_0,
  135313. _vq_quantmap__44c1_sm_p5_0,
  135314. 17,
  135315. 17
  135316. };
  135317. static static_codebook _44c1_sm_p5_0 = {
  135318. 2, 289,
  135319. _vq_lengthlist__44c1_sm_p5_0,
  135320. 1, -529530880, 1611661312, 5, 0,
  135321. _vq_quantlist__44c1_sm_p5_0,
  135322. NULL,
  135323. &_vq_auxt__44c1_sm_p5_0,
  135324. NULL,
  135325. 0
  135326. };
  135327. static long _vq_quantlist__44c1_sm_p6_0[] = {
  135328. 1,
  135329. 0,
  135330. 2,
  135331. };
  135332. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  135333. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135334. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135335. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  135336. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  135337. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  135338. 11,
  135339. };
  135340. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  135341. -5.5, 5.5,
  135342. };
  135343. static long _vq_quantmap__44c1_sm_p6_0[] = {
  135344. 1, 0, 2,
  135345. };
  135346. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  135347. _vq_quantthresh__44c1_sm_p6_0,
  135348. _vq_quantmap__44c1_sm_p6_0,
  135349. 3,
  135350. 3
  135351. };
  135352. static static_codebook _44c1_sm_p6_0 = {
  135353. 4, 81,
  135354. _vq_lengthlist__44c1_sm_p6_0,
  135355. 1, -529137664, 1618345984, 2, 0,
  135356. _vq_quantlist__44c1_sm_p6_0,
  135357. NULL,
  135358. &_vq_auxt__44c1_sm_p6_0,
  135359. NULL,
  135360. 0
  135361. };
  135362. static long _vq_quantlist__44c1_sm_p6_1[] = {
  135363. 5,
  135364. 4,
  135365. 6,
  135366. 3,
  135367. 7,
  135368. 2,
  135369. 8,
  135370. 1,
  135371. 9,
  135372. 0,
  135373. 10,
  135374. };
  135375. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  135376. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135377. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135378. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135379. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135380. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135381. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  135382. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135383. 10,10,10, 8, 8, 8, 8, 8, 8,
  135384. };
  135385. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  135386. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135387. 3.5, 4.5,
  135388. };
  135389. static long _vq_quantmap__44c1_sm_p6_1[] = {
  135390. 9, 7, 5, 3, 1, 0, 2, 4,
  135391. 6, 8, 10,
  135392. };
  135393. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  135394. _vq_quantthresh__44c1_sm_p6_1,
  135395. _vq_quantmap__44c1_sm_p6_1,
  135396. 11,
  135397. 11
  135398. };
  135399. static static_codebook _44c1_sm_p6_1 = {
  135400. 2, 121,
  135401. _vq_lengthlist__44c1_sm_p6_1,
  135402. 1, -531365888, 1611661312, 4, 0,
  135403. _vq_quantlist__44c1_sm_p6_1,
  135404. NULL,
  135405. &_vq_auxt__44c1_sm_p6_1,
  135406. NULL,
  135407. 0
  135408. };
  135409. static long _vq_quantlist__44c1_sm_p7_0[] = {
  135410. 6,
  135411. 5,
  135412. 7,
  135413. 4,
  135414. 8,
  135415. 3,
  135416. 9,
  135417. 2,
  135418. 10,
  135419. 1,
  135420. 11,
  135421. 0,
  135422. 12,
  135423. };
  135424. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  135425. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135426. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135427. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135428. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135429. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135430. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  135431. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  135432. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135433. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135434. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  135435. 0,12,12,11,11,13,12,14,13,
  135436. };
  135437. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  135438. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135439. 12.5, 17.5, 22.5, 27.5,
  135440. };
  135441. static long _vq_quantmap__44c1_sm_p7_0[] = {
  135442. 11, 9, 7, 5, 3, 1, 0, 2,
  135443. 4, 6, 8, 10, 12,
  135444. };
  135445. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  135446. _vq_quantthresh__44c1_sm_p7_0,
  135447. _vq_quantmap__44c1_sm_p7_0,
  135448. 13,
  135449. 13
  135450. };
  135451. static static_codebook _44c1_sm_p7_0 = {
  135452. 2, 169,
  135453. _vq_lengthlist__44c1_sm_p7_0,
  135454. 1, -526516224, 1616117760, 4, 0,
  135455. _vq_quantlist__44c1_sm_p7_0,
  135456. NULL,
  135457. &_vq_auxt__44c1_sm_p7_0,
  135458. NULL,
  135459. 0
  135460. };
  135461. static long _vq_quantlist__44c1_sm_p7_1[] = {
  135462. 2,
  135463. 1,
  135464. 3,
  135465. 0,
  135466. 4,
  135467. };
  135468. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  135469. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135470. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135471. };
  135472. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  135473. -1.5, -0.5, 0.5, 1.5,
  135474. };
  135475. static long _vq_quantmap__44c1_sm_p7_1[] = {
  135476. 3, 1, 0, 2, 4,
  135477. };
  135478. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  135479. _vq_quantthresh__44c1_sm_p7_1,
  135480. _vq_quantmap__44c1_sm_p7_1,
  135481. 5,
  135482. 5
  135483. };
  135484. static static_codebook _44c1_sm_p7_1 = {
  135485. 2, 25,
  135486. _vq_lengthlist__44c1_sm_p7_1,
  135487. 1, -533725184, 1611661312, 3, 0,
  135488. _vq_quantlist__44c1_sm_p7_1,
  135489. NULL,
  135490. &_vq_auxt__44c1_sm_p7_1,
  135491. NULL,
  135492. 0
  135493. };
  135494. static long _vq_quantlist__44c1_sm_p8_0[] = {
  135495. 6,
  135496. 5,
  135497. 7,
  135498. 4,
  135499. 8,
  135500. 3,
  135501. 9,
  135502. 2,
  135503. 10,
  135504. 1,
  135505. 11,
  135506. 0,
  135507. 12,
  135508. };
  135509. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  135510. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  135511. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  135512. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135513. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135514. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135515. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135516. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135517. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135518. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135519. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135520. 13,13,13,13,13,13,13,13,13,
  135521. };
  135522. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  135523. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135524. 552.5, 773.5, 994.5, 1215.5,
  135525. };
  135526. static long _vq_quantmap__44c1_sm_p8_0[] = {
  135527. 11, 9, 7, 5, 3, 1, 0, 2,
  135528. 4, 6, 8, 10, 12,
  135529. };
  135530. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  135531. _vq_quantthresh__44c1_sm_p8_0,
  135532. _vq_quantmap__44c1_sm_p8_0,
  135533. 13,
  135534. 13
  135535. };
  135536. static static_codebook _44c1_sm_p8_0 = {
  135537. 2, 169,
  135538. _vq_lengthlist__44c1_sm_p8_0,
  135539. 1, -514541568, 1627103232, 4, 0,
  135540. _vq_quantlist__44c1_sm_p8_0,
  135541. NULL,
  135542. &_vq_auxt__44c1_sm_p8_0,
  135543. NULL,
  135544. 0
  135545. };
  135546. static long _vq_quantlist__44c1_sm_p8_1[] = {
  135547. 6,
  135548. 5,
  135549. 7,
  135550. 4,
  135551. 8,
  135552. 3,
  135553. 9,
  135554. 2,
  135555. 10,
  135556. 1,
  135557. 11,
  135558. 0,
  135559. 12,
  135560. };
  135561. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  135562. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  135563. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  135564. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  135565. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  135566. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  135567. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  135568. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  135569. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  135570. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  135571. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  135572. 20,13,12,12,12,14,12,14,13,
  135573. };
  135574. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  135575. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135576. 42.5, 59.5, 76.5, 93.5,
  135577. };
  135578. static long _vq_quantmap__44c1_sm_p8_1[] = {
  135579. 11, 9, 7, 5, 3, 1, 0, 2,
  135580. 4, 6, 8, 10, 12,
  135581. };
  135582. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  135583. _vq_quantthresh__44c1_sm_p8_1,
  135584. _vq_quantmap__44c1_sm_p8_1,
  135585. 13,
  135586. 13
  135587. };
  135588. static static_codebook _44c1_sm_p8_1 = {
  135589. 2, 169,
  135590. _vq_lengthlist__44c1_sm_p8_1,
  135591. 1, -522616832, 1620115456, 4, 0,
  135592. _vq_quantlist__44c1_sm_p8_1,
  135593. NULL,
  135594. &_vq_auxt__44c1_sm_p8_1,
  135595. NULL,
  135596. 0
  135597. };
  135598. static long _vq_quantlist__44c1_sm_p8_2[] = {
  135599. 8,
  135600. 7,
  135601. 9,
  135602. 6,
  135603. 10,
  135604. 5,
  135605. 11,
  135606. 4,
  135607. 12,
  135608. 3,
  135609. 13,
  135610. 2,
  135611. 14,
  135612. 1,
  135613. 15,
  135614. 0,
  135615. 16,
  135616. };
  135617. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  135618. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135619. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135620. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135621. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135622. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135623. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135624. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135625. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  135626. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  135627. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135628. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  135629. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  135630. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  135631. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  135632. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135633. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  135634. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135635. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  135636. 9,
  135637. };
  135638. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  135639. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135640. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135641. };
  135642. static long _vq_quantmap__44c1_sm_p8_2[] = {
  135643. 15, 13, 11, 9, 7, 5, 3, 1,
  135644. 0, 2, 4, 6, 8, 10, 12, 14,
  135645. 16,
  135646. };
  135647. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  135648. _vq_quantthresh__44c1_sm_p8_2,
  135649. _vq_quantmap__44c1_sm_p8_2,
  135650. 17,
  135651. 17
  135652. };
  135653. static static_codebook _44c1_sm_p8_2 = {
  135654. 2, 289,
  135655. _vq_lengthlist__44c1_sm_p8_2,
  135656. 1, -529530880, 1611661312, 5, 0,
  135657. _vq_quantlist__44c1_sm_p8_2,
  135658. NULL,
  135659. &_vq_auxt__44c1_sm_p8_2,
  135660. NULL,
  135661. 0
  135662. };
  135663. static long _huff_lengthlist__44c1_sm_short[] = {
  135664. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  135665. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  135666. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  135667. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  135668. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  135669. 11,
  135670. };
  135671. static static_codebook _huff_book__44c1_sm_short = {
  135672. 2, 81,
  135673. _huff_lengthlist__44c1_sm_short,
  135674. 0, 0, 0, 0, 0,
  135675. NULL,
  135676. NULL,
  135677. NULL,
  135678. NULL,
  135679. 0
  135680. };
  135681. static long _huff_lengthlist__44cn1_s_long[] = {
  135682. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  135683. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  135684. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  135685. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  135686. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  135687. 20,
  135688. };
  135689. static static_codebook _huff_book__44cn1_s_long = {
  135690. 2, 81,
  135691. _huff_lengthlist__44cn1_s_long,
  135692. 0, 0, 0, 0, 0,
  135693. NULL,
  135694. NULL,
  135695. NULL,
  135696. NULL,
  135697. 0
  135698. };
  135699. static long _vq_quantlist__44cn1_s_p1_0[] = {
  135700. 1,
  135701. 0,
  135702. 2,
  135703. };
  135704. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  135705. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135706. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135711. 0, 0, 0, 7, 9,10, 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, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  135716. 0, 0, 0, 0, 8,10, 9, 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, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  135751. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  135756. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  135761. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  135797. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135802. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  135807. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  136116. };
  136117. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  136118. -0.5, 0.5,
  136119. };
  136120. static long _vq_quantmap__44cn1_s_p1_0[] = {
  136121. 1, 0, 2,
  136122. };
  136123. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  136124. _vq_quantthresh__44cn1_s_p1_0,
  136125. _vq_quantmap__44cn1_s_p1_0,
  136126. 3,
  136127. 3
  136128. };
  136129. static static_codebook _44cn1_s_p1_0 = {
  136130. 8, 6561,
  136131. _vq_lengthlist__44cn1_s_p1_0,
  136132. 1, -535822336, 1611661312, 2, 0,
  136133. _vq_quantlist__44cn1_s_p1_0,
  136134. NULL,
  136135. &_vq_auxt__44cn1_s_p1_0,
  136136. NULL,
  136137. 0
  136138. };
  136139. static long _vq_quantlist__44cn1_s_p2_0[] = {
  136140. 2,
  136141. 1,
  136142. 3,
  136143. 0,
  136144. 4,
  136145. };
  136146. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  136147. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0,
  136187. };
  136188. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  136189. -1.5, -0.5, 0.5, 1.5,
  136190. };
  136191. static long _vq_quantmap__44cn1_s_p2_0[] = {
  136192. 3, 1, 0, 2, 4,
  136193. };
  136194. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  136195. _vq_quantthresh__44cn1_s_p2_0,
  136196. _vq_quantmap__44cn1_s_p2_0,
  136197. 5,
  136198. 5
  136199. };
  136200. static static_codebook _44cn1_s_p2_0 = {
  136201. 4, 625,
  136202. _vq_lengthlist__44cn1_s_p2_0,
  136203. 1, -533725184, 1611661312, 3, 0,
  136204. _vq_quantlist__44cn1_s_p2_0,
  136205. NULL,
  136206. &_vq_auxt__44cn1_s_p2_0,
  136207. NULL,
  136208. 0
  136209. };
  136210. static long _vq_quantlist__44cn1_s_p3_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_p3_0[] = {
  136222. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136223. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136224. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136225. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136226. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0,
  136228. };
  136229. static float _vq_quantthresh__44cn1_s_p3_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_p3_0[] = {
  136233. 7, 5, 3, 1, 0, 2, 4, 6,
  136234. 8,
  136235. };
  136236. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  136237. _vq_quantthresh__44cn1_s_p3_0,
  136238. _vq_quantmap__44cn1_s_p3_0,
  136239. 9,
  136240. 9
  136241. };
  136242. static static_codebook _44cn1_s_p3_0 = {
  136243. 2, 81,
  136244. _vq_lengthlist__44cn1_s_p3_0,
  136245. 1, -531628032, 1611661312, 4, 0,
  136246. _vq_quantlist__44cn1_s_p3_0,
  136247. NULL,
  136248. &_vq_auxt__44cn1_s_p3_0,
  136249. NULL,
  136250. 0
  136251. };
  136252. static long _vq_quantlist__44cn1_s_p4_0[] = {
  136253. 4,
  136254. 3,
  136255. 5,
  136256. 2,
  136257. 6,
  136258. 1,
  136259. 7,
  136260. 0,
  136261. 8,
  136262. };
  136263. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  136264. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  136265. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136266. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  136267. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136268. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136269. 11,
  136270. };
  136271. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  136272. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136273. };
  136274. static long _vq_quantmap__44cn1_s_p4_0[] = {
  136275. 7, 5, 3, 1, 0, 2, 4, 6,
  136276. 8,
  136277. };
  136278. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  136279. _vq_quantthresh__44cn1_s_p4_0,
  136280. _vq_quantmap__44cn1_s_p4_0,
  136281. 9,
  136282. 9
  136283. };
  136284. static static_codebook _44cn1_s_p4_0 = {
  136285. 2, 81,
  136286. _vq_lengthlist__44cn1_s_p4_0,
  136287. 1, -531628032, 1611661312, 4, 0,
  136288. _vq_quantlist__44cn1_s_p4_0,
  136289. NULL,
  136290. &_vq_auxt__44cn1_s_p4_0,
  136291. NULL,
  136292. 0
  136293. };
  136294. static long _vq_quantlist__44cn1_s_p5_0[] = {
  136295. 8,
  136296. 7,
  136297. 9,
  136298. 6,
  136299. 10,
  136300. 5,
  136301. 11,
  136302. 4,
  136303. 12,
  136304. 3,
  136305. 13,
  136306. 2,
  136307. 14,
  136308. 1,
  136309. 15,
  136310. 0,
  136311. 16,
  136312. };
  136313. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  136314. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  136315. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  136316. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136317. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136318. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136319. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136320. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136321. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  136322. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136323. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  136324. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136325. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136326. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  136327. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136328. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  136329. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  136330. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  136332. 14,
  136333. };
  136334. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  136335. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136336. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136337. };
  136338. static long _vq_quantmap__44cn1_s_p5_0[] = {
  136339. 15, 13, 11, 9, 7, 5, 3, 1,
  136340. 0, 2, 4, 6, 8, 10, 12, 14,
  136341. 16,
  136342. };
  136343. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  136344. _vq_quantthresh__44cn1_s_p5_0,
  136345. _vq_quantmap__44cn1_s_p5_0,
  136346. 17,
  136347. 17
  136348. };
  136349. static static_codebook _44cn1_s_p5_0 = {
  136350. 2, 289,
  136351. _vq_lengthlist__44cn1_s_p5_0,
  136352. 1, -529530880, 1611661312, 5, 0,
  136353. _vq_quantlist__44cn1_s_p5_0,
  136354. NULL,
  136355. &_vq_auxt__44cn1_s_p5_0,
  136356. NULL,
  136357. 0
  136358. };
  136359. static long _vq_quantlist__44cn1_s_p6_0[] = {
  136360. 1,
  136361. 0,
  136362. 2,
  136363. };
  136364. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  136365. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  136366. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  136367. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  136368. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  136369. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  136370. 10,
  136371. };
  136372. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  136373. -5.5, 5.5,
  136374. };
  136375. static long _vq_quantmap__44cn1_s_p6_0[] = {
  136376. 1, 0, 2,
  136377. };
  136378. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  136379. _vq_quantthresh__44cn1_s_p6_0,
  136380. _vq_quantmap__44cn1_s_p6_0,
  136381. 3,
  136382. 3
  136383. };
  136384. static static_codebook _44cn1_s_p6_0 = {
  136385. 4, 81,
  136386. _vq_lengthlist__44cn1_s_p6_0,
  136387. 1, -529137664, 1618345984, 2, 0,
  136388. _vq_quantlist__44cn1_s_p6_0,
  136389. NULL,
  136390. &_vq_auxt__44cn1_s_p6_0,
  136391. NULL,
  136392. 0
  136393. };
  136394. static long _vq_quantlist__44cn1_s_p6_1[] = {
  136395. 5,
  136396. 4,
  136397. 6,
  136398. 3,
  136399. 7,
  136400. 2,
  136401. 8,
  136402. 1,
  136403. 9,
  136404. 0,
  136405. 10,
  136406. };
  136407. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  136408. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  136409. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  136410. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136411. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  136412. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  136413. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  136414. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  136415. 10,10,10, 9, 9, 9, 9, 9, 9,
  136416. };
  136417. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  136418. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136419. 3.5, 4.5,
  136420. };
  136421. static long _vq_quantmap__44cn1_s_p6_1[] = {
  136422. 9, 7, 5, 3, 1, 0, 2, 4,
  136423. 6, 8, 10,
  136424. };
  136425. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  136426. _vq_quantthresh__44cn1_s_p6_1,
  136427. _vq_quantmap__44cn1_s_p6_1,
  136428. 11,
  136429. 11
  136430. };
  136431. static static_codebook _44cn1_s_p6_1 = {
  136432. 2, 121,
  136433. _vq_lengthlist__44cn1_s_p6_1,
  136434. 1, -531365888, 1611661312, 4, 0,
  136435. _vq_quantlist__44cn1_s_p6_1,
  136436. NULL,
  136437. &_vq_auxt__44cn1_s_p6_1,
  136438. NULL,
  136439. 0
  136440. };
  136441. static long _vq_quantlist__44cn1_s_p7_0[] = {
  136442. 6,
  136443. 5,
  136444. 7,
  136445. 4,
  136446. 8,
  136447. 3,
  136448. 9,
  136449. 2,
  136450. 10,
  136451. 1,
  136452. 11,
  136453. 0,
  136454. 12,
  136455. };
  136456. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  136457. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  136458. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  136459. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136460. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136461. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  136462. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136463. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  136464. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  136465. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  136466. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  136467. 0,13,13,12,12,13,13,13,14,
  136468. };
  136469. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  136470. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136471. 12.5, 17.5, 22.5, 27.5,
  136472. };
  136473. static long _vq_quantmap__44cn1_s_p7_0[] = {
  136474. 11, 9, 7, 5, 3, 1, 0, 2,
  136475. 4, 6, 8, 10, 12,
  136476. };
  136477. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  136478. _vq_quantthresh__44cn1_s_p7_0,
  136479. _vq_quantmap__44cn1_s_p7_0,
  136480. 13,
  136481. 13
  136482. };
  136483. static static_codebook _44cn1_s_p7_0 = {
  136484. 2, 169,
  136485. _vq_lengthlist__44cn1_s_p7_0,
  136486. 1, -526516224, 1616117760, 4, 0,
  136487. _vq_quantlist__44cn1_s_p7_0,
  136488. NULL,
  136489. &_vq_auxt__44cn1_s_p7_0,
  136490. NULL,
  136491. 0
  136492. };
  136493. static long _vq_quantlist__44cn1_s_p7_1[] = {
  136494. 2,
  136495. 1,
  136496. 3,
  136497. 0,
  136498. 4,
  136499. };
  136500. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  136501. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136502. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136503. };
  136504. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  136505. -1.5, -0.5, 0.5, 1.5,
  136506. };
  136507. static long _vq_quantmap__44cn1_s_p7_1[] = {
  136508. 3, 1, 0, 2, 4,
  136509. };
  136510. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  136511. _vq_quantthresh__44cn1_s_p7_1,
  136512. _vq_quantmap__44cn1_s_p7_1,
  136513. 5,
  136514. 5
  136515. };
  136516. static static_codebook _44cn1_s_p7_1 = {
  136517. 2, 25,
  136518. _vq_lengthlist__44cn1_s_p7_1,
  136519. 1, -533725184, 1611661312, 3, 0,
  136520. _vq_quantlist__44cn1_s_p7_1,
  136521. NULL,
  136522. &_vq_auxt__44cn1_s_p7_1,
  136523. NULL,
  136524. 0
  136525. };
  136526. static long _vq_quantlist__44cn1_s_p8_0[] = {
  136527. 2,
  136528. 1,
  136529. 3,
  136530. 0,
  136531. 4,
  136532. };
  136533. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  136534. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  136535. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  136536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136537. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  136538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136541. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  136542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136543. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  136544. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  136545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136546. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136547. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136548. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136549. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  136550. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136551. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136552. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136554. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136555. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136558. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136559. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136561. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136563. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136565. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136566. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136567. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  136568. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136569. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136570. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136571. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136572. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136573. 12,
  136574. };
  136575. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  136576. -331.5, -110.5, 110.5, 331.5,
  136577. };
  136578. static long _vq_quantmap__44cn1_s_p8_0[] = {
  136579. 3, 1, 0, 2, 4,
  136580. };
  136581. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  136582. _vq_quantthresh__44cn1_s_p8_0,
  136583. _vq_quantmap__44cn1_s_p8_0,
  136584. 5,
  136585. 5
  136586. };
  136587. static static_codebook _44cn1_s_p8_0 = {
  136588. 4, 625,
  136589. _vq_lengthlist__44cn1_s_p8_0,
  136590. 1, -518283264, 1627103232, 3, 0,
  136591. _vq_quantlist__44cn1_s_p8_0,
  136592. NULL,
  136593. &_vq_auxt__44cn1_s_p8_0,
  136594. NULL,
  136595. 0
  136596. };
  136597. static long _vq_quantlist__44cn1_s_p8_1[] = {
  136598. 6,
  136599. 5,
  136600. 7,
  136601. 4,
  136602. 8,
  136603. 3,
  136604. 9,
  136605. 2,
  136606. 10,
  136607. 1,
  136608. 11,
  136609. 0,
  136610. 12,
  136611. };
  136612. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  136613. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  136614. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  136615. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  136616. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  136617. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  136618. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  136619. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  136620. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  136621. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  136622. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  136623. 15,12,12,11,11,14,12,13,14,
  136624. };
  136625. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  136626. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136627. 42.5, 59.5, 76.5, 93.5,
  136628. };
  136629. static long _vq_quantmap__44cn1_s_p8_1[] = {
  136630. 11, 9, 7, 5, 3, 1, 0, 2,
  136631. 4, 6, 8, 10, 12,
  136632. };
  136633. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  136634. _vq_quantthresh__44cn1_s_p8_1,
  136635. _vq_quantmap__44cn1_s_p8_1,
  136636. 13,
  136637. 13
  136638. };
  136639. static static_codebook _44cn1_s_p8_1 = {
  136640. 2, 169,
  136641. _vq_lengthlist__44cn1_s_p8_1,
  136642. 1, -522616832, 1620115456, 4, 0,
  136643. _vq_quantlist__44cn1_s_p8_1,
  136644. NULL,
  136645. &_vq_auxt__44cn1_s_p8_1,
  136646. NULL,
  136647. 0
  136648. };
  136649. static long _vq_quantlist__44cn1_s_p8_2[] = {
  136650. 8,
  136651. 7,
  136652. 9,
  136653. 6,
  136654. 10,
  136655. 5,
  136656. 11,
  136657. 4,
  136658. 12,
  136659. 3,
  136660. 13,
  136661. 2,
  136662. 14,
  136663. 1,
  136664. 15,
  136665. 0,
  136666. 16,
  136667. };
  136668. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  136669. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  136670. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136671. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136672. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  136673. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  136674. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  136675. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  136676. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  136677. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  136678. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  136679. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  136680. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  136681. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  136682. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  136683. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  136684. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136685. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136686. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  136687. 9,
  136688. };
  136689. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  136690. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136691. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136692. };
  136693. static long _vq_quantmap__44cn1_s_p8_2[] = {
  136694. 15, 13, 11, 9, 7, 5, 3, 1,
  136695. 0, 2, 4, 6, 8, 10, 12, 14,
  136696. 16,
  136697. };
  136698. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  136699. _vq_quantthresh__44cn1_s_p8_2,
  136700. _vq_quantmap__44cn1_s_p8_2,
  136701. 17,
  136702. 17
  136703. };
  136704. static static_codebook _44cn1_s_p8_2 = {
  136705. 2, 289,
  136706. _vq_lengthlist__44cn1_s_p8_2,
  136707. 1, -529530880, 1611661312, 5, 0,
  136708. _vq_quantlist__44cn1_s_p8_2,
  136709. NULL,
  136710. &_vq_auxt__44cn1_s_p8_2,
  136711. NULL,
  136712. 0
  136713. };
  136714. static long _huff_lengthlist__44cn1_s_short[] = {
  136715. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  136716. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  136717. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  136718. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  136719. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  136720. 10,
  136721. };
  136722. static static_codebook _huff_book__44cn1_s_short = {
  136723. 2, 81,
  136724. _huff_lengthlist__44cn1_s_short,
  136725. 0, 0, 0, 0, 0,
  136726. NULL,
  136727. NULL,
  136728. NULL,
  136729. NULL,
  136730. 0
  136731. };
  136732. static long _huff_lengthlist__44cn1_sm_long[] = {
  136733. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  136734. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  136735. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  136736. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  136737. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  136738. 17,
  136739. };
  136740. static static_codebook _huff_book__44cn1_sm_long = {
  136741. 2, 81,
  136742. _huff_lengthlist__44cn1_sm_long,
  136743. 0, 0, 0, 0, 0,
  136744. NULL,
  136745. NULL,
  136746. NULL,
  136747. NULL,
  136748. 0
  136749. };
  136750. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  136751. 1,
  136752. 0,
  136753. 2,
  136754. };
  136755. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  136756. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136757. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136762. 0, 0, 0, 7, 8, 9, 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, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136767. 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  136802. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  136807. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136812. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136848. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136853. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  136858. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  137167. };
  137168. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  137169. -0.5, 0.5,
  137170. };
  137171. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  137172. 1, 0, 2,
  137173. };
  137174. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  137175. _vq_quantthresh__44cn1_sm_p1_0,
  137176. _vq_quantmap__44cn1_sm_p1_0,
  137177. 3,
  137178. 3
  137179. };
  137180. static static_codebook _44cn1_sm_p1_0 = {
  137181. 8, 6561,
  137182. _vq_lengthlist__44cn1_sm_p1_0,
  137183. 1, -535822336, 1611661312, 2, 0,
  137184. _vq_quantlist__44cn1_sm_p1_0,
  137185. NULL,
  137186. &_vq_auxt__44cn1_sm_p1_0,
  137187. NULL,
  137188. 0
  137189. };
  137190. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  137191. 2,
  137192. 1,
  137193. 3,
  137194. 0,
  137195. 4,
  137196. };
  137197. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  137198. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0,
  137238. };
  137239. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  137240. -1.5, -0.5, 0.5, 1.5,
  137241. };
  137242. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  137243. 3, 1, 0, 2, 4,
  137244. };
  137245. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  137246. _vq_quantthresh__44cn1_sm_p2_0,
  137247. _vq_quantmap__44cn1_sm_p2_0,
  137248. 5,
  137249. 5
  137250. };
  137251. static static_codebook _44cn1_sm_p2_0 = {
  137252. 4, 625,
  137253. _vq_lengthlist__44cn1_sm_p2_0,
  137254. 1, -533725184, 1611661312, 3, 0,
  137255. _vq_quantlist__44cn1_sm_p2_0,
  137256. NULL,
  137257. &_vq_auxt__44cn1_sm_p2_0,
  137258. NULL,
  137259. 0
  137260. };
  137261. static long _vq_quantlist__44cn1_sm_p3_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_p3_0[] = {
  137273. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  137274. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137275. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137276. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  137277. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0,
  137279. };
  137280. static float _vq_quantthresh__44cn1_sm_p3_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_p3_0[] = {
  137284. 7, 5, 3, 1, 0, 2, 4, 6,
  137285. 8,
  137286. };
  137287. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  137288. _vq_quantthresh__44cn1_sm_p3_0,
  137289. _vq_quantmap__44cn1_sm_p3_0,
  137290. 9,
  137291. 9
  137292. };
  137293. static static_codebook _44cn1_sm_p3_0 = {
  137294. 2, 81,
  137295. _vq_lengthlist__44cn1_sm_p3_0,
  137296. 1, -531628032, 1611661312, 4, 0,
  137297. _vq_quantlist__44cn1_sm_p3_0,
  137298. NULL,
  137299. &_vq_auxt__44cn1_sm_p3_0,
  137300. NULL,
  137301. 0
  137302. };
  137303. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  137304. 4,
  137305. 3,
  137306. 5,
  137307. 2,
  137308. 6,
  137309. 1,
  137310. 7,
  137311. 0,
  137312. 8,
  137313. };
  137314. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  137315. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137316. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137317. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137318. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  137319. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  137320. 11,
  137321. };
  137322. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  137323. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137324. };
  137325. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  137326. 7, 5, 3, 1, 0, 2, 4, 6,
  137327. 8,
  137328. };
  137329. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  137330. _vq_quantthresh__44cn1_sm_p4_0,
  137331. _vq_quantmap__44cn1_sm_p4_0,
  137332. 9,
  137333. 9
  137334. };
  137335. static static_codebook _44cn1_sm_p4_0 = {
  137336. 2, 81,
  137337. _vq_lengthlist__44cn1_sm_p4_0,
  137338. 1, -531628032, 1611661312, 4, 0,
  137339. _vq_quantlist__44cn1_sm_p4_0,
  137340. NULL,
  137341. &_vq_auxt__44cn1_sm_p4_0,
  137342. NULL,
  137343. 0
  137344. };
  137345. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  137346. 8,
  137347. 7,
  137348. 9,
  137349. 6,
  137350. 10,
  137351. 5,
  137352. 11,
  137353. 4,
  137354. 12,
  137355. 3,
  137356. 13,
  137357. 2,
  137358. 14,
  137359. 1,
  137360. 15,
  137361. 0,
  137362. 16,
  137363. };
  137364. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  137365. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  137366. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  137367. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  137368. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137369. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  137370. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137371. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137372. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137373. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  137374. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137375. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  137376. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  137377. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  137378. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  137379. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  137380. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  137381. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  137383. 14,
  137384. };
  137385. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  137386. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137387. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137388. };
  137389. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  137390. 15, 13, 11, 9, 7, 5, 3, 1,
  137391. 0, 2, 4, 6, 8, 10, 12, 14,
  137392. 16,
  137393. };
  137394. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  137395. _vq_quantthresh__44cn1_sm_p5_0,
  137396. _vq_quantmap__44cn1_sm_p5_0,
  137397. 17,
  137398. 17
  137399. };
  137400. static static_codebook _44cn1_sm_p5_0 = {
  137401. 2, 289,
  137402. _vq_lengthlist__44cn1_sm_p5_0,
  137403. 1, -529530880, 1611661312, 5, 0,
  137404. _vq_quantlist__44cn1_sm_p5_0,
  137405. NULL,
  137406. &_vq_auxt__44cn1_sm_p5_0,
  137407. NULL,
  137408. 0
  137409. };
  137410. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  137411. 1,
  137412. 0,
  137413. 2,
  137414. };
  137415. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  137416. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  137417. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137418. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137419. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  137420. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  137421. 10,
  137422. };
  137423. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  137424. -5.5, 5.5,
  137425. };
  137426. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  137427. 1, 0, 2,
  137428. };
  137429. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  137430. _vq_quantthresh__44cn1_sm_p6_0,
  137431. _vq_quantmap__44cn1_sm_p6_0,
  137432. 3,
  137433. 3
  137434. };
  137435. static static_codebook _44cn1_sm_p6_0 = {
  137436. 4, 81,
  137437. _vq_lengthlist__44cn1_sm_p6_0,
  137438. 1, -529137664, 1618345984, 2, 0,
  137439. _vq_quantlist__44cn1_sm_p6_0,
  137440. NULL,
  137441. &_vq_auxt__44cn1_sm_p6_0,
  137442. NULL,
  137443. 0
  137444. };
  137445. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  137446. 5,
  137447. 4,
  137448. 6,
  137449. 3,
  137450. 7,
  137451. 2,
  137452. 8,
  137453. 1,
  137454. 9,
  137455. 0,
  137456. 10,
  137457. };
  137458. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  137459. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  137460. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137461. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137462. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137463. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137464. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  137465. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  137466. 10,10,10, 8, 9, 8, 8, 9, 8,
  137467. };
  137468. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  137469. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137470. 3.5, 4.5,
  137471. };
  137472. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  137473. 9, 7, 5, 3, 1, 0, 2, 4,
  137474. 6, 8, 10,
  137475. };
  137476. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  137477. _vq_quantthresh__44cn1_sm_p6_1,
  137478. _vq_quantmap__44cn1_sm_p6_1,
  137479. 11,
  137480. 11
  137481. };
  137482. static static_codebook _44cn1_sm_p6_1 = {
  137483. 2, 121,
  137484. _vq_lengthlist__44cn1_sm_p6_1,
  137485. 1, -531365888, 1611661312, 4, 0,
  137486. _vq_quantlist__44cn1_sm_p6_1,
  137487. NULL,
  137488. &_vq_auxt__44cn1_sm_p6_1,
  137489. NULL,
  137490. 0
  137491. };
  137492. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  137493. 6,
  137494. 5,
  137495. 7,
  137496. 4,
  137497. 8,
  137498. 3,
  137499. 9,
  137500. 2,
  137501. 10,
  137502. 1,
  137503. 11,
  137504. 0,
  137505. 12,
  137506. };
  137507. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  137508. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  137509. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  137510. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137511. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137512. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  137513. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  137514. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137515. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  137516. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  137517. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  137518. 0,13,12,12,12,13,13,13,14,
  137519. };
  137520. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  137521. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137522. 12.5, 17.5, 22.5, 27.5,
  137523. };
  137524. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  137525. 11, 9, 7, 5, 3, 1, 0, 2,
  137526. 4, 6, 8, 10, 12,
  137527. };
  137528. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  137529. _vq_quantthresh__44cn1_sm_p7_0,
  137530. _vq_quantmap__44cn1_sm_p7_0,
  137531. 13,
  137532. 13
  137533. };
  137534. static static_codebook _44cn1_sm_p7_0 = {
  137535. 2, 169,
  137536. _vq_lengthlist__44cn1_sm_p7_0,
  137537. 1, -526516224, 1616117760, 4, 0,
  137538. _vq_quantlist__44cn1_sm_p7_0,
  137539. NULL,
  137540. &_vq_auxt__44cn1_sm_p7_0,
  137541. NULL,
  137542. 0
  137543. };
  137544. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  137545. 2,
  137546. 1,
  137547. 3,
  137548. 0,
  137549. 4,
  137550. };
  137551. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  137552. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137553. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  137554. };
  137555. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  137556. -1.5, -0.5, 0.5, 1.5,
  137557. };
  137558. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  137559. 3, 1, 0, 2, 4,
  137560. };
  137561. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  137562. _vq_quantthresh__44cn1_sm_p7_1,
  137563. _vq_quantmap__44cn1_sm_p7_1,
  137564. 5,
  137565. 5
  137566. };
  137567. static static_codebook _44cn1_sm_p7_1 = {
  137568. 2, 25,
  137569. _vq_lengthlist__44cn1_sm_p7_1,
  137570. 1, -533725184, 1611661312, 3, 0,
  137571. _vq_quantlist__44cn1_sm_p7_1,
  137572. NULL,
  137573. &_vq_auxt__44cn1_sm_p7_1,
  137574. NULL,
  137575. 0
  137576. };
  137577. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  137578. 4,
  137579. 3,
  137580. 5,
  137581. 2,
  137582. 6,
  137583. 1,
  137584. 7,
  137585. 0,
  137586. 8,
  137587. };
  137588. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  137589. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  137590. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  137591. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  137592. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  137593. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  137594. 14,
  137595. };
  137596. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  137597. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137598. };
  137599. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  137600. 7, 5, 3, 1, 0, 2, 4, 6,
  137601. 8,
  137602. };
  137603. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  137604. _vq_quantthresh__44cn1_sm_p8_0,
  137605. _vq_quantmap__44cn1_sm_p8_0,
  137606. 9,
  137607. 9
  137608. };
  137609. static static_codebook _44cn1_sm_p8_0 = {
  137610. 2, 81,
  137611. _vq_lengthlist__44cn1_sm_p8_0,
  137612. 1, -516186112, 1627103232, 4, 0,
  137613. _vq_quantlist__44cn1_sm_p8_0,
  137614. NULL,
  137615. &_vq_auxt__44cn1_sm_p8_0,
  137616. NULL,
  137617. 0
  137618. };
  137619. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  137620. 6,
  137621. 5,
  137622. 7,
  137623. 4,
  137624. 8,
  137625. 3,
  137626. 9,
  137627. 2,
  137628. 10,
  137629. 1,
  137630. 11,
  137631. 0,
  137632. 12,
  137633. };
  137634. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  137635. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  137636. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  137637. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  137638. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  137639. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  137640. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  137641. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  137642. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  137643. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  137644. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  137645. 17,12,12,11,10,13,11,13,13,
  137646. };
  137647. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  137648. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137649. 42.5, 59.5, 76.5, 93.5,
  137650. };
  137651. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  137652. 11, 9, 7, 5, 3, 1, 0, 2,
  137653. 4, 6, 8, 10, 12,
  137654. };
  137655. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  137656. _vq_quantthresh__44cn1_sm_p8_1,
  137657. _vq_quantmap__44cn1_sm_p8_1,
  137658. 13,
  137659. 13
  137660. };
  137661. static static_codebook _44cn1_sm_p8_1 = {
  137662. 2, 169,
  137663. _vq_lengthlist__44cn1_sm_p8_1,
  137664. 1, -522616832, 1620115456, 4, 0,
  137665. _vq_quantlist__44cn1_sm_p8_1,
  137666. NULL,
  137667. &_vq_auxt__44cn1_sm_p8_1,
  137668. NULL,
  137669. 0
  137670. };
  137671. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  137672. 8,
  137673. 7,
  137674. 9,
  137675. 6,
  137676. 10,
  137677. 5,
  137678. 11,
  137679. 4,
  137680. 12,
  137681. 3,
  137682. 13,
  137683. 2,
  137684. 14,
  137685. 1,
  137686. 15,
  137687. 0,
  137688. 16,
  137689. };
  137690. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  137691. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  137692. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137693. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  137694. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137695. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  137696. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  137697. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  137698. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  137699. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  137700. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  137701. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  137702. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  137703. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  137704. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  137705. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  137706. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137707. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137708. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137709. 9,
  137710. };
  137711. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  137712. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137713. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137714. };
  137715. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  137716. 15, 13, 11, 9, 7, 5, 3, 1,
  137717. 0, 2, 4, 6, 8, 10, 12, 14,
  137718. 16,
  137719. };
  137720. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  137721. _vq_quantthresh__44cn1_sm_p8_2,
  137722. _vq_quantmap__44cn1_sm_p8_2,
  137723. 17,
  137724. 17
  137725. };
  137726. static static_codebook _44cn1_sm_p8_2 = {
  137727. 2, 289,
  137728. _vq_lengthlist__44cn1_sm_p8_2,
  137729. 1, -529530880, 1611661312, 5, 0,
  137730. _vq_quantlist__44cn1_sm_p8_2,
  137731. NULL,
  137732. &_vq_auxt__44cn1_sm_p8_2,
  137733. NULL,
  137734. 0
  137735. };
  137736. static long _huff_lengthlist__44cn1_sm_short[] = {
  137737. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  137738. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  137739. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  137740. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  137741. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  137742. 9,
  137743. };
  137744. static static_codebook _huff_book__44cn1_sm_short = {
  137745. 2, 81,
  137746. _huff_lengthlist__44cn1_sm_short,
  137747. 0, 0, 0, 0, 0,
  137748. NULL,
  137749. NULL,
  137750. NULL,
  137751. NULL,
  137752. 0
  137753. };
  137754. /********* End of inlined file: res_books_stereo.h *********/
  137755. /***** residue backends *********************************************/
  137756. static vorbis_info_residue0 _residue_44_low={
  137757. 0,-1, -1, 9,-1,
  137758. /* 0 1 2 3 4 5 6 7 */
  137759. {0},
  137760. {-1},
  137761. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137762. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  137763. };
  137764. static vorbis_info_residue0 _residue_44_mid={
  137765. 0,-1, -1, 10,-1,
  137766. /* 0 1 2 3 4 5 6 7 8 */
  137767. {0},
  137768. {-1},
  137769. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137770. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  137771. };
  137772. static vorbis_info_residue0 _residue_44_high={
  137773. 0,-1, -1, 10,-1,
  137774. /* 0 1 2 3 4 5 6 7 8 */
  137775. {0},
  137776. {-1},
  137777. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  137778. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  137779. };
  137780. static static_bookblock _resbook_44s_n1={
  137781. {
  137782. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  137783. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  137784. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  137785. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  137786. }
  137787. };
  137788. static static_bookblock _resbook_44sm_n1={
  137789. {
  137790. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  137791. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  137792. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  137793. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  137794. }
  137795. };
  137796. static static_bookblock _resbook_44s_0={
  137797. {
  137798. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  137799. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  137800. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  137801. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  137802. }
  137803. };
  137804. static static_bookblock _resbook_44sm_0={
  137805. {
  137806. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  137807. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  137808. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  137809. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  137810. }
  137811. };
  137812. static static_bookblock _resbook_44s_1={
  137813. {
  137814. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  137815. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  137816. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  137817. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  137818. }
  137819. };
  137820. static static_bookblock _resbook_44sm_1={
  137821. {
  137822. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  137823. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  137824. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  137825. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  137826. }
  137827. };
  137828. static static_bookblock _resbook_44s_2={
  137829. {
  137830. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  137831. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  137832. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  137833. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  137834. }
  137835. };
  137836. static static_bookblock _resbook_44s_3={
  137837. {
  137838. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  137839. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  137840. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  137841. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  137842. }
  137843. };
  137844. static static_bookblock _resbook_44s_4={
  137845. {
  137846. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  137847. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  137848. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  137849. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  137850. }
  137851. };
  137852. static static_bookblock _resbook_44s_5={
  137853. {
  137854. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  137855. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  137856. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  137857. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  137858. }
  137859. };
  137860. static static_bookblock _resbook_44s_6={
  137861. {
  137862. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  137863. {0,0,&_44c6_s_p4_0},
  137864. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  137865. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  137866. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  137867. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  137868. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  137869. }
  137870. };
  137871. static static_bookblock _resbook_44s_7={
  137872. {
  137873. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  137874. {0,0,&_44c7_s_p4_0},
  137875. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  137876. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  137877. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  137878. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  137879. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  137880. }
  137881. };
  137882. static static_bookblock _resbook_44s_8={
  137883. {
  137884. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  137885. {0,0,&_44c8_s_p4_0},
  137886. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  137887. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  137888. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  137889. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  137890. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  137891. }
  137892. };
  137893. static static_bookblock _resbook_44s_9={
  137894. {
  137895. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  137896. {0,0,&_44c9_s_p4_0},
  137897. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  137898. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  137899. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  137900. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  137901. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  137902. }
  137903. };
  137904. static vorbis_residue_template _res_44s_n1[]={
  137905. {2,0, &_residue_44_low,
  137906. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  137907. &_resbook_44s_n1,&_resbook_44sm_n1},
  137908. {2,0, &_residue_44_low,
  137909. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  137910. &_resbook_44s_n1,&_resbook_44sm_n1}
  137911. };
  137912. static vorbis_residue_template _res_44s_0[]={
  137913. {2,0, &_residue_44_low,
  137914. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  137915. &_resbook_44s_0,&_resbook_44sm_0},
  137916. {2,0, &_residue_44_low,
  137917. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  137918. &_resbook_44s_0,&_resbook_44sm_0}
  137919. };
  137920. static vorbis_residue_template _res_44s_1[]={
  137921. {2,0, &_residue_44_low,
  137922. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  137923. &_resbook_44s_1,&_resbook_44sm_1},
  137924. {2,0, &_residue_44_low,
  137925. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  137926. &_resbook_44s_1,&_resbook_44sm_1}
  137927. };
  137928. static vorbis_residue_template _res_44s_2[]={
  137929. {2,0, &_residue_44_mid,
  137930. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  137931. &_resbook_44s_2,&_resbook_44s_2},
  137932. {2,0, &_residue_44_mid,
  137933. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  137934. &_resbook_44s_2,&_resbook_44s_2}
  137935. };
  137936. static vorbis_residue_template _res_44s_3[]={
  137937. {2,0, &_residue_44_mid,
  137938. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  137939. &_resbook_44s_3,&_resbook_44s_3},
  137940. {2,0, &_residue_44_mid,
  137941. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  137942. &_resbook_44s_3,&_resbook_44s_3}
  137943. };
  137944. static vorbis_residue_template _res_44s_4[]={
  137945. {2,0, &_residue_44_mid,
  137946. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  137947. &_resbook_44s_4,&_resbook_44s_4},
  137948. {2,0, &_residue_44_mid,
  137949. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  137950. &_resbook_44s_4,&_resbook_44s_4}
  137951. };
  137952. static vorbis_residue_template _res_44s_5[]={
  137953. {2,0, &_residue_44_mid,
  137954. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  137955. &_resbook_44s_5,&_resbook_44s_5},
  137956. {2,0, &_residue_44_mid,
  137957. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  137958. &_resbook_44s_5,&_resbook_44s_5}
  137959. };
  137960. static vorbis_residue_template _res_44s_6[]={
  137961. {2,0, &_residue_44_high,
  137962. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  137963. &_resbook_44s_6,&_resbook_44s_6},
  137964. {2,0, &_residue_44_high,
  137965. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  137966. &_resbook_44s_6,&_resbook_44s_6}
  137967. };
  137968. static vorbis_residue_template _res_44s_7[]={
  137969. {2,0, &_residue_44_high,
  137970. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  137971. &_resbook_44s_7,&_resbook_44s_7},
  137972. {2,0, &_residue_44_high,
  137973. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  137974. &_resbook_44s_7,&_resbook_44s_7}
  137975. };
  137976. static vorbis_residue_template _res_44s_8[]={
  137977. {2,0, &_residue_44_high,
  137978. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  137979. &_resbook_44s_8,&_resbook_44s_8},
  137980. {2,0, &_residue_44_high,
  137981. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  137982. &_resbook_44s_8,&_resbook_44s_8}
  137983. };
  137984. static vorbis_residue_template _res_44s_9[]={
  137985. {2,0, &_residue_44_high,
  137986. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  137987. &_resbook_44s_9,&_resbook_44s_9},
  137988. {2,0, &_residue_44_high,
  137989. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  137990. &_resbook_44s_9,&_resbook_44s_9}
  137991. };
  137992. static vorbis_mapping_template _mapres_template_44_stereo[]={
  137993. { _map_nominal, _res_44s_n1 }, /* -1 */
  137994. { _map_nominal, _res_44s_0 }, /* 0 */
  137995. { _map_nominal, _res_44s_1 }, /* 1 */
  137996. { _map_nominal, _res_44s_2 }, /* 2 */
  137997. { _map_nominal, _res_44s_3 }, /* 3 */
  137998. { _map_nominal, _res_44s_4 }, /* 4 */
  137999. { _map_nominal, _res_44s_5 }, /* 5 */
  138000. { _map_nominal, _res_44s_6 }, /* 6 */
  138001. { _map_nominal, _res_44s_7 }, /* 7 */
  138002. { _map_nominal, _res_44s_8 }, /* 8 */
  138003. { _map_nominal, _res_44s_9 }, /* 9 */
  138004. };
  138005. /********* End of inlined file: residue_44.h *********/
  138006. /********* Start of inlined file: psych_44.h *********/
  138007. /* preecho trigger settings *****************************************/
  138008. static vorbis_info_psy_global _psy_global_44[5]={
  138009. {8, /* lines per eighth octave */
  138010. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  138011. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  138012. -6.f,
  138013. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138014. },
  138015. {8, /* lines per eighth octave */
  138016. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  138017. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  138018. -6.f,
  138019. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138020. },
  138021. {8, /* lines per eighth octave */
  138022. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  138023. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  138024. -6.f,
  138025. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138026. },
  138027. {8, /* lines per eighth octave */
  138028. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  138029. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  138030. -6.f,
  138031. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138032. },
  138033. {8, /* lines per eighth octave */
  138034. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  138035. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  138036. -6.f,
  138037. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  138038. },
  138039. };
  138040. /* noise compander lookups * low, mid, high quality ****************/
  138041. static compandblock _psy_compand_44[6]={
  138042. /* sub-mode Z short */
  138043. {{
  138044. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138045. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138046. 16,17,18,19,20,21,22, 23, /* 23dB */
  138047. 24,25,26,27,28,29,30, 31, /* 31dB */
  138048. 32,33,34,35,36,37,38, 39, /* 39dB */
  138049. }},
  138050. /* mode_Z nominal short */
  138051. {{
  138052. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  138053. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  138054. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  138055. 15,16,17,17,17,18,18, 19, /* 31dB */
  138056. 19,19,20,21,22,23,24, 25, /* 39dB */
  138057. }},
  138058. /* mode A short */
  138059. {{
  138060. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  138061. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  138062. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138063. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138064. 11,12,13,14,15,16,17, 18, /* 39dB */
  138065. }},
  138066. /* sub-mode Z long */
  138067. {{
  138068. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138069. 8, 9,10,11,12,13,14, 15, /* 15dB */
  138070. 16,17,18,19,20,21,22, 23, /* 23dB */
  138071. 24,25,26,27,28,29,30, 31, /* 31dB */
  138072. 32,33,34,35,36,37,38, 39, /* 39dB */
  138073. }},
  138074. /* mode_Z nominal long */
  138075. {{
  138076. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138077. 8, 9,10,11,12,12,13, 13, /* 15dB */
  138078. 13,14,14,14,15,15,15, 15, /* 23dB */
  138079. 16,16,17,17,17,18,18, 19, /* 31dB */
  138080. 19,19,20,21,22,23,24, 25, /* 39dB */
  138081. }},
  138082. /* mode A long */
  138083. {{
  138084. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  138085. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  138086. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  138087. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  138088. 11,12,13,14,15,16,17, 18, /* 39dB */
  138089. }}
  138090. };
  138091. /* tonal masking curve level adjustments *************************/
  138092. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  138093. /* 63 125 250 500 1 2 4 8 16 */
  138094. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  138095. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138096. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  138097. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138098. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  138099. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138100. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  138101. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138102. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  138103. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  138104. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138105. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138106. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138107. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138108. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138109. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138110. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138111. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138112. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138113. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138114. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138115. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138116. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138117. };
  138118. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  138119. /* 63 125 250 500 1 2 4 8 16 */
  138120. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  138121. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  138122. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  138123. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  138124. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  138125. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  138126. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  138127. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  138128. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  138129. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  138130. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  138131. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  138132. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  138133. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  138134. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  138135. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  138136. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  138137. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  138138. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  138139. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  138140. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  138141. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  138142. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  138143. };
  138144. /* noise bias (transition block) */
  138145. static noise3 _psy_noisebias_trans[12]={
  138146. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138147. /* -1 */
  138148. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138149. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138150. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138151. /* 0
  138152. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138153. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  138154. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138155. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138156. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  138157. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138158. /* 1
  138159. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138160. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138161. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138162. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138163. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138164. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138165. /* 2
  138166. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138167. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138168. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  138169. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138170. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138171. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  138172. /* 3
  138173. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138174. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138175. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138176. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138177. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138178. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138179. /* 4
  138180. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138181. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138182. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138183. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138184. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138185. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138186. /* 5
  138187. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138188. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138189. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  138190. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138191. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138192. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  138193. /* 6
  138194. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138195. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138196. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138197. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138198. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138199. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138200. /* 7
  138201. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138202. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  138203. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  138204. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138205. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138206. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138207. /* 8
  138208. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138209. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138210. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138211. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138212. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138213. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138214. /* 9
  138215. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138216. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138217. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138218. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138219. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  138220. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  138221. /* 10 */
  138222. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  138223. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  138224. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138225. };
  138226. /* noise bias (long block) */
  138227. static noise3 _psy_noisebias_long[12]={
  138228. /*63 125 250 500 1k 2k 4k 8k 16k*/
  138229. /* -1 */
  138230. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  138231. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  138232. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138233. /* 0 */
  138234. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138235. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  138236. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138237. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138238. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  138239. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138240. /* 1 */
  138241. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138242. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138243. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138244. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138245. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138246. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138247. /* 2 */
  138248. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138249. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138250. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138251. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138252. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138253. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138254. /* 3 */
  138255. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138256. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138257. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138258. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138259. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138260. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  138261. /* 4 */
  138262. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138263. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138264. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138265. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138266. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138267. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  138268. /* 5 */
  138269. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138270. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138271. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  138272. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138273. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138274. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  138275. /* 6 */
  138276. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138277. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138278. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138279. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138280. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138281. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  138282. /* 7 */
  138283. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138284. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  138285. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138286. /* 8 */
  138287. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  138288. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  138289. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138290. /* 9 */
  138291. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138292. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  138293. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138294. /* 10 */
  138295. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  138296. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  138297. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138298. };
  138299. /* noise bias (impulse block) */
  138300. static noise3 _psy_noisebias_impulse[12]={
  138301. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138302. /* -1 */
  138303. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138304. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138305. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138306. /* 0 */
  138307. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138308. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  138309. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  138310. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138311. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  138312. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138313. /* 1 */
  138314. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138315. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  138316. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  138317. /* 2 */
  138318. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138319. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138320. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138321. /* 3 */
  138322. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138323. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138324. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138325. /* 4 */
  138326. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138327. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138328. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138329. /* 5 */
  138330. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138331. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  138332. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  138333. /* 6
  138334. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138335. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  138336. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  138337. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138338. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  138339. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  138340. /* 7 */
  138341. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138342. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  138343. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  138344. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138345. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  138346. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138347. /* 8 */
  138348. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138349. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  138350. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138351. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138352. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  138353. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138354. /* 9 */
  138355. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138356. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  138357. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138358. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138359. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  138360. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138361. /* 10 */
  138362. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  138363. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  138364. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138365. };
  138366. /* noise bias (padding block) */
  138367. static noise3 _psy_noisebias_padding[12]={
  138368. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138369. /* -1 */
  138370. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138371. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138372. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138373. /* 0 */
  138374. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138375. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  138376. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  138377. /* 1 */
  138378. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138379. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138380. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  138381. /* 2 */
  138382. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138383. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138384. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  138385. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138386. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138387. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138388. /* 3 */
  138389. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138390. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138391. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138392. /* 4 */
  138393. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138394. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  138395. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138396. /* 5 */
  138397. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138398. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  138399. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  138400. /* 6 */
  138401. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138402. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  138403. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  138404. /* 7 */
  138405. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138406. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  138407. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  138408. /* 8 */
  138409. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  138410. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  138411. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  138412. /* 9 */
  138413. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  138414. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  138415. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  138416. /* 10 */
  138417. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  138418. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  138419. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138420. };
  138421. static noiseguard _psy_noiseguards_44[4]={
  138422. {3,3,15},
  138423. {3,3,15},
  138424. {10,10,100},
  138425. {10,10,100},
  138426. };
  138427. static int _psy_tone_suppress[12]={
  138428. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  138429. };
  138430. static int _psy_tone_0dB[12]={
  138431. 90,90,95,95,95,95,105,105,105,105,105,105,
  138432. };
  138433. static int _psy_noise_suppress[12]={
  138434. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  138435. };
  138436. static vorbis_info_psy _psy_info_template={
  138437. /* blockflag */
  138438. -1,
  138439. /* ath_adjatt, ath_maxatt */
  138440. -140.,-140.,
  138441. /* tonemask att boost/decay,suppr,curves */
  138442. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  138443. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  138444. 1, -0.f, .5f, .5f, 0,0,0,
  138445. /* noiseoffset*3, noisecompand, max_curve_dB */
  138446. {{-1},{-1},{-1}},{-1},105.f,
  138447. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  138448. 0,0,-1,-1,0.,
  138449. };
  138450. /* ath ****************/
  138451. static int _psy_ath_floater[12]={
  138452. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  138453. };
  138454. static int _psy_ath_abs[12]={
  138455. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  138456. };
  138457. /* stereo setup. These don't map directly to quality level, there's
  138458. an additional indirection as several of the below may be used in a
  138459. single bitmanaged stream
  138460. ****************/
  138461. /* various stereo possibilities */
  138462. /* stereo mode by base quality level */
  138463. static adj_stereo _psy_stereo_modes_44[12]={
  138464. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  138465. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138466. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138467. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  138468. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138469. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  138470. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138471. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138472. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  138473. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138474. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  138475. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138476. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138477. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138478. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  138479. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  138480. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138481. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138482. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138483. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  138484. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  138485. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  138486. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138487. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138488. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  138489. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138490. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138491. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138492. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  138493. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  138494. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138495. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  138496. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138497. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  138498. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138499. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  138500. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  138501. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138502. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  138503. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138504. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138505. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138506. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138507. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138508. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138509. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  138510. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138511. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  138512. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138513. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138514. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138515. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138516. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138517. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138518. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138519. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138520. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  138521. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138522. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138523. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138524. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138525. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138526. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138527. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138528. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138529. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  138530. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138531. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138532. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138533. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138534. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138535. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138536. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138537. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138538. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  138539. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138540. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138541. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138542. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138543. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  138544. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138545. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138546. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138547. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138548. };
  138549. /* tone master attenuation by base quality mode and bitrate tweak */
  138550. static att3 _psy_tone_masteratt_44[12]={
  138551. {{ 35, 21, 9}, 0, 0}, /* -1 */
  138552. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  138553. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  138554. {{ 25, 12, 2}, 0, 0}, /* 1 */
  138555. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  138556. {{ 20, 9, -3}, 0, 0}, /* 2 */
  138557. {{ 20, 9, -4}, 0, 0}, /* 3 */
  138558. {{ 20, 9, -4}, 0, 0}, /* 4 */
  138559. {{ 20, 6, -6}, 0, 0}, /* 5 */
  138560. {{ 20, 3, -10}, 0, 0}, /* 6 */
  138561. {{ 18, 1, -14}, 0, 0}, /* 7 */
  138562. {{ 18, 0, -16}, 0, 0}, /* 8 */
  138563. {{ 18, -2, -16}, 0, 0}, /* 9 */
  138564. {{ 12, -2, -20}, 0, 0}, /* 10 */
  138565. };
  138566. /* lowpass by mode **************/
  138567. static double _psy_lowpass_44[12]={
  138568. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  138569. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  138570. };
  138571. /* noise normalization **********/
  138572. static int _noise_start_short_44[11]={
  138573. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  138574. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  138575. };
  138576. static int _noise_start_long_44[11]={
  138577. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  138578. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  138579. };
  138580. static int _noise_part_short_44[11]={
  138581. 8,8,8,8,8,8,8,8,8,8,8
  138582. };
  138583. static int _noise_part_long_44[11]={
  138584. 32,32,32,32,32,32,32,32,32,32,32
  138585. };
  138586. static double _noise_thresh_44[11]={
  138587. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  138588. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  138589. };
  138590. static double _noise_thresh_5only[2]={
  138591. .5,.5,
  138592. };
  138593. /********* End of inlined file: psych_44.h *********/
  138594. static double rate_mapping_44_stereo[12]={
  138595. 22500.,32000.,40000.,48000.,56000.,64000.,
  138596. 80000.,96000.,112000.,128000.,160000.,250001.
  138597. };
  138598. static double quality_mapping_44[12]={
  138599. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  138600. };
  138601. static int blocksize_short_44[11]={
  138602. 512,256,256,256,256,256,256,256,256,256,256
  138603. };
  138604. static int blocksize_long_44[11]={
  138605. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  138606. };
  138607. static double _psy_compand_short_mapping[12]={
  138608. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  138609. };
  138610. static double _psy_compand_long_mapping[12]={
  138611. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  138612. };
  138613. static double _global_mapping_44[12]={
  138614. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  138615. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  138616. };
  138617. static int _floor_short_mapping_44[11]={
  138618. 1,0,0,2,2,4,5,5,5,5,5
  138619. };
  138620. static int _floor_long_mapping_44[11]={
  138621. 8,7,7,7,7,7,7,7,7,7,7
  138622. };
  138623. ve_setup_data_template ve_setup_44_stereo={
  138624. 11,
  138625. rate_mapping_44_stereo,
  138626. quality_mapping_44,
  138627. 2,
  138628. 40000,
  138629. 50000,
  138630. blocksize_short_44,
  138631. blocksize_long_44,
  138632. _psy_tone_masteratt_44,
  138633. _psy_tone_0dB,
  138634. _psy_tone_suppress,
  138635. _vp_tonemask_adj_otherblock,
  138636. _vp_tonemask_adj_longblock,
  138637. _vp_tonemask_adj_otherblock,
  138638. _psy_noiseguards_44,
  138639. _psy_noisebias_impulse,
  138640. _psy_noisebias_padding,
  138641. _psy_noisebias_trans,
  138642. _psy_noisebias_long,
  138643. _psy_noise_suppress,
  138644. _psy_compand_44,
  138645. _psy_compand_short_mapping,
  138646. _psy_compand_long_mapping,
  138647. {_noise_start_short_44,_noise_start_long_44},
  138648. {_noise_part_short_44,_noise_part_long_44},
  138649. _noise_thresh_44,
  138650. _psy_ath_floater,
  138651. _psy_ath_abs,
  138652. _psy_lowpass_44,
  138653. _psy_global_44,
  138654. _global_mapping_44,
  138655. _psy_stereo_modes_44,
  138656. _floor_books,
  138657. _floor,
  138658. _floor_short_mapping_44,
  138659. _floor_long_mapping_44,
  138660. _mapres_template_44_stereo
  138661. };
  138662. /********* End of inlined file: setup_44.h *********/
  138663. /********* Start of inlined file: setup_44u.h *********/
  138664. /********* Start of inlined file: residue_44u.h *********/
  138665. /********* Start of inlined file: res_books_uncoupled.h *********/
  138666. static long _vq_quantlist__16u0__p1_0[] = {
  138667. 1,
  138668. 0,
  138669. 2,
  138670. };
  138671. static long _vq_lengthlist__16u0__p1_0[] = {
  138672. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  138673. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  138674. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  138675. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  138676. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  138677. 12,
  138678. };
  138679. static float _vq_quantthresh__16u0__p1_0[] = {
  138680. -0.5, 0.5,
  138681. };
  138682. static long _vq_quantmap__16u0__p1_0[] = {
  138683. 1, 0, 2,
  138684. };
  138685. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  138686. _vq_quantthresh__16u0__p1_0,
  138687. _vq_quantmap__16u0__p1_0,
  138688. 3,
  138689. 3
  138690. };
  138691. static static_codebook _16u0__p1_0 = {
  138692. 4, 81,
  138693. _vq_lengthlist__16u0__p1_0,
  138694. 1, -535822336, 1611661312, 2, 0,
  138695. _vq_quantlist__16u0__p1_0,
  138696. NULL,
  138697. &_vq_auxt__16u0__p1_0,
  138698. NULL,
  138699. 0
  138700. };
  138701. static long _vq_quantlist__16u0__p2_0[] = {
  138702. 1,
  138703. 0,
  138704. 2,
  138705. };
  138706. static long _vq_lengthlist__16u0__p2_0[] = {
  138707. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  138708. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  138709. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  138710. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  138711. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  138712. 8,
  138713. };
  138714. static float _vq_quantthresh__16u0__p2_0[] = {
  138715. -0.5, 0.5,
  138716. };
  138717. static long _vq_quantmap__16u0__p2_0[] = {
  138718. 1, 0, 2,
  138719. };
  138720. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  138721. _vq_quantthresh__16u0__p2_0,
  138722. _vq_quantmap__16u0__p2_0,
  138723. 3,
  138724. 3
  138725. };
  138726. static static_codebook _16u0__p2_0 = {
  138727. 4, 81,
  138728. _vq_lengthlist__16u0__p2_0,
  138729. 1, -535822336, 1611661312, 2, 0,
  138730. _vq_quantlist__16u0__p2_0,
  138731. NULL,
  138732. &_vq_auxt__16u0__p2_0,
  138733. NULL,
  138734. 0
  138735. };
  138736. static long _vq_quantlist__16u0__p3_0[] = {
  138737. 2,
  138738. 1,
  138739. 3,
  138740. 0,
  138741. 4,
  138742. };
  138743. static long _vq_lengthlist__16u0__p3_0[] = {
  138744. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  138745. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  138746. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  138747. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  138748. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  138749. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  138750. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  138751. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  138752. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  138753. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  138754. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  138755. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  138756. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  138757. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  138758. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  138759. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  138760. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  138761. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  138762. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  138763. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  138764. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  138765. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  138766. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  138767. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  138768. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  138769. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  138770. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  138771. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  138772. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  138773. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  138774. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  138775. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  138776. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  138777. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  138778. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  138779. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  138780. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  138781. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  138782. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  138783. 18,
  138784. };
  138785. static float _vq_quantthresh__16u0__p3_0[] = {
  138786. -1.5, -0.5, 0.5, 1.5,
  138787. };
  138788. static long _vq_quantmap__16u0__p3_0[] = {
  138789. 3, 1, 0, 2, 4,
  138790. };
  138791. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  138792. _vq_quantthresh__16u0__p3_0,
  138793. _vq_quantmap__16u0__p3_0,
  138794. 5,
  138795. 5
  138796. };
  138797. static static_codebook _16u0__p3_0 = {
  138798. 4, 625,
  138799. _vq_lengthlist__16u0__p3_0,
  138800. 1, -533725184, 1611661312, 3, 0,
  138801. _vq_quantlist__16u0__p3_0,
  138802. NULL,
  138803. &_vq_auxt__16u0__p3_0,
  138804. NULL,
  138805. 0
  138806. };
  138807. static long _vq_quantlist__16u0__p4_0[] = {
  138808. 2,
  138809. 1,
  138810. 3,
  138811. 0,
  138812. 4,
  138813. };
  138814. static long _vq_lengthlist__16u0__p4_0[] = {
  138815. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  138816. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  138817. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  138818. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  138819. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  138820. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  138821. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  138822. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  138823. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138824. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  138825. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  138826. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  138827. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  138828. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  138829. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  138830. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  138831. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  138832. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  138833. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  138834. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  138835. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  138836. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  138837. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  138838. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  138839. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  138840. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  138841. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  138842. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  138843. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  138844. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  138845. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  138846. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  138847. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  138848. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  138849. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  138850. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  138851. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  138852. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  138853. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  138854. 11,
  138855. };
  138856. static float _vq_quantthresh__16u0__p4_0[] = {
  138857. -1.5, -0.5, 0.5, 1.5,
  138858. };
  138859. static long _vq_quantmap__16u0__p4_0[] = {
  138860. 3, 1, 0, 2, 4,
  138861. };
  138862. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  138863. _vq_quantthresh__16u0__p4_0,
  138864. _vq_quantmap__16u0__p4_0,
  138865. 5,
  138866. 5
  138867. };
  138868. static static_codebook _16u0__p4_0 = {
  138869. 4, 625,
  138870. _vq_lengthlist__16u0__p4_0,
  138871. 1, -533725184, 1611661312, 3, 0,
  138872. _vq_quantlist__16u0__p4_0,
  138873. NULL,
  138874. &_vq_auxt__16u0__p4_0,
  138875. NULL,
  138876. 0
  138877. };
  138878. static long _vq_quantlist__16u0__p5_0[] = {
  138879. 4,
  138880. 3,
  138881. 5,
  138882. 2,
  138883. 6,
  138884. 1,
  138885. 7,
  138886. 0,
  138887. 8,
  138888. };
  138889. static long _vq_lengthlist__16u0__p5_0[] = {
  138890. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138891. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  138892. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  138893. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138894. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  138895. 12,
  138896. };
  138897. static float _vq_quantthresh__16u0__p5_0[] = {
  138898. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138899. };
  138900. static long _vq_quantmap__16u0__p5_0[] = {
  138901. 7, 5, 3, 1, 0, 2, 4, 6,
  138902. 8,
  138903. };
  138904. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  138905. _vq_quantthresh__16u0__p5_0,
  138906. _vq_quantmap__16u0__p5_0,
  138907. 9,
  138908. 9
  138909. };
  138910. static static_codebook _16u0__p5_0 = {
  138911. 2, 81,
  138912. _vq_lengthlist__16u0__p5_0,
  138913. 1, -531628032, 1611661312, 4, 0,
  138914. _vq_quantlist__16u0__p5_0,
  138915. NULL,
  138916. &_vq_auxt__16u0__p5_0,
  138917. NULL,
  138918. 0
  138919. };
  138920. static long _vq_quantlist__16u0__p6_0[] = {
  138921. 6,
  138922. 5,
  138923. 7,
  138924. 4,
  138925. 8,
  138926. 3,
  138927. 9,
  138928. 2,
  138929. 10,
  138930. 1,
  138931. 11,
  138932. 0,
  138933. 12,
  138934. };
  138935. static long _vq_lengthlist__16u0__p6_0[] = {
  138936. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  138937. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  138938. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  138939. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  138940. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  138941. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  138942. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  138943. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  138944. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  138945. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  138946. 18, 0,19, 0, 0, 0, 0, 0, 0,
  138947. };
  138948. static float _vq_quantthresh__16u0__p6_0[] = {
  138949. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138950. 12.5, 17.5, 22.5, 27.5,
  138951. };
  138952. static long _vq_quantmap__16u0__p6_0[] = {
  138953. 11, 9, 7, 5, 3, 1, 0, 2,
  138954. 4, 6, 8, 10, 12,
  138955. };
  138956. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  138957. _vq_quantthresh__16u0__p6_0,
  138958. _vq_quantmap__16u0__p6_0,
  138959. 13,
  138960. 13
  138961. };
  138962. static static_codebook _16u0__p6_0 = {
  138963. 2, 169,
  138964. _vq_lengthlist__16u0__p6_0,
  138965. 1, -526516224, 1616117760, 4, 0,
  138966. _vq_quantlist__16u0__p6_0,
  138967. NULL,
  138968. &_vq_auxt__16u0__p6_0,
  138969. NULL,
  138970. 0
  138971. };
  138972. static long _vq_quantlist__16u0__p6_1[] = {
  138973. 2,
  138974. 1,
  138975. 3,
  138976. 0,
  138977. 4,
  138978. };
  138979. static long _vq_lengthlist__16u0__p6_1[] = {
  138980. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  138981. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  138982. };
  138983. static float _vq_quantthresh__16u0__p6_1[] = {
  138984. -1.5, -0.5, 0.5, 1.5,
  138985. };
  138986. static long _vq_quantmap__16u0__p6_1[] = {
  138987. 3, 1, 0, 2, 4,
  138988. };
  138989. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  138990. _vq_quantthresh__16u0__p6_1,
  138991. _vq_quantmap__16u0__p6_1,
  138992. 5,
  138993. 5
  138994. };
  138995. static static_codebook _16u0__p6_1 = {
  138996. 2, 25,
  138997. _vq_lengthlist__16u0__p6_1,
  138998. 1, -533725184, 1611661312, 3, 0,
  138999. _vq_quantlist__16u0__p6_1,
  139000. NULL,
  139001. &_vq_auxt__16u0__p6_1,
  139002. NULL,
  139003. 0
  139004. };
  139005. static long _vq_quantlist__16u0__p7_0[] = {
  139006. 1,
  139007. 0,
  139008. 2,
  139009. };
  139010. static long _vq_lengthlist__16u0__p7_0[] = {
  139011. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139012. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139013. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139014. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139015. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139016. 7,
  139017. };
  139018. static float _vq_quantthresh__16u0__p7_0[] = {
  139019. -157.5, 157.5,
  139020. };
  139021. static long _vq_quantmap__16u0__p7_0[] = {
  139022. 1, 0, 2,
  139023. };
  139024. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  139025. _vq_quantthresh__16u0__p7_0,
  139026. _vq_quantmap__16u0__p7_0,
  139027. 3,
  139028. 3
  139029. };
  139030. static static_codebook _16u0__p7_0 = {
  139031. 4, 81,
  139032. _vq_lengthlist__16u0__p7_0,
  139033. 1, -518803456, 1628680192, 2, 0,
  139034. _vq_quantlist__16u0__p7_0,
  139035. NULL,
  139036. &_vq_auxt__16u0__p7_0,
  139037. NULL,
  139038. 0
  139039. };
  139040. static long _vq_quantlist__16u0__p7_1[] = {
  139041. 7,
  139042. 6,
  139043. 8,
  139044. 5,
  139045. 9,
  139046. 4,
  139047. 10,
  139048. 3,
  139049. 11,
  139050. 2,
  139051. 12,
  139052. 1,
  139053. 13,
  139054. 0,
  139055. 14,
  139056. };
  139057. static long _vq_lengthlist__16u0__p7_1[] = {
  139058. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  139059. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  139060. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  139061. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  139062. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  139063. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  139064. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139065. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139066. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139067. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139068. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139069. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139070. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139071. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139072. 10,
  139073. };
  139074. static float _vq_quantthresh__16u0__p7_1[] = {
  139075. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139076. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139077. };
  139078. static long _vq_quantmap__16u0__p7_1[] = {
  139079. 13, 11, 9, 7, 5, 3, 1, 0,
  139080. 2, 4, 6, 8, 10, 12, 14,
  139081. };
  139082. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  139083. _vq_quantthresh__16u0__p7_1,
  139084. _vq_quantmap__16u0__p7_1,
  139085. 15,
  139086. 15
  139087. };
  139088. static static_codebook _16u0__p7_1 = {
  139089. 2, 225,
  139090. _vq_lengthlist__16u0__p7_1,
  139091. 1, -520986624, 1620377600, 4, 0,
  139092. _vq_quantlist__16u0__p7_1,
  139093. NULL,
  139094. &_vq_auxt__16u0__p7_1,
  139095. NULL,
  139096. 0
  139097. };
  139098. static long _vq_quantlist__16u0__p7_2[] = {
  139099. 10,
  139100. 9,
  139101. 11,
  139102. 8,
  139103. 12,
  139104. 7,
  139105. 13,
  139106. 6,
  139107. 14,
  139108. 5,
  139109. 15,
  139110. 4,
  139111. 16,
  139112. 3,
  139113. 17,
  139114. 2,
  139115. 18,
  139116. 1,
  139117. 19,
  139118. 0,
  139119. 20,
  139120. };
  139121. static long _vq_lengthlist__16u0__p7_2[] = {
  139122. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  139123. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  139124. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  139125. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  139126. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  139127. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  139128. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  139129. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  139130. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  139131. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  139132. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  139133. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  139134. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  139135. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  139136. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  139137. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  139138. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  139139. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  139140. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  139141. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  139142. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  139143. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  139144. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  139145. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  139146. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  139147. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  139148. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  139149. 10,10,12,11,10,11,11,11,10,
  139150. };
  139151. static float _vq_quantthresh__16u0__p7_2[] = {
  139152. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139153. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139154. 6.5, 7.5, 8.5, 9.5,
  139155. };
  139156. static long _vq_quantmap__16u0__p7_2[] = {
  139157. 19, 17, 15, 13, 11, 9, 7, 5,
  139158. 3, 1, 0, 2, 4, 6, 8, 10,
  139159. 12, 14, 16, 18, 20,
  139160. };
  139161. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  139162. _vq_quantthresh__16u0__p7_2,
  139163. _vq_quantmap__16u0__p7_2,
  139164. 21,
  139165. 21
  139166. };
  139167. static static_codebook _16u0__p7_2 = {
  139168. 2, 441,
  139169. _vq_lengthlist__16u0__p7_2,
  139170. 1, -529268736, 1611661312, 5, 0,
  139171. _vq_quantlist__16u0__p7_2,
  139172. NULL,
  139173. &_vq_auxt__16u0__p7_2,
  139174. NULL,
  139175. 0
  139176. };
  139177. static long _huff_lengthlist__16u0__single[] = {
  139178. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  139179. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  139180. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  139181. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  139182. };
  139183. static static_codebook _huff_book__16u0__single = {
  139184. 2, 64,
  139185. _huff_lengthlist__16u0__single,
  139186. 0, 0, 0, 0, 0,
  139187. NULL,
  139188. NULL,
  139189. NULL,
  139190. NULL,
  139191. 0
  139192. };
  139193. static long _huff_lengthlist__16u1__long[] = {
  139194. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  139195. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  139196. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  139197. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  139198. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  139199. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  139200. 16,13,16,18,
  139201. };
  139202. static static_codebook _huff_book__16u1__long = {
  139203. 2, 100,
  139204. _huff_lengthlist__16u1__long,
  139205. 0, 0, 0, 0, 0,
  139206. NULL,
  139207. NULL,
  139208. NULL,
  139209. NULL,
  139210. 0
  139211. };
  139212. static long _vq_quantlist__16u1__p1_0[] = {
  139213. 1,
  139214. 0,
  139215. 2,
  139216. };
  139217. static long _vq_lengthlist__16u1__p1_0[] = {
  139218. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  139219. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  139220. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  139221. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139222. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  139223. 11,
  139224. };
  139225. static float _vq_quantthresh__16u1__p1_0[] = {
  139226. -0.5, 0.5,
  139227. };
  139228. static long _vq_quantmap__16u1__p1_0[] = {
  139229. 1, 0, 2,
  139230. };
  139231. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  139232. _vq_quantthresh__16u1__p1_0,
  139233. _vq_quantmap__16u1__p1_0,
  139234. 3,
  139235. 3
  139236. };
  139237. static static_codebook _16u1__p1_0 = {
  139238. 4, 81,
  139239. _vq_lengthlist__16u1__p1_0,
  139240. 1, -535822336, 1611661312, 2, 0,
  139241. _vq_quantlist__16u1__p1_0,
  139242. NULL,
  139243. &_vq_auxt__16u1__p1_0,
  139244. NULL,
  139245. 0
  139246. };
  139247. static long _vq_quantlist__16u1__p2_0[] = {
  139248. 1,
  139249. 0,
  139250. 2,
  139251. };
  139252. static long _vq_lengthlist__16u1__p2_0[] = {
  139253. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  139254. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  139255. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  139256. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  139257. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  139258. 8,
  139259. };
  139260. static float _vq_quantthresh__16u1__p2_0[] = {
  139261. -0.5, 0.5,
  139262. };
  139263. static long _vq_quantmap__16u1__p2_0[] = {
  139264. 1, 0, 2,
  139265. };
  139266. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  139267. _vq_quantthresh__16u1__p2_0,
  139268. _vq_quantmap__16u1__p2_0,
  139269. 3,
  139270. 3
  139271. };
  139272. static static_codebook _16u1__p2_0 = {
  139273. 4, 81,
  139274. _vq_lengthlist__16u1__p2_0,
  139275. 1, -535822336, 1611661312, 2, 0,
  139276. _vq_quantlist__16u1__p2_0,
  139277. NULL,
  139278. &_vq_auxt__16u1__p2_0,
  139279. NULL,
  139280. 0
  139281. };
  139282. static long _vq_quantlist__16u1__p3_0[] = {
  139283. 2,
  139284. 1,
  139285. 3,
  139286. 0,
  139287. 4,
  139288. };
  139289. static long _vq_lengthlist__16u1__p3_0[] = {
  139290. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139291. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  139292. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  139293. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  139294. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  139295. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  139296. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  139297. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  139298. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  139299. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  139300. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  139301. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  139302. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  139303. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  139304. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  139305. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  139306. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  139307. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  139308. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  139309. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  139310. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  139311. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  139312. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  139313. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  139314. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  139315. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  139316. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  139317. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  139318. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  139319. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  139320. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  139321. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  139322. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  139323. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  139324. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  139325. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  139326. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  139327. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  139328. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  139329. 16,
  139330. };
  139331. static float _vq_quantthresh__16u1__p3_0[] = {
  139332. -1.5, -0.5, 0.5, 1.5,
  139333. };
  139334. static long _vq_quantmap__16u1__p3_0[] = {
  139335. 3, 1, 0, 2, 4,
  139336. };
  139337. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  139338. _vq_quantthresh__16u1__p3_0,
  139339. _vq_quantmap__16u1__p3_0,
  139340. 5,
  139341. 5
  139342. };
  139343. static static_codebook _16u1__p3_0 = {
  139344. 4, 625,
  139345. _vq_lengthlist__16u1__p3_0,
  139346. 1, -533725184, 1611661312, 3, 0,
  139347. _vq_quantlist__16u1__p3_0,
  139348. NULL,
  139349. &_vq_auxt__16u1__p3_0,
  139350. NULL,
  139351. 0
  139352. };
  139353. static long _vq_quantlist__16u1__p4_0[] = {
  139354. 2,
  139355. 1,
  139356. 3,
  139357. 0,
  139358. 4,
  139359. };
  139360. static long _vq_lengthlist__16u1__p4_0[] = {
  139361. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  139362. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  139363. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  139364. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  139365. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139366. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  139367. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  139368. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  139369. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  139370. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  139371. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  139372. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  139373. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  139374. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  139375. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  139376. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  139377. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  139378. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139379. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  139380. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  139381. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  139382. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  139383. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  139384. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  139385. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  139386. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  139387. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  139388. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  139389. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  139390. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  139391. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  139392. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  139393. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  139394. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  139395. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  139396. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  139397. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  139398. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  139399. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  139400. 11,
  139401. };
  139402. static float _vq_quantthresh__16u1__p4_0[] = {
  139403. -1.5, -0.5, 0.5, 1.5,
  139404. };
  139405. static long _vq_quantmap__16u1__p4_0[] = {
  139406. 3, 1, 0, 2, 4,
  139407. };
  139408. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  139409. _vq_quantthresh__16u1__p4_0,
  139410. _vq_quantmap__16u1__p4_0,
  139411. 5,
  139412. 5
  139413. };
  139414. static static_codebook _16u1__p4_0 = {
  139415. 4, 625,
  139416. _vq_lengthlist__16u1__p4_0,
  139417. 1, -533725184, 1611661312, 3, 0,
  139418. _vq_quantlist__16u1__p4_0,
  139419. NULL,
  139420. &_vq_auxt__16u1__p4_0,
  139421. NULL,
  139422. 0
  139423. };
  139424. static long _vq_quantlist__16u1__p5_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__p5_0[] = {
  139436. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139437. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139438. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  139439. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  139440. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  139441. 13,
  139442. };
  139443. static float _vq_quantthresh__16u1__p5_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__p5_0[] = {
  139447. 7, 5, 3, 1, 0, 2, 4, 6,
  139448. 8,
  139449. };
  139450. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  139451. _vq_quantthresh__16u1__p5_0,
  139452. _vq_quantmap__16u1__p5_0,
  139453. 9,
  139454. 9
  139455. };
  139456. static static_codebook _16u1__p5_0 = {
  139457. 2, 81,
  139458. _vq_lengthlist__16u1__p5_0,
  139459. 1, -531628032, 1611661312, 4, 0,
  139460. _vq_quantlist__16u1__p5_0,
  139461. NULL,
  139462. &_vq_auxt__16u1__p5_0,
  139463. NULL,
  139464. 0
  139465. };
  139466. static long _vq_quantlist__16u1__p6_0[] = {
  139467. 4,
  139468. 3,
  139469. 5,
  139470. 2,
  139471. 6,
  139472. 1,
  139473. 7,
  139474. 0,
  139475. 8,
  139476. };
  139477. static long _vq_lengthlist__16u1__p6_0[] = {
  139478. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  139479. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139480. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139481. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139482. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139483. 11,
  139484. };
  139485. static float _vq_quantthresh__16u1__p6_0[] = {
  139486. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139487. };
  139488. static long _vq_quantmap__16u1__p6_0[] = {
  139489. 7, 5, 3, 1, 0, 2, 4, 6,
  139490. 8,
  139491. };
  139492. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  139493. _vq_quantthresh__16u1__p6_0,
  139494. _vq_quantmap__16u1__p6_0,
  139495. 9,
  139496. 9
  139497. };
  139498. static static_codebook _16u1__p6_0 = {
  139499. 2, 81,
  139500. _vq_lengthlist__16u1__p6_0,
  139501. 1, -531628032, 1611661312, 4, 0,
  139502. _vq_quantlist__16u1__p6_0,
  139503. NULL,
  139504. &_vq_auxt__16u1__p6_0,
  139505. NULL,
  139506. 0
  139507. };
  139508. static long _vq_quantlist__16u1__p7_0[] = {
  139509. 1,
  139510. 0,
  139511. 2,
  139512. };
  139513. static long _vq_lengthlist__16u1__p7_0[] = {
  139514. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  139515. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  139516. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  139517. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  139518. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  139519. 13,
  139520. };
  139521. static float _vq_quantthresh__16u1__p7_0[] = {
  139522. -5.5, 5.5,
  139523. };
  139524. static long _vq_quantmap__16u1__p7_0[] = {
  139525. 1, 0, 2,
  139526. };
  139527. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  139528. _vq_quantthresh__16u1__p7_0,
  139529. _vq_quantmap__16u1__p7_0,
  139530. 3,
  139531. 3
  139532. };
  139533. static static_codebook _16u1__p7_0 = {
  139534. 4, 81,
  139535. _vq_lengthlist__16u1__p7_0,
  139536. 1, -529137664, 1618345984, 2, 0,
  139537. _vq_quantlist__16u1__p7_0,
  139538. NULL,
  139539. &_vq_auxt__16u1__p7_0,
  139540. NULL,
  139541. 0
  139542. };
  139543. static long _vq_quantlist__16u1__p7_1[] = {
  139544. 5,
  139545. 4,
  139546. 6,
  139547. 3,
  139548. 7,
  139549. 2,
  139550. 8,
  139551. 1,
  139552. 9,
  139553. 0,
  139554. 10,
  139555. };
  139556. static long _vq_lengthlist__16u1__p7_1[] = {
  139557. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  139558. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  139559. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139560. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  139561. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  139562. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  139563. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  139564. 8, 9, 9,10,10,10,10,10,10,
  139565. };
  139566. static float _vq_quantthresh__16u1__p7_1[] = {
  139567. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139568. 3.5, 4.5,
  139569. };
  139570. static long _vq_quantmap__16u1__p7_1[] = {
  139571. 9, 7, 5, 3, 1, 0, 2, 4,
  139572. 6, 8, 10,
  139573. };
  139574. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  139575. _vq_quantthresh__16u1__p7_1,
  139576. _vq_quantmap__16u1__p7_1,
  139577. 11,
  139578. 11
  139579. };
  139580. static static_codebook _16u1__p7_1 = {
  139581. 2, 121,
  139582. _vq_lengthlist__16u1__p7_1,
  139583. 1, -531365888, 1611661312, 4, 0,
  139584. _vq_quantlist__16u1__p7_1,
  139585. NULL,
  139586. &_vq_auxt__16u1__p7_1,
  139587. NULL,
  139588. 0
  139589. };
  139590. static long _vq_quantlist__16u1__p8_0[] = {
  139591. 5,
  139592. 4,
  139593. 6,
  139594. 3,
  139595. 7,
  139596. 2,
  139597. 8,
  139598. 1,
  139599. 9,
  139600. 0,
  139601. 10,
  139602. };
  139603. static long _vq_lengthlist__16u1__p8_0[] = {
  139604. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  139605. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  139606. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  139607. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  139608. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  139609. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  139610. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  139611. 13,14,14,15,15,16,16,15,16,
  139612. };
  139613. static float _vq_quantthresh__16u1__p8_0[] = {
  139614. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139615. 38.5, 49.5,
  139616. };
  139617. static long _vq_quantmap__16u1__p8_0[] = {
  139618. 9, 7, 5, 3, 1, 0, 2, 4,
  139619. 6, 8, 10,
  139620. };
  139621. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  139622. _vq_quantthresh__16u1__p8_0,
  139623. _vq_quantmap__16u1__p8_0,
  139624. 11,
  139625. 11
  139626. };
  139627. static static_codebook _16u1__p8_0 = {
  139628. 2, 121,
  139629. _vq_lengthlist__16u1__p8_0,
  139630. 1, -524582912, 1618345984, 4, 0,
  139631. _vq_quantlist__16u1__p8_0,
  139632. NULL,
  139633. &_vq_auxt__16u1__p8_0,
  139634. NULL,
  139635. 0
  139636. };
  139637. static long _vq_quantlist__16u1__p8_1[] = {
  139638. 5,
  139639. 4,
  139640. 6,
  139641. 3,
  139642. 7,
  139643. 2,
  139644. 8,
  139645. 1,
  139646. 9,
  139647. 0,
  139648. 10,
  139649. };
  139650. static long _vq_lengthlist__16u1__p8_1[] = {
  139651. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  139652. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  139653. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  139654. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  139655. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  139656. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  139657. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  139658. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  139659. };
  139660. static float _vq_quantthresh__16u1__p8_1[] = {
  139661. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139662. 3.5, 4.5,
  139663. };
  139664. static long _vq_quantmap__16u1__p8_1[] = {
  139665. 9, 7, 5, 3, 1, 0, 2, 4,
  139666. 6, 8, 10,
  139667. };
  139668. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  139669. _vq_quantthresh__16u1__p8_1,
  139670. _vq_quantmap__16u1__p8_1,
  139671. 11,
  139672. 11
  139673. };
  139674. static static_codebook _16u1__p8_1 = {
  139675. 2, 121,
  139676. _vq_lengthlist__16u1__p8_1,
  139677. 1, -531365888, 1611661312, 4, 0,
  139678. _vq_quantlist__16u1__p8_1,
  139679. NULL,
  139680. &_vq_auxt__16u1__p8_1,
  139681. NULL,
  139682. 0
  139683. };
  139684. static long _vq_quantlist__16u1__p9_0[] = {
  139685. 7,
  139686. 6,
  139687. 8,
  139688. 5,
  139689. 9,
  139690. 4,
  139691. 10,
  139692. 3,
  139693. 11,
  139694. 2,
  139695. 12,
  139696. 1,
  139697. 13,
  139698. 0,
  139699. 14,
  139700. };
  139701. static long _vq_lengthlist__16u1__p9_0[] = {
  139702. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139703. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139704. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139705. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139706. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139707. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139708. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139709. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139710. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139711. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139712. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139713. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139714. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139715. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139716. 8,
  139717. };
  139718. static float _vq_quantthresh__16u1__p9_0[] = {
  139719. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  139720. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  139721. };
  139722. static long _vq_quantmap__16u1__p9_0[] = {
  139723. 13, 11, 9, 7, 5, 3, 1, 0,
  139724. 2, 4, 6, 8, 10, 12, 14,
  139725. };
  139726. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  139727. _vq_quantthresh__16u1__p9_0,
  139728. _vq_quantmap__16u1__p9_0,
  139729. 15,
  139730. 15
  139731. };
  139732. static static_codebook _16u1__p9_0 = {
  139733. 2, 225,
  139734. _vq_lengthlist__16u1__p9_0,
  139735. 1, -514071552, 1627381760, 4, 0,
  139736. _vq_quantlist__16u1__p9_0,
  139737. NULL,
  139738. &_vq_auxt__16u1__p9_0,
  139739. NULL,
  139740. 0
  139741. };
  139742. static long _vq_quantlist__16u1__p9_1[] = {
  139743. 7,
  139744. 6,
  139745. 8,
  139746. 5,
  139747. 9,
  139748. 4,
  139749. 10,
  139750. 3,
  139751. 11,
  139752. 2,
  139753. 12,
  139754. 1,
  139755. 13,
  139756. 0,
  139757. 14,
  139758. };
  139759. static long _vq_lengthlist__16u1__p9_1[] = {
  139760. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  139761. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  139762. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  139763. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  139764. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  139765. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  139766. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  139767. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  139768. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  139769. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139770. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139771. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139772. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139773. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139774. 9,
  139775. };
  139776. static float _vq_quantthresh__16u1__p9_1[] = {
  139777. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  139778. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  139779. };
  139780. static long _vq_quantmap__16u1__p9_1[] = {
  139781. 13, 11, 9, 7, 5, 3, 1, 0,
  139782. 2, 4, 6, 8, 10, 12, 14,
  139783. };
  139784. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  139785. _vq_quantthresh__16u1__p9_1,
  139786. _vq_quantmap__16u1__p9_1,
  139787. 15,
  139788. 15
  139789. };
  139790. static static_codebook _16u1__p9_1 = {
  139791. 2, 225,
  139792. _vq_lengthlist__16u1__p9_1,
  139793. 1, -522338304, 1620115456, 4, 0,
  139794. _vq_quantlist__16u1__p9_1,
  139795. NULL,
  139796. &_vq_auxt__16u1__p9_1,
  139797. NULL,
  139798. 0
  139799. };
  139800. static long _vq_quantlist__16u1__p9_2[] = {
  139801. 8,
  139802. 7,
  139803. 9,
  139804. 6,
  139805. 10,
  139806. 5,
  139807. 11,
  139808. 4,
  139809. 12,
  139810. 3,
  139811. 13,
  139812. 2,
  139813. 14,
  139814. 1,
  139815. 15,
  139816. 0,
  139817. 16,
  139818. };
  139819. static long _vq_lengthlist__16u1__p9_2[] = {
  139820. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  139821. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  139822. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  139823. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  139824. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  139825. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  139826. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  139827. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  139828. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  139829. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  139830. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  139831. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  139832. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  139833. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  139834. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  139835. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  139836. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  139837. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  139838. 10,
  139839. };
  139840. static float _vq_quantthresh__16u1__p9_2[] = {
  139841. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139842. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139843. };
  139844. static long _vq_quantmap__16u1__p9_2[] = {
  139845. 15, 13, 11, 9, 7, 5, 3, 1,
  139846. 0, 2, 4, 6, 8, 10, 12, 14,
  139847. 16,
  139848. };
  139849. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  139850. _vq_quantthresh__16u1__p9_2,
  139851. _vq_quantmap__16u1__p9_2,
  139852. 17,
  139853. 17
  139854. };
  139855. static static_codebook _16u1__p9_2 = {
  139856. 2, 289,
  139857. _vq_lengthlist__16u1__p9_2,
  139858. 1, -529530880, 1611661312, 5, 0,
  139859. _vq_quantlist__16u1__p9_2,
  139860. NULL,
  139861. &_vq_auxt__16u1__p9_2,
  139862. NULL,
  139863. 0
  139864. };
  139865. static long _huff_lengthlist__16u1__short[] = {
  139866. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  139867. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  139868. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  139869. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  139870. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  139871. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  139872. 16,16,16,16,
  139873. };
  139874. static static_codebook _huff_book__16u1__short = {
  139875. 2, 100,
  139876. _huff_lengthlist__16u1__short,
  139877. 0, 0, 0, 0, 0,
  139878. NULL,
  139879. NULL,
  139880. NULL,
  139881. NULL,
  139882. 0
  139883. };
  139884. static long _huff_lengthlist__16u2__long[] = {
  139885. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  139886. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  139887. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  139888. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  139889. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  139890. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  139891. 13,14,18,18,
  139892. };
  139893. static static_codebook _huff_book__16u2__long = {
  139894. 2, 100,
  139895. _huff_lengthlist__16u2__long,
  139896. 0, 0, 0, 0, 0,
  139897. NULL,
  139898. NULL,
  139899. NULL,
  139900. NULL,
  139901. 0
  139902. };
  139903. static long _huff_lengthlist__16u2__short[] = {
  139904. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  139905. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  139906. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  139907. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  139908. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  139909. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  139910. 16,16,16,16,
  139911. };
  139912. static static_codebook _huff_book__16u2__short = {
  139913. 2, 100,
  139914. _huff_lengthlist__16u2__short,
  139915. 0, 0, 0, 0, 0,
  139916. NULL,
  139917. NULL,
  139918. NULL,
  139919. NULL,
  139920. 0
  139921. };
  139922. static long _vq_quantlist__16u2_p1_0[] = {
  139923. 1,
  139924. 0,
  139925. 2,
  139926. };
  139927. static long _vq_lengthlist__16u2_p1_0[] = {
  139928. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  139929. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  139930. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  139931. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  139932. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  139933. 10,
  139934. };
  139935. static float _vq_quantthresh__16u2_p1_0[] = {
  139936. -0.5, 0.5,
  139937. };
  139938. static long _vq_quantmap__16u2_p1_0[] = {
  139939. 1, 0, 2,
  139940. };
  139941. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  139942. _vq_quantthresh__16u2_p1_0,
  139943. _vq_quantmap__16u2_p1_0,
  139944. 3,
  139945. 3
  139946. };
  139947. static static_codebook _16u2_p1_0 = {
  139948. 4, 81,
  139949. _vq_lengthlist__16u2_p1_0,
  139950. 1, -535822336, 1611661312, 2, 0,
  139951. _vq_quantlist__16u2_p1_0,
  139952. NULL,
  139953. &_vq_auxt__16u2_p1_0,
  139954. NULL,
  139955. 0
  139956. };
  139957. static long _vq_quantlist__16u2_p2_0[] = {
  139958. 2,
  139959. 1,
  139960. 3,
  139961. 0,
  139962. 4,
  139963. };
  139964. static long _vq_lengthlist__16u2_p2_0[] = {
  139965. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139966. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  139967. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  139968. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  139969. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  139970. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  139971. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  139972. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  139973. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139974. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  139975. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  139976. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139977. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  139978. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  139979. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  139980. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  139981. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  139982. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  139983. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  139984. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  139985. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  139986. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  139987. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  139988. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  139989. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  139990. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  139991. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  139992. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  139993. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  139994. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  139995. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  139996. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  139997. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  139998. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  139999. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  140000. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  140001. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  140002. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  140003. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  140004. 13,
  140005. };
  140006. static float _vq_quantthresh__16u2_p2_0[] = {
  140007. -1.5, -0.5, 0.5, 1.5,
  140008. };
  140009. static long _vq_quantmap__16u2_p2_0[] = {
  140010. 3, 1, 0, 2, 4,
  140011. };
  140012. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  140013. _vq_quantthresh__16u2_p2_0,
  140014. _vq_quantmap__16u2_p2_0,
  140015. 5,
  140016. 5
  140017. };
  140018. static static_codebook _16u2_p2_0 = {
  140019. 4, 625,
  140020. _vq_lengthlist__16u2_p2_0,
  140021. 1, -533725184, 1611661312, 3, 0,
  140022. _vq_quantlist__16u2_p2_0,
  140023. NULL,
  140024. &_vq_auxt__16u2_p2_0,
  140025. NULL,
  140026. 0
  140027. };
  140028. static long _vq_quantlist__16u2_p3_0[] = {
  140029. 4,
  140030. 3,
  140031. 5,
  140032. 2,
  140033. 6,
  140034. 1,
  140035. 7,
  140036. 0,
  140037. 8,
  140038. };
  140039. static long _vq_lengthlist__16u2_p3_0[] = {
  140040. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  140041. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  140042. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  140043. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  140044. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  140045. 11,
  140046. };
  140047. static float _vq_quantthresh__16u2_p3_0[] = {
  140048. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140049. };
  140050. static long _vq_quantmap__16u2_p3_0[] = {
  140051. 7, 5, 3, 1, 0, 2, 4, 6,
  140052. 8,
  140053. };
  140054. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  140055. _vq_quantthresh__16u2_p3_0,
  140056. _vq_quantmap__16u2_p3_0,
  140057. 9,
  140058. 9
  140059. };
  140060. static static_codebook _16u2_p3_0 = {
  140061. 2, 81,
  140062. _vq_lengthlist__16u2_p3_0,
  140063. 1, -531628032, 1611661312, 4, 0,
  140064. _vq_quantlist__16u2_p3_0,
  140065. NULL,
  140066. &_vq_auxt__16u2_p3_0,
  140067. NULL,
  140068. 0
  140069. };
  140070. static long _vq_quantlist__16u2_p4_0[] = {
  140071. 8,
  140072. 7,
  140073. 9,
  140074. 6,
  140075. 10,
  140076. 5,
  140077. 11,
  140078. 4,
  140079. 12,
  140080. 3,
  140081. 13,
  140082. 2,
  140083. 14,
  140084. 1,
  140085. 15,
  140086. 0,
  140087. 16,
  140088. };
  140089. static long _vq_lengthlist__16u2_p4_0[] = {
  140090. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  140091. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140092. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140093. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140094. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140095. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  140096. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  140097. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  140098. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  140099. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  140100. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  140101. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  140102. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  140103. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  140104. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  140105. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  140106. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  140107. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  140108. 14,
  140109. };
  140110. static float _vq_quantthresh__16u2_p4_0[] = {
  140111. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140112. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140113. };
  140114. static long _vq_quantmap__16u2_p4_0[] = {
  140115. 15, 13, 11, 9, 7, 5, 3, 1,
  140116. 0, 2, 4, 6, 8, 10, 12, 14,
  140117. 16,
  140118. };
  140119. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  140120. _vq_quantthresh__16u2_p4_0,
  140121. _vq_quantmap__16u2_p4_0,
  140122. 17,
  140123. 17
  140124. };
  140125. static static_codebook _16u2_p4_0 = {
  140126. 2, 289,
  140127. _vq_lengthlist__16u2_p4_0,
  140128. 1, -529530880, 1611661312, 5, 0,
  140129. _vq_quantlist__16u2_p4_0,
  140130. NULL,
  140131. &_vq_auxt__16u2_p4_0,
  140132. NULL,
  140133. 0
  140134. };
  140135. static long _vq_quantlist__16u2_p5_0[] = {
  140136. 1,
  140137. 0,
  140138. 2,
  140139. };
  140140. static long _vq_lengthlist__16u2_p5_0[] = {
  140141. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  140142. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  140143. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  140144. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  140145. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  140146. 10,
  140147. };
  140148. static float _vq_quantthresh__16u2_p5_0[] = {
  140149. -5.5, 5.5,
  140150. };
  140151. static long _vq_quantmap__16u2_p5_0[] = {
  140152. 1, 0, 2,
  140153. };
  140154. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  140155. _vq_quantthresh__16u2_p5_0,
  140156. _vq_quantmap__16u2_p5_0,
  140157. 3,
  140158. 3
  140159. };
  140160. static static_codebook _16u2_p5_0 = {
  140161. 4, 81,
  140162. _vq_lengthlist__16u2_p5_0,
  140163. 1, -529137664, 1618345984, 2, 0,
  140164. _vq_quantlist__16u2_p5_0,
  140165. NULL,
  140166. &_vq_auxt__16u2_p5_0,
  140167. NULL,
  140168. 0
  140169. };
  140170. static long _vq_quantlist__16u2_p5_1[] = {
  140171. 5,
  140172. 4,
  140173. 6,
  140174. 3,
  140175. 7,
  140176. 2,
  140177. 8,
  140178. 1,
  140179. 9,
  140180. 0,
  140181. 10,
  140182. };
  140183. static long _vq_lengthlist__16u2_p5_1[] = {
  140184. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  140185. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  140186. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140187. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140188. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140189. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140190. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140191. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140192. };
  140193. static float _vq_quantthresh__16u2_p5_1[] = {
  140194. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140195. 3.5, 4.5,
  140196. };
  140197. static long _vq_quantmap__16u2_p5_1[] = {
  140198. 9, 7, 5, 3, 1, 0, 2, 4,
  140199. 6, 8, 10,
  140200. };
  140201. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  140202. _vq_quantthresh__16u2_p5_1,
  140203. _vq_quantmap__16u2_p5_1,
  140204. 11,
  140205. 11
  140206. };
  140207. static static_codebook _16u2_p5_1 = {
  140208. 2, 121,
  140209. _vq_lengthlist__16u2_p5_1,
  140210. 1, -531365888, 1611661312, 4, 0,
  140211. _vq_quantlist__16u2_p5_1,
  140212. NULL,
  140213. &_vq_auxt__16u2_p5_1,
  140214. NULL,
  140215. 0
  140216. };
  140217. static long _vq_quantlist__16u2_p6_0[] = {
  140218. 6,
  140219. 5,
  140220. 7,
  140221. 4,
  140222. 8,
  140223. 3,
  140224. 9,
  140225. 2,
  140226. 10,
  140227. 1,
  140228. 11,
  140229. 0,
  140230. 12,
  140231. };
  140232. static long _vq_lengthlist__16u2_p6_0[] = {
  140233. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  140234. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  140235. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  140236. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  140237. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  140238. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  140239. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  140240. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  140241. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  140242. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  140243. 12,13,13,14,14,14,14,15,15,
  140244. };
  140245. static float _vq_quantthresh__16u2_p6_0[] = {
  140246. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140247. 12.5, 17.5, 22.5, 27.5,
  140248. };
  140249. static long _vq_quantmap__16u2_p6_0[] = {
  140250. 11, 9, 7, 5, 3, 1, 0, 2,
  140251. 4, 6, 8, 10, 12,
  140252. };
  140253. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  140254. _vq_quantthresh__16u2_p6_0,
  140255. _vq_quantmap__16u2_p6_0,
  140256. 13,
  140257. 13
  140258. };
  140259. static static_codebook _16u2_p6_0 = {
  140260. 2, 169,
  140261. _vq_lengthlist__16u2_p6_0,
  140262. 1, -526516224, 1616117760, 4, 0,
  140263. _vq_quantlist__16u2_p6_0,
  140264. NULL,
  140265. &_vq_auxt__16u2_p6_0,
  140266. NULL,
  140267. 0
  140268. };
  140269. static long _vq_quantlist__16u2_p6_1[] = {
  140270. 2,
  140271. 1,
  140272. 3,
  140273. 0,
  140274. 4,
  140275. };
  140276. static long _vq_lengthlist__16u2_p6_1[] = {
  140277. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  140278. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  140279. };
  140280. static float _vq_quantthresh__16u2_p6_1[] = {
  140281. -1.5, -0.5, 0.5, 1.5,
  140282. };
  140283. static long _vq_quantmap__16u2_p6_1[] = {
  140284. 3, 1, 0, 2, 4,
  140285. };
  140286. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  140287. _vq_quantthresh__16u2_p6_1,
  140288. _vq_quantmap__16u2_p6_1,
  140289. 5,
  140290. 5
  140291. };
  140292. static static_codebook _16u2_p6_1 = {
  140293. 2, 25,
  140294. _vq_lengthlist__16u2_p6_1,
  140295. 1, -533725184, 1611661312, 3, 0,
  140296. _vq_quantlist__16u2_p6_1,
  140297. NULL,
  140298. &_vq_auxt__16u2_p6_1,
  140299. NULL,
  140300. 0
  140301. };
  140302. static long _vq_quantlist__16u2_p7_0[] = {
  140303. 6,
  140304. 5,
  140305. 7,
  140306. 4,
  140307. 8,
  140308. 3,
  140309. 9,
  140310. 2,
  140311. 10,
  140312. 1,
  140313. 11,
  140314. 0,
  140315. 12,
  140316. };
  140317. static long _vq_lengthlist__16u2_p7_0[] = {
  140318. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  140319. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  140320. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  140321. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  140322. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  140323. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  140324. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  140325. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  140326. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  140327. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  140328. 12,13,13,13,14,14,14,15,14,
  140329. };
  140330. static float _vq_quantthresh__16u2_p7_0[] = {
  140331. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  140332. 27.5, 38.5, 49.5, 60.5,
  140333. };
  140334. static long _vq_quantmap__16u2_p7_0[] = {
  140335. 11, 9, 7, 5, 3, 1, 0, 2,
  140336. 4, 6, 8, 10, 12,
  140337. };
  140338. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  140339. _vq_quantthresh__16u2_p7_0,
  140340. _vq_quantmap__16u2_p7_0,
  140341. 13,
  140342. 13
  140343. };
  140344. static static_codebook _16u2_p7_0 = {
  140345. 2, 169,
  140346. _vq_lengthlist__16u2_p7_0,
  140347. 1, -523206656, 1618345984, 4, 0,
  140348. _vq_quantlist__16u2_p7_0,
  140349. NULL,
  140350. &_vq_auxt__16u2_p7_0,
  140351. NULL,
  140352. 0
  140353. };
  140354. static long _vq_quantlist__16u2_p7_1[] = {
  140355. 5,
  140356. 4,
  140357. 6,
  140358. 3,
  140359. 7,
  140360. 2,
  140361. 8,
  140362. 1,
  140363. 9,
  140364. 0,
  140365. 10,
  140366. };
  140367. static long _vq_lengthlist__16u2_p7_1[] = {
  140368. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  140369. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  140370. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  140371. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  140372. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  140373. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  140374. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  140375. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140376. };
  140377. static float _vq_quantthresh__16u2_p7_1[] = {
  140378. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140379. 3.5, 4.5,
  140380. };
  140381. static long _vq_quantmap__16u2_p7_1[] = {
  140382. 9, 7, 5, 3, 1, 0, 2, 4,
  140383. 6, 8, 10,
  140384. };
  140385. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  140386. _vq_quantthresh__16u2_p7_1,
  140387. _vq_quantmap__16u2_p7_1,
  140388. 11,
  140389. 11
  140390. };
  140391. static static_codebook _16u2_p7_1 = {
  140392. 2, 121,
  140393. _vq_lengthlist__16u2_p7_1,
  140394. 1, -531365888, 1611661312, 4, 0,
  140395. _vq_quantlist__16u2_p7_1,
  140396. NULL,
  140397. &_vq_auxt__16u2_p7_1,
  140398. NULL,
  140399. 0
  140400. };
  140401. static long _vq_quantlist__16u2_p8_0[] = {
  140402. 7,
  140403. 6,
  140404. 8,
  140405. 5,
  140406. 9,
  140407. 4,
  140408. 10,
  140409. 3,
  140410. 11,
  140411. 2,
  140412. 12,
  140413. 1,
  140414. 13,
  140415. 0,
  140416. 14,
  140417. };
  140418. static long _vq_lengthlist__16u2_p8_0[] = {
  140419. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  140420. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  140421. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  140422. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  140423. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  140424. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  140425. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  140426. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  140427. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  140428. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  140429. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  140430. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  140431. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  140432. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  140433. 14,
  140434. };
  140435. static float _vq_quantthresh__16u2_p8_0[] = {
  140436. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140437. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140438. };
  140439. static long _vq_quantmap__16u2_p8_0[] = {
  140440. 13, 11, 9, 7, 5, 3, 1, 0,
  140441. 2, 4, 6, 8, 10, 12, 14,
  140442. };
  140443. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  140444. _vq_quantthresh__16u2_p8_0,
  140445. _vq_quantmap__16u2_p8_0,
  140446. 15,
  140447. 15
  140448. };
  140449. static static_codebook _16u2_p8_0 = {
  140450. 2, 225,
  140451. _vq_lengthlist__16u2_p8_0,
  140452. 1, -520986624, 1620377600, 4, 0,
  140453. _vq_quantlist__16u2_p8_0,
  140454. NULL,
  140455. &_vq_auxt__16u2_p8_0,
  140456. NULL,
  140457. 0
  140458. };
  140459. static long _vq_quantlist__16u2_p8_1[] = {
  140460. 10,
  140461. 9,
  140462. 11,
  140463. 8,
  140464. 12,
  140465. 7,
  140466. 13,
  140467. 6,
  140468. 14,
  140469. 5,
  140470. 15,
  140471. 4,
  140472. 16,
  140473. 3,
  140474. 17,
  140475. 2,
  140476. 18,
  140477. 1,
  140478. 19,
  140479. 0,
  140480. 20,
  140481. };
  140482. static long _vq_lengthlist__16u2_p8_1[] = {
  140483. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  140484. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  140485. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  140486. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  140487. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  140488. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  140489. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  140490. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  140491. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  140492. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  140493. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  140494. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  140495. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  140496. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  140497. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  140498. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  140499. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  140500. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  140501. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  140502. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  140503. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  140504. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  140505. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  140506. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  140507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140508. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  140509. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  140510. 11,11,10,11,11,11,10,11,11,
  140511. };
  140512. static float _vq_quantthresh__16u2_p8_1[] = {
  140513. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140514. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140515. 6.5, 7.5, 8.5, 9.5,
  140516. };
  140517. static long _vq_quantmap__16u2_p8_1[] = {
  140518. 19, 17, 15, 13, 11, 9, 7, 5,
  140519. 3, 1, 0, 2, 4, 6, 8, 10,
  140520. 12, 14, 16, 18, 20,
  140521. };
  140522. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  140523. _vq_quantthresh__16u2_p8_1,
  140524. _vq_quantmap__16u2_p8_1,
  140525. 21,
  140526. 21
  140527. };
  140528. static static_codebook _16u2_p8_1 = {
  140529. 2, 441,
  140530. _vq_lengthlist__16u2_p8_1,
  140531. 1, -529268736, 1611661312, 5, 0,
  140532. _vq_quantlist__16u2_p8_1,
  140533. NULL,
  140534. &_vq_auxt__16u2_p8_1,
  140535. NULL,
  140536. 0
  140537. };
  140538. static long _vq_quantlist__16u2_p9_0[] = {
  140539. 5586,
  140540. 4655,
  140541. 6517,
  140542. 3724,
  140543. 7448,
  140544. 2793,
  140545. 8379,
  140546. 1862,
  140547. 9310,
  140548. 931,
  140549. 10241,
  140550. 0,
  140551. 11172,
  140552. 5521,
  140553. 5651,
  140554. };
  140555. static long _vq_lengthlist__16u2_p9_0[] = {
  140556. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  140557. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140558. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140559. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140560. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140561. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140562. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140563. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140565. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140566. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140568. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  140569. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  140570. 5,
  140571. };
  140572. static float _vq_quantthresh__16u2_p9_0[] = {
  140573. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  140574. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  140575. };
  140576. static long _vq_quantmap__16u2_p9_0[] = {
  140577. 11, 9, 7, 5, 3, 1, 13, 0,
  140578. 14, 2, 4, 6, 8, 10, 12,
  140579. };
  140580. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  140581. _vq_quantthresh__16u2_p9_0,
  140582. _vq_quantmap__16u2_p9_0,
  140583. 15,
  140584. 15
  140585. };
  140586. static static_codebook _16u2_p9_0 = {
  140587. 2, 225,
  140588. _vq_lengthlist__16u2_p9_0,
  140589. 1, -510275072, 1611661312, 14, 0,
  140590. _vq_quantlist__16u2_p9_0,
  140591. NULL,
  140592. &_vq_auxt__16u2_p9_0,
  140593. NULL,
  140594. 0
  140595. };
  140596. static long _vq_quantlist__16u2_p9_1[] = {
  140597. 392,
  140598. 343,
  140599. 441,
  140600. 294,
  140601. 490,
  140602. 245,
  140603. 539,
  140604. 196,
  140605. 588,
  140606. 147,
  140607. 637,
  140608. 98,
  140609. 686,
  140610. 49,
  140611. 735,
  140612. 0,
  140613. 784,
  140614. 388,
  140615. 396,
  140616. };
  140617. static long _vq_lengthlist__16u2_p9_1[] = {
  140618. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  140619. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  140620. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  140621. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  140622. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  140623. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  140624. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140625. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  140626. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  140627. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140628. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140629. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140630. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140631. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140632. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  140633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140638. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  140639. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  140640. 11,11,11,11,11,11,11, 5, 4,
  140641. };
  140642. static float _vq_quantthresh__16u2_p9_1[] = {
  140643. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  140644. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  140645. 318.5, 367.5,
  140646. };
  140647. static long _vq_quantmap__16u2_p9_1[] = {
  140648. 15, 13, 11, 9, 7, 5, 3, 1,
  140649. 17, 0, 18, 2, 4, 6, 8, 10,
  140650. 12, 14, 16,
  140651. };
  140652. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  140653. _vq_quantthresh__16u2_p9_1,
  140654. _vq_quantmap__16u2_p9_1,
  140655. 19,
  140656. 19
  140657. };
  140658. static static_codebook _16u2_p9_1 = {
  140659. 2, 361,
  140660. _vq_lengthlist__16u2_p9_1,
  140661. 1, -518488064, 1611661312, 10, 0,
  140662. _vq_quantlist__16u2_p9_1,
  140663. NULL,
  140664. &_vq_auxt__16u2_p9_1,
  140665. NULL,
  140666. 0
  140667. };
  140668. static long _vq_quantlist__16u2_p9_2[] = {
  140669. 24,
  140670. 23,
  140671. 25,
  140672. 22,
  140673. 26,
  140674. 21,
  140675. 27,
  140676. 20,
  140677. 28,
  140678. 19,
  140679. 29,
  140680. 18,
  140681. 30,
  140682. 17,
  140683. 31,
  140684. 16,
  140685. 32,
  140686. 15,
  140687. 33,
  140688. 14,
  140689. 34,
  140690. 13,
  140691. 35,
  140692. 12,
  140693. 36,
  140694. 11,
  140695. 37,
  140696. 10,
  140697. 38,
  140698. 9,
  140699. 39,
  140700. 8,
  140701. 40,
  140702. 7,
  140703. 41,
  140704. 6,
  140705. 42,
  140706. 5,
  140707. 43,
  140708. 4,
  140709. 44,
  140710. 3,
  140711. 45,
  140712. 2,
  140713. 46,
  140714. 1,
  140715. 47,
  140716. 0,
  140717. 48,
  140718. };
  140719. static long _vq_lengthlist__16u2_p9_2[] = {
  140720. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  140721. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  140722. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  140723. 11,
  140724. };
  140725. static float _vq_quantthresh__16u2_p9_2[] = {
  140726. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  140727. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  140728. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140729. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140730. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  140731. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  140732. };
  140733. static long _vq_quantmap__16u2_p9_2[] = {
  140734. 47, 45, 43, 41, 39, 37, 35, 33,
  140735. 31, 29, 27, 25, 23, 21, 19, 17,
  140736. 15, 13, 11, 9, 7, 5, 3, 1,
  140737. 0, 2, 4, 6, 8, 10, 12, 14,
  140738. 16, 18, 20, 22, 24, 26, 28, 30,
  140739. 32, 34, 36, 38, 40, 42, 44, 46,
  140740. 48,
  140741. };
  140742. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  140743. _vq_quantthresh__16u2_p9_2,
  140744. _vq_quantmap__16u2_p9_2,
  140745. 49,
  140746. 49
  140747. };
  140748. static static_codebook _16u2_p9_2 = {
  140749. 1, 49,
  140750. _vq_lengthlist__16u2_p9_2,
  140751. 1, -526909440, 1611661312, 6, 0,
  140752. _vq_quantlist__16u2_p9_2,
  140753. NULL,
  140754. &_vq_auxt__16u2_p9_2,
  140755. NULL,
  140756. 0
  140757. };
  140758. static long _vq_quantlist__8u0__p1_0[] = {
  140759. 1,
  140760. 0,
  140761. 2,
  140762. };
  140763. static long _vq_lengthlist__8u0__p1_0[] = {
  140764. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  140765. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  140766. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  140767. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  140768. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  140769. 11,
  140770. };
  140771. static float _vq_quantthresh__8u0__p1_0[] = {
  140772. -0.5, 0.5,
  140773. };
  140774. static long _vq_quantmap__8u0__p1_0[] = {
  140775. 1, 0, 2,
  140776. };
  140777. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  140778. _vq_quantthresh__8u0__p1_0,
  140779. _vq_quantmap__8u0__p1_0,
  140780. 3,
  140781. 3
  140782. };
  140783. static static_codebook _8u0__p1_0 = {
  140784. 4, 81,
  140785. _vq_lengthlist__8u0__p1_0,
  140786. 1, -535822336, 1611661312, 2, 0,
  140787. _vq_quantlist__8u0__p1_0,
  140788. NULL,
  140789. &_vq_auxt__8u0__p1_0,
  140790. NULL,
  140791. 0
  140792. };
  140793. static long _vq_quantlist__8u0__p2_0[] = {
  140794. 1,
  140795. 0,
  140796. 2,
  140797. };
  140798. static long _vq_lengthlist__8u0__p2_0[] = {
  140799. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  140800. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  140801. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  140802. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  140803. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  140804. 8,
  140805. };
  140806. static float _vq_quantthresh__8u0__p2_0[] = {
  140807. -0.5, 0.5,
  140808. };
  140809. static long _vq_quantmap__8u0__p2_0[] = {
  140810. 1, 0, 2,
  140811. };
  140812. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  140813. _vq_quantthresh__8u0__p2_0,
  140814. _vq_quantmap__8u0__p2_0,
  140815. 3,
  140816. 3
  140817. };
  140818. static static_codebook _8u0__p2_0 = {
  140819. 4, 81,
  140820. _vq_lengthlist__8u0__p2_0,
  140821. 1, -535822336, 1611661312, 2, 0,
  140822. _vq_quantlist__8u0__p2_0,
  140823. NULL,
  140824. &_vq_auxt__8u0__p2_0,
  140825. NULL,
  140826. 0
  140827. };
  140828. static long _vq_quantlist__8u0__p3_0[] = {
  140829. 2,
  140830. 1,
  140831. 3,
  140832. 0,
  140833. 4,
  140834. };
  140835. static long _vq_lengthlist__8u0__p3_0[] = {
  140836. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  140837. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  140838. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  140839. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140840. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  140841. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  140842. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  140843. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  140844. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  140845. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  140846. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  140847. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  140848. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  140849. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  140850. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  140851. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  140852. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  140853. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  140854. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  140855. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  140856. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  140857. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  140858. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  140859. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  140860. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  140861. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  140862. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  140863. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  140864. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  140865. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  140866. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  140867. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  140868. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  140869. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  140870. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  140871. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  140872. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  140873. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  140874. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  140875. 16,
  140876. };
  140877. static float _vq_quantthresh__8u0__p3_0[] = {
  140878. -1.5, -0.5, 0.5, 1.5,
  140879. };
  140880. static long _vq_quantmap__8u0__p3_0[] = {
  140881. 3, 1, 0, 2, 4,
  140882. };
  140883. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  140884. _vq_quantthresh__8u0__p3_0,
  140885. _vq_quantmap__8u0__p3_0,
  140886. 5,
  140887. 5
  140888. };
  140889. static static_codebook _8u0__p3_0 = {
  140890. 4, 625,
  140891. _vq_lengthlist__8u0__p3_0,
  140892. 1, -533725184, 1611661312, 3, 0,
  140893. _vq_quantlist__8u0__p3_0,
  140894. NULL,
  140895. &_vq_auxt__8u0__p3_0,
  140896. NULL,
  140897. 0
  140898. };
  140899. static long _vq_quantlist__8u0__p4_0[] = {
  140900. 2,
  140901. 1,
  140902. 3,
  140903. 0,
  140904. 4,
  140905. };
  140906. static long _vq_lengthlist__8u0__p4_0[] = {
  140907. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  140908. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  140909. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  140910. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  140911. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  140912. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  140913. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  140914. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  140915. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  140916. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  140917. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  140918. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  140919. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  140920. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  140921. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  140922. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  140923. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  140924. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  140925. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  140926. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  140927. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  140928. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  140929. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  140930. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  140931. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  140932. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  140933. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  140934. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  140935. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  140936. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  140937. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  140938. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  140939. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  140940. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  140941. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  140942. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  140943. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  140944. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  140945. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  140946. 12,
  140947. };
  140948. static float _vq_quantthresh__8u0__p4_0[] = {
  140949. -1.5, -0.5, 0.5, 1.5,
  140950. };
  140951. static long _vq_quantmap__8u0__p4_0[] = {
  140952. 3, 1, 0, 2, 4,
  140953. };
  140954. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  140955. _vq_quantthresh__8u0__p4_0,
  140956. _vq_quantmap__8u0__p4_0,
  140957. 5,
  140958. 5
  140959. };
  140960. static static_codebook _8u0__p4_0 = {
  140961. 4, 625,
  140962. _vq_lengthlist__8u0__p4_0,
  140963. 1, -533725184, 1611661312, 3, 0,
  140964. _vq_quantlist__8u0__p4_0,
  140965. NULL,
  140966. &_vq_auxt__8u0__p4_0,
  140967. NULL,
  140968. 0
  140969. };
  140970. static long _vq_quantlist__8u0__p5_0[] = {
  140971. 4,
  140972. 3,
  140973. 5,
  140974. 2,
  140975. 6,
  140976. 1,
  140977. 7,
  140978. 0,
  140979. 8,
  140980. };
  140981. static long _vq_lengthlist__8u0__p5_0[] = {
  140982. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  140983. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  140984. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140985. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140986. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  140987. 12,
  140988. };
  140989. static float _vq_quantthresh__8u0__p5_0[] = {
  140990. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140991. };
  140992. static long _vq_quantmap__8u0__p5_0[] = {
  140993. 7, 5, 3, 1, 0, 2, 4, 6,
  140994. 8,
  140995. };
  140996. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  140997. _vq_quantthresh__8u0__p5_0,
  140998. _vq_quantmap__8u0__p5_0,
  140999. 9,
  141000. 9
  141001. };
  141002. static static_codebook _8u0__p5_0 = {
  141003. 2, 81,
  141004. _vq_lengthlist__8u0__p5_0,
  141005. 1, -531628032, 1611661312, 4, 0,
  141006. _vq_quantlist__8u0__p5_0,
  141007. NULL,
  141008. &_vq_auxt__8u0__p5_0,
  141009. NULL,
  141010. 0
  141011. };
  141012. static long _vq_quantlist__8u0__p6_0[] = {
  141013. 6,
  141014. 5,
  141015. 7,
  141016. 4,
  141017. 8,
  141018. 3,
  141019. 9,
  141020. 2,
  141021. 10,
  141022. 1,
  141023. 11,
  141024. 0,
  141025. 12,
  141026. };
  141027. static long _vq_lengthlist__8u0__p6_0[] = {
  141028. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  141029. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  141030. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  141031. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  141032. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  141033. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  141034. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  141035. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  141036. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  141037. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  141038. 16, 0,15, 0,17, 0, 0, 0, 0,
  141039. };
  141040. static float _vq_quantthresh__8u0__p6_0[] = {
  141041. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141042. 12.5, 17.5, 22.5, 27.5,
  141043. };
  141044. static long _vq_quantmap__8u0__p6_0[] = {
  141045. 11, 9, 7, 5, 3, 1, 0, 2,
  141046. 4, 6, 8, 10, 12,
  141047. };
  141048. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  141049. _vq_quantthresh__8u0__p6_0,
  141050. _vq_quantmap__8u0__p6_0,
  141051. 13,
  141052. 13
  141053. };
  141054. static static_codebook _8u0__p6_0 = {
  141055. 2, 169,
  141056. _vq_lengthlist__8u0__p6_0,
  141057. 1, -526516224, 1616117760, 4, 0,
  141058. _vq_quantlist__8u0__p6_0,
  141059. NULL,
  141060. &_vq_auxt__8u0__p6_0,
  141061. NULL,
  141062. 0
  141063. };
  141064. static long _vq_quantlist__8u0__p6_1[] = {
  141065. 2,
  141066. 1,
  141067. 3,
  141068. 0,
  141069. 4,
  141070. };
  141071. static long _vq_lengthlist__8u0__p6_1[] = {
  141072. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  141073. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  141074. };
  141075. static float _vq_quantthresh__8u0__p6_1[] = {
  141076. -1.5, -0.5, 0.5, 1.5,
  141077. };
  141078. static long _vq_quantmap__8u0__p6_1[] = {
  141079. 3, 1, 0, 2, 4,
  141080. };
  141081. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  141082. _vq_quantthresh__8u0__p6_1,
  141083. _vq_quantmap__8u0__p6_1,
  141084. 5,
  141085. 5
  141086. };
  141087. static static_codebook _8u0__p6_1 = {
  141088. 2, 25,
  141089. _vq_lengthlist__8u0__p6_1,
  141090. 1, -533725184, 1611661312, 3, 0,
  141091. _vq_quantlist__8u0__p6_1,
  141092. NULL,
  141093. &_vq_auxt__8u0__p6_1,
  141094. NULL,
  141095. 0
  141096. };
  141097. static long _vq_quantlist__8u0__p7_0[] = {
  141098. 1,
  141099. 0,
  141100. 2,
  141101. };
  141102. static long _vq_lengthlist__8u0__p7_0[] = {
  141103. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141104. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141105. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141106. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141107. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  141108. 7,
  141109. };
  141110. static float _vq_quantthresh__8u0__p7_0[] = {
  141111. -157.5, 157.5,
  141112. };
  141113. static long _vq_quantmap__8u0__p7_0[] = {
  141114. 1, 0, 2,
  141115. };
  141116. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  141117. _vq_quantthresh__8u0__p7_0,
  141118. _vq_quantmap__8u0__p7_0,
  141119. 3,
  141120. 3
  141121. };
  141122. static static_codebook _8u0__p7_0 = {
  141123. 4, 81,
  141124. _vq_lengthlist__8u0__p7_0,
  141125. 1, -518803456, 1628680192, 2, 0,
  141126. _vq_quantlist__8u0__p7_0,
  141127. NULL,
  141128. &_vq_auxt__8u0__p7_0,
  141129. NULL,
  141130. 0
  141131. };
  141132. static long _vq_quantlist__8u0__p7_1[] = {
  141133. 7,
  141134. 6,
  141135. 8,
  141136. 5,
  141137. 9,
  141138. 4,
  141139. 10,
  141140. 3,
  141141. 11,
  141142. 2,
  141143. 12,
  141144. 1,
  141145. 13,
  141146. 0,
  141147. 14,
  141148. };
  141149. static long _vq_lengthlist__8u0__p7_1[] = {
  141150. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  141151. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  141152. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  141153. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  141154. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  141155. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  141156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141162. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  141163. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141164. 10,
  141165. };
  141166. static float _vq_quantthresh__8u0__p7_1[] = {
  141167. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  141168. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  141169. };
  141170. static long _vq_quantmap__8u0__p7_1[] = {
  141171. 13, 11, 9, 7, 5, 3, 1, 0,
  141172. 2, 4, 6, 8, 10, 12, 14,
  141173. };
  141174. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  141175. _vq_quantthresh__8u0__p7_1,
  141176. _vq_quantmap__8u0__p7_1,
  141177. 15,
  141178. 15
  141179. };
  141180. static static_codebook _8u0__p7_1 = {
  141181. 2, 225,
  141182. _vq_lengthlist__8u0__p7_1,
  141183. 1, -520986624, 1620377600, 4, 0,
  141184. _vq_quantlist__8u0__p7_1,
  141185. NULL,
  141186. &_vq_auxt__8u0__p7_1,
  141187. NULL,
  141188. 0
  141189. };
  141190. static long _vq_quantlist__8u0__p7_2[] = {
  141191. 10,
  141192. 9,
  141193. 11,
  141194. 8,
  141195. 12,
  141196. 7,
  141197. 13,
  141198. 6,
  141199. 14,
  141200. 5,
  141201. 15,
  141202. 4,
  141203. 16,
  141204. 3,
  141205. 17,
  141206. 2,
  141207. 18,
  141208. 1,
  141209. 19,
  141210. 0,
  141211. 20,
  141212. };
  141213. static long _vq_lengthlist__8u0__p7_2[] = {
  141214. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  141215. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  141216. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  141217. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  141218. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  141219. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  141220. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  141221. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  141222. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  141223. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  141224. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  141225. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  141226. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  141227. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  141228. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  141229. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  141230. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  141231. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  141232. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  141233. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  141234. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  141235. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  141236. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  141237. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  141238. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  141239. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  141240. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  141241. 11,12,11,11,11,10,10,11,11,
  141242. };
  141243. static float _vq_quantthresh__8u0__p7_2[] = {
  141244. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141245. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141246. 6.5, 7.5, 8.5, 9.5,
  141247. };
  141248. static long _vq_quantmap__8u0__p7_2[] = {
  141249. 19, 17, 15, 13, 11, 9, 7, 5,
  141250. 3, 1, 0, 2, 4, 6, 8, 10,
  141251. 12, 14, 16, 18, 20,
  141252. };
  141253. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  141254. _vq_quantthresh__8u0__p7_2,
  141255. _vq_quantmap__8u0__p7_2,
  141256. 21,
  141257. 21
  141258. };
  141259. static static_codebook _8u0__p7_2 = {
  141260. 2, 441,
  141261. _vq_lengthlist__8u0__p7_2,
  141262. 1, -529268736, 1611661312, 5, 0,
  141263. _vq_quantlist__8u0__p7_2,
  141264. NULL,
  141265. &_vq_auxt__8u0__p7_2,
  141266. NULL,
  141267. 0
  141268. };
  141269. static long _huff_lengthlist__8u0__single[] = {
  141270. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  141271. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  141272. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  141273. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  141274. };
  141275. static static_codebook _huff_book__8u0__single = {
  141276. 2, 64,
  141277. _huff_lengthlist__8u0__single,
  141278. 0, 0, 0, 0, 0,
  141279. NULL,
  141280. NULL,
  141281. NULL,
  141282. NULL,
  141283. 0
  141284. };
  141285. static long _vq_quantlist__8u1__p1_0[] = {
  141286. 1,
  141287. 0,
  141288. 2,
  141289. };
  141290. static long _vq_lengthlist__8u1__p1_0[] = {
  141291. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  141292. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  141293. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  141294. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  141295. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  141296. 10,
  141297. };
  141298. static float _vq_quantthresh__8u1__p1_0[] = {
  141299. -0.5, 0.5,
  141300. };
  141301. static long _vq_quantmap__8u1__p1_0[] = {
  141302. 1, 0, 2,
  141303. };
  141304. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  141305. _vq_quantthresh__8u1__p1_0,
  141306. _vq_quantmap__8u1__p1_0,
  141307. 3,
  141308. 3
  141309. };
  141310. static static_codebook _8u1__p1_0 = {
  141311. 4, 81,
  141312. _vq_lengthlist__8u1__p1_0,
  141313. 1, -535822336, 1611661312, 2, 0,
  141314. _vq_quantlist__8u1__p1_0,
  141315. NULL,
  141316. &_vq_auxt__8u1__p1_0,
  141317. NULL,
  141318. 0
  141319. };
  141320. static long _vq_quantlist__8u1__p2_0[] = {
  141321. 1,
  141322. 0,
  141323. 2,
  141324. };
  141325. static long _vq_lengthlist__8u1__p2_0[] = {
  141326. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  141327. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  141328. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  141329. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  141330. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  141331. 7,
  141332. };
  141333. static float _vq_quantthresh__8u1__p2_0[] = {
  141334. -0.5, 0.5,
  141335. };
  141336. static long _vq_quantmap__8u1__p2_0[] = {
  141337. 1, 0, 2,
  141338. };
  141339. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  141340. _vq_quantthresh__8u1__p2_0,
  141341. _vq_quantmap__8u1__p2_0,
  141342. 3,
  141343. 3
  141344. };
  141345. static static_codebook _8u1__p2_0 = {
  141346. 4, 81,
  141347. _vq_lengthlist__8u1__p2_0,
  141348. 1, -535822336, 1611661312, 2, 0,
  141349. _vq_quantlist__8u1__p2_0,
  141350. NULL,
  141351. &_vq_auxt__8u1__p2_0,
  141352. NULL,
  141353. 0
  141354. };
  141355. static long _vq_quantlist__8u1__p3_0[] = {
  141356. 2,
  141357. 1,
  141358. 3,
  141359. 0,
  141360. 4,
  141361. };
  141362. static long _vq_lengthlist__8u1__p3_0[] = {
  141363. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  141364. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  141365. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  141366. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  141367. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  141368. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  141369. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  141370. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  141371. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  141372. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  141373. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  141374. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  141375. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  141376. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  141377. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  141378. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  141379. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  141380. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  141381. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  141382. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  141383. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  141384. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  141385. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  141386. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  141387. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  141388. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  141389. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  141390. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  141391. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  141392. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  141393. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  141394. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  141395. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  141396. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  141397. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  141398. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  141399. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  141400. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  141401. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  141402. 16,
  141403. };
  141404. static float _vq_quantthresh__8u1__p3_0[] = {
  141405. -1.5, -0.5, 0.5, 1.5,
  141406. };
  141407. static long _vq_quantmap__8u1__p3_0[] = {
  141408. 3, 1, 0, 2, 4,
  141409. };
  141410. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  141411. _vq_quantthresh__8u1__p3_0,
  141412. _vq_quantmap__8u1__p3_0,
  141413. 5,
  141414. 5
  141415. };
  141416. static static_codebook _8u1__p3_0 = {
  141417. 4, 625,
  141418. _vq_lengthlist__8u1__p3_0,
  141419. 1, -533725184, 1611661312, 3, 0,
  141420. _vq_quantlist__8u1__p3_0,
  141421. NULL,
  141422. &_vq_auxt__8u1__p3_0,
  141423. NULL,
  141424. 0
  141425. };
  141426. static long _vq_quantlist__8u1__p4_0[] = {
  141427. 2,
  141428. 1,
  141429. 3,
  141430. 0,
  141431. 4,
  141432. };
  141433. static long _vq_lengthlist__8u1__p4_0[] = {
  141434. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  141435. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  141436. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  141437. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  141438. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  141439. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  141440. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  141441. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  141442. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  141443. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  141444. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  141445. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  141446. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  141447. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  141448. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  141449. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  141450. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  141451. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  141452. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  141453. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  141454. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  141455. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  141456. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  141457. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  141458. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  141459. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  141460. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  141461. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  141462. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  141463. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  141464. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  141465. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  141466. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  141467. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  141468. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  141469. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  141470. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  141471. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  141472. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  141473. 10,
  141474. };
  141475. static float _vq_quantthresh__8u1__p4_0[] = {
  141476. -1.5, -0.5, 0.5, 1.5,
  141477. };
  141478. static long _vq_quantmap__8u1__p4_0[] = {
  141479. 3, 1, 0, 2, 4,
  141480. };
  141481. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  141482. _vq_quantthresh__8u1__p4_0,
  141483. _vq_quantmap__8u1__p4_0,
  141484. 5,
  141485. 5
  141486. };
  141487. static static_codebook _8u1__p4_0 = {
  141488. 4, 625,
  141489. _vq_lengthlist__8u1__p4_0,
  141490. 1, -533725184, 1611661312, 3, 0,
  141491. _vq_quantlist__8u1__p4_0,
  141492. NULL,
  141493. &_vq_auxt__8u1__p4_0,
  141494. NULL,
  141495. 0
  141496. };
  141497. static long _vq_quantlist__8u1__p5_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__p5_0[] = {
  141509. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  141510. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  141511. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  141512. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  141513. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  141514. 13,
  141515. };
  141516. static float _vq_quantthresh__8u1__p5_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__p5_0[] = {
  141520. 7, 5, 3, 1, 0, 2, 4, 6,
  141521. 8,
  141522. };
  141523. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  141524. _vq_quantthresh__8u1__p5_0,
  141525. _vq_quantmap__8u1__p5_0,
  141526. 9,
  141527. 9
  141528. };
  141529. static static_codebook _8u1__p5_0 = {
  141530. 2, 81,
  141531. _vq_lengthlist__8u1__p5_0,
  141532. 1, -531628032, 1611661312, 4, 0,
  141533. _vq_quantlist__8u1__p5_0,
  141534. NULL,
  141535. &_vq_auxt__8u1__p5_0,
  141536. NULL,
  141537. 0
  141538. };
  141539. static long _vq_quantlist__8u1__p6_0[] = {
  141540. 4,
  141541. 3,
  141542. 5,
  141543. 2,
  141544. 6,
  141545. 1,
  141546. 7,
  141547. 0,
  141548. 8,
  141549. };
  141550. static long _vq_lengthlist__8u1__p6_0[] = {
  141551. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  141552. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  141553. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  141554. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  141555. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141556. 10,
  141557. };
  141558. static float _vq_quantthresh__8u1__p6_0[] = {
  141559. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141560. };
  141561. static long _vq_quantmap__8u1__p6_0[] = {
  141562. 7, 5, 3, 1, 0, 2, 4, 6,
  141563. 8,
  141564. };
  141565. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  141566. _vq_quantthresh__8u1__p6_0,
  141567. _vq_quantmap__8u1__p6_0,
  141568. 9,
  141569. 9
  141570. };
  141571. static static_codebook _8u1__p6_0 = {
  141572. 2, 81,
  141573. _vq_lengthlist__8u1__p6_0,
  141574. 1, -531628032, 1611661312, 4, 0,
  141575. _vq_quantlist__8u1__p6_0,
  141576. NULL,
  141577. &_vq_auxt__8u1__p6_0,
  141578. NULL,
  141579. 0
  141580. };
  141581. static long _vq_quantlist__8u1__p7_0[] = {
  141582. 1,
  141583. 0,
  141584. 2,
  141585. };
  141586. static long _vq_lengthlist__8u1__p7_0[] = {
  141587. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  141588. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  141589. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  141590. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  141591. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  141592. 11,
  141593. };
  141594. static float _vq_quantthresh__8u1__p7_0[] = {
  141595. -5.5, 5.5,
  141596. };
  141597. static long _vq_quantmap__8u1__p7_0[] = {
  141598. 1, 0, 2,
  141599. };
  141600. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  141601. _vq_quantthresh__8u1__p7_0,
  141602. _vq_quantmap__8u1__p7_0,
  141603. 3,
  141604. 3
  141605. };
  141606. static static_codebook _8u1__p7_0 = {
  141607. 4, 81,
  141608. _vq_lengthlist__8u1__p7_0,
  141609. 1, -529137664, 1618345984, 2, 0,
  141610. _vq_quantlist__8u1__p7_0,
  141611. NULL,
  141612. &_vq_auxt__8u1__p7_0,
  141613. NULL,
  141614. 0
  141615. };
  141616. static long _vq_quantlist__8u1__p7_1[] = {
  141617. 5,
  141618. 4,
  141619. 6,
  141620. 3,
  141621. 7,
  141622. 2,
  141623. 8,
  141624. 1,
  141625. 9,
  141626. 0,
  141627. 10,
  141628. };
  141629. static long _vq_lengthlist__8u1__p7_1[] = {
  141630. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  141631. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  141632. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  141633. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141634. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  141635. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  141636. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  141637. 9, 9, 9, 9, 9,10,10,10,10,
  141638. };
  141639. static float _vq_quantthresh__8u1__p7_1[] = {
  141640. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141641. 3.5, 4.5,
  141642. };
  141643. static long _vq_quantmap__8u1__p7_1[] = {
  141644. 9, 7, 5, 3, 1, 0, 2, 4,
  141645. 6, 8, 10,
  141646. };
  141647. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  141648. _vq_quantthresh__8u1__p7_1,
  141649. _vq_quantmap__8u1__p7_1,
  141650. 11,
  141651. 11
  141652. };
  141653. static static_codebook _8u1__p7_1 = {
  141654. 2, 121,
  141655. _vq_lengthlist__8u1__p7_1,
  141656. 1, -531365888, 1611661312, 4, 0,
  141657. _vq_quantlist__8u1__p7_1,
  141658. NULL,
  141659. &_vq_auxt__8u1__p7_1,
  141660. NULL,
  141661. 0
  141662. };
  141663. static long _vq_quantlist__8u1__p8_0[] = {
  141664. 5,
  141665. 4,
  141666. 6,
  141667. 3,
  141668. 7,
  141669. 2,
  141670. 8,
  141671. 1,
  141672. 9,
  141673. 0,
  141674. 10,
  141675. };
  141676. static long _vq_lengthlist__8u1__p8_0[] = {
  141677. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  141678. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  141679. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  141680. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  141681. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  141682. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  141683. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  141684. 12,13,13,14,14,15,15,15,15,
  141685. };
  141686. static float _vq_quantthresh__8u1__p8_0[] = {
  141687. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  141688. 38.5, 49.5,
  141689. };
  141690. static long _vq_quantmap__8u1__p8_0[] = {
  141691. 9, 7, 5, 3, 1, 0, 2, 4,
  141692. 6, 8, 10,
  141693. };
  141694. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  141695. _vq_quantthresh__8u1__p8_0,
  141696. _vq_quantmap__8u1__p8_0,
  141697. 11,
  141698. 11
  141699. };
  141700. static static_codebook _8u1__p8_0 = {
  141701. 2, 121,
  141702. _vq_lengthlist__8u1__p8_0,
  141703. 1, -524582912, 1618345984, 4, 0,
  141704. _vq_quantlist__8u1__p8_0,
  141705. NULL,
  141706. &_vq_auxt__8u1__p8_0,
  141707. NULL,
  141708. 0
  141709. };
  141710. static long _vq_quantlist__8u1__p8_1[] = {
  141711. 5,
  141712. 4,
  141713. 6,
  141714. 3,
  141715. 7,
  141716. 2,
  141717. 8,
  141718. 1,
  141719. 9,
  141720. 0,
  141721. 10,
  141722. };
  141723. static long _vq_lengthlist__8u1__p8_1[] = {
  141724. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  141725. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  141726. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  141727. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  141728. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141729. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  141730. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  141731. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141732. };
  141733. static float _vq_quantthresh__8u1__p8_1[] = {
  141734. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141735. 3.5, 4.5,
  141736. };
  141737. static long _vq_quantmap__8u1__p8_1[] = {
  141738. 9, 7, 5, 3, 1, 0, 2, 4,
  141739. 6, 8, 10,
  141740. };
  141741. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  141742. _vq_quantthresh__8u1__p8_1,
  141743. _vq_quantmap__8u1__p8_1,
  141744. 11,
  141745. 11
  141746. };
  141747. static static_codebook _8u1__p8_1 = {
  141748. 2, 121,
  141749. _vq_lengthlist__8u1__p8_1,
  141750. 1, -531365888, 1611661312, 4, 0,
  141751. _vq_quantlist__8u1__p8_1,
  141752. NULL,
  141753. &_vq_auxt__8u1__p8_1,
  141754. NULL,
  141755. 0
  141756. };
  141757. static long _vq_quantlist__8u1__p9_0[] = {
  141758. 7,
  141759. 6,
  141760. 8,
  141761. 5,
  141762. 9,
  141763. 4,
  141764. 10,
  141765. 3,
  141766. 11,
  141767. 2,
  141768. 12,
  141769. 1,
  141770. 13,
  141771. 0,
  141772. 14,
  141773. };
  141774. static long _vq_lengthlist__8u1__p9_0[] = {
  141775. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  141776. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  141777. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141778. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141787. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  141788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141789. 10,
  141790. };
  141791. static float _vq_quantthresh__8u1__p9_0[] = {
  141792. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  141793. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  141794. };
  141795. static long _vq_quantmap__8u1__p9_0[] = {
  141796. 13, 11, 9, 7, 5, 3, 1, 0,
  141797. 2, 4, 6, 8, 10, 12, 14,
  141798. };
  141799. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  141800. _vq_quantthresh__8u1__p9_0,
  141801. _vq_quantmap__8u1__p9_0,
  141802. 15,
  141803. 15
  141804. };
  141805. static static_codebook _8u1__p9_0 = {
  141806. 2, 225,
  141807. _vq_lengthlist__8u1__p9_0,
  141808. 1, -514071552, 1627381760, 4, 0,
  141809. _vq_quantlist__8u1__p9_0,
  141810. NULL,
  141811. &_vq_auxt__8u1__p9_0,
  141812. NULL,
  141813. 0
  141814. };
  141815. static long _vq_quantlist__8u1__p9_1[] = {
  141816. 7,
  141817. 6,
  141818. 8,
  141819. 5,
  141820. 9,
  141821. 4,
  141822. 10,
  141823. 3,
  141824. 11,
  141825. 2,
  141826. 12,
  141827. 1,
  141828. 13,
  141829. 0,
  141830. 14,
  141831. };
  141832. static long _vq_lengthlist__8u1__p9_1[] = {
  141833. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  141834. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  141835. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  141836. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  141837. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  141838. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  141839. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  141840. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  141841. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  141842. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  141843. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  141844. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  141845. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  141846. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  141847. 13,
  141848. };
  141849. static float _vq_quantthresh__8u1__p9_1[] = {
  141850. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141851. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141852. };
  141853. static long _vq_quantmap__8u1__p9_1[] = {
  141854. 13, 11, 9, 7, 5, 3, 1, 0,
  141855. 2, 4, 6, 8, 10, 12, 14,
  141856. };
  141857. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  141858. _vq_quantthresh__8u1__p9_1,
  141859. _vq_quantmap__8u1__p9_1,
  141860. 15,
  141861. 15
  141862. };
  141863. static static_codebook _8u1__p9_1 = {
  141864. 2, 225,
  141865. _vq_lengthlist__8u1__p9_1,
  141866. 1, -522338304, 1620115456, 4, 0,
  141867. _vq_quantlist__8u1__p9_1,
  141868. NULL,
  141869. &_vq_auxt__8u1__p9_1,
  141870. NULL,
  141871. 0
  141872. };
  141873. static long _vq_quantlist__8u1__p9_2[] = {
  141874. 8,
  141875. 7,
  141876. 9,
  141877. 6,
  141878. 10,
  141879. 5,
  141880. 11,
  141881. 4,
  141882. 12,
  141883. 3,
  141884. 13,
  141885. 2,
  141886. 14,
  141887. 1,
  141888. 15,
  141889. 0,
  141890. 16,
  141891. };
  141892. static long _vq_lengthlist__8u1__p9_2[] = {
  141893. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141894. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  141895. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141896. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  141897. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141898. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  141899. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141900. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  141901. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141902. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141903. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141904. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  141905. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  141906. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141907. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  141908. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  141909. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141910. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141911. 10,
  141912. };
  141913. static float _vq_quantthresh__8u1__p9_2[] = {
  141914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141916. };
  141917. static long _vq_quantmap__8u1__p9_2[] = {
  141918. 15, 13, 11, 9, 7, 5, 3, 1,
  141919. 0, 2, 4, 6, 8, 10, 12, 14,
  141920. 16,
  141921. };
  141922. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  141923. _vq_quantthresh__8u1__p9_2,
  141924. _vq_quantmap__8u1__p9_2,
  141925. 17,
  141926. 17
  141927. };
  141928. static static_codebook _8u1__p9_2 = {
  141929. 2, 289,
  141930. _vq_lengthlist__8u1__p9_2,
  141931. 1, -529530880, 1611661312, 5, 0,
  141932. _vq_quantlist__8u1__p9_2,
  141933. NULL,
  141934. &_vq_auxt__8u1__p9_2,
  141935. NULL,
  141936. 0
  141937. };
  141938. static long _huff_lengthlist__8u1__single[] = {
  141939. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  141940. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  141941. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  141942. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  141943. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  141944. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  141945. 13, 8, 8,15,
  141946. };
  141947. static static_codebook _huff_book__8u1__single = {
  141948. 2, 100,
  141949. _huff_lengthlist__8u1__single,
  141950. 0, 0, 0, 0, 0,
  141951. NULL,
  141952. NULL,
  141953. NULL,
  141954. NULL,
  141955. 0
  141956. };
  141957. static long _huff_lengthlist__44u0__long[] = {
  141958. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141959. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141960. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141961. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141962. };
  141963. static static_codebook _huff_book__44u0__long = {
  141964. 2, 64,
  141965. _huff_lengthlist__44u0__long,
  141966. 0, 0, 0, 0, 0,
  141967. NULL,
  141968. NULL,
  141969. NULL,
  141970. NULL,
  141971. 0
  141972. };
  141973. static long _vq_quantlist__44u0__p1_0[] = {
  141974. 1,
  141975. 0,
  141976. 2,
  141977. };
  141978. static long _vq_lengthlist__44u0__p1_0[] = {
  141979. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141980. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141981. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141982. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141983. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141984. 13,
  141985. };
  141986. static float _vq_quantthresh__44u0__p1_0[] = {
  141987. -0.5, 0.5,
  141988. };
  141989. static long _vq_quantmap__44u0__p1_0[] = {
  141990. 1, 0, 2,
  141991. };
  141992. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  141993. _vq_quantthresh__44u0__p1_0,
  141994. _vq_quantmap__44u0__p1_0,
  141995. 3,
  141996. 3
  141997. };
  141998. static static_codebook _44u0__p1_0 = {
  141999. 4, 81,
  142000. _vq_lengthlist__44u0__p1_0,
  142001. 1, -535822336, 1611661312, 2, 0,
  142002. _vq_quantlist__44u0__p1_0,
  142003. NULL,
  142004. &_vq_auxt__44u0__p1_0,
  142005. NULL,
  142006. 0
  142007. };
  142008. static long _vq_quantlist__44u0__p2_0[] = {
  142009. 1,
  142010. 0,
  142011. 2,
  142012. };
  142013. static long _vq_lengthlist__44u0__p2_0[] = {
  142014. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  142015. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  142016. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142017. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  142018. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142019. 9,
  142020. };
  142021. static float _vq_quantthresh__44u0__p2_0[] = {
  142022. -0.5, 0.5,
  142023. };
  142024. static long _vq_quantmap__44u0__p2_0[] = {
  142025. 1, 0, 2,
  142026. };
  142027. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  142028. _vq_quantthresh__44u0__p2_0,
  142029. _vq_quantmap__44u0__p2_0,
  142030. 3,
  142031. 3
  142032. };
  142033. static static_codebook _44u0__p2_0 = {
  142034. 4, 81,
  142035. _vq_lengthlist__44u0__p2_0,
  142036. 1, -535822336, 1611661312, 2, 0,
  142037. _vq_quantlist__44u0__p2_0,
  142038. NULL,
  142039. &_vq_auxt__44u0__p2_0,
  142040. NULL,
  142041. 0
  142042. };
  142043. static long _vq_quantlist__44u0__p3_0[] = {
  142044. 2,
  142045. 1,
  142046. 3,
  142047. 0,
  142048. 4,
  142049. };
  142050. static long _vq_lengthlist__44u0__p3_0[] = {
  142051. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142052. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142053. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142054. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142055. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142056. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142057. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142058. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142059. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142060. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142061. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142062. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142063. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142064. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142065. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142066. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142067. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142068. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142069. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142070. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142071. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142072. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142073. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142074. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142075. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142076. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142077. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142078. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142079. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142080. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142081. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142082. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142083. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142084. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142085. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142086. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142087. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142088. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142089. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142090. 19,
  142091. };
  142092. static float _vq_quantthresh__44u0__p3_0[] = {
  142093. -1.5, -0.5, 0.5, 1.5,
  142094. };
  142095. static long _vq_quantmap__44u0__p3_0[] = {
  142096. 3, 1, 0, 2, 4,
  142097. };
  142098. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  142099. _vq_quantthresh__44u0__p3_0,
  142100. _vq_quantmap__44u0__p3_0,
  142101. 5,
  142102. 5
  142103. };
  142104. static static_codebook _44u0__p3_0 = {
  142105. 4, 625,
  142106. _vq_lengthlist__44u0__p3_0,
  142107. 1, -533725184, 1611661312, 3, 0,
  142108. _vq_quantlist__44u0__p3_0,
  142109. NULL,
  142110. &_vq_auxt__44u0__p3_0,
  142111. NULL,
  142112. 0
  142113. };
  142114. static long _vq_quantlist__44u0__p4_0[] = {
  142115. 2,
  142116. 1,
  142117. 3,
  142118. 0,
  142119. 4,
  142120. };
  142121. static long _vq_lengthlist__44u0__p4_0[] = {
  142122. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142123. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142124. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142125. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142126. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142127. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142128. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142129. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142130. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142131. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142132. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142133. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142134. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142135. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142136. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142137. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142138. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142139. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142140. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142141. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142142. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142143. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142144. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142145. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142146. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142147. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142148. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142149. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142150. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142151. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142152. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142153. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142154. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142155. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142156. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142157. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142158. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142159. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142160. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142161. 12,
  142162. };
  142163. static float _vq_quantthresh__44u0__p4_0[] = {
  142164. -1.5, -0.5, 0.5, 1.5,
  142165. };
  142166. static long _vq_quantmap__44u0__p4_0[] = {
  142167. 3, 1, 0, 2, 4,
  142168. };
  142169. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  142170. _vq_quantthresh__44u0__p4_0,
  142171. _vq_quantmap__44u0__p4_0,
  142172. 5,
  142173. 5
  142174. };
  142175. static static_codebook _44u0__p4_0 = {
  142176. 4, 625,
  142177. _vq_lengthlist__44u0__p4_0,
  142178. 1, -533725184, 1611661312, 3, 0,
  142179. _vq_quantlist__44u0__p4_0,
  142180. NULL,
  142181. &_vq_auxt__44u0__p4_0,
  142182. NULL,
  142183. 0
  142184. };
  142185. static long _vq_quantlist__44u0__p5_0[] = {
  142186. 4,
  142187. 3,
  142188. 5,
  142189. 2,
  142190. 6,
  142191. 1,
  142192. 7,
  142193. 0,
  142194. 8,
  142195. };
  142196. static long _vq_lengthlist__44u0__p5_0[] = {
  142197. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142198. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142199. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142200. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142201. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142202. 12,
  142203. };
  142204. static float _vq_quantthresh__44u0__p5_0[] = {
  142205. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142206. };
  142207. static long _vq_quantmap__44u0__p5_0[] = {
  142208. 7, 5, 3, 1, 0, 2, 4, 6,
  142209. 8,
  142210. };
  142211. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  142212. _vq_quantthresh__44u0__p5_0,
  142213. _vq_quantmap__44u0__p5_0,
  142214. 9,
  142215. 9
  142216. };
  142217. static static_codebook _44u0__p5_0 = {
  142218. 2, 81,
  142219. _vq_lengthlist__44u0__p5_0,
  142220. 1, -531628032, 1611661312, 4, 0,
  142221. _vq_quantlist__44u0__p5_0,
  142222. NULL,
  142223. &_vq_auxt__44u0__p5_0,
  142224. NULL,
  142225. 0
  142226. };
  142227. static long _vq_quantlist__44u0__p6_0[] = {
  142228. 6,
  142229. 5,
  142230. 7,
  142231. 4,
  142232. 8,
  142233. 3,
  142234. 9,
  142235. 2,
  142236. 10,
  142237. 1,
  142238. 11,
  142239. 0,
  142240. 12,
  142241. };
  142242. static long _vq_lengthlist__44u0__p6_0[] = {
  142243. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142244. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142245. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142246. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142247. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142248. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142249. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142250. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142251. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142252. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142253. 15,17,16,17,18,17,17,18, 0,
  142254. };
  142255. static float _vq_quantthresh__44u0__p6_0[] = {
  142256. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142257. 12.5, 17.5, 22.5, 27.5,
  142258. };
  142259. static long _vq_quantmap__44u0__p6_0[] = {
  142260. 11, 9, 7, 5, 3, 1, 0, 2,
  142261. 4, 6, 8, 10, 12,
  142262. };
  142263. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  142264. _vq_quantthresh__44u0__p6_0,
  142265. _vq_quantmap__44u0__p6_0,
  142266. 13,
  142267. 13
  142268. };
  142269. static static_codebook _44u0__p6_0 = {
  142270. 2, 169,
  142271. _vq_lengthlist__44u0__p6_0,
  142272. 1, -526516224, 1616117760, 4, 0,
  142273. _vq_quantlist__44u0__p6_0,
  142274. NULL,
  142275. &_vq_auxt__44u0__p6_0,
  142276. NULL,
  142277. 0
  142278. };
  142279. static long _vq_quantlist__44u0__p6_1[] = {
  142280. 2,
  142281. 1,
  142282. 3,
  142283. 0,
  142284. 4,
  142285. };
  142286. static long _vq_lengthlist__44u0__p6_1[] = {
  142287. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142288. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142289. };
  142290. static float _vq_quantthresh__44u0__p6_1[] = {
  142291. -1.5, -0.5, 0.5, 1.5,
  142292. };
  142293. static long _vq_quantmap__44u0__p6_1[] = {
  142294. 3, 1, 0, 2, 4,
  142295. };
  142296. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  142297. _vq_quantthresh__44u0__p6_1,
  142298. _vq_quantmap__44u0__p6_1,
  142299. 5,
  142300. 5
  142301. };
  142302. static static_codebook _44u0__p6_1 = {
  142303. 2, 25,
  142304. _vq_lengthlist__44u0__p6_1,
  142305. 1, -533725184, 1611661312, 3, 0,
  142306. _vq_quantlist__44u0__p6_1,
  142307. NULL,
  142308. &_vq_auxt__44u0__p6_1,
  142309. NULL,
  142310. 0
  142311. };
  142312. static long _vq_quantlist__44u0__p7_0[] = {
  142313. 2,
  142314. 1,
  142315. 3,
  142316. 0,
  142317. 4,
  142318. };
  142319. static long _vq_lengthlist__44u0__p7_0[] = {
  142320. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  142321. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142322. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142323. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142324. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142325. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142326. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142327. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  142328. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142329. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142330. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142331. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142332. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142333. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142334. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142335. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142336. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142337. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142338. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142339. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142340. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142341. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142342. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142343. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142350. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  142351. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142352. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142355. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142357. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142359. 10,
  142360. };
  142361. static float _vq_quantthresh__44u0__p7_0[] = {
  142362. -253.5, -84.5, 84.5, 253.5,
  142363. };
  142364. static long _vq_quantmap__44u0__p7_0[] = {
  142365. 3, 1, 0, 2, 4,
  142366. };
  142367. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  142368. _vq_quantthresh__44u0__p7_0,
  142369. _vq_quantmap__44u0__p7_0,
  142370. 5,
  142371. 5
  142372. };
  142373. static static_codebook _44u0__p7_0 = {
  142374. 4, 625,
  142375. _vq_lengthlist__44u0__p7_0,
  142376. 1, -518709248, 1626677248, 3, 0,
  142377. _vq_quantlist__44u0__p7_0,
  142378. NULL,
  142379. &_vq_auxt__44u0__p7_0,
  142380. NULL,
  142381. 0
  142382. };
  142383. static long _vq_quantlist__44u0__p7_1[] = {
  142384. 6,
  142385. 5,
  142386. 7,
  142387. 4,
  142388. 8,
  142389. 3,
  142390. 9,
  142391. 2,
  142392. 10,
  142393. 1,
  142394. 11,
  142395. 0,
  142396. 12,
  142397. };
  142398. static long _vq_lengthlist__44u0__p7_1[] = {
  142399. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142400. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142401. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142402. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142403. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142404. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142405. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142406. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142407. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142408. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142409. 15,15,15,15,15,15,15,15,15,
  142410. };
  142411. static float _vq_quantthresh__44u0__p7_1[] = {
  142412. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142413. 32.5, 45.5, 58.5, 71.5,
  142414. };
  142415. static long _vq_quantmap__44u0__p7_1[] = {
  142416. 11, 9, 7, 5, 3, 1, 0, 2,
  142417. 4, 6, 8, 10, 12,
  142418. };
  142419. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  142420. _vq_quantthresh__44u0__p7_1,
  142421. _vq_quantmap__44u0__p7_1,
  142422. 13,
  142423. 13
  142424. };
  142425. static static_codebook _44u0__p7_1 = {
  142426. 2, 169,
  142427. _vq_lengthlist__44u0__p7_1,
  142428. 1, -523010048, 1618608128, 4, 0,
  142429. _vq_quantlist__44u0__p7_1,
  142430. NULL,
  142431. &_vq_auxt__44u0__p7_1,
  142432. NULL,
  142433. 0
  142434. };
  142435. static long _vq_quantlist__44u0__p7_2[] = {
  142436. 6,
  142437. 5,
  142438. 7,
  142439. 4,
  142440. 8,
  142441. 3,
  142442. 9,
  142443. 2,
  142444. 10,
  142445. 1,
  142446. 11,
  142447. 0,
  142448. 12,
  142449. };
  142450. static long _vq_lengthlist__44u0__p7_2[] = {
  142451. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142452. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142453. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142454. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142455. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142456. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142457. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142458. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142459. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142460. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142461. 9, 9, 9,10, 9, 9,10,10, 9,
  142462. };
  142463. static float _vq_quantthresh__44u0__p7_2[] = {
  142464. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142465. 2.5, 3.5, 4.5, 5.5,
  142466. };
  142467. static long _vq_quantmap__44u0__p7_2[] = {
  142468. 11, 9, 7, 5, 3, 1, 0, 2,
  142469. 4, 6, 8, 10, 12,
  142470. };
  142471. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  142472. _vq_quantthresh__44u0__p7_2,
  142473. _vq_quantmap__44u0__p7_2,
  142474. 13,
  142475. 13
  142476. };
  142477. static static_codebook _44u0__p7_2 = {
  142478. 2, 169,
  142479. _vq_lengthlist__44u0__p7_2,
  142480. 1, -531103744, 1611661312, 4, 0,
  142481. _vq_quantlist__44u0__p7_2,
  142482. NULL,
  142483. &_vq_auxt__44u0__p7_2,
  142484. NULL,
  142485. 0
  142486. };
  142487. static long _huff_lengthlist__44u0__short[] = {
  142488. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142489. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142490. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142491. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142492. };
  142493. static static_codebook _huff_book__44u0__short = {
  142494. 2, 64,
  142495. _huff_lengthlist__44u0__short,
  142496. 0, 0, 0, 0, 0,
  142497. NULL,
  142498. NULL,
  142499. NULL,
  142500. NULL,
  142501. 0
  142502. };
  142503. static long _huff_lengthlist__44u1__long[] = {
  142504. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  142505. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  142506. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  142507. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  142508. };
  142509. static static_codebook _huff_book__44u1__long = {
  142510. 2, 64,
  142511. _huff_lengthlist__44u1__long,
  142512. 0, 0, 0, 0, 0,
  142513. NULL,
  142514. NULL,
  142515. NULL,
  142516. NULL,
  142517. 0
  142518. };
  142519. static long _vq_quantlist__44u1__p1_0[] = {
  142520. 1,
  142521. 0,
  142522. 2,
  142523. };
  142524. static long _vq_lengthlist__44u1__p1_0[] = {
  142525. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142526. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142527. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  142528. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  142529. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  142530. 13,
  142531. };
  142532. static float _vq_quantthresh__44u1__p1_0[] = {
  142533. -0.5, 0.5,
  142534. };
  142535. static long _vq_quantmap__44u1__p1_0[] = {
  142536. 1, 0, 2,
  142537. };
  142538. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  142539. _vq_quantthresh__44u1__p1_0,
  142540. _vq_quantmap__44u1__p1_0,
  142541. 3,
  142542. 3
  142543. };
  142544. static static_codebook _44u1__p1_0 = {
  142545. 4, 81,
  142546. _vq_lengthlist__44u1__p1_0,
  142547. 1, -535822336, 1611661312, 2, 0,
  142548. _vq_quantlist__44u1__p1_0,
  142549. NULL,
  142550. &_vq_auxt__44u1__p1_0,
  142551. NULL,
  142552. 0
  142553. };
  142554. static long _vq_quantlist__44u1__p2_0[] = {
  142555. 1,
  142556. 0,
  142557. 2,
  142558. };
  142559. static long _vq_lengthlist__44u1__p2_0[] = {
  142560. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  142561. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  142562. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142563. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  142564. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142565. 9,
  142566. };
  142567. static float _vq_quantthresh__44u1__p2_0[] = {
  142568. -0.5, 0.5,
  142569. };
  142570. static long _vq_quantmap__44u1__p2_0[] = {
  142571. 1, 0, 2,
  142572. };
  142573. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  142574. _vq_quantthresh__44u1__p2_0,
  142575. _vq_quantmap__44u1__p2_0,
  142576. 3,
  142577. 3
  142578. };
  142579. static static_codebook _44u1__p2_0 = {
  142580. 4, 81,
  142581. _vq_lengthlist__44u1__p2_0,
  142582. 1, -535822336, 1611661312, 2, 0,
  142583. _vq_quantlist__44u1__p2_0,
  142584. NULL,
  142585. &_vq_auxt__44u1__p2_0,
  142586. NULL,
  142587. 0
  142588. };
  142589. static long _vq_quantlist__44u1__p3_0[] = {
  142590. 2,
  142591. 1,
  142592. 3,
  142593. 0,
  142594. 4,
  142595. };
  142596. static long _vq_lengthlist__44u1__p3_0[] = {
  142597. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142598. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142599. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142600. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142601. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142602. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142603. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142604. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142605. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142606. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142607. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142608. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142609. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142610. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142611. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142612. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142613. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142614. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142615. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142616. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142617. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142618. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142619. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142620. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142621. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142622. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142623. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142624. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142625. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142626. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142627. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142628. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142629. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142630. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142631. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142632. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142633. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142634. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142635. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142636. 19,
  142637. };
  142638. static float _vq_quantthresh__44u1__p3_0[] = {
  142639. -1.5, -0.5, 0.5, 1.5,
  142640. };
  142641. static long _vq_quantmap__44u1__p3_0[] = {
  142642. 3, 1, 0, 2, 4,
  142643. };
  142644. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  142645. _vq_quantthresh__44u1__p3_0,
  142646. _vq_quantmap__44u1__p3_0,
  142647. 5,
  142648. 5
  142649. };
  142650. static static_codebook _44u1__p3_0 = {
  142651. 4, 625,
  142652. _vq_lengthlist__44u1__p3_0,
  142653. 1, -533725184, 1611661312, 3, 0,
  142654. _vq_quantlist__44u1__p3_0,
  142655. NULL,
  142656. &_vq_auxt__44u1__p3_0,
  142657. NULL,
  142658. 0
  142659. };
  142660. static long _vq_quantlist__44u1__p4_0[] = {
  142661. 2,
  142662. 1,
  142663. 3,
  142664. 0,
  142665. 4,
  142666. };
  142667. static long _vq_lengthlist__44u1__p4_0[] = {
  142668. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142669. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142670. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142671. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142672. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142673. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142674. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142675. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142676. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142677. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142678. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142679. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142680. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142681. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142682. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142683. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142684. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142685. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142686. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142687. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142688. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142689. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142690. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142691. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142692. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142693. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142694. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142695. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142696. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142697. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142698. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142699. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142700. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142701. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142702. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142703. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142704. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142705. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142706. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142707. 12,
  142708. };
  142709. static float _vq_quantthresh__44u1__p4_0[] = {
  142710. -1.5, -0.5, 0.5, 1.5,
  142711. };
  142712. static long _vq_quantmap__44u1__p4_0[] = {
  142713. 3, 1, 0, 2, 4,
  142714. };
  142715. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  142716. _vq_quantthresh__44u1__p4_0,
  142717. _vq_quantmap__44u1__p4_0,
  142718. 5,
  142719. 5
  142720. };
  142721. static static_codebook _44u1__p4_0 = {
  142722. 4, 625,
  142723. _vq_lengthlist__44u1__p4_0,
  142724. 1, -533725184, 1611661312, 3, 0,
  142725. _vq_quantlist__44u1__p4_0,
  142726. NULL,
  142727. &_vq_auxt__44u1__p4_0,
  142728. NULL,
  142729. 0
  142730. };
  142731. static long _vq_quantlist__44u1__p5_0[] = {
  142732. 4,
  142733. 3,
  142734. 5,
  142735. 2,
  142736. 6,
  142737. 1,
  142738. 7,
  142739. 0,
  142740. 8,
  142741. };
  142742. static long _vq_lengthlist__44u1__p5_0[] = {
  142743. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142744. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142745. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142746. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142747. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142748. 12,
  142749. };
  142750. static float _vq_quantthresh__44u1__p5_0[] = {
  142751. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142752. };
  142753. static long _vq_quantmap__44u1__p5_0[] = {
  142754. 7, 5, 3, 1, 0, 2, 4, 6,
  142755. 8,
  142756. };
  142757. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  142758. _vq_quantthresh__44u1__p5_0,
  142759. _vq_quantmap__44u1__p5_0,
  142760. 9,
  142761. 9
  142762. };
  142763. static static_codebook _44u1__p5_0 = {
  142764. 2, 81,
  142765. _vq_lengthlist__44u1__p5_0,
  142766. 1, -531628032, 1611661312, 4, 0,
  142767. _vq_quantlist__44u1__p5_0,
  142768. NULL,
  142769. &_vq_auxt__44u1__p5_0,
  142770. NULL,
  142771. 0
  142772. };
  142773. static long _vq_quantlist__44u1__p6_0[] = {
  142774. 6,
  142775. 5,
  142776. 7,
  142777. 4,
  142778. 8,
  142779. 3,
  142780. 9,
  142781. 2,
  142782. 10,
  142783. 1,
  142784. 11,
  142785. 0,
  142786. 12,
  142787. };
  142788. static long _vq_lengthlist__44u1__p6_0[] = {
  142789. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142790. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142791. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142792. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142793. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142794. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142795. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142796. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142797. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142798. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142799. 15,17,16,17,18,17,17,18, 0,
  142800. };
  142801. static float _vq_quantthresh__44u1__p6_0[] = {
  142802. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142803. 12.5, 17.5, 22.5, 27.5,
  142804. };
  142805. static long _vq_quantmap__44u1__p6_0[] = {
  142806. 11, 9, 7, 5, 3, 1, 0, 2,
  142807. 4, 6, 8, 10, 12,
  142808. };
  142809. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  142810. _vq_quantthresh__44u1__p6_0,
  142811. _vq_quantmap__44u1__p6_0,
  142812. 13,
  142813. 13
  142814. };
  142815. static static_codebook _44u1__p6_0 = {
  142816. 2, 169,
  142817. _vq_lengthlist__44u1__p6_0,
  142818. 1, -526516224, 1616117760, 4, 0,
  142819. _vq_quantlist__44u1__p6_0,
  142820. NULL,
  142821. &_vq_auxt__44u1__p6_0,
  142822. NULL,
  142823. 0
  142824. };
  142825. static long _vq_quantlist__44u1__p6_1[] = {
  142826. 2,
  142827. 1,
  142828. 3,
  142829. 0,
  142830. 4,
  142831. };
  142832. static long _vq_lengthlist__44u1__p6_1[] = {
  142833. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142834. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142835. };
  142836. static float _vq_quantthresh__44u1__p6_1[] = {
  142837. -1.5, -0.5, 0.5, 1.5,
  142838. };
  142839. static long _vq_quantmap__44u1__p6_1[] = {
  142840. 3, 1, 0, 2, 4,
  142841. };
  142842. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  142843. _vq_quantthresh__44u1__p6_1,
  142844. _vq_quantmap__44u1__p6_1,
  142845. 5,
  142846. 5
  142847. };
  142848. static static_codebook _44u1__p6_1 = {
  142849. 2, 25,
  142850. _vq_lengthlist__44u1__p6_1,
  142851. 1, -533725184, 1611661312, 3, 0,
  142852. _vq_quantlist__44u1__p6_1,
  142853. NULL,
  142854. &_vq_auxt__44u1__p6_1,
  142855. NULL,
  142856. 0
  142857. };
  142858. static long _vq_quantlist__44u1__p7_0[] = {
  142859. 3,
  142860. 2,
  142861. 4,
  142862. 1,
  142863. 5,
  142864. 0,
  142865. 6,
  142866. };
  142867. static long _vq_lengthlist__44u1__p7_0[] = {
  142868. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142869. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142870. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142871. 8,
  142872. };
  142873. static float _vq_quantthresh__44u1__p7_0[] = {
  142874. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  142875. };
  142876. static long _vq_quantmap__44u1__p7_0[] = {
  142877. 5, 3, 1, 0, 2, 4, 6,
  142878. };
  142879. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  142880. _vq_quantthresh__44u1__p7_0,
  142881. _vq_quantmap__44u1__p7_0,
  142882. 7,
  142883. 7
  142884. };
  142885. static static_codebook _44u1__p7_0 = {
  142886. 2, 49,
  142887. _vq_lengthlist__44u1__p7_0,
  142888. 1, -518017024, 1626677248, 3, 0,
  142889. _vq_quantlist__44u1__p7_0,
  142890. NULL,
  142891. &_vq_auxt__44u1__p7_0,
  142892. NULL,
  142893. 0
  142894. };
  142895. static long _vq_quantlist__44u1__p7_1[] = {
  142896. 6,
  142897. 5,
  142898. 7,
  142899. 4,
  142900. 8,
  142901. 3,
  142902. 9,
  142903. 2,
  142904. 10,
  142905. 1,
  142906. 11,
  142907. 0,
  142908. 12,
  142909. };
  142910. static long _vq_lengthlist__44u1__p7_1[] = {
  142911. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142912. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142913. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142914. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142915. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142916. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142917. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142918. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142919. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142920. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142921. 15,15,15,15,15,15,15,15,15,
  142922. };
  142923. static float _vq_quantthresh__44u1__p7_1[] = {
  142924. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142925. 32.5, 45.5, 58.5, 71.5,
  142926. };
  142927. static long _vq_quantmap__44u1__p7_1[] = {
  142928. 11, 9, 7, 5, 3, 1, 0, 2,
  142929. 4, 6, 8, 10, 12,
  142930. };
  142931. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  142932. _vq_quantthresh__44u1__p7_1,
  142933. _vq_quantmap__44u1__p7_1,
  142934. 13,
  142935. 13
  142936. };
  142937. static static_codebook _44u1__p7_1 = {
  142938. 2, 169,
  142939. _vq_lengthlist__44u1__p7_1,
  142940. 1, -523010048, 1618608128, 4, 0,
  142941. _vq_quantlist__44u1__p7_1,
  142942. NULL,
  142943. &_vq_auxt__44u1__p7_1,
  142944. NULL,
  142945. 0
  142946. };
  142947. static long _vq_quantlist__44u1__p7_2[] = {
  142948. 6,
  142949. 5,
  142950. 7,
  142951. 4,
  142952. 8,
  142953. 3,
  142954. 9,
  142955. 2,
  142956. 10,
  142957. 1,
  142958. 11,
  142959. 0,
  142960. 12,
  142961. };
  142962. static long _vq_lengthlist__44u1__p7_2[] = {
  142963. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142964. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142965. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142966. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142967. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142968. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142969. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142970. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142971. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142972. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142973. 9, 9, 9,10, 9, 9,10,10, 9,
  142974. };
  142975. static float _vq_quantthresh__44u1__p7_2[] = {
  142976. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142977. 2.5, 3.5, 4.5, 5.5,
  142978. };
  142979. static long _vq_quantmap__44u1__p7_2[] = {
  142980. 11, 9, 7, 5, 3, 1, 0, 2,
  142981. 4, 6, 8, 10, 12,
  142982. };
  142983. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  142984. _vq_quantthresh__44u1__p7_2,
  142985. _vq_quantmap__44u1__p7_2,
  142986. 13,
  142987. 13
  142988. };
  142989. static static_codebook _44u1__p7_2 = {
  142990. 2, 169,
  142991. _vq_lengthlist__44u1__p7_2,
  142992. 1, -531103744, 1611661312, 4, 0,
  142993. _vq_quantlist__44u1__p7_2,
  142994. NULL,
  142995. &_vq_auxt__44u1__p7_2,
  142996. NULL,
  142997. 0
  142998. };
  142999. static long _huff_lengthlist__44u1__short[] = {
  143000. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  143001. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  143002. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  143003. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  143004. };
  143005. static static_codebook _huff_book__44u1__short = {
  143006. 2, 64,
  143007. _huff_lengthlist__44u1__short,
  143008. 0, 0, 0, 0, 0,
  143009. NULL,
  143010. NULL,
  143011. NULL,
  143012. NULL,
  143013. 0
  143014. };
  143015. static long _huff_lengthlist__44u2__long[] = {
  143016. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  143017. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  143018. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  143019. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  143020. };
  143021. static static_codebook _huff_book__44u2__long = {
  143022. 2, 64,
  143023. _huff_lengthlist__44u2__long,
  143024. 0, 0, 0, 0, 0,
  143025. NULL,
  143026. NULL,
  143027. NULL,
  143028. NULL,
  143029. 0
  143030. };
  143031. static long _vq_quantlist__44u2__p1_0[] = {
  143032. 1,
  143033. 0,
  143034. 2,
  143035. };
  143036. static long _vq_lengthlist__44u2__p1_0[] = {
  143037. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  143038. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143039. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  143040. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  143041. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  143042. 13,
  143043. };
  143044. static float _vq_quantthresh__44u2__p1_0[] = {
  143045. -0.5, 0.5,
  143046. };
  143047. static long _vq_quantmap__44u2__p1_0[] = {
  143048. 1, 0, 2,
  143049. };
  143050. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  143051. _vq_quantthresh__44u2__p1_0,
  143052. _vq_quantmap__44u2__p1_0,
  143053. 3,
  143054. 3
  143055. };
  143056. static static_codebook _44u2__p1_0 = {
  143057. 4, 81,
  143058. _vq_lengthlist__44u2__p1_0,
  143059. 1, -535822336, 1611661312, 2, 0,
  143060. _vq_quantlist__44u2__p1_0,
  143061. NULL,
  143062. &_vq_auxt__44u2__p1_0,
  143063. NULL,
  143064. 0
  143065. };
  143066. static long _vq_quantlist__44u2__p2_0[] = {
  143067. 1,
  143068. 0,
  143069. 2,
  143070. };
  143071. static long _vq_lengthlist__44u2__p2_0[] = {
  143072. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143073. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  143074. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143075. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143076. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143077. 9,
  143078. };
  143079. static float _vq_quantthresh__44u2__p2_0[] = {
  143080. -0.5, 0.5,
  143081. };
  143082. static long _vq_quantmap__44u2__p2_0[] = {
  143083. 1, 0, 2,
  143084. };
  143085. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  143086. _vq_quantthresh__44u2__p2_0,
  143087. _vq_quantmap__44u2__p2_0,
  143088. 3,
  143089. 3
  143090. };
  143091. static static_codebook _44u2__p2_0 = {
  143092. 4, 81,
  143093. _vq_lengthlist__44u2__p2_0,
  143094. 1, -535822336, 1611661312, 2, 0,
  143095. _vq_quantlist__44u2__p2_0,
  143096. NULL,
  143097. &_vq_auxt__44u2__p2_0,
  143098. NULL,
  143099. 0
  143100. };
  143101. static long _vq_quantlist__44u2__p3_0[] = {
  143102. 2,
  143103. 1,
  143104. 3,
  143105. 0,
  143106. 4,
  143107. };
  143108. static long _vq_lengthlist__44u2__p3_0[] = {
  143109. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143110. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143111. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143112. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143113. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  143114. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  143115. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143116. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  143117. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143118. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143119. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  143120. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143121. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  143122. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  143123. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  143124. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  143125. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143126. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  143127. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  143128. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  143129. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  143130. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  143131. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  143132. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  143133. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  143134. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  143135. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  143136. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  143137. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  143138. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  143139. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  143140. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  143141. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  143142. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  143143. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  143144. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  143145. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  143146. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  143147. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  143148. 0,
  143149. };
  143150. static float _vq_quantthresh__44u2__p3_0[] = {
  143151. -1.5, -0.5, 0.5, 1.5,
  143152. };
  143153. static long _vq_quantmap__44u2__p3_0[] = {
  143154. 3, 1, 0, 2, 4,
  143155. };
  143156. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  143157. _vq_quantthresh__44u2__p3_0,
  143158. _vq_quantmap__44u2__p3_0,
  143159. 5,
  143160. 5
  143161. };
  143162. static static_codebook _44u2__p3_0 = {
  143163. 4, 625,
  143164. _vq_lengthlist__44u2__p3_0,
  143165. 1, -533725184, 1611661312, 3, 0,
  143166. _vq_quantlist__44u2__p3_0,
  143167. NULL,
  143168. &_vq_auxt__44u2__p3_0,
  143169. NULL,
  143170. 0
  143171. };
  143172. static long _vq_quantlist__44u2__p4_0[] = {
  143173. 2,
  143174. 1,
  143175. 3,
  143176. 0,
  143177. 4,
  143178. };
  143179. static long _vq_lengthlist__44u2__p4_0[] = {
  143180. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143181. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143182. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143183. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  143184. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  143185. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143186. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  143187. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  143188. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143189. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143190. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  143191. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143192. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  143193. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  143194. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  143195. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  143196. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143197. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143198. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143199. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143200. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143201. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  143202. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143203. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143204. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143205. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  143206. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  143207. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  143208. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143209. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  143210. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  143211. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  143212. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  143213. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143214. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143215. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  143216. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143217. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  143218. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  143219. 13,
  143220. };
  143221. static float _vq_quantthresh__44u2__p4_0[] = {
  143222. -1.5, -0.5, 0.5, 1.5,
  143223. };
  143224. static long _vq_quantmap__44u2__p4_0[] = {
  143225. 3, 1, 0, 2, 4,
  143226. };
  143227. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  143228. _vq_quantthresh__44u2__p4_0,
  143229. _vq_quantmap__44u2__p4_0,
  143230. 5,
  143231. 5
  143232. };
  143233. static static_codebook _44u2__p4_0 = {
  143234. 4, 625,
  143235. _vq_lengthlist__44u2__p4_0,
  143236. 1, -533725184, 1611661312, 3, 0,
  143237. _vq_quantlist__44u2__p4_0,
  143238. NULL,
  143239. &_vq_auxt__44u2__p4_0,
  143240. NULL,
  143241. 0
  143242. };
  143243. static long _vq_quantlist__44u2__p5_0[] = {
  143244. 4,
  143245. 3,
  143246. 5,
  143247. 2,
  143248. 6,
  143249. 1,
  143250. 7,
  143251. 0,
  143252. 8,
  143253. };
  143254. static long _vq_lengthlist__44u2__p5_0[] = {
  143255. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  143256. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143257. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  143258. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  143259. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  143260. 13,
  143261. };
  143262. static float _vq_quantthresh__44u2__p5_0[] = {
  143263. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143264. };
  143265. static long _vq_quantmap__44u2__p5_0[] = {
  143266. 7, 5, 3, 1, 0, 2, 4, 6,
  143267. 8,
  143268. };
  143269. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  143270. _vq_quantthresh__44u2__p5_0,
  143271. _vq_quantmap__44u2__p5_0,
  143272. 9,
  143273. 9
  143274. };
  143275. static static_codebook _44u2__p5_0 = {
  143276. 2, 81,
  143277. _vq_lengthlist__44u2__p5_0,
  143278. 1, -531628032, 1611661312, 4, 0,
  143279. _vq_quantlist__44u2__p5_0,
  143280. NULL,
  143281. &_vq_auxt__44u2__p5_0,
  143282. NULL,
  143283. 0
  143284. };
  143285. static long _vq_quantlist__44u2__p6_0[] = {
  143286. 6,
  143287. 5,
  143288. 7,
  143289. 4,
  143290. 8,
  143291. 3,
  143292. 9,
  143293. 2,
  143294. 10,
  143295. 1,
  143296. 11,
  143297. 0,
  143298. 12,
  143299. };
  143300. static long _vq_lengthlist__44u2__p6_0[] = {
  143301. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  143302. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  143303. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  143304. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  143305. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  143306. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  143307. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  143308. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  143309. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  143310. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  143311. 15,17,17,16,18,17,18, 0, 0,
  143312. };
  143313. static float _vq_quantthresh__44u2__p6_0[] = {
  143314. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143315. 12.5, 17.5, 22.5, 27.5,
  143316. };
  143317. static long _vq_quantmap__44u2__p6_0[] = {
  143318. 11, 9, 7, 5, 3, 1, 0, 2,
  143319. 4, 6, 8, 10, 12,
  143320. };
  143321. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  143322. _vq_quantthresh__44u2__p6_0,
  143323. _vq_quantmap__44u2__p6_0,
  143324. 13,
  143325. 13
  143326. };
  143327. static static_codebook _44u2__p6_0 = {
  143328. 2, 169,
  143329. _vq_lengthlist__44u2__p6_0,
  143330. 1, -526516224, 1616117760, 4, 0,
  143331. _vq_quantlist__44u2__p6_0,
  143332. NULL,
  143333. &_vq_auxt__44u2__p6_0,
  143334. NULL,
  143335. 0
  143336. };
  143337. static long _vq_quantlist__44u2__p6_1[] = {
  143338. 2,
  143339. 1,
  143340. 3,
  143341. 0,
  143342. 4,
  143343. };
  143344. static long _vq_lengthlist__44u2__p6_1[] = {
  143345. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143346. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143347. };
  143348. static float _vq_quantthresh__44u2__p6_1[] = {
  143349. -1.5, -0.5, 0.5, 1.5,
  143350. };
  143351. static long _vq_quantmap__44u2__p6_1[] = {
  143352. 3, 1, 0, 2, 4,
  143353. };
  143354. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  143355. _vq_quantthresh__44u2__p6_1,
  143356. _vq_quantmap__44u2__p6_1,
  143357. 5,
  143358. 5
  143359. };
  143360. static static_codebook _44u2__p6_1 = {
  143361. 2, 25,
  143362. _vq_lengthlist__44u2__p6_1,
  143363. 1, -533725184, 1611661312, 3, 0,
  143364. _vq_quantlist__44u2__p6_1,
  143365. NULL,
  143366. &_vq_auxt__44u2__p6_1,
  143367. NULL,
  143368. 0
  143369. };
  143370. static long _vq_quantlist__44u2__p7_0[] = {
  143371. 4,
  143372. 3,
  143373. 5,
  143374. 2,
  143375. 6,
  143376. 1,
  143377. 7,
  143378. 0,
  143379. 8,
  143380. };
  143381. static long _vq_lengthlist__44u2__p7_0[] = {
  143382. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  143383. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  143384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143387. 11,
  143388. };
  143389. static float _vq_quantthresh__44u2__p7_0[] = {
  143390. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  143391. };
  143392. static long _vq_quantmap__44u2__p7_0[] = {
  143393. 7, 5, 3, 1, 0, 2, 4, 6,
  143394. 8,
  143395. };
  143396. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  143397. _vq_quantthresh__44u2__p7_0,
  143398. _vq_quantmap__44u2__p7_0,
  143399. 9,
  143400. 9
  143401. };
  143402. static static_codebook _44u2__p7_0 = {
  143403. 2, 81,
  143404. _vq_lengthlist__44u2__p7_0,
  143405. 1, -516612096, 1626677248, 4, 0,
  143406. _vq_quantlist__44u2__p7_0,
  143407. NULL,
  143408. &_vq_auxt__44u2__p7_0,
  143409. NULL,
  143410. 0
  143411. };
  143412. static long _vq_quantlist__44u2__p7_1[] = {
  143413. 6,
  143414. 5,
  143415. 7,
  143416. 4,
  143417. 8,
  143418. 3,
  143419. 9,
  143420. 2,
  143421. 10,
  143422. 1,
  143423. 11,
  143424. 0,
  143425. 12,
  143426. };
  143427. static long _vq_lengthlist__44u2__p7_1[] = {
  143428. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  143429. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  143430. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  143431. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  143432. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  143433. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  143434. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  143435. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  143436. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  143437. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  143438. 14,14,14,17,15,17,17,17,17,
  143439. };
  143440. static float _vq_quantthresh__44u2__p7_1[] = {
  143441. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143442. 32.5, 45.5, 58.5, 71.5,
  143443. };
  143444. static long _vq_quantmap__44u2__p7_1[] = {
  143445. 11, 9, 7, 5, 3, 1, 0, 2,
  143446. 4, 6, 8, 10, 12,
  143447. };
  143448. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  143449. _vq_quantthresh__44u2__p7_1,
  143450. _vq_quantmap__44u2__p7_1,
  143451. 13,
  143452. 13
  143453. };
  143454. static static_codebook _44u2__p7_1 = {
  143455. 2, 169,
  143456. _vq_lengthlist__44u2__p7_1,
  143457. 1, -523010048, 1618608128, 4, 0,
  143458. _vq_quantlist__44u2__p7_1,
  143459. NULL,
  143460. &_vq_auxt__44u2__p7_1,
  143461. NULL,
  143462. 0
  143463. };
  143464. static long _vq_quantlist__44u2__p7_2[] = {
  143465. 6,
  143466. 5,
  143467. 7,
  143468. 4,
  143469. 8,
  143470. 3,
  143471. 9,
  143472. 2,
  143473. 10,
  143474. 1,
  143475. 11,
  143476. 0,
  143477. 12,
  143478. };
  143479. static long _vq_lengthlist__44u2__p7_2[] = {
  143480. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  143481. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  143482. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  143483. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143484. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  143485. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  143486. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143487. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143488. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  143489. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  143490. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143491. };
  143492. static float _vq_quantthresh__44u2__p7_2[] = {
  143493. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143494. 2.5, 3.5, 4.5, 5.5,
  143495. };
  143496. static long _vq_quantmap__44u2__p7_2[] = {
  143497. 11, 9, 7, 5, 3, 1, 0, 2,
  143498. 4, 6, 8, 10, 12,
  143499. };
  143500. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  143501. _vq_quantthresh__44u2__p7_2,
  143502. _vq_quantmap__44u2__p7_2,
  143503. 13,
  143504. 13
  143505. };
  143506. static static_codebook _44u2__p7_2 = {
  143507. 2, 169,
  143508. _vq_lengthlist__44u2__p7_2,
  143509. 1, -531103744, 1611661312, 4, 0,
  143510. _vq_quantlist__44u2__p7_2,
  143511. NULL,
  143512. &_vq_auxt__44u2__p7_2,
  143513. NULL,
  143514. 0
  143515. };
  143516. static long _huff_lengthlist__44u2__short[] = {
  143517. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  143518. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  143519. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  143520. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  143521. };
  143522. static static_codebook _huff_book__44u2__short = {
  143523. 2, 64,
  143524. _huff_lengthlist__44u2__short,
  143525. 0, 0, 0, 0, 0,
  143526. NULL,
  143527. NULL,
  143528. NULL,
  143529. NULL,
  143530. 0
  143531. };
  143532. static long _huff_lengthlist__44u3__long[] = {
  143533. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  143534. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  143535. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  143536. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  143537. };
  143538. static static_codebook _huff_book__44u3__long = {
  143539. 2, 64,
  143540. _huff_lengthlist__44u3__long,
  143541. 0, 0, 0, 0, 0,
  143542. NULL,
  143543. NULL,
  143544. NULL,
  143545. NULL,
  143546. 0
  143547. };
  143548. static long _vq_quantlist__44u3__p1_0[] = {
  143549. 1,
  143550. 0,
  143551. 2,
  143552. };
  143553. static long _vq_lengthlist__44u3__p1_0[] = {
  143554. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143555. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143556. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  143557. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143558. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  143559. 13,
  143560. };
  143561. static float _vq_quantthresh__44u3__p1_0[] = {
  143562. -0.5, 0.5,
  143563. };
  143564. static long _vq_quantmap__44u3__p1_0[] = {
  143565. 1, 0, 2,
  143566. };
  143567. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  143568. _vq_quantthresh__44u3__p1_0,
  143569. _vq_quantmap__44u3__p1_0,
  143570. 3,
  143571. 3
  143572. };
  143573. static static_codebook _44u3__p1_0 = {
  143574. 4, 81,
  143575. _vq_lengthlist__44u3__p1_0,
  143576. 1, -535822336, 1611661312, 2, 0,
  143577. _vq_quantlist__44u3__p1_0,
  143578. NULL,
  143579. &_vq_auxt__44u3__p1_0,
  143580. NULL,
  143581. 0
  143582. };
  143583. static long _vq_quantlist__44u3__p2_0[] = {
  143584. 1,
  143585. 0,
  143586. 2,
  143587. };
  143588. static long _vq_lengthlist__44u3__p2_0[] = {
  143589. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143590. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  143591. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143592. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143593. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  143594. 9,
  143595. };
  143596. static float _vq_quantthresh__44u3__p2_0[] = {
  143597. -0.5, 0.5,
  143598. };
  143599. static long _vq_quantmap__44u3__p2_0[] = {
  143600. 1, 0, 2,
  143601. };
  143602. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  143603. _vq_quantthresh__44u3__p2_0,
  143604. _vq_quantmap__44u3__p2_0,
  143605. 3,
  143606. 3
  143607. };
  143608. static static_codebook _44u3__p2_0 = {
  143609. 4, 81,
  143610. _vq_lengthlist__44u3__p2_0,
  143611. 1, -535822336, 1611661312, 2, 0,
  143612. _vq_quantlist__44u3__p2_0,
  143613. NULL,
  143614. &_vq_auxt__44u3__p2_0,
  143615. NULL,
  143616. 0
  143617. };
  143618. static long _vq_quantlist__44u3__p3_0[] = {
  143619. 2,
  143620. 1,
  143621. 3,
  143622. 0,
  143623. 4,
  143624. };
  143625. static long _vq_lengthlist__44u3__p3_0[] = {
  143626. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143627. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143628. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143629. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143630. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  143631. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  143632. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  143633. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  143634. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143635. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143636. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  143637. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143638. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  143639. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  143640. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  143641. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  143642. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  143643. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  143644. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  143645. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  143646. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  143647. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  143648. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  143649. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  143650. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  143651. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  143652. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  143653. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  143654. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  143655. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  143656. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  143657. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  143658. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  143659. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  143660. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  143661. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  143662. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  143663. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  143664. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  143665. 0,
  143666. };
  143667. static float _vq_quantthresh__44u3__p3_0[] = {
  143668. -1.5, -0.5, 0.5, 1.5,
  143669. };
  143670. static long _vq_quantmap__44u3__p3_0[] = {
  143671. 3, 1, 0, 2, 4,
  143672. };
  143673. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  143674. _vq_quantthresh__44u3__p3_0,
  143675. _vq_quantmap__44u3__p3_0,
  143676. 5,
  143677. 5
  143678. };
  143679. static static_codebook _44u3__p3_0 = {
  143680. 4, 625,
  143681. _vq_lengthlist__44u3__p3_0,
  143682. 1, -533725184, 1611661312, 3, 0,
  143683. _vq_quantlist__44u3__p3_0,
  143684. NULL,
  143685. &_vq_auxt__44u3__p3_0,
  143686. NULL,
  143687. 0
  143688. };
  143689. static long _vq_quantlist__44u3__p4_0[] = {
  143690. 2,
  143691. 1,
  143692. 3,
  143693. 0,
  143694. 4,
  143695. };
  143696. static long _vq_lengthlist__44u3__p4_0[] = {
  143697. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143698. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143699. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  143700. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  143701. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  143702. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143703. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  143704. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  143705. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143706. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143707. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  143708. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143709. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  143710. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  143711. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  143712. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143713. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  143714. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143715. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143716. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  143717. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143718. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  143719. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143720. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143721. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  143722. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  143723. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  143724. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  143725. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143726. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  143727. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  143728. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  143729. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  143730. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143731. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  143732. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  143733. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  143734. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  143735. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  143736. 13,
  143737. };
  143738. static float _vq_quantthresh__44u3__p4_0[] = {
  143739. -1.5, -0.5, 0.5, 1.5,
  143740. };
  143741. static long _vq_quantmap__44u3__p4_0[] = {
  143742. 3, 1, 0, 2, 4,
  143743. };
  143744. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  143745. _vq_quantthresh__44u3__p4_0,
  143746. _vq_quantmap__44u3__p4_0,
  143747. 5,
  143748. 5
  143749. };
  143750. static static_codebook _44u3__p4_0 = {
  143751. 4, 625,
  143752. _vq_lengthlist__44u3__p4_0,
  143753. 1, -533725184, 1611661312, 3, 0,
  143754. _vq_quantlist__44u3__p4_0,
  143755. NULL,
  143756. &_vq_auxt__44u3__p4_0,
  143757. NULL,
  143758. 0
  143759. };
  143760. static long _vq_quantlist__44u3__p5_0[] = {
  143761. 4,
  143762. 3,
  143763. 5,
  143764. 2,
  143765. 6,
  143766. 1,
  143767. 7,
  143768. 0,
  143769. 8,
  143770. };
  143771. static long _vq_lengthlist__44u3__p5_0[] = {
  143772. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  143773. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  143774. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  143775. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143776. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  143777. 12,
  143778. };
  143779. static float _vq_quantthresh__44u3__p5_0[] = {
  143780. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143781. };
  143782. static long _vq_quantmap__44u3__p5_0[] = {
  143783. 7, 5, 3, 1, 0, 2, 4, 6,
  143784. 8,
  143785. };
  143786. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  143787. _vq_quantthresh__44u3__p5_0,
  143788. _vq_quantmap__44u3__p5_0,
  143789. 9,
  143790. 9
  143791. };
  143792. static static_codebook _44u3__p5_0 = {
  143793. 2, 81,
  143794. _vq_lengthlist__44u3__p5_0,
  143795. 1, -531628032, 1611661312, 4, 0,
  143796. _vq_quantlist__44u3__p5_0,
  143797. NULL,
  143798. &_vq_auxt__44u3__p5_0,
  143799. NULL,
  143800. 0
  143801. };
  143802. static long _vq_quantlist__44u3__p6_0[] = {
  143803. 6,
  143804. 5,
  143805. 7,
  143806. 4,
  143807. 8,
  143808. 3,
  143809. 9,
  143810. 2,
  143811. 10,
  143812. 1,
  143813. 11,
  143814. 0,
  143815. 12,
  143816. };
  143817. static long _vq_lengthlist__44u3__p6_0[] = {
  143818. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  143819. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  143820. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143821. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  143822. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  143823. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  143824. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  143825. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  143826. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  143827. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  143828. 15,16,16,16,17,18,16,20,18,
  143829. };
  143830. static float _vq_quantthresh__44u3__p6_0[] = {
  143831. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143832. 12.5, 17.5, 22.5, 27.5,
  143833. };
  143834. static long _vq_quantmap__44u3__p6_0[] = {
  143835. 11, 9, 7, 5, 3, 1, 0, 2,
  143836. 4, 6, 8, 10, 12,
  143837. };
  143838. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  143839. _vq_quantthresh__44u3__p6_0,
  143840. _vq_quantmap__44u3__p6_0,
  143841. 13,
  143842. 13
  143843. };
  143844. static static_codebook _44u3__p6_0 = {
  143845. 2, 169,
  143846. _vq_lengthlist__44u3__p6_0,
  143847. 1, -526516224, 1616117760, 4, 0,
  143848. _vq_quantlist__44u3__p6_0,
  143849. NULL,
  143850. &_vq_auxt__44u3__p6_0,
  143851. NULL,
  143852. 0
  143853. };
  143854. static long _vq_quantlist__44u3__p6_1[] = {
  143855. 2,
  143856. 1,
  143857. 3,
  143858. 0,
  143859. 4,
  143860. };
  143861. static long _vq_lengthlist__44u3__p6_1[] = {
  143862. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143863. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143864. };
  143865. static float _vq_quantthresh__44u3__p6_1[] = {
  143866. -1.5, -0.5, 0.5, 1.5,
  143867. };
  143868. static long _vq_quantmap__44u3__p6_1[] = {
  143869. 3, 1, 0, 2, 4,
  143870. };
  143871. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  143872. _vq_quantthresh__44u3__p6_1,
  143873. _vq_quantmap__44u3__p6_1,
  143874. 5,
  143875. 5
  143876. };
  143877. static static_codebook _44u3__p6_1 = {
  143878. 2, 25,
  143879. _vq_lengthlist__44u3__p6_1,
  143880. 1, -533725184, 1611661312, 3, 0,
  143881. _vq_quantlist__44u3__p6_1,
  143882. NULL,
  143883. &_vq_auxt__44u3__p6_1,
  143884. NULL,
  143885. 0
  143886. };
  143887. static long _vq_quantlist__44u3__p7_0[] = {
  143888. 4,
  143889. 3,
  143890. 5,
  143891. 2,
  143892. 6,
  143893. 1,
  143894. 7,
  143895. 0,
  143896. 8,
  143897. };
  143898. static long _vq_lengthlist__44u3__p7_0[] = {
  143899. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  143900. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143901. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143902. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143903. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143904. 9,
  143905. };
  143906. static float _vq_quantthresh__44u3__p7_0[] = {
  143907. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  143908. };
  143909. static long _vq_quantmap__44u3__p7_0[] = {
  143910. 7, 5, 3, 1, 0, 2, 4, 6,
  143911. 8,
  143912. };
  143913. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  143914. _vq_quantthresh__44u3__p7_0,
  143915. _vq_quantmap__44u3__p7_0,
  143916. 9,
  143917. 9
  143918. };
  143919. static static_codebook _44u3__p7_0 = {
  143920. 2, 81,
  143921. _vq_lengthlist__44u3__p7_0,
  143922. 1, -515907584, 1627381760, 4, 0,
  143923. _vq_quantlist__44u3__p7_0,
  143924. NULL,
  143925. &_vq_auxt__44u3__p7_0,
  143926. NULL,
  143927. 0
  143928. };
  143929. static long _vq_quantlist__44u3__p7_1[] = {
  143930. 7,
  143931. 6,
  143932. 8,
  143933. 5,
  143934. 9,
  143935. 4,
  143936. 10,
  143937. 3,
  143938. 11,
  143939. 2,
  143940. 12,
  143941. 1,
  143942. 13,
  143943. 0,
  143944. 14,
  143945. };
  143946. static long _vq_lengthlist__44u3__p7_1[] = {
  143947. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  143948. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  143949. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  143950. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  143951. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  143952. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  143953. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  143954. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  143955. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  143956. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  143957. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  143958. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  143959. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  143960. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  143961. 17,
  143962. };
  143963. static float _vq_quantthresh__44u3__p7_1[] = {
  143964. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143965. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143966. };
  143967. static long _vq_quantmap__44u3__p7_1[] = {
  143968. 13, 11, 9, 7, 5, 3, 1, 0,
  143969. 2, 4, 6, 8, 10, 12, 14,
  143970. };
  143971. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  143972. _vq_quantthresh__44u3__p7_1,
  143973. _vq_quantmap__44u3__p7_1,
  143974. 15,
  143975. 15
  143976. };
  143977. static static_codebook _44u3__p7_1 = {
  143978. 2, 225,
  143979. _vq_lengthlist__44u3__p7_1,
  143980. 1, -522338304, 1620115456, 4, 0,
  143981. _vq_quantlist__44u3__p7_1,
  143982. NULL,
  143983. &_vq_auxt__44u3__p7_1,
  143984. NULL,
  143985. 0
  143986. };
  143987. static long _vq_quantlist__44u3__p7_2[] = {
  143988. 8,
  143989. 7,
  143990. 9,
  143991. 6,
  143992. 10,
  143993. 5,
  143994. 11,
  143995. 4,
  143996. 12,
  143997. 3,
  143998. 13,
  143999. 2,
  144000. 14,
  144001. 1,
  144002. 15,
  144003. 0,
  144004. 16,
  144005. };
  144006. static long _vq_lengthlist__44u3__p7_2[] = {
  144007. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144008. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144009. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  144010. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144011. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144012. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144013. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  144014. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144015. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  144016. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  144017. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144018. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  144019. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  144020. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144021. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  144022. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  144023. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144024. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  144025. 11,
  144026. };
  144027. static float _vq_quantthresh__44u3__p7_2[] = {
  144028. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144029. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144030. };
  144031. static long _vq_quantmap__44u3__p7_2[] = {
  144032. 15, 13, 11, 9, 7, 5, 3, 1,
  144033. 0, 2, 4, 6, 8, 10, 12, 14,
  144034. 16,
  144035. };
  144036. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  144037. _vq_quantthresh__44u3__p7_2,
  144038. _vq_quantmap__44u3__p7_2,
  144039. 17,
  144040. 17
  144041. };
  144042. static static_codebook _44u3__p7_2 = {
  144043. 2, 289,
  144044. _vq_lengthlist__44u3__p7_2,
  144045. 1, -529530880, 1611661312, 5, 0,
  144046. _vq_quantlist__44u3__p7_2,
  144047. NULL,
  144048. &_vq_auxt__44u3__p7_2,
  144049. NULL,
  144050. 0
  144051. };
  144052. static long _huff_lengthlist__44u3__short[] = {
  144053. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  144054. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  144055. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  144056. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  144057. };
  144058. static static_codebook _huff_book__44u3__short = {
  144059. 2, 64,
  144060. _huff_lengthlist__44u3__short,
  144061. 0, 0, 0, 0, 0,
  144062. NULL,
  144063. NULL,
  144064. NULL,
  144065. NULL,
  144066. 0
  144067. };
  144068. static long _huff_lengthlist__44u4__long[] = {
  144069. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  144070. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  144071. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  144072. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  144073. };
  144074. static static_codebook _huff_book__44u4__long = {
  144075. 2, 64,
  144076. _huff_lengthlist__44u4__long,
  144077. 0, 0, 0, 0, 0,
  144078. NULL,
  144079. NULL,
  144080. NULL,
  144081. NULL,
  144082. 0
  144083. };
  144084. static long _vq_quantlist__44u4__p1_0[] = {
  144085. 1,
  144086. 0,
  144087. 2,
  144088. };
  144089. static long _vq_lengthlist__44u4__p1_0[] = {
  144090. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  144091. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  144092. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  144093. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  144094. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  144095. 13,
  144096. };
  144097. static float _vq_quantthresh__44u4__p1_0[] = {
  144098. -0.5, 0.5,
  144099. };
  144100. static long _vq_quantmap__44u4__p1_0[] = {
  144101. 1, 0, 2,
  144102. };
  144103. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  144104. _vq_quantthresh__44u4__p1_0,
  144105. _vq_quantmap__44u4__p1_0,
  144106. 3,
  144107. 3
  144108. };
  144109. static static_codebook _44u4__p1_0 = {
  144110. 4, 81,
  144111. _vq_lengthlist__44u4__p1_0,
  144112. 1, -535822336, 1611661312, 2, 0,
  144113. _vq_quantlist__44u4__p1_0,
  144114. NULL,
  144115. &_vq_auxt__44u4__p1_0,
  144116. NULL,
  144117. 0
  144118. };
  144119. static long _vq_quantlist__44u4__p2_0[] = {
  144120. 1,
  144121. 0,
  144122. 2,
  144123. };
  144124. static long _vq_lengthlist__44u4__p2_0[] = {
  144125. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  144126. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  144127. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  144128. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  144129. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  144130. 9,
  144131. };
  144132. static float _vq_quantthresh__44u4__p2_0[] = {
  144133. -0.5, 0.5,
  144134. };
  144135. static long _vq_quantmap__44u4__p2_0[] = {
  144136. 1, 0, 2,
  144137. };
  144138. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  144139. _vq_quantthresh__44u4__p2_0,
  144140. _vq_quantmap__44u4__p2_0,
  144141. 3,
  144142. 3
  144143. };
  144144. static static_codebook _44u4__p2_0 = {
  144145. 4, 81,
  144146. _vq_lengthlist__44u4__p2_0,
  144147. 1, -535822336, 1611661312, 2, 0,
  144148. _vq_quantlist__44u4__p2_0,
  144149. NULL,
  144150. &_vq_auxt__44u4__p2_0,
  144151. NULL,
  144152. 0
  144153. };
  144154. static long _vq_quantlist__44u4__p3_0[] = {
  144155. 2,
  144156. 1,
  144157. 3,
  144158. 0,
  144159. 4,
  144160. };
  144161. static long _vq_lengthlist__44u4__p3_0[] = {
  144162. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  144163. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144164. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  144165. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  144166. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  144167. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  144168. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  144169. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  144170. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  144171. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  144172. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  144173. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  144174. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  144175. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  144176. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  144177. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  144178. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  144179. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  144180. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  144181. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  144182. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  144183. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  144184. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  144185. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  144186. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  144187. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  144188. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  144189. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  144190. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  144191. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  144192. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  144193. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  144194. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  144195. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  144196. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  144197. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  144198. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  144199. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  144200. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  144201. 0,
  144202. };
  144203. static float _vq_quantthresh__44u4__p3_0[] = {
  144204. -1.5, -0.5, 0.5, 1.5,
  144205. };
  144206. static long _vq_quantmap__44u4__p3_0[] = {
  144207. 3, 1, 0, 2, 4,
  144208. };
  144209. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  144210. _vq_quantthresh__44u4__p3_0,
  144211. _vq_quantmap__44u4__p3_0,
  144212. 5,
  144213. 5
  144214. };
  144215. static static_codebook _44u4__p3_0 = {
  144216. 4, 625,
  144217. _vq_lengthlist__44u4__p3_0,
  144218. 1, -533725184, 1611661312, 3, 0,
  144219. _vq_quantlist__44u4__p3_0,
  144220. NULL,
  144221. &_vq_auxt__44u4__p3_0,
  144222. NULL,
  144223. 0
  144224. };
  144225. static long _vq_quantlist__44u4__p4_0[] = {
  144226. 2,
  144227. 1,
  144228. 3,
  144229. 0,
  144230. 4,
  144231. };
  144232. static long _vq_lengthlist__44u4__p4_0[] = {
  144233. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144234. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144235. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144236. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144237. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144238. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144239. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  144240. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  144241. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144242. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144243. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144244. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144245. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144246. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  144247. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144248. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144249. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144250. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144251. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144252. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144253. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144254. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144255. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144256. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144257. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144258. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  144259. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  144260. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  144261. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  144262. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  144263. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  144264. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144265. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144266. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  144267. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144268. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  144269. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144270. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  144271. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  144272. 13,
  144273. };
  144274. static float _vq_quantthresh__44u4__p4_0[] = {
  144275. -1.5, -0.5, 0.5, 1.5,
  144276. };
  144277. static long _vq_quantmap__44u4__p4_0[] = {
  144278. 3, 1, 0, 2, 4,
  144279. };
  144280. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  144281. _vq_quantthresh__44u4__p4_0,
  144282. _vq_quantmap__44u4__p4_0,
  144283. 5,
  144284. 5
  144285. };
  144286. static static_codebook _44u4__p4_0 = {
  144287. 4, 625,
  144288. _vq_lengthlist__44u4__p4_0,
  144289. 1, -533725184, 1611661312, 3, 0,
  144290. _vq_quantlist__44u4__p4_0,
  144291. NULL,
  144292. &_vq_auxt__44u4__p4_0,
  144293. NULL,
  144294. 0
  144295. };
  144296. static long _vq_quantlist__44u4__p5_0[] = {
  144297. 4,
  144298. 3,
  144299. 5,
  144300. 2,
  144301. 6,
  144302. 1,
  144303. 7,
  144304. 0,
  144305. 8,
  144306. };
  144307. static long _vq_lengthlist__44u4__p5_0[] = {
  144308. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  144309. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  144310. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  144311. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144312. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  144313. 12,
  144314. };
  144315. static float _vq_quantthresh__44u4__p5_0[] = {
  144316. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144317. };
  144318. static long _vq_quantmap__44u4__p5_0[] = {
  144319. 7, 5, 3, 1, 0, 2, 4, 6,
  144320. 8,
  144321. };
  144322. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  144323. _vq_quantthresh__44u4__p5_0,
  144324. _vq_quantmap__44u4__p5_0,
  144325. 9,
  144326. 9
  144327. };
  144328. static static_codebook _44u4__p5_0 = {
  144329. 2, 81,
  144330. _vq_lengthlist__44u4__p5_0,
  144331. 1, -531628032, 1611661312, 4, 0,
  144332. _vq_quantlist__44u4__p5_0,
  144333. NULL,
  144334. &_vq_auxt__44u4__p5_0,
  144335. NULL,
  144336. 0
  144337. };
  144338. static long _vq_quantlist__44u4__p6_0[] = {
  144339. 6,
  144340. 5,
  144341. 7,
  144342. 4,
  144343. 8,
  144344. 3,
  144345. 9,
  144346. 2,
  144347. 10,
  144348. 1,
  144349. 11,
  144350. 0,
  144351. 12,
  144352. };
  144353. static long _vq_lengthlist__44u4__p6_0[] = {
  144354. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  144355. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  144356. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144357. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  144358. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  144359. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  144360. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  144361. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  144362. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  144363. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  144364. 16,16,16,17,17,18,17,20,21,
  144365. };
  144366. static float _vq_quantthresh__44u4__p6_0[] = {
  144367. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144368. 12.5, 17.5, 22.5, 27.5,
  144369. };
  144370. static long _vq_quantmap__44u4__p6_0[] = {
  144371. 11, 9, 7, 5, 3, 1, 0, 2,
  144372. 4, 6, 8, 10, 12,
  144373. };
  144374. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  144375. _vq_quantthresh__44u4__p6_0,
  144376. _vq_quantmap__44u4__p6_0,
  144377. 13,
  144378. 13
  144379. };
  144380. static static_codebook _44u4__p6_0 = {
  144381. 2, 169,
  144382. _vq_lengthlist__44u4__p6_0,
  144383. 1, -526516224, 1616117760, 4, 0,
  144384. _vq_quantlist__44u4__p6_0,
  144385. NULL,
  144386. &_vq_auxt__44u4__p6_0,
  144387. NULL,
  144388. 0
  144389. };
  144390. static long _vq_quantlist__44u4__p6_1[] = {
  144391. 2,
  144392. 1,
  144393. 3,
  144394. 0,
  144395. 4,
  144396. };
  144397. static long _vq_lengthlist__44u4__p6_1[] = {
  144398. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144399. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144400. };
  144401. static float _vq_quantthresh__44u4__p6_1[] = {
  144402. -1.5, -0.5, 0.5, 1.5,
  144403. };
  144404. static long _vq_quantmap__44u4__p6_1[] = {
  144405. 3, 1, 0, 2, 4,
  144406. };
  144407. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  144408. _vq_quantthresh__44u4__p6_1,
  144409. _vq_quantmap__44u4__p6_1,
  144410. 5,
  144411. 5
  144412. };
  144413. static static_codebook _44u4__p6_1 = {
  144414. 2, 25,
  144415. _vq_lengthlist__44u4__p6_1,
  144416. 1, -533725184, 1611661312, 3, 0,
  144417. _vq_quantlist__44u4__p6_1,
  144418. NULL,
  144419. &_vq_auxt__44u4__p6_1,
  144420. NULL,
  144421. 0
  144422. };
  144423. static long _vq_quantlist__44u4__p7_0[] = {
  144424. 6,
  144425. 5,
  144426. 7,
  144427. 4,
  144428. 8,
  144429. 3,
  144430. 9,
  144431. 2,
  144432. 10,
  144433. 1,
  144434. 11,
  144435. 0,
  144436. 12,
  144437. };
  144438. static long _vq_lengthlist__44u4__p7_0[] = {
  144439. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  144440. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  144441. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144442. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144443. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144444. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144445. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144446. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144447. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144448. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144449. 11,11,11,11,11,11,11,11,11,
  144450. };
  144451. static float _vq_quantthresh__44u4__p7_0[] = {
  144452. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144453. 637.5, 892.5, 1147.5, 1402.5,
  144454. };
  144455. static long _vq_quantmap__44u4__p7_0[] = {
  144456. 11, 9, 7, 5, 3, 1, 0, 2,
  144457. 4, 6, 8, 10, 12,
  144458. };
  144459. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  144460. _vq_quantthresh__44u4__p7_0,
  144461. _vq_quantmap__44u4__p7_0,
  144462. 13,
  144463. 13
  144464. };
  144465. static static_codebook _44u4__p7_0 = {
  144466. 2, 169,
  144467. _vq_lengthlist__44u4__p7_0,
  144468. 1, -514332672, 1627381760, 4, 0,
  144469. _vq_quantlist__44u4__p7_0,
  144470. NULL,
  144471. &_vq_auxt__44u4__p7_0,
  144472. NULL,
  144473. 0
  144474. };
  144475. static long _vq_quantlist__44u4__p7_1[] = {
  144476. 7,
  144477. 6,
  144478. 8,
  144479. 5,
  144480. 9,
  144481. 4,
  144482. 10,
  144483. 3,
  144484. 11,
  144485. 2,
  144486. 12,
  144487. 1,
  144488. 13,
  144489. 0,
  144490. 14,
  144491. };
  144492. static long _vq_lengthlist__44u4__p7_1[] = {
  144493. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  144494. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  144495. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  144496. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  144497. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  144498. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  144499. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  144500. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  144501. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  144502. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  144503. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  144504. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  144505. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  144506. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  144507. 16,
  144508. };
  144509. static float _vq_quantthresh__44u4__p7_1[] = {
  144510. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144511. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144512. };
  144513. static long _vq_quantmap__44u4__p7_1[] = {
  144514. 13, 11, 9, 7, 5, 3, 1, 0,
  144515. 2, 4, 6, 8, 10, 12, 14,
  144516. };
  144517. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  144518. _vq_quantthresh__44u4__p7_1,
  144519. _vq_quantmap__44u4__p7_1,
  144520. 15,
  144521. 15
  144522. };
  144523. static static_codebook _44u4__p7_1 = {
  144524. 2, 225,
  144525. _vq_lengthlist__44u4__p7_1,
  144526. 1, -522338304, 1620115456, 4, 0,
  144527. _vq_quantlist__44u4__p7_1,
  144528. NULL,
  144529. &_vq_auxt__44u4__p7_1,
  144530. NULL,
  144531. 0
  144532. };
  144533. static long _vq_quantlist__44u4__p7_2[] = {
  144534. 8,
  144535. 7,
  144536. 9,
  144537. 6,
  144538. 10,
  144539. 5,
  144540. 11,
  144541. 4,
  144542. 12,
  144543. 3,
  144544. 13,
  144545. 2,
  144546. 14,
  144547. 1,
  144548. 15,
  144549. 0,
  144550. 16,
  144551. };
  144552. static long _vq_lengthlist__44u4__p7_2[] = {
  144553. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144554. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144555. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144556. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144557. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144558. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144559. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144560. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144561. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  144562. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  144563. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144564. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  144565. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144566. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  144567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  144568. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144569. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144570. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  144571. 10,
  144572. };
  144573. static float _vq_quantthresh__44u4__p7_2[] = {
  144574. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144575. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144576. };
  144577. static long _vq_quantmap__44u4__p7_2[] = {
  144578. 15, 13, 11, 9, 7, 5, 3, 1,
  144579. 0, 2, 4, 6, 8, 10, 12, 14,
  144580. 16,
  144581. };
  144582. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  144583. _vq_quantthresh__44u4__p7_2,
  144584. _vq_quantmap__44u4__p7_2,
  144585. 17,
  144586. 17
  144587. };
  144588. static static_codebook _44u4__p7_2 = {
  144589. 2, 289,
  144590. _vq_lengthlist__44u4__p7_2,
  144591. 1, -529530880, 1611661312, 5, 0,
  144592. _vq_quantlist__44u4__p7_2,
  144593. NULL,
  144594. &_vq_auxt__44u4__p7_2,
  144595. NULL,
  144596. 0
  144597. };
  144598. static long _huff_lengthlist__44u4__short[] = {
  144599. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  144600. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  144601. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  144602. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  144603. };
  144604. static static_codebook _huff_book__44u4__short = {
  144605. 2, 64,
  144606. _huff_lengthlist__44u4__short,
  144607. 0, 0, 0, 0, 0,
  144608. NULL,
  144609. NULL,
  144610. NULL,
  144611. NULL,
  144612. 0
  144613. };
  144614. static long _huff_lengthlist__44u5__long[] = {
  144615. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  144616. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  144617. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  144618. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  144619. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  144620. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  144621. 14, 8, 7, 8,
  144622. };
  144623. static static_codebook _huff_book__44u5__long = {
  144624. 2, 100,
  144625. _huff_lengthlist__44u5__long,
  144626. 0, 0, 0, 0, 0,
  144627. NULL,
  144628. NULL,
  144629. NULL,
  144630. NULL,
  144631. 0
  144632. };
  144633. static long _vq_quantlist__44u5__p1_0[] = {
  144634. 1,
  144635. 0,
  144636. 2,
  144637. };
  144638. static long _vq_lengthlist__44u5__p1_0[] = {
  144639. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144640. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  144641. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144642. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  144643. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  144644. 12,
  144645. };
  144646. static float _vq_quantthresh__44u5__p1_0[] = {
  144647. -0.5, 0.5,
  144648. };
  144649. static long _vq_quantmap__44u5__p1_0[] = {
  144650. 1, 0, 2,
  144651. };
  144652. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  144653. _vq_quantthresh__44u5__p1_0,
  144654. _vq_quantmap__44u5__p1_0,
  144655. 3,
  144656. 3
  144657. };
  144658. static static_codebook _44u5__p1_0 = {
  144659. 4, 81,
  144660. _vq_lengthlist__44u5__p1_0,
  144661. 1, -535822336, 1611661312, 2, 0,
  144662. _vq_quantlist__44u5__p1_0,
  144663. NULL,
  144664. &_vq_auxt__44u5__p1_0,
  144665. NULL,
  144666. 0
  144667. };
  144668. static long _vq_quantlist__44u5__p2_0[] = {
  144669. 1,
  144670. 0,
  144671. 2,
  144672. };
  144673. static long _vq_lengthlist__44u5__p2_0[] = {
  144674. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144675. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144676. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  144677. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144678. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144679. 9,
  144680. };
  144681. static float _vq_quantthresh__44u5__p2_0[] = {
  144682. -0.5, 0.5,
  144683. };
  144684. static long _vq_quantmap__44u5__p2_0[] = {
  144685. 1, 0, 2,
  144686. };
  144687. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  144688. _vq_quantthresh__44u5__p2_0,
  144689. _vq_quantmap__44u5__p2_0,
  144690. 3,
  144691. 3
  144692. };
  144693. static static_codebook _44u5__p2_0 = {
  144694. 4, 81,
  144695. _vq_lengthlist__44u5__p2_0,
  144696. 1, -535822336, 1611661312, 2, 0,
  144697. _vq_quantlist__44u5__p2_0,
  144698. NULL,
  144699. &_vq_auxt__44u5__p2_0,
  144700. NULL,
  144701. 0
  144702. };
  144703. static long _vq_quantlist__44u5__p3_0[] = {
  144704. 2,
  144705. 1,
  144706. 3,
  144707. 0,
  144708. 4,
  144709. };
  144710. static long _vq_lengthlist__44u5__p3_0[] = {
  144711. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144712. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144713. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144714. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  144715. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  144716. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  144717. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144718. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  144719. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  144720. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  144721. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  144722. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  144723. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  144724. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  144725. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  144726. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  144727. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144728. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  144729. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  144730. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  144731. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  144732. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  144733. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  144734. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  144735. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  144736. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  144737. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  144738. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  144739. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  144740. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  144741. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  144742. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  144743. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  144744. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  144745. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  144746. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  144747. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  144748. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  144749. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  144750. 0,
  144751. };
  144752. static float _vq_quantthresh__44u5__p3_0[] = {
  144753. -1.5, -0.5, 0.5, 1.5,
  144754. };
  144755. static long _vq_quantmap__44u5__p3_0[] = {
  144756. 3, 1, 0, 2, 4,
  144757. };
  144758. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  144759. _vq_quantthresh__44u5__p3_0,
  144760. _vq_quantmap__44u5__p3_0,
  144761. 5,
  144762. 5
  144763. };
  144764. static static_codebook _44u5__p3_0 = {
  144765. 4, 625,
  144766. _vq_lengthlist__44u5__p3_0,
  144767. 1, -533725184, 1611661312, 3, 0,
  144768. _vq_quantlist__44u5__p3_0,
  144769. NULL,
  144770. &_vq_auxt__44u5__p3_0,
  144771. NULL,
  144772. 0
  144773. };
  144774. static long _vq_quantlist__44u5__p4_0[] = {
  144775. 2,
  144776. 1,
  144777. 3,
  144778. 0,
  144779. 4,
  144780. };
  144781. static long _vq_lengthlist__44u5__p4_0[] = {
  144782. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144783. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  144784. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  144785. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144786. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  144787. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144788. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144789. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  144790. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  144791. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  144792. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  144793. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144794. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144795. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  144796. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  144797. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  144798. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  144799. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144800. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  144801. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  144802. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  144803. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  144804. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  144805. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  144806. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  144807. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144808. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  144809. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  144810. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  144811. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  144812. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  144813. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144814. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  144815. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  144816. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  144817. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  144818. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  144819. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  144820. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  144821. 12,
  144822. };
  144823. static float _vq_quantthresh__44u5__p4_0[] = {
  144824. -1.5, -0.5, 0.5, 1.5,
  144825. };
  144826. static long _vq_quantmap__44u5__p4_0[] = {
  144827. 3, 1, 0, 2, 4,
  144828. };
  144829. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  144830. _vq_quantthresh__44u5__p4_0,
  144831. _vq_quantmap__44u5__p4_0,
  144832. 5,
  144833. 5
  144834. };
  144835. static static_codebook _44u5__p4_0 = {
  144836. 4, 625,
  144837. _vq_lengthlist__44u5__p4_0,
  144838. 1, -533725184, 1611661312, 3, 0,
  144839. _vq_quantlist__44u5__p4_0,
  144840. NULL,
  144841. &_vq_auxt__44u5__p4_0,
  144842. NULL,
  144843. 0
  144844. };
  144845. static long _vq_quantlist__44u5__p5_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__p5_0[] = {
  144857. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144858. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  144859. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  144860. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  144861. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  144862. 14,
  144863. };
  144864. static float _vq_quantthresh__44u5__p5_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__p5_0[] = {
  144868. 7, 5, 3, 1, 0, 2, 4, 6,
  144869. 8,
  144870. };
  144871. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  144872. _vq_quantthresh__44u5__p5_0,
  144873. _vq_quantmap__44u5__p5_0,
  144874. 9,
  144875. 9
  144876. };
  144877. static static_codebook _44u5__p5_0 = {
  144878. 2, 81,
  144879. _vq_lengthlist__44u5__p5_0,
  144880. 1, -531628032, 1611661312, 4, 0,
  144881. _vq_quantlist__44u5__p5_0,
  144882. NULL,
  144883. &_vq_auxt__44u5__p5_0,
  144884. NULL,
  144885. 0
  144886. };
  144887. static long _vq_quantlist__44u5__p6_0[] = {
  144888. 4,
  144889. 3,
  144890. 5,
  144891. 2,
  144892. 6,
  144893. 1,
  144894. 7,
  144895. 0,
  144896. 8,
  144897. };
  144898. static long _vq_lengthlist__44u5__p6_0[] = {
  144899. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144900. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144901. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144902. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144903. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  144904. 11,
  144905. };
  144906. static float _vq_quantthresh__44u5__p6_0[] = {
  144907. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144908. };
  144909. static long _vq_quantmap__44u5__p6_0[] = {
  144910. 7, 5, 3, 1, 0, 2, 4, 6,
  144911. 8,
  144912. };
  144913. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  144914. _vq_quantthresh__44u5__p6_0,
  144915. _vq_quantmap__44u5__p6_0,
  144916. 9,
  144917. 9
  144918. };
  144919. static static_codebook _44u5__p6_0 = {
  144920. 2, 81,
  144921. _vq_lengthlist__44u5__p6_0,
  144922. 1, -531628032, 1611661312, 4, 0,
  144923. _vq_quantlist__44u5__p6_0,
  144924. NULL,
  144925. &_vq_auxt__44u5__p6_0,
  144926. NULL,
  144927. 0
  144928. };
  144929. static long _vq_quantlist__44u5__p7_0[] = {
  144930. 1,
  144931. 0,
  144932. 2,
  144933. };
  144934. static long _vq_lengthlist__44u5__p7_0[] = {
  144935. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  144936. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  144937. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  144938. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  144939. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  144940. 12,
  144941. };
  144942. static float _vq_quantthresh__44u5__p7_0[] = {
  144943. -5.5, 5.5,
  144944. };
  144945. static long _vq_quantmap__44u5__p7_0[] = {
  144946. 1, 0, 2,
  144947. };
  144948. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  144949. _vq_quantthresh__44u5__p7_0,
  144950. _vq_quantmap__44u5__p7_0,
  144951. 3,
  144952. 3
  144953. };
  144954. static static_codebook _44u5__p7_0 = {
  144955. 4, 81,
  144956. _vq_lengthlist__44u5__p7_0,
  144957. 1, -529137664, 1618345984, 2, 0,
  144958. _vq_quantlist__44u5__p7_0,
  144959. NULL,
  144960. &_vq_auxt__44u5__p7_0,
  144961. NULL,
  144962. 0
  144963. };
  144964. static long _vq_quantlist__44u5__p7_1[] = {
  144965. 5,
  144966. 4,
  144967. 6,
  144968. 3,
  144969. 7,
  144970. 2,
  144971. 8,
  144972. 1,
  144973. 9,
  144974. 0,
  144975. 10,
  144976. };
  144977. static long _vq_lengthlist__44u5__p7_1[] = {
  144978. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144979. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  144980. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144981. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  144982. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144983. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144984. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144985. 9, 9, 9, 9, 9,10,10,10,10,
  144986. };
  144987. static float _vq_quantthresh__44u5__p7_1[] = {
  144988. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144989. 3.5, 4.5,
  144990. };
  144991. static long _vq_quantmap__44u5__p7_1[] = {
  144992. 9, 7, 5, 3, 1, 0, 2, 4,
  144993. 6, 8, 10,
  144994. };
  144995. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  144996. _vq_quantthresh__44u5__p7_1,
  144997. _vq_quantmap__44u5__p7_1,
  144998. 11,
  144999. 11
  145000. };
  145001. static static_codebook _44u5__p7_1 = {
  145002. 2, 121,
  145003. _vq_lengthlist__44u5__p7_1,
  145004. 1, -531365888, 1611661312, 4, 0,
  145005. _vq_quantlist__44u5__p7_1,
  145006. NULL,
  145007. &_vq_auxt__44u5__p7_1,
  145008. NULL,
  145009. 0
  145010. };
  145011. static long _vq_quantlist__44u5__p8_0[] = {
  145012. 5,
  145013. 4,
  145014. 6,
  145015. 3,
  145016. 7,
  145017. 2,
  145018. 8,
  145019. 1,
  145020. 9,
  145021. 0,
  145022. 10,
  145023. };
  145024. static long _vq_lengthlist__44u5__p8_0[] = {
  145025. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145026. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145027. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  145028. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  145029. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  145030. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  145031. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  145032. 12,13,13,14,14,14,14,15,15,
  145033. };
  145034. static float _vq_quantthresh__44u5__p8_0[] = {
  145035. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145036. 38.5, 49.5,
  145037. };
  145038. static long _vq_quantmap__44u5__p8_0[] = {
  145039. 9, 7, 5, 3, 1, 0, 2, 4,
  145040. 6, 8, 10,
  145041. };
  145042. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  145043. _vq_quantthresh__44u5__p8_0,
  145044. _vq_quantmap__44u5__p8_0,
  145045. 11,
  145046. 11
  145047. };
  145048. static static_codebook _44u5__p8_0 = {
  145049. 2, 121,
  145050. _vq_lengthlist__44u5__p8_0,
  145051. 1, -524582912, 1618345984, 4, 0,
  145052. _vq_quantlist__44u5__p8_0,
  145053. NULL,
  145054. &_vq_auxt__44u5__p8_0,
  145055. NULL,
  145056. 0
  145057. };
  145058. static long _vq_quantlist__44u5__p8_1[] = {
  145059. 5,
  145060. 4,
  145061. 6,
  145062. 3,
  145063. 7,
  145064. 2,
  145065. 8,
  145066. 1,
  145067. 9,
  145068. 0,
  145069. 10,
  145070. };
  145071. static long _vq_lengthlist__44u5__p8_1[] = {
  145072. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  145073. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  145074. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  145075. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145076. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  145077. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145078. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145079. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145080. };
  145081. static float _vq_quantthresh__44u5__p8_1[] = {
  145082. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145083. 3.5, 4.5,
  145084. };
  145085. static long _vq_quantmap__44u5__p8_1[] = {
  145086. 9, 7, 5, 3, 1, 0, 2, 4,
  145087. 6, 8, 10,
  145088. };
  145089. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  145090. _vq_quantthresh__44u5__p8_1,
  145091. _vq_quantmap__44u5__p8_1,
  145092. 11,
  145093. 11
  145094. };
  145095. static static_codebook _44u5__p8_1 = {
  145096. 2, 121,
  145097. _vq_lengthlist__44u5__p8_1,
  145098. 1, -531365888, 1611661312, 4, 0,
  145099. _vq_quantlist__44u5__p8_1,
  145100. NULL,
  145101. &_vq_auxt__44u5__p8_1,
  145102. NULL,
  145103. 0
  145104. };
  145105. static long _vq_quantlist__44u5__p9_0[] = {
  145106. 6,
  145107. 5,
  145108. 7,
  145109. 4,
  145110. 8,
  145111. 3,
  145112. 9,
  145113. 2,
  145114. 10,
  145115. 1,
  145116. 11,
  145117. 0,
  145118. 12,
  145119. };
  145120. static long _vq_lengthlist__44u5__p9_0[] = {
  145121. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  145122. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  145123. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  145124. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  145125. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145126. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145127. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145128. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  145129. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  145130. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145131. 12,12,12,12,12,12,12,12,12,
  145132. };
  145133. static float _vq_quantthresh__44u5__p9_0[] = {
  145134. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  145135. 637.5, 892.5, 1147.5, 1402.5,
  145136. };
  145137. static long _vq_quantmap__44u5__p9_0[] = {
  145138. 11, 9, 7, 5, 3, 1, 0, 2,
  145139. 4, 6, 8, 10, 12,
  145140. };
  145141. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  145142. _vq_quantthresh__44u5__p9_0,
  145143. _vq_quantmap__44u5__p9_0,
  145144. 13,
  145145. 13
  145146. };
  145147. static static_codebook _44u5__p9_0 = {
  145148. 2, 169,
  145149. _vq_lengthlist__44u5__p9_0,
  145150. 1, -514332672, 1627381760, 4, 0,
  145151. _vq_quantlist__44u5__p9_0,
  145152. NULL,
  145153. &_vq_auxt__44u5__p9_0,
  145154. NULL,
  145155. 0
  145156. };
  145157. static long _vq_quantlist__44u5__p9_1[] = {
  145158. 7,
  145159. 6,
  145160. 8,
  145161. 5,
  145162. 9,
  145163. 4,
  145164. 10,
  145165. 3,
  145166. 11,
  145167. 2,
  145168. 12,
  145169. 1,
  145170. 13,
  145171. 0,
  145172. 14,
  145173. };
  145174. static long _vq_lengthlist__44u5__p9_1[] = {
  145175. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  145176. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  145177. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  145178. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  145179. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  145180. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  145181. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  145182. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  145183. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  145184. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  145185. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  145186. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  145187. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  145188. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  145189. 14,
  145190. };
  145191. static float _vq_quantthresh__44u5__p9_1[] = {
  145192. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145193. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145194. };
  145195. static long _vq_quantmap__44u5__p9_1[] = {
  145196. 13, 11, 9, 7, 5, 3, 1, 0,
  145197. 2, 4, 6, 8, 10, 12, 14,
  145198. };
  145199. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  145200. _vq_quantthresh__44u5__p9_1,
  145201. _vq_quantmap__44u5__p9_1,
  145202. 15,
  145203. 15
  145204. };
  145205. static static_codebook _44u5__p9_1 = {
  145206. 2, 225,
  145207. _vq_lengthlist__44u5__p9_1,
  145208. 1, -522338304, 1620115456, 4, 0,
  145209. _vq_quantlist__44u5__p9_1,
  145210. NULL,
  145211. &_vq_auxt__44u5__p9_1,
  145212. NULL,
  145213. 0
  145214. };
  145215. static long _vq_quantlist__44u5__p9_2[] = {
  145216. 8,
  145217. 7,
  145218. 9,
  145219. 6,
  145220. 10,
  145221. 5,
  145222. 11,
  145223. 4,
  145224. 12,
  145225. 3,
  145226. 13,
  145227. 2,
  145228. 14,
  145229. 1,
  145230. 15,
  145231. 0,
  145232. 16,
  145233. };
  145234. static long _vq_lengthlist__44u5__p9_2[] = {
  145235. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145236. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145237. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145238. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145239. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145240. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145241. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145242. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145243. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145244. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  145245. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  145246. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145247. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145248. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145249. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145250. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145251. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145252. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  145253. 10,
  145254. };
  145255. static float _vq_quantthresh__44u5__p9_2[] = {
  145256. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145257. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145258. };
  145259. static long _vq_quantmap__44u5__p9_2[] = {
  145260. 15, 13, 11, 9, 7, 5, 3, 1,
  145261. 0, 2, 4, 6, 8, 10, 12, 14,
  145262. 16,
  145263. };
  145264. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  145265. _vq_quantthresh__44u5__p9_2,
  145266. _vq_quantmap__44u5__p9_2,
  145267. 17,
  145268. 17
  145269. };
  145270. static static_codebook _44u5__p9_2 = {
  145271. 2, 289,
  145272. _vq_lengthlist__44u5__p9_2,
  145273. 1, -529530880, 1611661312, 5, 0,
  145274. _vq_quantlist__44u5__p9_2,
  145275. NULL,
  145276. &_vq_auxt__44u5__p9_2,
  145277. NULL,
  145278. 0
  145279. };
  145280. static long _huff_lengthlist__44u5__short[] = {
  145281. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  145282. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  145283. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  145284. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  145285. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  145286. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  145287. 6, 8,15,17,
  145288. };
  145289. static static_codebook _huff_book__44u5__short = {
  145290. 2, 100,
  145291. _huff_lengthlist__44u5__short,
  145292. 0, 0, 0, 0, 0,
  145293. NULL,
  145294. NULL,
  145295. NULL,
  145296. NULL,
  145297. 0
  145298. };
  145299. static long _huff_lengthlist__44u6__long[] = {
  145300. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  145301. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  145302. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  145303. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  145304. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  145305. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  145306. 13, 8, 7, 7,
  145307. };
  145308. static static_codebook _huff_book__44u6__long = {
  145309. 2, 100,
  145310. _huff_lengthlist__44u6__long,
  145311. 0, 0, 0, 0, 0,
  145312. NULL,
  145313. NULL,
  145314. NULL,
  145315. NULL,
  145316. 0
  145317. };
  145318. static long _vq_quantlist__44u6__p1_0[] = {
  145319. 1,
  145320. 0,
  145321. 2,
  145322. };
  145323. static long _vq_lengthlist__44u6__p1_0[] = {
  145324. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145325. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  145326. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145327. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  145328. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  145329. 12,
  145330. };
  145331. static float _vq_quantthresh__44u6__p1_0[] = {
  145332. -0.5, 0.5,
  145333. };
  145334. static long _vq_quantmap__44u6__p1_0[] = {
  145335. 1, 0, 2,
  145336. };
  145337. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  145338. _vq_quantthresh__44u6__p1_0,
  145339. _vq_quantmap__44u6__p1_0,
  145340. 3,
  145341. 3
  145342. };
  145343. static static_codebook _44u6__p1_0 = {
  145344. 4, 81,
  145345. _vq_lengthlist__44u6__p1_0,
  145346. 1, -535822336, 1611661312, 2, 0,
  145347. _vq_quantlist__44u6__p1_0,
  145348. NULL,
  145349. &_vq_auxt__44u6__p1_0,
  145350. NULL,
  145351. 0
  145352. };
  145353. static long _vq_quantlist__44u6__p2_0[] = {
  145354. 1,
  145355. 0,
  145356. 2,
  145357. };
  145358. static long _vq_lengthlist__44u6__p2_0[] = {
  145359. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145360. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145361. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  145362. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145363. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145364. 9,
  145365. };
  145366. static float _vq_quantthresh__44u6__p2_0[] = {
  145367. -0.5, 0.5,
  145368. };
  145369. static long _vq_quantmap__44u6__p2_0[] = {
  145370. 1, 0, 2,
  145371. };
  145372. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  145373. _vq_quantthresh__44u6__p2_0,
  145374. _vq_quantmap__44u6__p2_0,
  145375. 3,
  145376. 3
  145377. };
  145378. static static_codebook _44u6__p2_0 = {
  145379. 4, 81,
  145380. _vq_lengthlist__44u6__p2_0,
  145381. 1, -535822336, 1611661312, 2, 0,
  145382. _vq_quantlist__44u6__p2_0,
  145383. NULL,
  145384. &_vq_auxt__44u6__p2_0,
  145385. NULL,
  145386. 0
  145387. };
  145388. static long _vq_quantlist__44u6__p3_0[] = {
  145389. 2,
  145390. 1,
  145391. 3,
  145392. 0,
  145393. 4,
  145394. };
  145395. static long _vq_lengthlist__44u6__p3_0[] = {
  145396. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145397. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145398. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145399. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  145400. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  145401. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  145402. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  145403. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  145404. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  145405. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  145406. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  145407. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  145408. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  145409. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  145410. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  145411. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  145412. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  145413. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145414. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  145415. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  145416. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  145417. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  145418. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  145419. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  145420. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  145421. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  145422. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  145423. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  145424. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  145425. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  145426. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  145427. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  145428. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  145429. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  145430. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  145431. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  145432. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  145433. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  145434. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  145435. 19,
  145436. };
  145437. static float _vq_quantthresh__44u6__p3_0[] = {
  145438. -1.5, -0.5, 0.5, 1.5,
  145439. };
  145440. static long _vq_quantmap__44u6__p3_0[] = {
  145441. 3, 1, 0, 2, 4,
  145442. };
  145443. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  145444. _vq_quantthresh__44u6__p3_0,
  145445. _vq_quantmap__44u6__p3_0,
  145446. 5,
  145447. 5
  145448. };
  145449. static static_codebook _44u6__p3_0 = {
  145450. 4, 625,
  145451. _vq_lengthlist__44u6__p3_0,
  145452. 1, -533725184, 1611661312, 3, 0,
  145453. _vq_quantlist__44u6__p3_0,
  145454. NULL,
  145455. &_vq_auxt__44u6__p3_0,
  145456. NULL,
  145457. 0
  145458. };
  145459. static long _vq_quantlist__44u6__p4_0[] = {
  145460. 2,
  145461. 1,
  145462. 3,
  145463. 0,
  145464. 4,
  145465. };
  145466. static long _vq_lengthlist__44u6__p4_0[] = {
  145467. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145468. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145469. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145470. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  145471. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145472. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  145473. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145474. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  145475. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145476. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145477. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  145478. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145479. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145480. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  145481. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  145482. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  145483. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  145484. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145485. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  145486. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  145487. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  145488. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  145489. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  145490. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145491. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  145492. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145493. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  145494. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  145495. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  145496. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  145497. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  145498. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145499. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  145500. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  145501. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145502. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  145503. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  145504. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  145505. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  145506. 13,
  145507. };
  145508. static float _vq_quantthresh__44u6__p4_0[] = {
  145509. -1.5, -0.5, 0.5, 1.5,
  145510. };
  145511. static long _vq_quantmap__44u6__p4_0[] = {
  145512. 3, 1, 0, 2, 4,
  145513. };
  145514. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  145515. _vq_quantthresh__44u6__p4_0,
  145516. _vq_quantmap__44u6__p4_0,
  145517. 5,
  145518. 5
  145519. };
  145520. static static_codebook _44u6__p4_0 = {
  145521. 4, 625,
  145522. _vq_lengthlist__44u6__p4_0,
  145523. 1, -533725184, 1611661312, 3, 0,
  145524. _vq_quantlist__44u6__p4_0,
  145525. NULL,
  145526. &_vq_auxt__44u6__p4_0,
  145527. NULL,
  145528. 0
  145529. };
  145530. static long _vq_quantlist__44u6__p5_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__p5_0[] = {
  145542. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145543. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  145544. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  145545. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  145546. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  145547. 14,
  145548. };
  145549. static float _vq_quantthresh__44u6__p5_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__p5_0[] = {
  145553. 7, 5, 3, 1, 0, 2, 4, 6,
  145554. 8,
  145555. };
  145556. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  145557. _vq_quantthresh__44u6__p5_0,
  145558. _vq_quantmap__44u6__p5_0,
  145559. 9,
  145560. 9
  145561. };
  145562. static static_codebook _44u6__p5_0 = {
  145563. 2, 81,
  145564. _vq_lengthlist__44u6__p5_0,
  145565. 1, -531628032, 1611661312, 4, 0,
  145566. _vq_quantlist__44u6__p5_0,
  145567. NULL,
  145568. &_vq_auxt__44u6__p5_0,
  145569. NULL,
  145570. 0
  145571. };
  145572. static long _vq_quantlist__44u6__p6_0[] = {
  145573. 4,
  145574. 3,
  145575. 5,
  145576. 2,
  145577. 6,
  145578. 1,
  145579. 7,
  145580. 0,
  145581. 8,
  145582. };
  145583. static long _vq_lengthlist__44u6__p6_0[] = {
  145584. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145585. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  145586. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  145587. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  145588. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  145589. 12,
  145590. };
  145591. static float _vq_quantthresh__44u6__p6_0[] = {
  145592. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145593. };
  145594. static long _vq_quantmap__44u6__p6_0[] = {
  145595. 7, 5, 3, 1, 0, 2, 4, 6,
  145596. 8,
  145597. };
  145598. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  145599. _vq_quantthresh__44u6__p6_0,
  145600. _vq_quantmap__44u6__p6_0,
  145601. 9,
  145602. 9
  145603. };
  145604. static static_codebook _44u6__p6_0 = {
  145605. 2, 81,
  145606. _vq_lengthlist__44u6__p6_0,
  145607. 1, -531628032, 1611661312, 4, 0,
  145608. _vq_quantlist__44u6__p6_0,
  145609. NULL,
  145610. &_vq_auxt__44u6__p6_0,
  145611. NULL,
  145612. 0
  145613. };
  145614. static long _vq_quantlist__44u6__p7_0[] = {
  145615. 1,
  145616. 0,
  145617. 2,
  145618. };
  145619. static long _vq_lengthlist__44u6__p7_0[] = {
  145620. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  145621. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  145622. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  145623. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  145624. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  145625. 10,
  145626. };
  145627. static float _vq_quantthresh__44u6__p7_0[] = {
  145628. -5.5, 5.5,
  145629. };
  145630. static long _vq_quantmap__44u6__p7_0[] = {
  145631. 1, 0, 2,
  145632. };
  145633. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  145634. _vq_quantthresh__44u6__p7_0,
  145635. _vq_quantmap__44u6__p7_0,
  145636. 3,
  145637. 3
  145638. };
  145639. static static_codebook _44u6__p7_0 = {
  145640. 4, 81,
  145641. _vq_lengthlist__44u6__p7_0,
  145642. 1, -529137664, 1618345984, 2, 0,
  145643. _vq_quantlist__44u6__p7_0,
  145644. NULL,
  145645. &_vq_auxt__44u6__p7_0,
  145646. NULL,
  145647. 0
  145648. };
  145649. static long _vq_quantlist__44u6__p7_1[] = {
  145650. 5,
  145651. 4,
  145652. 6,
  145653. 3,
  145654. 7,
  145655. 2,
  145656. 8,
  145657. 1,
  145658. 9,
  145659. 0,
  145660. 10,
  145661. };
  145662. static long _vq_lengthlist__44u6__p7_1[] = {
  145663. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  145664. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  145665. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145666. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  145667. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  145668. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  145669. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  145670. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145671. };
  145672. static float _vq_quantthresh__44u6__p7_1[] = {
  145673. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145674. 3.5, 4.5,
  145675. };
  145676. static long _vq_quantmap__44u6__p7_1[] = {
  145677. 9, 7, 5, 3, 1, 0, 2, 4,
  145678. 6, 8, 10,
  145679. };
  145680. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  145681. _vq_quantthresh__44u6__p7_1,
  145682. _vq_quantmap__44u6__p7_1,
  145683. 11,
  145684. 11
  145685. };
  145686. static static_codebook _44u6__p7_1 = {
  145687. 2, 121,
  145688. _vq_lengthlist__44u6__p7_1,
  145689. 1, -531365888, 1611661312, 4, 0,
  145690. _vq_quantlist__44u6__p7_1,
  145691. NULL,
  145692. &_vq_auxt__44u6__p7_1,
  145693. NULL,
  145694. 0
  145695. };
  145696. static long _vq_quantlist__44u6__p8_0[] = {
  145697. 5,
  145698. 4,
  145699. 6,
  145700. 3,
  145701. 7,
  145702. 2,
  145703. 8,
  145704. 1,
  145705. 9,
  145706. 0,
  145707. 10,
  145708. };
  145709. static long _vq_lengthlist__44u6__p8_0[] = {
  145710. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145711. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145712. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  145713. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  145714. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  145715. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  145716. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  145717. 12,13,13,14,14,14,15,15,15,
  145718. };
  145719. static float _vq_quantthresh__44u6__p8_0[] = {
  145720. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145721. 38.5, 49.5,
  145722. };
  145723. static long _vq_quantmap__44u6__p8_0[] = {
  145724. 9, 7, 5, 3, 1, 0, 2, 4,
  145725. 6, 8, 10,
  145726. };
  145727. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  145728. _vq_quantthresh__44u6__p8_0,
  145729. _vq_quantmap__44u6__p8_0,
  145730. 11,
  145731. 11
  145732. };
  145733. static static_codebook _44u6__p8_0 = {
  145734. 2, 121,
  145735. _vq_lengthlist__44u6__p8_0,
  145736. 1, -524582912, 1618345984, 4, 0,
  145737. _vq_quantlist__44u6__p8_0,
  145738. NULL,
  145739. &_vq_auxt__44u6__p8_0,
  145740. NULL,
  145741. 0
  145742. };
  145743. static long _vq_quantlist__44u6__p8_1[] = {
  145744. 5,
  145745. 4,
  145746. 6,
  145747. 3,
  145748. 7,
  145749. 2,
  145750. 8,
  145751. 1,
  145752. 9,
  145753. 0,
  145754. 10,
  145755. };
  145756. static long _vq_lengthlist__44u6__p8_1[] = {
  145757. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  145758. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  145759. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  145760. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145761. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  145762. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145763. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145764. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145765. };
  145766. static float _vq_quantthresh__44u6__p8_1[] = {
  145767. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145768. 3.5, 4.5,
  145769. };
  145770. static long _vq_quantmap__44u6__p8_1[] = {
  145771. 9, 7, 5, 3, 1, 0, 2, 4,
  145772. 6, 8, 10,
  145773. };
  145774. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  145775. _vq_quantthresh__44u6__p8_1,
  145776. _vq_quantmap__44u6__p8_1,
  145777. 11,
  145778. 11
  145779. };
  145780. static static_codebook _44u6__p8_1 = {
  145781. 2, 121,
  145782. _vq_lengthlist__44u6__p8_1,
  145783. 1, -531365888, 1611661312, 4, 0,
  145784. _vq_quantlist__44u6__p8_1,
  145785. NULL,
  145786. &_vq_auxt__44u6__p8_1,
  145787. NULL,
  145788. 0
  145789. };
  145790. static long _vq_quantlist__44u6__p9_0[] = {
  145791. 7,
  145792. 6,
  145793. 8,
  145794. 5,
  145795. 9,
  145796. 4,
  145797. 10,
  145798. 3,
  145799. 11,
  145800. 2,
  145801. 12,
  145802. 1,
  145803. 13,
  145804. 0,
  145805. 14,
  145806. };
  145807. static long _vq_lengthlist__44u6__p9_0[] = {
  145808. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  145809. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  145810. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  145811. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  145812. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145813. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145814. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145815. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145816. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145817. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145818. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145819. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145820. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145821. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145822. 14,
  145823. };
  145824. static float _vq_quantthresh__44u6__p9_0[] = {
  145825. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145826. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145827. };
  145828. static long _vq_quantmap__44u6__p9_0[] = {
  145829. 13, 11, 9, 7, 5, 3, 1, 0,
  145830. 2, 4, 6, 8, 10, 12, 14,
  145831. };
  145832. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  145833. _vq_quantthresh__44u6__p9_0,
  145834. _vq_quantmap__44u6__p9_0,
  145835. 15,
  145836. 15
  145837. };
  145838. static static_codebook _44u6__p9_0 = {
  145839. 2, 225,
  145840. _vq_lengthlist__44u6__p9_0,
  145841. 1, -514071552, 1627381760, 4, 0,
  145842. _vq_quantlist__44u6__p9_0,
  145843. NULL,
  145844. &_vq_auxt__44u6__p9_0,
  145845. NULL,
  145846. 0
  145847. };
  145848. static long _vq_quantlist__44u6__p9_1[] = {
  145849. 7,
  145850. 6,
  145851. 8,
  145852. 5,
  145853. 9,
  145854. 4,
  145855. 10,
  145856. 3,
  145857. 11,
  145858. 2,
  145859. 12,
  145860. 1,
  145861. 13,
  145862. 0,
  145863. 14,
  145864. };
  145865. static long _vq_lengthlist__44u6__p9_1[] = {
  145866. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  145867. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  145868. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  145869. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  145870. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  145871. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  145872. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  145873. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  145874. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  145875. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  145876. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  145877. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  145878. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  145879. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  145880. 13,
  145881. };
  145882. static float _vq_quantthresh__44u6__p9_1[] = {
  145883. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145884. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145885. };
  145886. static long _vq_quantmap__44u6__p9_1[] = {
  145887. 13, 11, 9, 7, 5, 3, 1, 0,
  145888. 2, 4, 6, 8, 10, 12, 14,
  145889. };
  145890. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  145891. _vq_quantthresh__44u6__p9_1,
  145892. _vq_quantmap__44u6__p9_1,
  145893. 15,
  145894. 15
  145895. };
  145896. static static_codebook _44u6__p9_1 = {
  145897. 2, 225,
  145898. _vq_lengthlist__44u6__p9_1,
  145899. 1, -522338304, 1620115456, 4, 0,
  145900. _vq_quantlist__44u6__p9_1,
  145901. NULL,
  145902. &_vq_auxt__44u6__p9_1,
  145903. NULL,
  145904. 0
  145905. };
  145906. static long _vq_quantlist__44u6__p9_2[] = {
  145907. 8,
  145908. 7,
  145909. 9,
  145910. 6,
  145911. 10,
  145912. 5,
  145913. 11,
  145914. 4,
  145915. 12,
  145916. 3,
  145917. 13,
  145918. 2,
  145919. 14,
  145920. 1,
  145921. 15,
  145922. 0,
  145923. 16,
  145924. };
  145925. static long _vq_lengthlist__44u6__p9_2[] = {
  145926. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  145927. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145928. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  145929. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145930. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145931. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145932. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145933. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145934. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145935. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  145936. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  145937. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145938. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  145939. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  145940. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  145941. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  145942. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  145943. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  145944. 10,
  145945. };
  145946. static float _vq_quantthresh__44u6__p9_2[] = {
  145947. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145948. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145949. };
  145950. static long _vq_quantmap__44u6__p9_2[] = {
  145951. 15, 13, 11, 9, 7, 5, 3, 1,
  145952. 0, 2, 4, 6, 8, 10, 12, 14,
  145953. 16,
  145954. };
  145955. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  145956. _vq_quantthresh__44u6__p9_2,
  145957. _vq_quantmap__44u6__p9_2,
  145958. 17,
  145959. 17
  145960. };
  145961. static static_codebook _44u6__p9_2 = {
  145962. 2, 289,
  145963. _vq_lengthlist__44u6__p9_2,
  145964. 1, -529530880, 1611661312, 5, 0,
  145965. _vq_quantlist__44u6__p9_2,
  145966. NULL,
  145967. &_vq_auxt__44u6__p9_2,
  145968. NULL,
  145969. 0
  145970. };
  145971. static long _huff_lengthlist__44u6__short[] = {
  145972. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  145973. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  145974. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  145975. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  145976. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  145977. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  145978. 7, 6, 9,16,
  145979. };
  145980. static static_codebook _huff_book__44u6__short = {
  145981. 2, 100,
  145982. _huff_lengthlist__44u6__short,
  145983. 0, 0, 0, 0, 0,
  145984. NULL,
  145985. NULL,
  145986. NULL,
  145987. NULL,
  145988. 0
  145989. };
  145990. static long _huff_lengthlist__44u7__long[] = {
  145991. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  145992. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  145993. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  145994. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  145995. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  145996. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  145997. 12, 8, 6, 7,
  145998. };
  145999. static static_codebook _huff_book__44u7__long = {
  146000. 2, 100,
  146001. _huff_lengthlist__44u7__long,
  146002. 0, 0, 0, 0, 0,
  146003. NULL,
  146004. NULL,
  146005. NULL,
  146006. NULL,
  146007. 0
  146008. };
  146009. static long _vq_quantlist__44u7__p1_0[] = {
  146010. 1,
  146011. 0,
  146012. 2,
  146013. };
  146014. static long _vq_lengthlist__44u7__p1_0[] = {
  146015. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  146016. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  146017. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  146018. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  146019. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  146020. 12,
  146021. };
  146022. static float _vq_quantthresh__44u7__p1_0[] = {
  146023. -0.5, 0.5,
  146024. };
  146025. static long _vq_quantmap__44u7__p1_0[] = {
  146026. 1, 0, 2,
  146027. };
  146028. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  146029. _vq_quantthresh__44u7__p1_0,
  146030. _vq_quantmap__44u7__p1_0,
  146031. 3,
  146032. 3
  146033. };
  146034. static static_codebook _44u7__p1_0 = {
  146035. 4, 81,
  146036. _vq_lengthlist__44u7__p1_0,
  146037. 1, -535822336, 1611661312, 2, 0,
  146038. _vq_quantlist__44u7__p1_0,
  146039. NULL,
  146040. &_vq_auxt__44u7__p1_0,
  146041. NULL,
  146042. 0
  146043. };
  146044. static long _vq_quantlist__44u7__p2_0[] = {
  146045. 1,
  146046. 0,
  146047. 2,
  146048. };
  146049. static long _vq_lengthlist__44u7__p2_0[] = {
  146050. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  146051. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  146052. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  146053. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  146054. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  146055. 9,
  146056. };
  146057. static float _vq_quantthresh__44u7__p2_0[] = {
  146058. -0.5, 0.5,
  146059. };
  146060. static long _vq_quantmap__44u7__p2_0[] = {
  146061. 1, 0, 2,
  146062. };
  146063. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  146064. _vq_quantthresh__44u7__p2_0,
  146065. _vq_quantmap__44u7__p2_0,
  146066. 3,
  146067. 3
  146068. };
  146069. static static_codebook _44u7__p2_0 = {
  146070. 4, 81,
  146071. _vq_lengthlist__44u7__p2_0,
  146072. 1, -535822336, 1611661312, 2, 0,
  146073. _vq_quantlist__44u7__p2_0,
  146074. NULL,
  146075. &_vq_auxt__44u7__p2_0,
  146076. NULL,
  146077. 0
  146078. };
  146079. static long _vq_quantlist__44u7__p3_0[] = {
  146080. 2,
  146081. 1,
  146082. 3,
  146083. 0,
  146084. 4,
  146085. };
  146086. static long _vq_lengthlist__44u7__p3_0[] = {
  146087. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146088. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  146089. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  146090. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  146091. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  146092. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  146093. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  146094. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  146095. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  146096. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146097. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  146098. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146099. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  146100. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  146101. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  146102. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  146103. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  146104. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  146105. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  146106. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  146107. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  146108. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  146109. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  146110. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  146111. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  146112. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  146113. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  146114. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  146115. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  146116. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  146117. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  146118. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  146119. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  146120. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  146121. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  146122. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  146123. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  146124. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  146125. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  146126. 0,
  146127. };
  146128. static float _vq_quantthresh__44u7__p3_0[] = {
  146129. -1.5, -0.5, 0.5, 1.5,
  146130. };
  146131. static long _vq_quantmap__44u7__p3_0[] = {
  146132. 3, 1, 0, 2, 4,
  146133. };
  146134. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  146135. _vq_quantthresh__44u7__p3_0,
  146136. _vq_quantmap__44u7__p3_0,
  146137. 5,
  146138. 5
  146139. };
  146140. static static_codebook _44u7__p3_0 = {
  146141. 4, 625,
  146142. _vq_lengthlist__44u7__p3_0,
  146143. 1, -533725184, 1611661312, 3, 0,
  146144. _vq_quantlist__44u7__p3_0,
  146145. NULL,
  146146. &_vq_auxt__44u7__p3_0,
  146147. NULL,
  146148. 0
  146149. };
  146150. static long _vq_quantlist__44u7__p4_0[] = {
  146151. 2,
  146152. 1,
  146153. 3,
  146154. 0,
  146155. 4,
  146156. };
  146157. static long _vq_lengthlist__44u7__p4_0[] = {
  146158. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  146159. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  146160. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  146161. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  146162. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  146163. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  146164. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  146165. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  146166. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  146167. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  146168. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  146169. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  146170. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  146171. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  146172. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  146173. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146174. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  146175. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146176. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  146177. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  146178. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146179. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146180. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  146181. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146182. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  146183. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  146184. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146185. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  146186. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  146187. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  146188. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  146189. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146190. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  146191. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146192. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  146193. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146194. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  146195. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  146196. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  146197. 14,
  146198. };
  146199. static float _vq_quantthresh__44u7__p4_0[] = {
  146200. -1.5, -0.5, 0.5, 1.5,
  146201. };
  146202. static long _vq_quantmap__44u7__p4_0[] = {
  146203. 3, 1, 0, 2, 4,
  146204. };
  146205. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  146206. _vq_quantthresh__44u7__p4_0,
  146207. _vq_quantmap__44u7__p4_0,
  146208. 5,
  146209. 5
  146210. };
  146211. static static_codebook _44u7__p4_0 = {
  146212. 4, 625,
  146213. _vq_lengthlist__44u7__p4_0,
  146214. 1, -533725184, 1611661312, 3, 0,
  146215. _vq_quantlist__44u7__p4_0,
  146216. NULL,
  146217. &_vq_auxt__44u7__p4_0,
  146218. NULL,
  146219. 0
  146220. };
  146221. static long _vq_quantlist__44u7__p5_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__p5_0[] = {
  146233. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146234. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  146235. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  146236. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  146237. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  146238. 14,
  146239. };
  146240. static float _vq_quantthresh__44u7__p5_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__p5_0[] = {
  146244. 7, 5, 3, 1, 0, 2, 4, 6,
  146245. 8,
  146246. };
  146247. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  146248. _vq_quantthresh__44u7__p5_0,
  146249. _vq_quantmap__44u7__p5_0,
  146250. 9,
  146251. 9
  146252. };
  146253. static static_codebook _44u7__p5_0 = {
  146254. 2, 81,
  146255. _vq_lengthlist__44u7__p5_0,
  146256. 1, -531628032, 1611661312, 4, 0,
  146257. _vq_quantlist__44u7__p5_0,
  146258. NULL,
  146259. &_vq_auxt__44u7__p5_0,
  146260. NULL,
  146261. 0
  146262. };
  146263. static long _vq_quantlist__44u7__p6_0[] = {
  146264. 4,
  146265. 3,
  146266. 5,
  146267. 2,
  146268. 6,
  146269. 1,
  146270. 7,
  146271. 0,
  146272. 8,
  146273. };
  146274. static long _vq_lengthlist__44u7__p6_0[] = {
  146275. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  146276. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146277. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146278. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  146279. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  146280. 12,
  146281. };
  146282. static float _vq_quantthresh__44u7__p6_0[] = {
  146283. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146284. };
  146285. static long _vq_quantmap__44u7__p6_0[] = {
  146286. 7, 5, 3, 1, 0, 2, 4, 6,
  146287. 8,
  146288. };
  146289. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  146290. _vq_quantthresh__44u7__p6_0,
  146291. _vq_quantmap__44u7__p6_0,
  146292. 9,
  146293. 9
  146294. };
  146295. static static_codebook _44u7__p6_0 = {
  146296. 2, 81,
  146297. _vq_lengthlist__44u7__p6_0,
  146298. 1, -531628032, 1611661312, 4, 0,
  146299. _vq_quantlist__44u7__p6_0,
  146300. NULL,
  146301. &_vq_auxt__44u7__p6_0,
  146302. NULL,
  146303. 0
  146304. };
  146305. static long _vq_quantlist__44u7__p7_0[] = {
  146306. 1,
  146307. 0,
  146308. 2,
  146309. };
  146310. static long _vq_lengthlist__44u7__p7_0[] = {
  146311. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  146312. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  146313. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  146314. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  146315. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  146316. 10,
  146317. };
  146318. static float _vq_quantthresh__44u7__p7_0[] = {
  146319. -5.5, 5.5,
  146320. };
  146321. static long _vq_quantmap__44u7__p7_0[] = {
  146322. 1, 0, 2,
  146323. };
  146324. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  146325. _vq_quantthresh__44u7__p7_0,
  146326. _vq_quantmap__44u7__p7_0,
  146327. 3,
  146328. 3
  146329. };
  146330. static static_codebook _44u7__p7_0 = {
  146331. 4, 81,
  146332. _vq_lengthlist__44u7__p7_0,
  146333. 1, -529137664, 1618345984, 2, 0,
  146334. _vq_quantlist__44u7__p7_0,
  146335. NULL,
  146336. &_vq_auxt__44u7__p7_0,
  146337. NULL,
  146338. 0
  146339. };
  146340. static long _vq_quantlist__44u7__p7_1[] = {
  146341. 5,
  146342. 4,
  146343. 6,
  146344. 3,
  146345. 7,
  146346. 2,
  146347. 8,
  146348. 1,
  146349. 9,
  146350. 0,
  146351. 10,
  146352. };
  146353. static long _vq_lengthlist__44u7__p7_1[] = {
  146354. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  146355. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  146356. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  146357. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  146358. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  146359. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146360. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  146361. 8, 9, 9, 9, 9, 9,10,10,10,
  146362. };
  146363. static float _vq_quantthresh__44u7__p7_1[] = {
  146364. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146365. 3.5, 4.5,
  146366. };
  146367. static long _vq_quantmap__44u7__p7_1[] = {
  146368. 9, 7, 5, 3, 1, 0, 2, 4,
  146369. 6, 8, 10,
  146370. };
  146371. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  146372. _vq_quantthresh__44u7__p7_1,
  146373. _vq_quantmap__44u7__p7_1,
  146374. 11,
  146375. 11
  146376. };
  146377. static static_codebook _44u7__p7_1 = {
  146378. 2, 121,
  146379. _vq_lengthlist__44u7__p7_1,
  146380. 1, -531365888, 1611661312, 4, 0,
  146381. _vq_quantlist__44u7__p7_1,
  146382. NULL,
  146383. &_vq_auxt__44u7__p7_1,
  146384. NULL,
  146385. 0
  146386. };
  146387. static long _vq_quantlist__44u7__p8_0[] = {
  146388. 5,
  146389. 4,
  146390. 6,
  146391. 3,
  146392. 7,
  146393. 2,
  146394. 8,
  146395. 1,
  146396. 9,
  146397. 0,
  146398. 10,
  146399. };
  146400. static long _vq_lengthlist__44u7__p8_0[] = {
  146401. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146402. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  146403. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  146404. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  146405. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  146406. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  146407. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  146408. 12,13,13,14,14,15,15,15,16,
  146409. };
  146410. static float _vq_quantthresh__44u7__p8_0[] = {
  146411. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146412. 38.5, 49.5,
  146413. };
  146414. static long _vq_quantmap__44u7__p8_0[] = {
  146415. 9, 7, 5, 3, 1, 0, 2, 4,
  146416. 6, 8, 10,
  146417. };
  146418. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  146419. _vq_quantthresh__44u7__p8_0,
  146420. _vq_quantmap__44u7__p8_0,
  146421. 11,
  146422. 11
  146423. };
  146424. static static_codebook _44u7__p8_0 = {
  146425. 2, 121,
  146426. _vq_lengthlist__44u7__p8_0,
  146427. 1, -524582912, 1618345984, 4, 0,
  146428. _vq_quantlist__44u7__p8_0,
  146429. NULL,
  146430. &_vq_auxt__44u7__p8_0,
  146431. NULL,
  146432. 0
  146433. };
  146434. static long _vq_quantlist__44u7__p8_1[] = {
  146435. 5,
  146436. 4,
  146437. 6,
  146438. 3,
  146439. 7,
  146440. 2,
  146441. 8,
  146442. 1,
  146443. 9,
  146444. 0,
  146445. 10,
  146446. };
  146447. static long _vq_lengthlist__44u7__p8_1[] = {
  146448. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  146449. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  146450. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  146451. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146452. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146453. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  146454. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  146455. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  146456. };
  146457. static float _vq_quantthresh__44u7__p8_1[] = {
  146458. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146459. 3.5, 4.5,
  146460. };
  146461. static long _vq_quantmap__44u7__p8_1[] = {
  146462. 9, 7, 5, 3, 1, 0, 2, 4,
  146463. 6, 8, 10,
  146464. };
  146465. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  146466. _vq_quantthresh__44u7__p8_1,
  146467. _vq_quantmap__44u7__p8_1,
  146468. 11,
  146469. 11
  146470. };
  146471. static static_codebook _44u7__p8_1 = {
  146472. 2, 121,
  146473. _vq_lengthlist__44u7__p8_1,
  146474. 1, -531365888, 1611661312, 4, 0,
  146475. _vq_quantlist__44u7__p8_1,
  146476. NULL,
  146477. &_vq_auxt__44u7__p8_1,
  146478. NULL,
  146479. 0
  146480. };
  146481. static long _vq_quantlist__44u7__p9_0[] = {
  146482. 5,
  146483. 4,
  146484. 6,
  146485. 3,
  146486. 7,
  146487. 2,
  146488. 8,
  146489. 1,
  146490. 9,
  146491. 0,
  146492. 10,
  146493. };
  146494. static long _vq_lengthlist__44u7__p9_0[] = {
  146495. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  146496. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  146497. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146499. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146500. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146501. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146502. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146503. };
  146504. static float _vq_quantthresh__44u7__p9_0[] = {
  146505. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  146506. 2229.5, 2866.5,
  146507. };
  146508. static long _vq_quantmap__44u7__p9_0[] = {
  146509. 9, 7, 5, 3, 1, 0, 2, 4,
  146510. 6, 8, 10,
  146511. };
  146512. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  146513. _vq_quantthresh__44u7__p9_0,
  146514. _vq_quantmap__44u7__p9_0,
  146515. 11,
  146516. 11
  146517. };
  146518. static static_codebook _44u7__p9_0 = {
  146519. 2, 121,
  146520. _vq_lengthlist__44u7__p9_0,
  146521. 1, -512171520, 1630791680, 4, 0,
  146522. _vq_quantlist__44u7__p9_0,
  146523. NULL,
  146524. &_vq_auxt__44u7__p9_0,
  146525. NULL,
  146526. 0
  146527. };
  146528. static long _vq_quantlist__44u7__p9_1[] = {
  146529. 6,
  146530. 5,
  146531. 7,
  146532. 4,
  146533. 8,
  146534. 3,
  146535. 9,
  146536. 2,
  146537. 10,
  146538. 1,
  146539. 11,
  146540. 0,
  146541. 12,
  146542. };
  146543. static long _vq_lengthlist__44u7__p9_1[] = {
  146544. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  146545. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  146546. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  146547. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  146548. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  146549. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  146550. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  146551. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  146552. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  146553. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  146554. 15,15,15,15,17,17,16,17,16,
  146555. };
  146556. static float _vq_quantthresh__44u7__p9_1[] = {
  146557. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  146558. 122.5, 171.5, 220.5, 269.5,
  146559. };
  146560. static long _vq_quantmap__44u7__p9_1[] = {
  146561. 11, 9, 7, 5, 3, 1, 0, 2,
  146562. 4, 6, 8, 10, 12,
  146563. };
  146564. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  146565. _vq_quantthresh__44u7__p9_1,
  146566. _vq_quantmap__44u7__p9_1,
  146567. 13,
  146568. 13
  146569. };
  146570. static static_codebook _44u7__p9_1 = {
  146571. 2, 169,
  146572. _vq_lengthlist__44u7__p9_1,
  146573. 1, -518889472, 1622704128, 4, 0,
  146574. _vq_quantlist__44u7__p9_1,
  146575. NULL,
  146576. &_vq_auxt__44u7__p9_1,
  146577. NULL,
  146578. 0
  146579. };
  146580. static long _vq_quantlist__44u7__p9_2[] = {
  146581. 24,
  146582. 23,
  146583. 25,
  146584. 22,
  146585. 26,
  146586. 21,
  146587. 27,
  146588. 20,
  146589. 28,
  146590. 19,
  146591. 29,
  146592. 18,
  146593. 30,
  146594. 17,
  146595. 31,
  146596. 16,
  146597. 32,
  146598. 15,
  146599. 33,
  146600. 14,
  146601. 34,
  146602. 13,
  146603. 35,
  146604. 12,
  146605. 36,
  146606. 11,
  146607. 37,
  146608. 10,
  146609. 38,
  146610. 9,
  146611. 39,
  146612. 8,
  146613. 40,
  146614. 7,
  146615. 41,
  146616. 6,
  146617. 42,
  146618. 5,
  146619. 43,
  146620. 4,
  146621. 44,
  146622. 3,
  146623. 45,
  146624. 2,
  146625. 46,
  146626. 1,
  146627. 47,
  146628. 0,
  146629. 48,
  146630. };
  146631. static long _vq_lengthlist__44u7__p9_2[] = {
  146632. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  146633. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146634. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  146635. 8,
  146636. };
  146637. static float _vq_quantthresh__44u7__p9_2[] = {
  146638. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146639. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146640. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146641. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146642. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146643. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146644. };
  146645. static long _vq_quantmap__44u7__p9_2[] = {
  146646. 47, 45, 43, 41, 39, 37, 35, 33,
  146647. 31, 29, 27, 25, 23, 21, 19, 17,
  146648. 15, 13, 11, 9, 7, 5, 3, 1,
  146649. 0, 2, 4, 6, 8, 10, 12, 14,
  146650. 16, 18, 20, 22, 24, 26, 28, 30,
  146651. 32, 34, 36, 38, 40, 42, 44, 46,
  146652. 48,
  146653. };
  146654. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  146655. _vq_quantthresh__44u7__p9_2,
  146656. _vq_quantmap__44u7__p9_2,
  146657. 49,
  146658. 49
  146659. };
  146660. static static_codebook _44u7__p9_2 = {
  146661. 1, 49,
  146662. _vq_lengthlist__44u7__p9_2,
  146663. 1, -526909440, 1611661312, 6, 0,
  146664. _vq_quantlist__44u7__p9_2,
  146665. NULL,
  146666. &_vq_auxt__44u7__p9_2,
  146667. NULL,
  146668. 0
  146669. };
  146670. static long _huff_lengthlist__44u7__short[] = {
  146671. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  146672. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  146673. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  146674. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  146675. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  146676. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  146677. 6, 8, 5, 9,
  146678. };
  146679. static static_codebook _huff_book__44u7__short = {
  146680. 2, 100,
  146681. _huff_lengthlist__44u7__short,
  146682. 0, 0, 0, 0, 0,
  146683. NULL,
  146684. NULL,
  146685. NULL,
  146686. NULL,
  146687. 0
  146688. };
  146689. static long _huff_lengthlist__44u8__long[] = {
  146690. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  146691. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  146692. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  146693. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  146694. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  146695. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  146696. 10, 8, 8, 9,
  146697. };
  146698. static static_codebook _huff_book__44u8__long = {
  146699. 2, 100,
  146700. _huff_lengthlist__44u8__long,
  146701. 0, 0, 0, 0, 0,
  146702. NULL,
  146703. NULL,
  146704. NULL,
  146705. NULL,
  146706. 0
  146707. };
  146708. static long _huff_lengthlist__44u8__short[] = {
  146709. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  146710. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  146711. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  146712. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  146713. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  146714. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  146715. 10,10,15,17,
  146716. };
  146717. static static_codebook _huff_book__44u8__short = {
  146718. 2, 100,
  146719. _huff_lengthlist__44u8__short,
  146720. 0, 0, 0, 0, 0,
  146721. NULL,
  146722. NULL,
  146723. NULL,
  146724. NULL,
  146725. 0
  146726. };
  146727. static long _vq_quantlist__44u8_p1_0[] = {
  146728. 1,
  146729. 0,
  146730. 2,
  146731. };
  146732. static long _vq_lengthlist__44u8_p1_0[] = {
  146733. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  146734. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  146735. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  146736. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  146737. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  146738. 10,
  146739. };
  146740. static float _vq_quantthresh__44u8_p1_0[] = {
  146741. -0.5, 0.5,
  146742. };
  146743. static long _vq_quantmap__44u8_p1_0[] = {
  146744. 1, 0, 2,
  146745. };
  146746. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  146747. _vq_quantthresh__44u8_p1_0,
  146748. _vq_quantmap__44u8_p1_0,
  146749. 3,
  146750. 3
  146751. };
  146752. static static_codebook _44u8_p1_0 = {
  146753. 4, 81,
  146754. _vq_lengthlist__44u8_p1_0,
  146755. 1, -535822336, 1611661312, 2, 0,
  146756. _vq_quantlist__44u8_p1_0,
  146757. NULL,
  146758. &_vq_auxt__44u8_p1_0,
  146759. NULL,
  146760. 0
  146761. };
  146762. static long _vq_quantlist__44u8_p2_0[] = {
  146763. 2,
  146764. 1,
  146765. 3,
  146766. 0,
  146767. 4,
  146768. };
  146769. static long _vq_lengthlist__44u8_p2_0[] = {
  146770. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146771. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146772. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  146773. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  146774. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  146775. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  146776. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146777. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  146778. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146779. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146780. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  146781. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146782. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  146783. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  146784. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  146785. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  146786. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  146787. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  146788. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  146789. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  146790. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  146791. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  146792. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  146793. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146794. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  146795. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146796. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  146797. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  146798. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  146799. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  146800. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  146801. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146802. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  146803. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  146804. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146805. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  146806. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  146807. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  146808. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  146809. 14,
  146810. };
  146811. static float _vq_quantthresh__44u8_p2_0[] = {
  146812. -1.5, -0.5, 0.5, 1.5,
  146813. };
  146814. static long _vq_quantmap__44u8_p2_0[] = {
  146815. 3, 1, 0, 2, 4,
  146816. };
  146817. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  146818. _vq_quantthresh__44u8_p2_0,
  146819. _vq_quantmap__44u8_p2_0,
  146820. 5,
  146821. 5
  146822. };
  146823. static static_codebook _44u8_p2_0 = {
  146824. 4, 625,
  146825. _vq_lengthlist__44u8_p2_0,
  146826. 1, -533725184, 1611661312, 3, 0,
  146827. _vq_quantlist__44u8_p2_0,
  146828. NULL,
  146829. &_vq_auxt__44u8_p2_0,
  146830. NULL,
  146831. 0
  146832. };
  146833. static long _vq_quantlist__44u8_p3_0[] = {
  146834. 4,
  146835. 3,
  146836. 5,
  146837. 2,
  146838. 6,
  146839. 1,
  146840. 7,
  146841. 0,
  146842. 8,
  146843. };
  146844. static long _vq_lengthlist__44u8_p3_0[] = {
  146845. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146846. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146847. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  146848. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  146849. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  146850. 12,
  146851. };
  146852. static float _vq_quantthresh__44u8_p3_0[] = {
  146853. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146854. };
  146855. static long _vq_quantmap__44u8_p3_0[] = {
  146856. 7, 5, 3, 1, 0, 2, 4, 6,
  146857. 8,
  146858. };
  146859. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  146860. _vq_quantthresh__44u8_p3_0,
  146861. _vq_quantmap__44u8_p3_0,
  146862. 9,
  146863. 9
  146864. };
  146865. static static_codebook _44u8_p3_0 = {
  146866. 2, 81,
  146867. _vq_lengthlist__44u8_p3_0,
  146868. 1, -531628032, 1611661312, 4, 0,
  146869. _vq_quantlist__44u8_p3_0,
  146870. NULL,
  146871. &_vq_auxt__44u8_p3_0,
  146872. NULL,
  146873. 0
  146874. };
  146875. static long _vq_quantlist__44u8_p4_0[] = {
  146876. 8,
  146877. 7,
  146878. 9,
  146879. 6,
  146880. 10,
  146881. 5,
  146882. 11,
  146883. 4,
  146884. 12,
  146885. 3,
  146886. 13,
  146887. 2,
  146888. 14,
  146889. 1,
  146890. 15,
  146891. 0,
  146892. 16,
  146893. };
  146894. static long _vq_lengthlist__44u8_p4_0[] = {
  146895. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  146896. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  146897. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  146898. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  146899. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  146900. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  146901. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  146902. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  146903. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  146904. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  146905. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  146906. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  146907. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  146908. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  146909. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  146910. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  146911. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  146912. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  146913. 14,
  146914. };
  146915. static float _vq_quantthresh__44u8_p4_0[] = {
  146916. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146917. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146918. };
  146919. static long _vq_quantmap__44u8_p4_0[] = {
  146920. 15, 13, 11, 9, 7, 5, 3, 1,
  146921. 0, 2, 4, 6, 8, 10, 12, 14,
  146922. 16,
  146923. };
  146924. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  146925. _vq_quantthresh__44u8_p4_0,
  146926. _vq_quantmap__44u8_p4_0,
  146927. 17,
  146928. 17
  146929. };
  146930. static static_codebook _44u8_p4_0 = {
  146931. 2, 289,
  146932. _vq_lengthlist__44u8_p4_0,
  146933. 1, -529530880, 1611661312, 5, 0,
  146934. _vq_quantlist__44u8_p4_0,
  146935. NULL,
  146936. &_vq_auxt__44u8_p4_0,
  146937. NULL,
  146938. 0
  146939. };
  146940. static long _vq_quantlist__44u8_p5_0[] = {
  146941. 1,
  146942. 0,
  146943. 2,
  146944. };
  146945. static long _vq_lengthlist__44u8_p5_0[] = {
  146946. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146947. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146948. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  146949. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146950. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146951. 10,
  146952. };
  146953. static float _vq_quantthresh__44u8_p5_0[] = {
  146954. -5.5, 5.5,
  146955. };
  146956. static long _vq_quantmap__44u8_p5_0[] = {
  146957. 1, 0, 2,
  146958. };
  146959. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  146960. _vq_quantthresh__44u8_p5_0,
  146961. _vq_quantmap__44u8_p5_0,
  146962. 3,
  146963. 3
  146964. };
  146965. static static_codebook _44u8_p5_0 = {
  146966. 4, 81,
  146967. _vq_lengthlist__44u8_p5_0,
  146968. 1, -529137664, 1618345984, 2, 0,
  146969. _vq_quantlist__44u8_p5_0,
  146970. NULL,
  146971. &_vq_auxt__44u8_p5_0,
  146972. NULL,
  146973. 0
  146974. };
  146975. static long _vq_quantlist__44u8_p5_1[] = {
  146976. 5,
  146977. 4,
  146978. 6,
  146979. 3,
  146980. 7,
  146981. 2,
  146982. 8,
  146983. 1,
  146984. 9,
  146985. 0,
  146986. 10,
  146987. };
  146988. static long _vq_lengthlist__44u8_p5_1[] = {
  146989. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  146990. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  146991. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  146992. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146993. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  146994. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146995. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  146996. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  146997. };
  146998. static float _vq_quantthresh__44u8_p5_1[] = {
  146999. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147000. 3.5, 4.5,
  147001. };
  147002. static long _vq_quantmap__44u8_p5_1[] = {
  147003. 9, 7, 5, 3, 1, 0, 2, 4,
  147004. 6, 8, 10,
  147005. };
  147006. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  147007. _vq_quantthresh__44u8_p5_1,
  147008. _vq_quantmap__44u8_p5_1,
  147009. 11,
  147010. 11
  147011. };
  147012. static static_codebook _44u8_p5_1 = {
  147013. 2, 121,
  147014. _vq_lengthlist__44u8_p5_1,
  147015. 1, -531365888, 1611661312, 4, 0,
  147016. _vq_quantlist__44u8_p5_1,
  147017. NULL,
  147018. &_vq_auxt__44u8_p5_1,
  147019. NULL,
  147020. 0
  147021. };
  147022. static long _vq_quantlist__44u8_p6_0[] = {
  147023. 6,
  147024. 5,
  147025. 7,
  147026. 4,
  147027. 8,
  147028. 3,
  147029. 9,
  147030. 2,
  147031. 10,
  147032. 1,
  147033. 11,
  147034. 0,
  147035. 12,
  147036. };
  147037. static long _vq_lengthlist__44u8_p6_0[] = {
  147038. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147039. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  147040. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  147041. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  147042. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  147043. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147044. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147045. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  147046. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  147047. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147048. 11,11,11,11,11,12,11,12,12,
  147049. };
  147050. static float _vq_quantthresh__44u8_p6_0[] = {
  147051. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147052. 12.5, 17.5, 22.5, 27.5,
  147053. };
  147054. static long _vq_quantmap__44u8_p6_0[] = {
  147055. 11, 9, 7, 5, 3, 1, 0, 2,
  147056. 4, 6, 8, 10, 12,
  147057. };
  147058. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  147059. _vq_quantthresh__44u8_p6_0,
  147060. _vq_quantmap__44u8_p6_0,
  147061. 13,
  147062. 13
  147063. };
  147064. static static_codebook _44u8_p6_0 = {
  147065. 2, 169,
  147066. _vq_lengthlist__44u8_p6_0,
  147067. 1, -526516224, 1616117760, 4, 0,
  147068. _vq_quantlist__44u8_p6_0,
  147069. NULL,
  147070. &_vq_auxt__44u8_p6_0,
  147071. NULL,
  147072. 0
  147073. };
  147074. static long _vq_quantlist__44u8_p6_1[] = {
  147075. 2,
  147076. 1,
  147077. 3,
  147078. 0,
  147079. 4,
  147080. };
  147081. static long _vq_lengthlist__44u8_p6_1[] = {
  147082. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147083. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147084. };
  147085. static float _vq_quantthresh__44u8_p6_1[] = {
  147086. -1.5, -0.5, 0.5, 1.5,
  147087. };
  147088. static long _vq_quantmap__44u8_p6_1[] = {
  147089. 3, 1, 0, 2, 4,
  147090. };
  147091. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  147092. _vq_quantthresh__44u8_p6_1,
  147093. _vq_quantmap__44u8_p6_1,
  147094. 5,
  147095. 5
  147096. };
  147097. static static_codebook _44u8_p6_1 = {
  147098. 2, 25,
  147099. _vq_lengthlist__44u8_p6_1,
  147100. 1, -533725184, 1611661312, 3, 0,
  147101. _vq_quantlist__44u8_p6_1,
  147102. NULL,
  147103. &_vq_auxt__44u8_p6_1,
  147104. NULL,
  147105. 0
  147106. };
  147107. static long _vq_quantlist__44u8_p7_0[] = {
  147108. 6,
  147109. 5,
  147110. 7,
  147111. 4,
  147112. 8,
  147113. 3,
  147114. 9,
  147115. 2,
  147116. 10,
  147117. 1,
  147118. 11,
  147119. 0,
  147120. 12,
  147121. };
  147122. static long _vq_lengthlist__44u8_p7_0[] = {
  147123. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  147124. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  147125. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  147126. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  147127. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147128. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147129. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  147130. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  147131. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  147132. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  147133. 13,13,14,14,14,15,15,15,16,
  147134. };
  147135. static float _vq_quantthresh__44u8_p7_0[] = {
  147136. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147137. 27.5, 38.5, 49.5, 60.5,
  147138. };
  147139. static long _vq_quantmap__44u8_p7_0[] = {
  147140. 11, 9, 7, 5, 3, 1, 0, 2,
  147141. 4, 6, 8, 10, 12,
  147142. };
  147143. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  147144. _vq_quantthresh__44u8_p7_0,
  147145. _vq_quantmap__44u8_p7_0,
  147146. 13,
  147147. 13
  147148. };
  147149. static static_codebook _44u8_p7_0 = {
  147150. 2, 169,
  147151. _vq_lengthlist__44u8_p7_0,
  147152. 1, -523206656, 1618345984, 4, 0,
  147153. _vq_quantlist__44u8_p7_0,
  147154. NULL,
  147155. &_vq_auxt__44u8_p7_0,
  147156. NULL,
  147157. 0
  147158. };
  147159. static long _vq_quantlist__44u8_p7_1[] = {
  147160. 5,
  147161. 4,
  147162. 6,
  147163. 3,
  147164. 7,
  147165. 2,
  147166. 8,
  147167. 1,
  147168. 9,
  147169. 0,
  147170. 10,
  147171. };
  147172. static long _vq_lengthlist__44u8_p7_1[] = {
  147173. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147174. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147175. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147176. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  147177. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  147178. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147179. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147180. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147181. };
  147182. static float _vq_quantthresh__44u8_p7_1[] = {
  147183. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147184. 3.5, 4.5,
  147185. };
  147186. static long _vq_quantmap__44u8_p7_1[] = {
  147187. 9, 7, 5, 3, 1, 0, 2, 4,
  147188. 6, 8, 10,
  147189. };
  147190. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  147191. _vq_quantthresh__44u8_p7_1,
  147192. _vq_quantmap__44u8_p7_1,
  147193. 11,
  147194. 11
  147195. };
  147196. static static_codebook _44u8_p7_1 = {
  147197. 2, 121,
  147198. _vq_lengthlist__44u8_p7_1,
  147199. 1, -531365888, 1611661312, 4, 0,
  147200. _vq_quantlist__44u8_p7_1,
  147201. NULL,
  147202. &_vq_auxt__44u8_p7_1,
  147203. NULL,
  147204. 0
  147205. };
  147206. static long _vq_quantlist__44u8_p8_0[] = {
  147207. 7,
  147208. 6,
  147209. 8,
  147210. 5,
  147211. 9,
  147212. 4,
  147213. 10,
  147214. 3,
  147215. 11,
  147216. 2,
  147217. 12,
  147218. 1,
  147219. 13,
  147220. 0,
  147221. 14,
  147222. };
  147223. static long _vq_lengthlist__44u8_p8_0[] = {
  147224. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  147225. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147226. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  147227. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  147228. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  147229. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  147230. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  147231. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  147232. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  147233. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  147234. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  147235. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  147236. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  147237. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  147238. 17,
  147239. };
  147240. static float _vq_quantthresh__44u8_p8_0[] = {
  147241. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147242. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147243. };
  147244. static long _vq_quantmap__44u8_p8_0[] = {
  147245. 13, 11, 9, 7, 5, 3, 1, 0,
  147246. 2, 4, 6, 8, 10, 12, 14,
  147247. };
  147248. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  147249. _vq_quantthresh__44u8_p8_0,
  147250. _vq_quantmap__44u8_p8_0,
  147251. 15,
  147252. 15
  147253. };
  147254. static static_codebook _44u8_p8_0 = {
  147255. 2, 225,
  147256. _vq_lengthlist__44u8_p8_0,
  147257. 1, -520986624, 1620377600, 4, 0,
  147258. _vq_quantlist__44u8_p8_0,
  147259. NULL,
  147260. &_vq_auxt__44u8_p8_0,
  147261. NULL,
  147262. 0
  147263. };
  147264. static long _vq_quantlist__44u8_p8_1[] = {
  147265. 10,
  147266. 9,
  147267. 11,
  147268. 8,
  147269. 12,
  147270. 7,
  147271. 13,
  147272. 6,
  147273. 14,
  147274. 5,
  147275. 15,
  147276. 4,
  147277. 16,
  147278. 3,
  147279. 17,
  147280. 2,
  147281. 18,
  147282. 1,
  147283. 19,
  147284. 0,
  147285. 20,
  147286. };
  147287. static long _vq_lengthlist__44u8_p8_1[] = {
  147288. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147289. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147290. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  147291. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147292. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147293. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147294. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147295. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  147296. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147297. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147298. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  147299. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  147300. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147301. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147302. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147303. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147304. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  147305. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147306. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147307. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147308. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147309. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147310. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147311. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147312. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147313. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147314. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  147315. 10,10,10,10,10,10,10,10,10,
  147316. };
  147317. static float _vq_quantthresh__44u8_p8_1[] = {
  147318. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  147319. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  147320. 6.5, 7.5, 8.5, 9.5,
  147321. };
  147322. static long _vq_quantmap__44u8_p8_1[] = {
  147323. 19, 17, 15, 13, 11, 9, 7, 5,
  147324. 3, 1, 0, 2, 4, 6, 8, 10,
  147325. 12, 14, 16, 18, 20,
  147326. };
  147327. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  147328. _vq_quantthresh__44u8_p8_1,
  147329. _vq_quantmap__44u8_p8_1,
  147330. 21,
  147331. 21
  147332. };
  147333. static static_codebook _44u8_p8_1 = {
  147334. 2, 441,
  147335. _vq_lengthlist__44u8_p8_1,
  147336. 1, -529268736, 1611661312, 5, 0,
  147337. _vq_quantlist__44u8_p8_1,
  147338. NULL,
  147339. &_vq_auxt__44u8_p8_1,
  147340. NULL,
  147341. 0
  147342. };
  147343. static long _vq_quantlist__44u8_p9_0[] = {
  147344. 4,
  147345. 3,
  147346. 5,
  147347. 2,
  147348. 6,
  147349. 1,
  147350. 7,
  147351. 0,
  147352. 8,
  147353. };
  147354. static long _vq_lengthlist__44u8_p9_0[] = {
  147355. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  147356. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147357. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147358. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147359. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147360. 8,
  147361. };
  147362. static float _vq_quantthresh__44u8_p9_0[] = {
  147363. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  147364. };
  147365. static long _vq_quantmap__44u8_p9_0[] = {
  147366. 7, 5, 3, 1, 0, 2, 4, 6,
  147367. 8,
  147368. };
  147369. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  147370. _vq_quantthresh__44u8_p9_0,
  147371. _vq_quantmap__44u8_p9_0,
  147372. 9,
  147373. 9
  147374. };
  147375. static static_codebook _44u8_p9_0 = {
  147376. 2, 81,
  147377. _vq_lengthlist__44u8_p9_0,
  147378. 1, -511895552, 1631393792, 4, 0,
  147379. _vq_quantlist__44u8_p9_0,
  147380. NULL,
  147381. &_vq_auxt__44u8_p9_0,
  147382. NULL,
  147383. 0
  147384. };
  147385. static long _vq_quantlist__44u8_p9_1[] = {
  147386. 9,
  147387. 8,
  147388. 10,
  147389. 7,
  147390. 11,
  147391. 6,
  147392. 12,
  147393. 5,
  147394. 13,
  147395. 4,
  147396. 14,
  147397. 3,
  147398. 15,
  147399. 2,
  147400. 16,
  147401. 1,
  147402. 17,
  147403. 0,
  147404. 18,
  147405. };
  147406. static long _vq_lengthlist__44u8_p9_1[] = {
  147407. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  147408. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  147409. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  147410. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  147411. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  147412. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  147413. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  147414. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  147415. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  147416. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  147417. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  147418. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  147419. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  147420. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  147421. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  147422. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  147423. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  147424. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  147425. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  147426. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  147427. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  147428. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  147429. 16,15,16,16,16,16,16,16,16,
  147430. };
  147431. static float _vq_quantthresh__44u8_p9_1[] = {
  147432. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  147433. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  147434. 367.5, 416.5,
  147435. };
  147436. static long _vq_quantmap__44u8_p9_1[] = {
  147437. 17, 15, 13, 11, 9, 7, 5, 3,
  147438. 1, 0, 2, 4, 6, 8, 10, 12,
  147439. 14, 16, 18,
  147440. };
  147441. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  147442. _vq_quantthresh__44u8_p9_1,
  147443. _vq_quantmap__44u8_p9_1,
  147444. 19,
  147445. 19
  147446. };
  147447. static static_codebook _44u8_p9_1 = {
  147448. 2, 361,
  147449. _vq_lengthlist__44u8_p9_1,
  147450. 1, -518287360, 1622704128, 5, 0,
  147451. _vq_quantlist__44u8_p9_1,
  147452. NULL,
  147453. &_vq_auxt__44u8_p9_1,
  147454. NULL,
  147455. 0
  147456. };
  147457. static long _vq_quantlist__44u8_p9_2[] = {
  147458. 24,
  147459. 23,
  147460. 25,
  147461. 22,
  147462. 26,
  147463. 21,
  147464. 27,
  147465. 20,
  147466. 28,
  147467. 19,
  147468. 29,
  147469. 18,
  147470. 30,
  147471. 17,
  147472. 31,
  147473. 16,
  147474. 32,
  147475. 15,
  147476. 33,
  147477. 14,
  147478. 34,
  147479. 13,
  147480. 35,
  147481. 12,
  147482. 36,
  147483. 11,
  147484. 37,
  147485. 10,
  147486. 38,
  147487. 9,
  147488. 39,
  147489. 8,
  147490. 40,
  147491. 7,
  147492. 41,
  147493. 6,
  147494. 42,
  147495. 5,
  147496. 43,
  147497. 4,
  147498. 44,
  147499. 3,
  147500. 45,
  147501. 2,
  147502. 46,
  147503. 1,
  147504. 47,
  147505. 0,
  147506. 48,
  147507. };
  147508. static long _vq_lengthlist__44u8_p9_2[] = {
  147509. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  147510. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147511. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147512. 7,
  147513. };
  147514. static float _vq_quantthresh__44u8_p9_2[] = {
  147515. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147516. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147517. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147518. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147519. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147520. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147521. };
  147522. static long _vq_quantmap__44u8_p9_2[] = {
  147523. 47, 45, 43, 41, 39, 37, 35, 33,
  147524. 31, 29, 27, 25, 23, 21, 19, 17,
  147525. 15, 13, 11, 9, 7, 5, 3, 1,
  147526. 0, 2, 4, 6, 8, 10, 12, 14,
  147527. 16, 18, 20, 22, 24, 26, 28, 30,
  147528. 32, 34, 36, 38, 40, 42, 44, 46,
  147529. 48,
  147530. };
  147531. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  147532. _vq_quantthresh__44u8_p9_2,
  147533. _vq_quantmap__44u8_p9_2,
  147534. 49,
  147535. 49
  147536. };
  147537. static static_codebook _44u8_p9_2 = {
  147538. 1, 49,
  147539. _vq_lengthlist__44u8_p9_2,
  147540. 1, -526909440, 1611661312, 6, 0,
  147541. _vq_quantlist__44u8_p9_2,
  147542. NULL,
  147543. &_vq_auxt__44u8_p9_2,
  147544. NULL,
  147545. 0
  147546. };
  147547. static long _huff_lengthlist__44u9__long[] = {
  147548. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  147549. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  147550. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  147551. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  147552. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  147553. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  147554. 10, 8, 8, 9,
  147555. };
  147556. static static_codebook _huff_book__44u9__long = {
  147557. 2, 100,
  147558. _huff_lengthlist__44u9__long,
  147559. 0, 0, 0, 0, 0,
  147560. NULL,
  147561. NULL,
  147562. NULL,
  147563. NULL,
  147564. 0
  147565. };
  147566. static long _huff_lengthlist__44u9__short[] = {
  147567. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  147568. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  147569. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  147570. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  147571. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  147572. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  147573. 9, 9,12,15,
  147574. };
  147575. static static_codebook _huff_book__44u9__short = {
  147576. 2, 100,
  147577. _huff_lengthlist__44u9__short,
  147578. 0, 0, 0, 0, 0,
  147579. NULL,
  147580. NULL,
  147581. NULL,
  147582. NULL,
  147583. 0
  147584. };
  147585. static long _vq_quantlist__44u9_p1_0[] = {
  147586. 1,
  147587. 0,
  147588. 2,
  147589. };
  147590. static long _vq_lengthlist__44u9_p1_0[] = {
  147591. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  147592. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  147593. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  147594. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  147595. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  147596. 10,
  147597. };
  147598. static float _vq_quantthresh__44u9_p1_0[] = {
  147599. -0.5, 0.5,
  147600. };
  147601. static long _vq_quantmap__44u9_p1_0[] = {
  147602. 1, 0, 2,
  147603. };
  147604. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  147605. _vq_quantthresh__44u9_p1_0,
  147606. _vq_quantmap__44u9_p1_0,
  147607. 3,
  147608. 3
  147609. };
  147610. static static_codebook _44u9_p1_0 = {
  147611. 4, 81,
  147612. _vq_lengthlist__44u9_p1_0,
  147613. 1, -535822336, 1611661312, 2, 0,
  147614. _vq_quantlist__44u9_p1_0,
  147615. NULL,
  147616. &_vq_auxt__44u9_p1_0,
  147617. NULL,
  147618. 0
  147619. };
  147620. static long _vq_quantlist__44u9_p2_0[] = {
  147621. 2,
  147622. 1,
  147623. 3,
  147624. 0,
  147625. 4,
  147626. };
  147627. static long _vq_lengthlist__44u9_p2_0[] = {
  147628. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  147629. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  147630. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  147631. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  147632. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  147633. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  147634. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  147635. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  147636. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  147637. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  147638. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  147639. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  147640. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  147641. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  147642. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  147643. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  147644. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  147645. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  147646. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  147647. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  147648. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  147649. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  147650. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  147651. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  147652. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  147653. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  147654. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  147655. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  147656. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  147657. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  147658. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  147659. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  147660. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  147661. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  147662. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  147663. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  147664. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  147665. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  147666. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  147667. 14,
  147668. };
  147669. static float _vq_quantthresh__44u9_p2_0[] = {
  147670. -1.5, -0.5, 0.5, 1.5,
  147671. };
  147672. static long _vq_quantmap__44u9_p2_0[] = {
  147673. 3, 1, 0, 2, 4,
  147674. };
  147675. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  147676. _vq_quantthresh__44u9_p2_0,
  147677. _vq_quantmap__44u9_p2_0,
  147678. 5,
  147679. 5
  147680. };
  147681. static static_codebook _44u9_p2_0 = {
  147682. 4, 625,
  147683. _vq_lengthlist__44u9_p2_0,
  147684. 1, -533725184, 1611661312, 3, 0,
  147685. _vq_quantlist__44u9_p2_0,
  147686. NULL,
  147687. &_vq_auxt__44u9_p2_0,
  147688. NULL,
  147689. 0
  147690. };
  147691. static long _vq_quantlist__44u9_p3_0[] = {
  147692. 4,
  147693. 3,
  147694. 5,
  147695. 2,
  147696. 6,
  147697. 1,
  147698. 7,
  147699. 0,
  147700. 8,
  147701. };
  147702. static long _vq_lengthlist__44u9_p3_0[] = {
  147703. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  147704. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147705. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  147706. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  147707. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  147708. 11,
  147709. };
  147710. static float _vq_quantthresh__44u9_p3_0[] = {
  147711. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147712. };
  147713. static long _vq_quantmap__44u9_p3_0[] = {
  147714. 7, 5, 3, 1, 0, 2, 4, 6,
  147715. 8,
  147716. };
  147717. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  147718. _vq_quantthresh__44u9_p3_0,
  147719. _vq_quantmap__44u9_p3_0,
  147720. 9,
  147721. 9
  147722. };
  147723. static static_codebook _44u9_p3_0 = {
  147724. 2, 81,
  147725. _vq_lengthlist__44u9_p3_0,
  147726. 1, -531628032, 1611661312, 4, 0,
  147727. _vq_quantlist__44u9_p3_0,
  147728. NULL,
  147729. &_vq_auxt__44u9_p3_0,
  147730. NULL,
  147731. 0
  147732. };
  147733. static long _vq_quantlist__44u9_p4_0[] = {
  147734. 8,
  147735. 7,
  147736. 9,
  147737. 6,
  147738. 10,
  147739. 5,
  147740. 11,
  147741. 4,
  147742. 12,
  147743. 3,
  147744. 13,
  147745. 2,
  147746. 14,
  147747. 1,
  147748. 15,
  147749. 0,
  147750. 16,
  147751. };
  147752. static long _vq_lengthlist__44u9_p4_0[] = {
  147753. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  147754. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  147755. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  147756. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  147757. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  147758. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  147759. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  147760. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  147761. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  147762. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  147763. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  147764. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  147765. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  147766. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  147767. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  147768. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  147769. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  147770. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  147771. 14,
  147772. };
  147773. static float _vq_quantthresh__44u9_p4_0[] = {
  147774. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147775. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147776. };
  147777. static long _vq_quantmap__44u9_p4_0[] = {
  147778. 15, 13, 11, 9, 7, 5, 3, 1,
  147779. 0, 2, 4, 6, 8, 10, 12, 14,
  147780. 16,
  147781. };
  147782. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  147783. _vq_quantthresh__44u9_p4_0,
  147784. _vq_quantmap__44u9_p4_0,
  147785. 17,
  147786. 17
  147787. };
  147788. static static_codebook _44u9_p4_0 = {
  147789. 2, 289,
  147790. _vq_lengthlist__44u9_p4_0,
  147791. 1, -529530880, 1611661312, 5, 0,
  147792. _vq_quantlist__44u9_p4_0,
  147793. NULL,
  147794. &_vq_auxt__44u9_p4_0,
  147795. NULL,
  147796. 0
  147797. };
  147798. static long _vq_quantlist__44u9_p5_0[] = {
  147799. 1,
  147800. 0,
  147801. 2,
  147802. };
  147803. static long _vq_lengthlist__44u9_p5_0[] = {
  147804. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  147805. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  147806. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  147807. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  147808. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  147809. 10,
  147810. };
  147811. static float _vq_quantthresh__44u9_p5_0[] = {
  147812. -5.5, 5.5,
  147813. };
  147814. static long _vq_quantmap__44u9_p5_0[] = {
  147815. 1, 0, 2,
  147816. };
  147817. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  147818. _vq_quantthresh__44u9_p5_0,
  147819. _vq_quantmap__44u9_p5_0,
  147820. 3,
  147821. 3
  147822. };
  147823. static static_codebook _44u9_p5_0 = {
  147824. 4, 81,
  147825. _vq_lengthlist__44u9_p5_0,
  147826. 1, -529137664, 1618345984, 2, 0,
  147827. _vq_quantlist__44u9_p5_0,
  147828. NULL,
  147829. &_vq_auxt__44u9_p5_0,
  147830. NULL,
  147831. 0
  147832. };
  147833. static long _vq_quantlist__44u9_p5_1[] = {
  147834. 5,
  147835. 4,
  147836. 6,
  147837. 3,
  147838. 7,
  147839. 2,
  147840. 8,
  147841. 1,
  147842. 9,
  147843. 0,
  147844. 10,
  147845. };
  147846. static long _vq_lengthlist__44u9_p5_1[] = {
  147847. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  147848. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  147849. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  147850. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147851. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147852. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  147853. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  147854. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147855. };
  147856. static float _vq_quantthresh__44u9_p5_1[] = {
  147857. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147858. 3.5, 4.5,
  147859. };
  147860. static long _vq_quantmap__44u9_p5_1[] = {
  147861. 9, 7, 5, 3, 1, 0, 2, 4,
  147862. 6, 8, 10,
  147863. };
  147864. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  147865. _vq_quantthresh__44u9_p5_1,
  147866. _vq_quantmap__44u9_p5_1,
  147867. 11,
  147868. 11
  147869. };
  147870. static static_codebook _44u9_p5_1 = {
  147871. 2, 121,
  147872. _vq_lengthlist__44u9_p5_1,
  147873. 1, -531365888, 1611661312, 4, 0,
  147874. _vq_quantlist__44u9_p5_1,
  147875. NULL,
  147876. &_vq_auxt__44u9_p5_1,
  147877. NULL,
  147878. 0
  147879. };
  147880. static long _vq_quantlist__44u9_p6_0[] = {
  147881. 6,
  147882. 5,
  147883. 7,
  147884. 4,
  147885. 8,
  147886. 3,
  147887. 9,
  147888. 2,
  147889. 10,
  147890. 1,
  147891. 11,
  147892. 0,
  147893. 12,
  147894. };
  147895. static long _vq_lengthlist__44u9_p6_0[] = {
  147896. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147897. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  147898. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147899. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  147900. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  147901. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147902. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147903. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  147904. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  147905. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147906. 10,11,11,11,11,12,11,12,12,
  147907. };
  147908. static float _vq_quantthresh__44u9_p6_0[] = {
  147909. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147910. 12.5, 17.5, 22.5, 27.5,
  147911. };
  147912. static long _vq_quantmap__44u9_p6_0[] = {
  147913. 11, 9, 7, 5, 3, 1, 0, 2,
  147914. 4, 6, 8, 10, 12,
  147915. };
  147916. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  147917. _vq_quantthresh__44u9_p6_0,
  147918. _vq_quantmap__44u9_p6_0,
  147919. 13,
  147920. 13
  147921. };
  147922. static static_codebook _44u9_p6_0 = {
  147923. 2, 169,
  147924. _vq_lengthlist__44u9_p6_0,
  147925. 1, -526516224, 1616117760, 4, 0,
  147926. _vq_quantlist__44u9_p6_0,
  147927. NULL,
  147928. &_vq_auxt__44u9_p6_0,
  147929. NULL,
  147930. 0
  147931. };
  147932. static long _vq_quantlist__44u9_p6_1[] = {
  147933. 2,
  147934. 1,
  147935. 3,
  147936. 0,
  147937. 4,
  147938. };
  147939. static long _vq_lengthlist__44u9_p6_1[] = {
  147940. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  147941. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147942. };
  147943. static float _vq_quantthresh__44u9_p6_1[] = {
  147944. -1.5, -0.5, 0.5, 1.5,
  147945. };
  147946. static long _vq_quantmap__44u9_p6_1[] = {
  147947. 3, 1, 0, 2, 4,
  147948. };
  147949. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  147950. _vq_quantthresh__44u9_p6_1,
  147951. _vq_quantmap__44u9_p6_1,
  147952. 5,
  147953. 5
  147954. };
  147955. static static_codebook _44u9_p6_1 = {
  147956. 2, 25,
  147957. _vq_lengthlist__44u9_p6_1,
  147958. 1, -533725184, 1611661312, 3, 0,
  147959. _vq_quantlist__44u9_p6_1,
  147960. NULL,
  147961. &_vq_auxt__44u9_p6_1,
  147962. NULL,
  147963. 0
  147964. };
  147965. static long _vq_quantlist__44u9_p7_0[] = {
  147966. 6,
  147967. 5,
  147968. 7,
  147969. 4,
  147970. 8,
  147971. 3,
  147972. 9,
  147973. 2,
  147974. 10,
  147975. 1,
  147976. 11,
  147977. 0,
  147978. 12,
  147979. };
  147980. static long _vq_lengthlist__44u9_p7_0[] = {
  147981. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  147982. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  147983. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  147984. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  147985. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147986. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147987. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  147988. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  147989. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  147990. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  147991. 12,13,13,14,14,14,15,15,15,
  147992. };
  147993. static float _vq_quantthresh__44u9_p7_0[] = {
  147994. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147995. 27.5, 38.5, 49.5, 60.5,
  147996. };
  147997. static long _vq_quantmap__44u9_p7_0[] = {
  147998. 11, 9, 7, 5, 3, 1, 0, 2,
  147999. 4, 6, 8, 10, 12,
  148000. };
  148001. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  148002. _vq_quantthresh__44u9_p7_0,
  148003. _vq_quantmap__44u9_p7_0,
  148004. 13,
  148005. 13
  148006. };
  148007. static static_codebook _44u9_p7_0 = {
  148008. 2, 169,
  148009. _vq_lengthlist__44u9_p7_0,
  148010. 1, -523206656, 1618345984, 4, 0,
  148011. _vq_quantlist__44u9_p7_0,
  148012. NULL,
  148013. &_vq_auxt__44u9_p7_0,
  148014. NULL,
  148015. 0
  148016. };
  148017. static long _vq_quantlist__44u9_p7_1[] = {
  148018. 5,
  148019. 4,
  148020. 6,
  148021. 3,
  148022. 7,
  148023. 2,
  148024. 8,
  148025. 1,
  148026. 9,
  148027. 0,
  148028. 10,
  148029. };
  148030. static long _vq_lengthlist__44u9_p7_1[] = {
  148031. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  148032. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  148033. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  148034. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148035. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148036. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148037. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  148038. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  148039. };
  148040. static float _vq_quantthresh__44u9_p7_1[] = {
  148041. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148042. 3.5, 4.5,
  148043. };
  148044. static long _vq_quantmap__44u9_p7_1[] = {
  148045. 9, 7, 5, 3, 1, 0, 2, 4,
  148046. 6, 8, 10,
  148047. };
  148048. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  148049. _vq_quantthresh__44u9_p7_1,
  148050. _vq_quantmap__44u9_p7_1,
  148051. 11,
  148052. 11
  148053. };
  148054. static static_codebook _44u9_p7_1 = {
  148055. 2, 121,
  148056. _vq_lengthlist__44u9_p7_1,
  148057. 1, -531365888, 1611661312, 4, 0,
  148058. _vq_quantlist__44u9_p7_1,
  148059. NULL,
  148060. &_vq_auxt__44u9_p7_1,
  148061. NULL,
  148062. 0
  148063. };
  148064. static long _vq_quantlist__44u9_p8_0[] = {
  148065. 7,
  148066. 6,
  148067. 8,
  148068. 5,
  148069. 9,
  148070. 4,
  148071. 10,
  148072. 3,
  148073. 11,
  148074. 2,
  148075. 12,
  148076. 1,
  148077. 13,
  148078. 0,
  148079. 14,
  148080. };
  148081. static long _vq_lengthlist__44u9_p8_0[] = {
  148082. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  148083. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  148084. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  148085. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  148086. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  148087. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  148088. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  148089. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  148090. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  148091. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  148092. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  148093. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  148094. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  148095. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  148096. 15,
  148097. };
  148098. static float _vq_quantthresh__44u9_p8_0[] = {
  148099. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  148100. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  148101. };
  148102. static long _vq_quantmap__44u9_p8_0[] = {
  148103. 13, 11, 9, 7, 5, 3, 1, 0,
  148104. 2, 4, 6, 8, 10, 12, 14,
  148105. };
  148106. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  148107. _vq_quantthresh__44u9_p8_0,
  148108. _vq_quantmap__44u9_p8_0,
  148109. 15,
  148110. 15
  148111. };
  148112. static static_codebook _44u9_p8_0 = {
  148113. 2, 225,
  148114. _vq_lengthlist__44u9_p8_0,
  148115. 1, -520986624, 1620377600, 4, 0,
  148116. _vq_quantlist__44u9_p8_0,
  148117. NULL,
  148118. &_vq_auxt__44u9_p8_0,
  148119. NULL,
  148120. 0
  148121. };
  148122. static long _vq_quantlist__44u9_p8_1[] = {
  148123. 10,
  148124. 9,
  148125. 11,
  148126. 8,
  148127. 12,
  148128. 7,
  148129. 13,
  148130. 6,
  148131. 14,
  148132. 5,
  148133. 15,
  148134. 4,
  148135. 16,
  148136. 3,
  148137. 17,
  148138. 2,
  148139. 18,
  148140. 1,
  148141. 19,
  148142. 0,
  148143. 20,
  148144. };
  148145. static long _vq_lengthlist__44u9_p8_1[] = {
  148146. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148147. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  148148. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  148149. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  148150. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148151. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148152. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  148153. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  148154. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148155. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148156. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148157. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  148158. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148159. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  148160. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148161. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148162. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148163. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  148164. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  148165. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148166. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148167. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  148168. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  148169. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  148170. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148171. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148172. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148173. 10,10,10,10,10,10,10,10,10,
  148174. };
  148175. static float _vq_quantthresh__44u9_p8_1[] = {
  148176. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148177. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148178. 6.5, 7.5, 8.5, 9.5,
  148179. };
  148180. static long _vq_quantmap__44u9_p8_1[] = {
  148181. 19, 17, 15, 13, 11, 9, 7, 5,
  148182. 3, 1, 0, 2, 4, 6, 8, 10,
  148183. 12, 14, 16, 18, 20,
  148184. };
  148185. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  148186. _vq_quantthresh__44u9_p8_1,
  148187. _vq_quantmap__44u9_p8_1,
  148188. 21,
  148189. 21
  148190. };
  148191. static static_codebook _44u9_p8_1 = {
  148192. 2, 441,
  148193. _vq_lengthlist__44u9_p8_1,
  148194. 1, -529268736, 1611661312, 5, 0,
  148195. _vq_quantlist__44u9_p8_1,
  148196. NULL,
  148197. &_vq_auxt__44u9_p8_1,
  148198. NULL,
  148199. 0
  148200. };
  148201. static long _vq_quantlist__44u9_p9_0[] = {
  148202. 7,
  148203. 6,
  148204. 8,
  148205. 5,
  148206. 9,
  148207. 4,
  148208. 10,
  148209. 3,
  148210. 11,
  148211. 2,
  148212. 12,
  148213. 1,
  148214. 13,
  148215. 0,
  148216. 14,
  148217. };
  148218. static long _vq_lengthlist__44u9_p9_0[] = {
  148219. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  148220. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  148221. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148223. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148224. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148225. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148226. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148227. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148228. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148229. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148231. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148232. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148233. 10,
  148234. };
  148235. static float _vq_quantthresh__44u9_p9_0[] = {
  148236. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  148237. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  148238. };
  148239. static long _vq_quantmap__44u9_p9_0[] = {
  148240. 13, 11, 9, 7, 5, 3, 1, 0,
  148241. 2, 4, 6, 8, 10, 12, 14,
  148242. };
  148243. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  148244. _vq_quantthresh__44u9_p9_0,
  148245. _vq_quantmap__44u9_p9_0,
  148246. 15,
  148247. 15
  148248. };
  148249. static static_codebook _44u9_p9_0 = {
  148250. 2, 225,
  148251. _vq_lengthlist__44u9_p9_0,
  148252. 1, -510036736, 1631393792, 4, 0,
  148253. _vq_quantlist__44u9_p9_0,
  148254. NULL,
  148255. &_vq_auxt__44u9_p9_0,
  148256. NULL,
  148257. 0
  148258. };
  148259. static long _vq_quantlist__44u9_p9_1[] = {
  148260. 9,
  148261. 8,
  148262. 10,
  148263. 7,
  148264. 11,
  148265. 6,
  148266. 12,
  148267. 5,
  148268. 13,
  148269. 4,
  148270. 14,
  148271. 3,
  148272. 15,
  148273. 2,
  148274. 16,
  148275. 1,
  148276. 17,
  148277. 0,
  148278. 18,
  148279. };
  148280. static long _vq_lengthlist__44u9_p9_1[] = {
  148281. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  148282. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  148283. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  148284. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  148285. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  148286. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  148287. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  148288. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  148289. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  148290. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  148291. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  148292. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  148293. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  148294. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  148295. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  148296. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  148297. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  148298. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  148299. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  148300. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  148301. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  148302. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  148303. 17,17,15,17,15,17,16,16,17,
  148304. };
  148305. static float _vq_quantthresh__44u9_p9_1[] = {
  148306. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148307. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148308. 367.5, 416.5,
  148309. };
  148310. static long _vq_quantmap__44u9_p9_1[] = {
  148311. 17, 15, 13, 11, 9, 7, 5, 3,
  148312. 1, 0, 2, 4, 6, 8, 10, 12,
  148313. 14, 16, 18,
  148314. };
  148315. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  148316. _vq_quantthresh__44u9_p9_1,
  148317. _vq_quantmap__44u9_p9_1,
  148318. 19,
  148319. 19
  148320. };
  148321. static static_codebook _44u9_p9_1 = {
  148322. 2, 361,
  148323. _vq_lengthlist__44u9_p9_1,
  148324. 1, -518287360, 1622704128, 5, 0,
  148325. _vq_quantlist__44u9_p9_1,
  148326. NULL,
  148327. &_vq_auxt__44u9_p9_1,
  148328. NULL,
  148329. 0
  148330. };
  148331. static long _vq_quantlist__44u9_p9_2[] = {
  148332. 24,
  148333. 23,
  148334. 25,
  148335. 22,
  148336. 26,
  148337. 21,
  148338. 27,
  148339. 20,
  148340. 28,
  148341. 19,
  148342. 29,
  148343. 18,
  148344. 30,
  148345. 17,
  148346. 31,
  148347. 16,
  148348. 32,
  148349. 15,
  148350. 33,
  148351. 14,
  148352. 34,
  148353. 13,
  148354. 35,
  148355. 12,
  148356. 36,
  148357. 11,
  148358. 37,
  148359. 10,
  148360. 38,
  148361. 9,
  148362. 39,
  148363. 8,
  148364. 40,
  148365. 7,
  148366. 41,
  148367. 6,
  148368. 42,
  148369. 5,
  148370. 43,
  148371. 4,
  148372. 44,
  148373. 3,
  148374. 45,
  148375. 2,
  148376. 46,
  148377. 1,
  148378. 47,
  148379. 0,
  148380. 48,
  148381. };
  148382. static long _vq_lengthlist__44u9_p9_2[] = {
  148383. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  148384. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148385. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148386. 7,
  148387. };
  148388. static float _vq_quantthresh__44u9_p9_2[] = {
  148389. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148390. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148391. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148392. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148393. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148394. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148395. };
  148396. static long _vq_quantmap__44u9_p9_2[] = {
  148397. 47, 45, 43, 41, 39, 37, 35, 33,
  148398. 31, 29, 27, 25, 23, 21, 19, 17,
  148399. 15, 13, 11, 9, 7, 5, 3, 1,
  148400. 0, 2, 4, 6, 8, 10, 12, 14,
  148401. 16, 18, 20, 22, 24, 26, 28, 30,
  148402. 32, 34, 36, 38, 40, 42, 44, 46,
  148403. 48,
  148404. };
  148405. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  148406. _vq_quantthresh__44u9_p9_2,
  148407. _vq_quantmap__44u9_p9_2,
  148408. 49,
  148409. 49
  148410. };
  148411. static static_codebook _44u9_p9_2 = {
  148412. 1, 49,
  148413. _vq_lengthlist__44u9_p9_2,
  148414. 1, -526909440, 1611661312, 6, 0,
  148415. _vq_quantlist__44u9_p9_2,
  148416. NULL,
  148417. &_vq_auxt__44u9_p9_2,
  148418. NULL,
  148419. 0
  148420. };
  148421. static long _huff_lengthlist__44un1__long[] = {
  148422. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  148423. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  148424. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  148425. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  148426. };
  148427. static static_codebook _huff_book__44un1__long = {
  148428. 2, 64,
  148429. _huff_lengthlist__44un1__long,
  148430. 0, 0, 0, 0, 0,
  148431. NULL,
  148432. NULL,
  148433. NULL,
  148434. NULL,
  148435. 0
  148436. };
  148437. static long _vq_quantlist__44un1__p1_0[] = {
  148438. 1,
  148439. 0,
  148440. 2,
  148441. };
  148442. static long _vq_lengthlist__44un1__p1_0[] = {
  148443. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148444. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  148445. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  148446. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  148447. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  148448. 12,
  148449. };
  148450. static float _vq_quantthresh__44un1__p1_0[] = {
  148451. -0.5, 0.5,
  148452. };
  148453. static long _vq_quantmap__44un1__p1_0[] = {
  148454. 1, 0, 2,
  148455. };
  148456. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  148457. _vq_quantthresh__44un1__p1_0,
  148458. _vq_quantmap__44un1__p1_0,
  148459. 3,
  148460. 3
  148461. };
  148462. static static_codebook _44un1__p1_0 = {
  148463. 4, 81,
  148464. _vq_lengthlist__44un1__p1_0,
  148465. 1, -535822336, 1611661312, 2, 0,
  148466. _vq_quantlist__44un1__p1_0,
  148467. NULL,
  148468. &_vq_auxt__44un1__p1_0,
  148469. NULL,
  148470. 0
  148471. };
  148472. static long _vq_quantlist__44un1__p2_0[] = {
  148473. 1,
  148474. 0,
  148475. 2,
  148476. };
  148477. static long _vq_lengthlist__44un1__p2_0[] = {
  148478. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  148479. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  148480. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  148481. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  148482. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  148483. 8,
  148484. };
  148485. static float _vq_quantthresh__44un1__p2_0[] = {
  148486. -0.5, 0.5,
  148487. };
  148488. static long _vq_quantmap__44un1__p2_0[] = {
  148489. 1, 0, 2,
  148490. };
  148491. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  148492. _vq_quantthresh__44un1__p2_0,
  148493. _vq_quantmap__44un1__p2_0,
  148494. 3,
  148495. 3
  148496. };
  148497. static static_codebook _44un1__p2_0 = {
  148498. 4, 81,
  148499. _vq_lengthlist__44un1__p2_0,
  148500. 1, -535822336, 1611661312, 2, 0,
  148501. _vq_quantlist__44un1__p2_0,
  148502. NULL,
  148503. &_vq_auxt__44un1__p2_0,
  148504. NULL,
  148505. 0
  148506. };
  148507. static long _vq_quantlist__44un1__p3_0[] = {
  148508. 2,
  148509. 1,
  148510. 3,
  148511. 0,
  148512. 4,
  148513. };
  148514. static long _vq_lengthlist__44un1__p3_0[] = {
  148515. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  148516. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  148517. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  148518. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  148519. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  148520. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  148521. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  148522. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  148523. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  148524. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  148525. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  148526. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  148527. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  148528. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  148529. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  148530. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  148531. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  148532. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  148533. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  148534. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  148535. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  148536. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  148537. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  148538. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  148539. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  148540. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  148541. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  148542. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  148543. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  148544. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  148545. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  148546. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  148547. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  148548. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  148549. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  148550. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  148551. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  148552. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  148553. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  148554. 17,
  148555. };
  148556. static float _vq_quantthresh__44un1__p3_0[] = {
  148557. -1.5, -0.5, 0.5, 1.5,
  148558. };
  148559. static long _vq_quantmap__44un1__p3_0[] = {
  148560. 3, 1, 0, 2, 4,
  148561. };
  148562. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  148563. _vq_quantthresh__44un1__p3_0,
  148564. _vq_quantmap__44un1__p3_0,
  148565. 5,
  148566. 5
  148567. };
  148568. static static_codebook _44un1__p3_0 = {
  148569. 4, 625,
  148570. _vq_lengthlist__44un1__p3_0,
  148571. 1, -533725184, 1611661312, 3, 0,
  148572. _vq_quantlist__44un1__p3_0,
  148573. NULL,
  148574. &_vq_auxt__44un1__p3_0,
  148575. NULL,
  148576. 0
  148577. };
  148578. static long _vq_quantlist__44un1__p4_0[] = {
  148579. 2,
  148580. 1,
  148581. 3,
  148582. 0,
  148583. 4,
  148584. };
  148585. static long _vq_lengthlist__44un1__p4_0[] = {
  148586. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  148587. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  148588. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  148589. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  148590. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  148591. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  148592. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  148593. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  148594. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  148595. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  148596. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  148597. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  148598. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  148599. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  148600. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  148601. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  148602. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  148603. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  148604. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  148605. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  148606. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  148607. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  148608. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  148609. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  148610. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  148611. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  148612. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  148613. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  148614. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  148615. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  148616. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  148617. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  148618. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  148619. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  148620. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  148621. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  148622. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  148623. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  148624. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  148625. 12,
  148626. };
  148627. static float _vq_quantthresh__44un1__p4_0[] = {
  148628. -1.5, -0.5, 0.5, 1.5,
  148629. };
  148630. static long _vq_quantmap__44un1__p4_0[] = {
  148631. 3, 1, 0, 2, 4,
  148632. };
  148633. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  148634. _vq_quantthresh__44un1__p4_0,
  148635. _vq_quantmap__44un1__p4_0,
  148636. 5,
  148637. 5
  148638. };
  148639. static static_codebook _44un1__p4_0 = {
  148640. 4, 625,
  148641. _vq_lengthlist__44un1__p4_0,
  148642. 1, -533725184, 1611661312, 3, 0,
  148643. _vq_quantlist__44un1__p4_0,
  148644. NULL,
  148645. &_vq_auxt__44un1__p4_0,
  148646. NULL,
  148647. 0
  148648. };
  148649. static long _vq_quantlist__44un1__p5_0[] = {
  148650. 4,
  148651. 3,
  148652. 5,
  148653. 2,
  148654. 6,
  148655. 1,
  148656. 7,
  148657. 0,
  148658. 8,
  148659. };
  148660. static long _vq_lengthlist__44un1__p5_0[] = {
  148661. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  148662. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  148663. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  148664. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  148665. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148666. 12,
  148667. };
  148668. static float _vq_quantthresh__44un1__p5_0[] = {
  148669. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148670. };
  148671. static long _vq_quantmap__44un1__p5_0[] = {
  148672. 7, 5, 3, 1, 0, 2, 4, 6,
  148673. 8,
  148674. };
  148675. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  148676. _vq_quantthresh__44un1__p5_0,
  148677. _vq_quantmap__44un1__p5_0,
  148678. 9,
  148679. 9
  148680. };
  148681. static static_codebook _44un1__p5_0 = {
  148682. 2, 81,
  148683. _vq_lengthlist__44un1__p5_0,
  148684. 1, -531628032, 1611661312, 4, 0,
  148685. _vq_quantlist__44un1__p5_0,
  148686. NULL,
  148687. &_vq_auxt__44un1__p5_0,
  148688. NULL,
  148689. 0
  148690. };
  148691. static long _vq_quantlist__44un1__p6_0[] = {
  148692. 6,
  148693. 5,
  148694. 7,
  148695. 4,
  148696. 8,
  148697. 3,
  148698. 9,
  148699. 2,
  148700. 10,
  148701. 1,
  148702. 11,
  148703. 0,
  148704. 12,
  148705. };
  148706. static long _vq_lengthlist__44un1__p6_0[] = {
  148707. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  148708. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  148709. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  148710. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  148711. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  148712. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  148713. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  148714. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  148715. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  148716. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  148717. 16, 0,15,18,18, 0,16, 0, 0,
  148718. };
  148719. static float _vq_quantthresh__44un1__p6_0[] = {
  148720. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148721. 12.5, 17.5, 22.5, 27.5,
  148722. };
  148723. static long _vq_quantmap__44un1__p6_0[] = {
  148724. 11, 9, 7, 5, 3, 1, 0, 2,
  148725. 4, 6, 8, 10, 12,
  148726. };
  148727. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  148728. _vq_quantthresh__44un1__p6_0,
  148729. _vq_quantmap__44un1__p6_0,
  148730. 13,
  148731. 13
  148732. };
  148733. static static_codebook _44un1__p6_0 = {
  148734. 2, 169,
  148735. _vq_lengthlist__44un1__p6_0,
  148736. 1, -526516224, 1616117760, 4, 0,
  148737. _vq_quantlist__44un1__p6_0,
  148738. NULL,
  148739. &_vq_auxt__44un1__p6_0,
  148740. NULL,
  148741. 0
  148742. };
  148743. static long _vq_quantlist__44un1__p6_1[] = {
  148744. 2,
  148745. 1,
  148746. 3,
  148747. 0,
  148748. 4,
  148749. };
  148750. static long _vq_lengthlist__44un1__p6_1[] = {
  148751. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  148752. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  148753. };
  148754. static float _vq_quantthresh__44un1__p6_1[] = {
  148755. -1.5, -0.5, 0.5, 1.5,
  148756. };
  148757. static long _vq_quantmap__44un1__p6_1[] = {
  148758. 3, 1, 0, 2, 4,
  148759. };
  148760. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  148761. _vq_quantthresh__44un1__p6_1,
  148762. _vq_quantmap__44un1__p6_1,
  148763. 5,
  148764. 5
  148765. };
  148766. static static_codebook _44un1__p6_1 = {
  148767. 2, 25,
  148768. _vq_lengthlist__44un1__p6_1,
  148769. 1, -533725184, 1611661312, 3, 0,
  148770. _vq_quantlist__44un1__p6_1,
  148771. NULL,
  148772. &_vq_auxt__44un1__p6_1,
  148773. NULL,
  148774. 0
  148775. };
  148776. static long _vq_quantlist__44un1__p7_0[] = {
  148777. 2,
  148778. 1,
  148779. 3,
  148780. 0,
  148781. 4,
  148782. };
  148783. static long _vq_lengthlist__44un1__p7_0[] = {
  148784. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  148785. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  148786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148787. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148791. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  148792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  148795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148799. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  148800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148801. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  148802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148810. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148820. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148821. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148822. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148823. 10,
  148824. };
  148825. static float _vq_quantthresh__44un1__p7_0[] = {
  148826. -253.5, -84.5, 84.5, 253.5,
  148827. };
  148828. static long _vq_quantmap__44un1__p7_0[] = {
  148829. 3, 1, 0, 2, 4,
  148830. };
  148831. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  148832. _vq_quantthresh__44un1__p7_0,
  148833. _vq_quantmap__44un1__p7_0,
  148834. 5,
  148835. 5
  148836. };
  148837. static static_codebook _44un1__p7_0 = {
  148838. 4, 625,
  148839. _vq_lengthlist__44un1__p7_0,
  148840. 1, -518709248, 1626677248, 3, 0,
  148841. _vq_quantlist__44un1__p7_0,
  148842. NULL,
  148843. &_vq_auxt__44un1__p7_0,
  148844. NULL,
  148845. 0
  148846. };
  148847. static long _vq_quantlist__44un1__p7_1[] = {
  148848. 6,
  148849. 5,
  148850. 7,
  148851. 4,
  148852. 8,
  148853. 3,
  148854. 9,
  148855. 2,
  148856. 10,
  148857. 1,
  148858. 11,
  148859. 0,
  148860. 12,
  148861. };
  148862. static long _vq_lengthlist__44un1__p7_1[] = {
  148863. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  148864. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  148865. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  148866. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  148867. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  148868. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  148869. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  148870. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  148871. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  148872. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  148873. 12,13,13,12,13,13,14,14,14,
  148874. };
  148875. static float _vq_quantthresh__44un1__p7_1[] = {
  148876. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  148877. 32.5, 45.5, 58.5, 71.5,
  148878. };
  148879. static long _vq_quantmap__44un1__p7_1[] = {
  148880. 11, 9, 7, 5, 3, 1, 0, 2,
  148881. 4, 6, 8, 10, 12,
  148882. };
  148883. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  148884. _vq_quantthresh__44un1__p7_1,
  148885. _vq_quantmap__44un1__p7_1,
  148886. 13,
  148887. 13
  148888. };
  148889. static static_codebook _44un1__p7_1 = {
  148890. 2, 169,
  148891. _vq_lengthlist__44un1__p7_1,
  148892. 1, -523010048, 1618608128, 4, 0,
  148893. _vq_quantlist__44un1__p7_1,
  148894. NULL,
  148895. &_vq_auxt__44un1__p7_1,
  148896. NULL,
  148897. 0
  148898. };
  148899. static long _vq_quantlist__44un1__p7_2[] = {
  148900. 6,
  148901. 5,
  148902. 7,
  148903. 4,
  148904. 8,
  148905. 3,
  148906. 9,
  148907. 2,
  148908. 10,
  148909. 1,
  148910. 11,
  148911. 0,
  148912. 12,
  148913. };
  148914. static long _vq_lengthlist__44un1__p7_2[] = {
  148915. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  148916. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  148917. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  148918. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  148919. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  148920. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  148921. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  148922. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  148923. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  148924. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  148925. 9, 9, 9,10,10,10,10,10,10,
  148926. };
  148927. static float _vq_quantthresh__44un1__p7_2[] = {
  148928. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148929. 2.5, 3.5, 4.5, 5.5,
  148930. };
  148931. static long _vq_quantmap__44un1__p7_2[] = {
  148932. 11, 9, 7, 5, 3, 1, 0, 2,
  148933. 4, 6, 8, 10, 12,
  148934. };
  148935. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  148936. _vq_quantthresh__44un1__p7_2,
  148937. _vq_quantmap__44un1__p7_2,
  148938. 13,
  148939. 13
  148940. };
  148941. static static_codebook _44un1__p7_2 = {
  148942. 2, 169,
  148943. _vq_lengthlist__44un1__p7_2,
  148944. 1, -531103744, 1611661312, 4, 0,
  148945. _vq_quantlist__44un1__p7_2,
  148946. NULL,
  148947. &_vq_auxt__44un1__p7_2,
  148948. NULL,
  148949. 0
  148950. };
  148951. static long _huff_lengthlist__44un1__short[] = {
  148952. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  148953. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  148954. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  148955. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  148956. };
  148957. static static_codebook _huff_book__44un1__short = {
  148958. 2, 64,
  148959. _huff_lengthlist__44un1__short,
  148960. 0, 0, 0, 0, 0,
  148961. NULL,
  148962. NULL,
  148963. NULL,
  148964. NULL,
  148965. 0
  148966. };
  148967. /********* End of inlined file: res_books_uncoupled.h *********/
  148968. /***** residue backends *********************************************/
  148969. static vorbis_info_residue0 _residue_44_low_un={
  148970. 0,-1, -1, 8,-1,
  148971. {0},
  148972. {-1},
  148973. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  148974. { -1, 25, -1, 45, -1, -1, -1}
  148975. };
  148976. static vorbis_info_residue0 _residue_44_mid_un={
  148977. 0,-1, -1, 10,-1,
  148978. /* 0 1 2 3 4 5 6 7 8 9 */
  148979. {0},
  148980. {-1},
  148981. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  148982. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  148983. };
  148984. static vorbis_info_residue0 _residue_44_hi_un={
  148985. 0,-1, -1, 10,-1,
  148986. /* 0 1 2 3 4 5 6 7 8 9 */
  148987. {0},
  148988. {-1},
  148989. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  148990. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  148991. };
  148992. /* mapping conventions:
  148993. only one submap (this would change for efficient 5.1 support for example)*/
  148994. /* Four psychoacoustic profiles are used, one for each blocktype */
  148995. static vorbis_info_mapping0 _map_nominal_u[2]={
  148996. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  148997. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  148998. };
  148999. static static_bookblock _resbook_44u_n1={
  149000. {
  149001. {0},
  149002. {0,0,&_44un1__p1_0},
  149003. {0,0,&_44un1__p2_0},
  149004. {0,0,&_44un1__p3_0},
  149005. {0,0,&_44un1__p4_0},
  149006. {0,0,&_44un1__p5_0},
  149007. {&_44un1__p6_0,&_44un1__p6_1},
  149008. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  149009. }
  149010. };
  149011. static static_bookblock _resbook_44u_0={
  149012. {
  149013. {0},
  149014. {0,0,&_44u0__p1_0},
  149015. {0,0,&_44u0__p2_0},
  149016. {0,0,&_44u0__p3_0},
  149017. {0,0,&_44u0__p4_0},
  149018. {0,0,&_44u0__p5_0},
  149019. {&_44u0__p6_0,&_44u0__p6_1},
  149020. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  149021. }
  149022. };
  149023. static static_bookblock _resbook_44u_1={
  149024. {
  149025. {0},
  149026. {0,0,&_44u1__p1_0},
  149027. {0,0,&_44u1__p2_0},
  149028. {0,0,&_44u1__p3_0},
  149029. {0,0,&_44u1__p4_0},
  149030. {0,0,&_44u1__p5_0},
  149031. {&_44u1__p6_0,&_44u1__p6_1},
  149032. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  149033. }
  149034. };
  149035. static static_bookblock _resbook_44u_2={
  149036. {
  149037. {0},
  149038. {0,0,&_44u2__p1_0},
  149039. {0,0,&_44u2__p2_0},
  149040. {0,0,&_44u2__p3_0},
  149041. {0,0,&_44u2__p4_0},
  149042. {0,0,&_44u2__p5_0},
  149043. {&_44u2__p6_0,&_44u2__p6_1},
  149044. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  149045. }
  149046. };
  149047. static static_bookblock _resbook_44u_3={
  149048. {
  149049. {0},
  149050. {0,0,&_44u3__p1_0},
  149051. {0,0,&_44u3__p2_0},
  149052. {0,0,&_44u3__p3_0},
  149053. {0,0,&_44u3__p4_0},
  149054. {0,0,&_44u3__p5_0},
  149055. {&_44u3__p6_0,&_44u3__p6_1},
  149056. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  149057. }
  149058. };
  149059. static static_bookblock _resbook_44u_4={
  149060. {
  149061. {0},
  149062. {0,0,&_44u4__p1_0},
  149063. {0,0,&_44u4__p2_0},
  149064. {0,0,&_44u4__p3_0},
  149065. {0,0,&_44u4__p4_0},
  149066. {0,0,&_44u4__p5_0},
  149067. {&_44u4__p6_0,&_44u4__p6_1},
  149068. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  149069. }
  149070. };
  149071. static static_bookblock _resbook_44u_5={
  149072. {
  149073. {0},
  149074. {0,0,&_44u5__p1_0},
  149075. {0,0,&_44u5__p2_0},
  149076. {0,0,&_44u5__p3_0},
  149077. {0,0,&_44u5__p4_0},
  149078. {0,0,&_44u5__p5_0},
  149079. {0,0,&_44u5__p6_0},
  149080. {&_44u5__p7_0,&_44u5__p7_1},
  149081. {&_44u5__p8_0,&_44u5__p8_1},
  149082. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  149083. }
  149084. };
  149085. static static_bookblock _resbook_44u_6={
  149086. {
  149087. {0},
  149088. {0,0,&_44u6__p1_0},
  149089. {0,0,&_44u6__p2_0},
  149090. {0,0,&_44u6__p3_0},
  149091. {0,0,&_44u6__p4_0},
  149092. {0,0,&_44u6__p5_0},
  149093. {0,0,&_44u6__p6_0},
  149094. {&_44u6__p7_0,&_44u6__p7_1},
  149095. {&_44u6__p8_0,&_44u6__p8_1},
  149096. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  149097. }
  149098. };
  149099. static static_bookblock _resbook_44u_7={
  149100. {
  149101. {0},
  149102. {0,0,&_44u7__p1_0},
  149103. {0,0,&_44u7__p2_0},
  149104. {0,0,&_44u7__p3_0},
  149105. {0,0,&_44u7__p4_0},
  149106. {0,0,&_44u7__p5_0},
  149107. {0,0,&_44u7__p6_0},
  149108. {&_44u7__p7_0,&_44u7__p7_1},
  149109. {&_44u7__p8_0,&_44u7__p8_1},
  149110. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  149111. }
  149112. };
  149113. static static_bookblock _resbook_44u_8={
  149114. {
  149115. {0},
  149116. {0,0,&_44u8_p1_0},
  149117. {0,0,&_44u8_p2_0},
  149118. {0,0,&_44u8_p3_0},
  149119. {0,0,&_44u8_p4_0},
  149120. {&_44u8_p5_0,&_44u8_p5_1},
  149121. {&_44u8_p6_0,&_44u8_p6_1},
  149122. {&_44u8_p7_0,&_44u8_p7_1},
  149123. {&_44u8_p8_0,&_44u8_p8_1},
  149124. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  149125. }
  149126. };
  149127. static static_bookblock _resbook_44u_9={
  149128. {
  149129. {0},
  149130. {0,0,&_44u9_p1_0},
  149131. {0,0,&_44u9_p2_0},
  149132. {0,0,&_44u9_p3_0},
  149133. {0,0,&_44u9_p4_0},
  149134. {&_44u9_p5_0,&_44u9_p5_1},
  149135. {&_44u9_p6_0,&_44u9_p6_1},
  149136. {&_44u9_p7_0,&_44u9_p7_1},
  149137. {&_44u9_p8_0,&_44u9_p8_1},
  149138. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  149139. }
  149140. };
  149141. static vorbis_residue_template _res_44u_n1[]={
  149142. {1,0, &_residue_44_low_un,
  149143. &_huff_book__44un1__short,&_huff_book__44un1__short,
  149144. &_resbook_44u_n1,&_resbook_44u_n1},
  149145. {1,0, &_residue_44_low_un,
  149146. &_huff_book__44un1__long,&_huff_book__44un1__long,
  149147. &_resbook_44u_n1,&_resbook_44u_n1}
  149148. };
  149149. static vorbis_residue_template _res_44u_0[]={
  149150. {1,0, &_residue_44_low_un,
  149151. &_huff_book__44u0__short,&_huff_book__44u0__short,
  149152. &_resbook_44u_0,&_resbook_44u_0},
  149153. {1,0, &_residue_44_low_un,
  149154. &_huff_book__44u0__long,&_huff_book__44u0__long,
  149155. &_resbook_44u_0,&_resbook_44u_0}
  149156. };
  149157. static vorbis_residue_template _res_44u_1[]={
  149158. {1,0, &_residue_44_low_un,
  149159. &_huff_book__44u1__short,&_huff_book__44u1__short,
  149160. &_resbook_44u_1,&_resbook_44u_1},
  149161. {1,0, &_residue_44_low_un,
  149162. &_huff_book__44u1__long,&_huff_book__44u1__long,
  149163. &_resbook_44u_1,&_resbook_44u_1}
  149164. };
  149165. static vorbis_residue_template _res_44u_2[]={
  149166. {1,0, &_residue_44_low_un,
  149167. &_huff_book__44u2__short,&_huff_book__44u2__short,
  149168. &_resbook_44u_2,&_resbook_44u_2},
  149169. {1,0, &_residue_44_low_un,
  149170. &_huff_book__44u2__long,&_huff_book__44u2__long,
  149171. &_resbook_44u_2,&_resbook_44u_2}
  149172. };
  149173. static vorbis_residue_template _res_44u_3[]={
  149174. {1,0, &_residue_44_low_un,
  149175. &_huff_book__44u3__short,&_huff_book__44u3__short,
  149176. &_resbook_44u_3,&_resbook_44u_3},
  149177. {1,0, &_residue_44_low_un,
  149178. &_huff_book__44u3__long,&_huff_book__44u3__long,
  149179. &_resbook_44u_3,&_resbook_44u_3}
  149180. };
  149181. static vorbis_residue_template _res_44u_4[]={
  149182. {1,0, &_residue_44_low_un,
  149183. &_huff_book__44u4__short,&_huff_book__44u4__short,
  149184. &_resbook_44u_4,&_resbook_44u_4},
  149185. {1,0, &_residue_44_low_un,
  149186. &_huff_book__44u4__long,&_huff_book__44u4__long,
  149187. &_resbook_44u_4,&_resbook_44u_4}
  149188. };
  149189. static vorbis_residue_template _res_44u_5[]={
  149190. {1,0, &_residue_44_mid_un,
  149191. &_huff_book__44u5__short,&_huff_book__44u5__short,
  149192. &_resbook_44u_5,&_resbook_44u_5},
  149193. {1,0, &_residue_44_mid_un,
  149194. &_huff_book__44u5__long,&_huff_book__44u5__long,
  149195. &_resbook_44u_5,&_resbook_44u_5}
  149196. };
  149197. static vorbis_residue_template _res_44u_6[]={
  149198. {1,0, &_residue_44_mid_un,
  149199. &_huff_book__44u6__short,&_huff_book__44u6__short,
  149200. &_resbook_44u_6,&_resbook_44u_6},
  149201. {1,0, &_residue_44_mid_un,
  149202. &_huff_book__44u6__long,&_huff_book__44u6__long,
  149203. &_resbook_44u_6,&_resbook_44u_6}
  149204. };
  149205. static vorbis_residue_template _res_44u_7[]={
  149206. {1,0, &_residue_44_mid_un,
  149207. &_huff_book__44u7__short,&_huff_book__44u7__short,
  149208. &_resbook_44u_7,&_resbook_44u_7},
  149209. {1,0, &_residue_44_mid_un,
  149210. &_huff_book__44u7__long,&_huff_book__44u7__long,
  149211. &_resbook_44u_7,&_resbook_44u_7}
  149212. };
  149213. static vorbis_residue_template _res_44u_8[]={
  149214. {1,0, &_residue_44_hi_un,
  149215. &_huff_book__44u8__short,&_huff_book__44u8__short,
  149216. &_resbook_44u_8,&_resbook_44u_8},
  149217. {1,0, &_residue_44_hi_un,
  149218. &_huff_book__44u8__long,&_huff_book__44u8__long,
  149219. &_resbook_44u_8,&_resbook_44u_8}
  149220. };
  149221. static vorbis_residue_template _res_44u_9[]={
  149222. {1,0, &_residue_44_hi_un,
  149223. &_huff_book__44u9__short,&_huff_book__44u9__short,
  149224. &_resbook_44u_9,&_resbook_44u_9},
  149225. {1,0, &_residue_44_hi_un,
  149226. &_huff_book__44u9__long,&_huff_book__44u9__long,
  149227. &_resbook_44u_9,&_resbook_44u_9}
  149228. };
  149229. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  149230. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  149231. { _map_nominal_u, _res_44u_0 }, /* 0 */
  149232. { _map_nominal_u, _res_44u_1 }, /* 1 */
  149233. { _map_nominal_u, _res_44u_2 }, /* 2 */
  149234. { _map_nominal_u, _res_44u_3 }, /* 3 */
  149235. { _map_nominal_u, _res_44u_4 }, /* 4 */
  149236. { _map_nominal_u, _res_44u_5 }, /* 5 */
  149237. { _map_nominal_u, _res_44u_6 }, /* 6 */
  149238. { _map_nominal_u, _res_44u_7 }, /* 7 */
  149239. { _map_nominal_u, _res_44u_8 }, /* 8 */
  149240. { _map_nominal_u, _res_44u_9 }, /* 9 */
  149241. };
  149242. /********* End of inlined file: residue_44u.h *********/
  149243. static double rate_mapping_44_un[12]={
  149244. 32000.,48000.,60000.,70000.,80000.,86000.,
  149245. 96000.,110000.,120000.,140000.,160000.,240001.
  149246. };
  149247. ve_setup_data_template ve_setup_44_uncoupled={
  149248. 11,
  149249. rate_mapping_44_un,
  149250. quality_mapping_44,
  149251. -1,
  149252. 40000,
  149253. 50000,
  149254. blocksize_short_44,
  149255. blocksize_long_44,
  149256. _psy_tone_masteratt_44,
  149257. _psy_tone_0dB,
  149258. _psy_tone_suppress,
  149259. _vp_tonemask_adj_otherblock,
  149260. _vp_tonemask_adj_longblock,
  149261. _vp_tonemask_adj_otherblock,
  149262. _psy_noiseguards_44,
  149263. _psy_noisebias_impulse,
  149264. _psy_noisebias_padding,
  149265. _psy_noisebias_trans,
  149266. _psy_noisebias_long,
  149267. _psy_noise_suppress,
  149268. _psy_compand_44,
  149269. _psy_compand_short_mapping,
  149270. _psy_compand_long_mapping,
  149271. {_noise_start_short_44,_noise_start_long_44},
  149272. {_noise_part_short_44,_noise_part_long_44},
  149273. _noise_thresh_44,
  149274. _psy_ath_floater,
  149275. _psy_ath_abs,
  149276. _psy_lowpass_44,
  149277. _psy_global_44,
  149278. _global_mapping_44,
  149279. NULL,
  149280. _floor_books,
  149281. _floor,
  149282. _floor_short_mapping_44,
  149283. _floor_long_mapping_44,
  149284. _mapres_template_44_uncoupled
  149285. };
  149286. /********* End of inlined file: setup_44u.h *********/
  149287. /********* Start of inlined file: setup_32.h *********/
  149288. static double rate_mapping_32[12]={
  149289. 18000.,28000.,35000.,45000.,56000.,60000.,
  149290. 75000.,90000.,100000.,115000.,150000.,190000.,
  149291. };
  149292. static double rate_mapping_32_un[12]={
  149293. 30000.,42000.,52000.,64000.,72000.,78000.,
  149294. 86000.,92000.,110000.,120000.,140000.,190000.,
  149295. };
  149296. static double _psy_lowpass_32[12]={
  149297. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  149298. };
  149299. ve_setup_data_template ve_setup_32_stereo={
  149300. 11,
  149301. rate_mapping_32,
  149302. quality_mapping_44,
  149303. 2,
  149304. 26000,
  149305. 40000,
  149306. blocksize_short_44,
  149307. blocksize_long_44,
  149308. _psy_tone_masteratt_44,
  149309. _psy_tone_0dB,
  149310. _psy_tone_suppress,
  149311. _vp_tonemask_adj_otherblock,
  149312. _vp_tonemask_adj_longblock,
  149313. _vp_tonemask_adj_otherblock,
  149314. _psy_noiseguards_44,
  149315. _psy_noisebias_impulse,
  149316. _psy_noisebias_padding,
  149317. _psy_noisebias_trans,
  149318. _psy_noisebias_long,
  149319. _psy_noise_suppress,
  149320. _psy_compand_44,
  149321. _psy_compand_short_mapping,
  149322. _psy_compand_long_mapping,
  149323. {_noise_start_short_44,_noise_start_long_44},
  149324. {_noise_part_short_44,_noise_part_long_44},
  149325. _noise_thresh_44,
  149326. _psy_ath_floater,
  149327. _psy_ath_abs,
  149328. _psy_lowpass_32,
  149329. _psy_global_44,
  149330. _global_mapping_44,
  149331. _psy_stereo_modes_44,
  149332. _floor_books,
  149333. _floor,
  149334. _floor_short_mapping_44,
  149335. _floor_long_mapping_44,
  149336. _mapres_template_44_stereo
  149337. };
  149338. ve_setup_data_template ve_setup_32_uncoupled={
  149339. 11,
  149340. rate_mapping_32_un,
  149341. quality_mapping_44,
  149342. -1,
  149343. 26000,
  149344. 40000,
  149345. blocksize_short_44,
  149346. blocksize_long_44,
  149347. _psy_tone_masteratt_44,
  149348. _psy_tone_0dB,
  149349. _psy_tone_suppress,
  149350. _vp_tonemask_adj_otherblock,
  149351. _vp_tonemask_adj_longblock,
  149352. _vp_tonemask_adj_otherblock,
  149353. _psy_noiseguards_44,
  149354. _psy_noisebias_impulse,
  149355. _psy_noisebias_padding,
  149356. _psy_noisebias_trans,
  149357. _psy_noisebias_long,
  149358. _psy_noise_suppress,
  149359. _psy_compand_44,
  149360. _psy_compand_short_mapping,
  149361. _psy_compand_long_mapping,
  149362. {_noise_start_short_44,_noise_start_long_44},
  149363. {_noise_part_short_44,_noise_part_long_44},
  149364. _noise_thresh_44,
  149365. _psy_ath_floater,
  149366. _psy_ath_abs,
  149367. _psy_lowpass_32,
  149368. _psy_global_44,
  149369. _global_mapping_44,
  149370. NULL,
  149371. _floor_books,
  149372. _floor,
  149373. _floor_short_mapping_44,
  149374. _floor_long_mapping_44,
  149375. _mapres_template_44_uncoupled
  149376. };
  149377. /********* End of inlined file: setup_32.h *********/
  149378. /********* Start of inlined file: setup_8.h *********/
  149379. /********* Start of inlined file: psych_8.h *********/
  149380. static att3 _psy_tone_masteratt_8[3]={
  149381. {{ 32, 25, 12}, 0, 0}, /* 0 */
  149382. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149383. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149384. };
  149385. static vp_adjblock _vp_tonemask_adj_8[3]={
  149386. /* adjust for mode zero */
  149387. /* 63 125 250 500 1 2 4 8 16 */
  149388. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149389. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149390. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  149391. };
  149392. static noise3 _psy_noisebias_8[3]={
  149393. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149394. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149395. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  149396. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149397. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149398. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149399. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149400. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149401. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149402. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149403. };
  149404. /* stereo mode by base quality level */
  149405. static adj_stereo _psy_stereo_modes_8[3]={
  149406. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149407. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149408. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149409. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149410. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149411. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149412. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149413. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149414. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149415. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149416. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149417. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149418. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149419. };
  149420. static noiseguard _psy_noiseguards_8[2]={
  149421. {10,10,-1},
  149422. {10,10,-1},
  149423. };
  149424. static compandblock _psy_compand_8[2]={
  149425. {{
  149426. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  149427. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  149428. 12,12,13,13,14,14,15, 15, /* 23dB */
  149429. 16,16,17,17,17,18,18, 19, /* 31dB */
  149430. 19,19,20,21,22,23,24, 25, /* 39dB */
  149431. }},
  149432. {{
  149433. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  149434. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  149435. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  149436. 9,10,11,12,13,14,15, 16, /* 31dB */
  149437. 17,18,19,20,21,22,23, 24, /* 39dB */
  149438. }},
  149439. };
  149440. static double _psy_lowpass_8[3]={3.,4.,4.};
  149441. static int _noise_start_8[2]={
  149442. 64,64,
  149443. };
  149444. static int _noise_part_8[2]={
  149445. 8,8,
  149446. };
  149447. static int _psy_ath_floater_8[3]={
  149448. -100,-100,-105,
  149449. };
  149450. static int _psy_ath_abs_8[3]={
  149451. -130,-130,-140,
  149452. };
  149453. /********* End of inlined file: psych_8.h *********/
  149454. /********* Start of inlined file: residue_8.h *********/
  149455. /***** residue backends *********************************************/
  149456. static static_bookblock _resbook_8s_0={
  149457. {
  149458. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  149459. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  149460. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  149461. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  149462. }
  149463. };
  149464. static static_bookblock _resbook_8s_1={
  149465. {
  149466. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  149467. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  149468. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  149469. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  149470. }
  149471. };
  149472. static vorbis_residue_template _res_8s_0[]={
  149473. {2,0, &_residue_44_mid,
  149474. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  149475. &_resbook_8s_0,&_resbook_8s_0},
  149476. };
  149477. static vorbis_residue_template _res_8s_1[]={
  149478. {2,0, &_residue_44_mid,
  149479. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  149480. &_resbook_8s_1,&_resbook_8s_1},
  149481. };
  149482. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  149483. { _map_nominal, _res_8s_0 }, /* 0 */
  149484. { _map_nominal, _res_8s_1 }, /* 1 */
  149485. };
  149486. static static_bookblock _resbook_8u_0={
  149487. {
  149488. {0},
  149489. {0,0,&_8u0__p1_0},
  149490. {0,0,&_8u0__p2_0},
  149491. {0,0,&_8u0__p3_0},
  149492. {0,0,&_8u0__p4_0},
  149493. {0,0,&_8u0__p5_0},
  149494. {&_8u0__p6_0,&_8u0__p6_1},
  149495. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  149496. }
  149497. };
  149498. static static_bookblock _resbook_8u_1={
  149499. {
  149500. {0},
  149501. {0,0,&_8u1__p1_0},
  149502. {0,0,&_8u1__p2_0},
  149503. {0,0,&_8u1__p3_0},
  149504. {0,0,&_8u1__p4_0},
  149505. {0,0,&_8u1__p5_0},
  149506. {0,0,&_8u1__p6_0},
  149507. {&_8u1__p7_0,&_8u1__p7_1},
  149508. {&_8u1__p8_0,&_8u1__p8_1},
  149509. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  149510. }
  149511. };
  149512. static vorbis_residue_template _res_8u_0[]={
  149513. {1,0, &_residue_44_low_un,
  149514. &_huff_book__8u0__single,&_huff_book__8u0__single,
  149515. &_resbook_8u_0,&_resbook_8u_0},
  149516. };
  149517. static vorbis_residue_template _res_8u_1[]={
  149518. {1,0, &_residue_44_mid_un,
  149519. &_huff_book__8u1__single,&_huff_book__8u1__single,
  149520. &_resbook_8u_1,&_resbook_8u_1},
  149521. };
  149522. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  149523. { _map_nominal_u, _res_8u_0 }, /* 0 */
  149524. { _map_nominal_u, _res_8u_1 }, /* 1 */
  149525. };
  149526. /********* End of inlined file: residue_8.h *********/
  149527. static int blocksize_8[2]={
  149528. 512,512
  149529. };
  149530. static int _floor_mapping_8[2]={
  149531. 6,6,
  149532. };
  149533. static double rate_mapping_8[3]={
  149534. 6000.,9000.,32000.,
  149535. };
  149536. static double rate_mapping_8_uncoupled[3]={
  149537. 8000.,14000.,42000.,
  149538. };
  149539. static double quality_mapping_8[3]={
  149540. -.1,.0,1.
  149541. };
  149542. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  149543. static double _global_mapping_8[3]={ 1., 2., 3. };
  149544. ve_setup_data_template ve_setup_8_stereo={
  149545. 2,
  149546. rate_mapping_8,
  149547. quality_mapping_8,
  149548. 2,
  149549. 8000,
  149550. 9000,
  149551. blocksize_8,
  149552. blocksize_8,
  149553. _psy_tone_masteratt_8,
  149554. _psy_tone_0dB,
  149555. _psy_tone_suppress,
  149556. _vp_tonemask_adj_8,
  149557. NULL,
  149558. _vp_tonemask_adj_8,
  149559. _psy_noiseguards_8,
  149560. _psy_noisebias_8,
  149561. _psy_noisebias_8,
  149562. NULL,
  149563. NULL,
  149564. _psy_noise_suppress,
  149565. _psy_compand_8,
  149566. _psy_compand_8_mapping,
  149567. NULL,
  149568. {_noise_start_8,_noise_start_8},
  149569. {_noise_part_8,_noise_part_8},
  149570. _noise_thresh_5only,
  149571. _psy_ath_floater_8,
  149572. _psy_ath_abs_8,
  149573. _psy_lowpass_8,
  149574. _psy_global_44,
  149575. _global_mapping_8,
  149576. _psy_stereo_modes_8,
  149577. _floor_books,
  149578. _floor,
  149579. _floor_mapping_8,
  149580. NULL,
  149581. _mapres_template_8_stereo
  149582. };
  149583. ve_setup_data_template ve_setup_8_uncoupled={
  149584. 2,
  149585. rate_mapping_8_uncoupled,
  149586. quality_mapping_8,
  149587. -1,
  149588. 8000,
  149589. 9000,
  149590. blocksize_8,
  149591. blocksize_8,
  149592. _psy_tone_masteratt_8,
  149593. _psy_tone_0dB,
  149594. _psy_tone_suppress,
  149595. _vp_tonemask_adj_8,
  149596. NULL,
  149597. _vp_tonemask_adj_8,
  149598. _psy_noiseguards_8,
  149599. _psy_noisebias_8,
  149600. _psy_noisebias_8,
  149601. NULL,
  149602. NULL,
  149603. _psy_noise_suppress,
  149604. _psy_compand_8,
  149605. _psy_compand_8_mapping,
  149606. NULL,
  149607. {_noise_start_8,_noise_start_8},
  149608. {_noise_part_8,_noise_part_8},
  149609. _noise_thresh_5only,
  149610. _psy_ath_floater_8,
  149611. _psy_ath_abs_8,
  149612. _psy_lowpass_8,
  149613. _psy_global_44,
  149614. _global_mapping_8,
  149615. _psy_stereo_modes_8,
  149616. _floor_books,
  149617. _floor,
  149618. _floor_mapping_8,
  149619. NULL,
  149620. _mapres_template_8_uncoupled
  149621. };
  149622. /********* End of inlined file: setup_8.h *********/
  149623. /********* Start of inlined file: setup_11.h *********/
  149624. /********* Start of inlined file: psych_11.h *********/
  149625. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  149626. static att3 _psy_tone_masteratt_11[3]={
  149627. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149628. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149629. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149630. };
  149631. static vp_adjblock _vp_tonemask_adj_11[3]={
  149632. /* adjust for mode zero */
  149633. /* 63 125 250 500 1 2 4 8 16 */
  149634. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  149635. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  149636. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  149637. };
  149638. static noise3 _psy_noisebias_11[3]={
  149639. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149640. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149641. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  149642. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149643. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149644. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149645. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149646. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149647. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149648. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149649. };
  149650. static double _noise_thresh_11[3]={ .3,.5,.5 };
  149651. /********* End of inlined file: psych_11.h *********/
  149652. static int blocksize_11[2]={
  149653. 512,512
  149654. };
  149655. static int _floor_mapping_11[2]={
  149656. 6,6,
  149657. };
  149658. static double rate_mapping_11[3]={
  149659. 8000.,13000.,44000.,
  149660. };
  149661. static double rate_mapping_11_uncoupled[3]={
  149662. 12000.,20000.,50000.,
  149663. };
  149664. static double quality_mapping_11[3]={
  149665. -.1,.0,1.
  149666. };
  149667. ve_setup_data_template ve_setup_11_stereo={
  149668. 2,
  149669. rate_mapping_11,
  149670. quality_mapping_11,
  149671. 2,
  149672. 9000,
  149673. 15000,
  149674. blocksize_11,
  149675. blocksize_11,
  149676. _psy_tone_masteratt_11,
  149677. _psy_tone_0dB,
  149678. _psy_tone_suppress,
  149679. _vp_tonemask_adj_11,
  149680. NULL,
  149681. _vp_tonemask_adj_11,
  149682. _psy_noiseguards_8,
  149683. _psy_noisebias_11,
  149684. _psy_noisebias_11,
  149685. NULL,
  149686. NULL,
  149687. _psy_noise_suppress,
  149688. _psy_compand_8,
  149689. _psy_compand_8_mapping,
  149690. NULL,
  149691. {_noise_start_8,_noise_start_8},
  149692. {_noise_part_8,_noise_part_8},
  149693. _noise_thresh_11,
  149694. _psy_ath_floater_8,
  149695. _psy_ath_abs_8,
  149696. _psy_lowpass_11,
  149697. _psy_global_44,
  149698. _global_mapping_8,
  149699. _psy_stereo_modes_8,
  149700. _floor_books,
  149701. _floor,
  149702. _floor_mapping_11,
  149703. NULL,
  149704. _mapres_template_8_stereo
  149705. };
  149706. ve_setup_data_template ve_setup_11_uncoupled={
  149707. 2,
  149708. rate_mapping_11_uncoupled,
  149709. quality_mapping_11,
  149710. -1,
  149711. 9000,
  149712. 15000,
  149713. blocksize_11,
  149714. blocksize_11,
  149715. _psy_tone_masteratt_11,
  149716. _psy_tone_0dB,
  149717. _psy_tone_suppress,
  149718. _vp_tonemask_adj_11,
  149719. NULL,
  149720. _vp_tonemask_adj_11,
  149721. _psy_noiseguards_8,
  149722. _psy_noisebias_11,
  149723. _psy_noisebias_11,
  149724. NULL,
  149725. NULL,
  149726. _psy_noise_suppress,
  149727. _psy_compand_8,
  149728. _psy_compand_8_mapping,
  149729. NULL,
  149730. {_noise_start_8,_noise_start_8},
  149731. {_noise_part_8,_noise_part_8},
  149732. _noise_thresh_11,
  149733. _psy_ath_floater_8,
  149734. _psy_ath_abs_8,
  149735. _psy_lowpass_11,
  149736. _psy_global_44,
  149737. _global_mapping_8,
  149738. _psy_stereo_modes_8,
  149739. _floor_books,
  149740. _floor,
  149741. _floor_mapping_11,
  149742. NULL,
  149743. _mapres_template_8_uncoupled
  149744. };
  149745. /********* End of inlined file: setup_11.h *********/
  149746. /********* Start of inlined file: setup_16.h *********/
  149747. /********* Start of inlined file: psych_16.h *********/
  149748. /* stereo mode by base quality level */
  149749. static adj_stereo _psy_stereo_modes_16[4]={
  149750. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149751. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149752. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149753. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  149754. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149755. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149756. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149757. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  149758. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149759. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149760. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149761. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149762. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149763. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149764. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149765. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  149766. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149767. };
  149768. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  149769. static att3 _psy_tone_masteratt_16[4]={
  149770. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149771. {{ 25, 22, 12}, 0, 0}, /* 0 */
  149772. {{ 20, 12, 0}, 0, 0}, /* 0 */
  149773. {{ 15, 0, -14}, 0, 0}, /* 0 */
  149774. };
  149775. static vp_adjblock _vp_tonemask_adj_16[4]={
  149776. /* adjust for mode zero */
  149777. /* 63 125 250 500 1 2 4 8 16 */
  149778. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  149779. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  149780. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149781. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149782. };
  149783. static noise3 _psy_noisebias_16_short[4]={
  149784. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149785. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149786. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149787. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149788. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149789. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  149790. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149791. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149792. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  149793. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149794. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149795. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149796. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149797. };
  149798. static noise3 _psy_noisebias_16_impulse[4]={
  149799. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149800. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149801. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149802. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149803. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  149804. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  149805. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149806. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  149807. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  149808. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149809. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149810. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  149811. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149812. };
  149813. static noise3 _psy_noisebias_16[4]={
  149814. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149815. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  149816. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149817. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149818. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149819. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149820. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149821. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149822. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  149823. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149824. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149825. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149826. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149827. };
  149828. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  149829. static int _noise_start_16[3]={ 256,256,9999 };
  149830. static int _noise_part_16[4]={ 8,8,8,8 };
  149831. static int _psy_ath_floater_16[4]={
  149832. -100,-100,-100,-105,
  149833. };
  149834. static int _psy_ath_abs_16[4]={
  149835. -130,-130,-130,-140,
  149836. };
  149837. /********* End of inlined file: psych_16.h *********/
  149838. /********* Start of inlined file: residue_16.h *********/
  149839. /***** residue backends *********************************************/
  149840. static static_bookblock _resbook_16s_0={
  149841. {
  149842. {0},
  149843. {0,0,&_16c0_s_p1_0},
  149844. {0,0,&_16c0_s_p2_0},
  149845. {0,0,&_16c0_s_p3_0},
  149846. {0,0,&_16c0_s_p4_0},
  149847. {0,0,&_16c0_s_p5_0},
  149848. {0,0,&_16c0_s_p6_0},
  149849. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  149850. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  149851. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  149852. }
  149853. };
  149854. static static_bookblock _resbook_16s_1={
  149855. {
  149856. {0},
  149857. {0,0,&_16c1_s_p1_0},
  149858. {0,0,&_16c1_s_p2_0},
  149859. {0,0,&_16c1_s_p3_0},
  149860. {0,0,&_16c1_s_p4_0},
  149861. {0,0,&_16c1_s_p5_0},
  149862. {0,0,&_16c1_s_p6_0},
  149863. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  149864. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  149865. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  149866. }
  149867. };
  149868. static static_bookblock _resbook_16s_2={
  149869. {
  149870. {0},
  149871. {0,0,&_16c2_s_p1_0},
  149872. {0,0,&_16c2_s_p2_0},
  149873. {0,0,&_16c2_s_p3_0},
  149874. {0,0,&_16c2_s_p4_0},
  149875. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  149876. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  149877. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  149878. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  149879. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  149880. }
  149881. };
  149882. static vorbis_residue_template _res_16s_0[]={
  149883. {2,0, &_residue_44_mid,
  149884. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  149885. &_resbook_16s_0,&_resbook_16s_0},
  149886. };
  149887. static vorbis_residue_template _res_16s_1[]={
  149888. {2,0, &_residue_44_mid,
  149889. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  149890. &_resbook_16s_1,&_resbook_16s_1},
  149891. {2,0, &_residue_44_mid,
  149892. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  149893. &_resbook_16s_1,&_resbook_16s_1}
  149894. };
  149895. static vorbis_residue_template _res_16s_2[]={
  149896. {2,0, &_residue_44_high,
  149897. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  149898. &_resbook_16s_2,&_resbook_16s_2},
  149899. {2,0, &_residue_44_high,
  149900. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  149901. &_resbook_16s_2,&_resbook_16s_2}
  149902. };
  149903. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  149904. { _map_nominal, _res_16s_0 }, /* 0 */
  149905. { _map_nominal, _res_16s_1 }, /* 1 */
  149906. { _map_nominal, _res_16s_2 }, /* 2 */
  149907. };
  149908. static static_bookblock _resbook_16u_0={
  149909. {
  149910. {0},
  149911. {0,0,&_16u0__p1_0},
  149912. {0,0,&_16u0__p2_0},
  149913. {0,0,&_16u0__p3_0},
  149914. {0,0,&_16u0__p4_0},
  149915. {0,0,&_16u0__p5_0},
  149916. {&_16u0__p6_0,&_16u0__p6_1},
  149917. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  149918. }
  149919. };
  149920. static static_bookblock _resbook_16u_1={
  149921. {
  149922. {0},
  149923. {0,0,&_16u1__p1_0},
  149924. {0,0,&_16u1__p2_0},
  149925. {0,0,&_16u1__p3_0},
  149926. {0,0,&_16u1__p4_0},
  149927. {0,0,&_16u1__p5_0},
  149928. {0,0,&_16u1__p6_0},
  149929. {&_16u1__p7_0,&_16u1__p7_1},
  149930. {&_16u1__p8_0,&_16u1__p8_1},
  149931. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  149932. }
  149933. };
  149934. static static_bookblock _resbook_16u_2={
  149935. {
  149936. {0},
  149937. {0,0,&_16u2_p1_0},
  149938. {0,0,&_16u2_p2_0},
  149939. {0,0,&_16u2_p3_0},
  149940. {0,0,&_16u2_p4_0},
  149941. {&_16u2_p5_0,&_16u2_p5_1},
  149942. {&_16u2_p6_0,&_16u2_p6_1},
  149943. {&_16u2_p7_0,&_16u2_p7_1},
  149944. {&_16u2_p8_0,&_16u2_p8_1},
  149945. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  149946. }
  149947. };
  149948. static vorbis_residue_template _res_16u_0[]={
  149949. {1,0, &_residue_44_low_un,
  149950. &_huff_book__16u0__single,&_huff_book__16u0__single,
  149951. &_resbook_16u_0,&_resbook_16u_0},
  149952. };
  149953. static vorbis_residue_template _res_16u_1[]={
  149954. {1,0, &_residue_44_mid_un,
  149955. &_huff_book__16u1__short,&_huff_book__16u1__short,
  149956. &_resbook_16u_1,&_resbook_16u_1},
  149957. {1,0, &_residue_44_mid_un,
  149958. &_huff_book__16u1__long,&_huff_book__16u1__long,
  149959. &_resbook_16u_1,&_resbook_16u_1}
  149960. };
  149961. static vorbis_residue_template _res_16u_2[]={
  149962. {1,0, &_residue_44_hi_un,
  149963. &_huff_book__16u2__short,&_huff_book__16u2__short,
  149964. &_resbook_16u_2,&_resbook_16u_2},
  149965. {1,0, &_residue_44_hi_un,
  149966. &_huff_book__16u2__long,&_huff_book__16u2__long,
  149967. &_resbook_16u_2,&_resbook_16u_2}
  149968. };
  149969. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  149970. { _map_nominal_u, _res_16u_0 }, /* 0 */
  149971. { _map_nominal_u, _res_16u_1 }, /* 1 */
  149972. { _map_nominal_u, _res_16u_2 }, /* 2 */
  149973. };
  149974. /********* End of inlined file: residue_16.h *********/
  149975. static int blocksize_16_short[3]={
  149976. 1024,512,512
  149977. };
  149978. static int blocksize_16_long[3]={
  149979. 1024,1024,1024
  149980. };
  149981. static int _floor_mapping_16_short[3]={
  149982. 9,3,3
  149983. };
  149984. static int _floor_mapping_16[3]={
  149985. 9,9,9
  149986. };
  149987. static double rate_mapping_16[4]={
  149988. 12000.,20000.,44000.,86000.
  149989. };
  149990. static double rate_mapping_16_uncoupled[4]={
  149991. 16000.,28000.,64000.,100000.
  149992. };
  149993. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  149994. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  149995. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  149996. ve_setup_data_template ve_setup_16_stereo={
  149997. 3,
  149998. rate_mapping_16,
  149999. quality_mapping_16,
  150000. 2,
  150001. 15000,
  150002. 19000,
  150003. blocksize_16_short,
  150004. blocksize_16_long,
  150005. _psy_tone_masteratt_16,
  150006. _psy_tone_0dB,
  150007. _psy_tone_suppress,
  150008. _vp_tonemask_adj_16,
  150009. _vp_tonemask_adj_16,
  150010. _vp_tonemask_adj_16,
  150011. _psy_noiseguards_8,
  150012. _psy_noisebias_16_impulse,
  150013. _psy_noisebias_16_short,
  150014. _psy_noisebias_16_short,
  150015. _psy_noisebias_16,
  150016. _psy_noise_suppress,
  150017. _psy_compand_8,
  150018. _psy_compand_16_mapping,
  150019. _psy_compand_16_mapping,
  150020. {_noise_start_16,_noise_start_16},
  150021. { _noise_part_16, _noise_part_16},
  150022. _noise_thresh_16,
  150023. _psy_ath_floater_16,
  150024. _psy_ath_abs_16,
  150025. _psy_lowpass_16,
  150026. _psy_global_44,
  150027. _global_mapping_16,
  150028. _psy_stereo_modes_16,
  150029. _floor_books,
  150030. _floor,
  150031. _floor_mapping_16_short,
  150032. _floor_mapping_16,
  150033. _mapres_template_16_stereo
  150034. };
  150035. ve_setup_data_template ve_setup_16_uncoupled={
  150036. 3,
  150037. rate_mapping_16_uncoupled,
  150038. quality_mapping_16,
  150039. -1,
  150040. 15000,
  150041. 19000,
  150042. blocksize_16_short,
  150043. blocksize_16_long,
  150044. _psy_tone_masteratt_16,
  150045. _psy_tone_0dB,
  150046. _psy_tone_suppress,
  150047. _vp_tonemask_adj_16,
  150048. _vp_tonemask_adj_16,
  150049. _vp_tonemask_adj_16,
  150050. _psy_noiseguards_8,
  150051. _psy_noisebias_16_impulse,
  150052. _psy_noisebias_16_short,
  150053. _psy_noisebias_16_short,
  150054. _psy_noisebias_16,
  150055. _psy_noise_suppress,
  150056. _psy_compand_8,
  150057. _psy_compand_16_mapping,
  150058. _psy_compand_16_mapping,
  150059. {_noise_start_16,_noise_start_16},
  150060. { _noise_part_16, _noise_part_16},
  150061. _noise_thresh_16,
  150062. _psy_ath_floater_16,
  150063. _psy_ath_abs_16,
  150064. _psy_lowpass_16,
  150065. _psy_global_44,
  150066. _global_mapping_16,
  150067. _psy_stereo_modes_16,
  150068. _floor_books,
  150069. _floor,
  150070. _floor_mapping_16_short,
  150071. _floor_mapping_16,
  150072. _mapres_template_16_uncoupled
  150073. };
  150074. /********* End of inlined file: setup_16.h *********/
  150075. /********* Start of inlined file: setup_22.h *********/
  150076. static double rate_mapping_22[4]={
  150077. 15000.,20000.,44000.,86000.
  150078. };
  150079. static double rate_mapping_22_uncoupled[4]={
  150080. 16000.,28000.,50000.,90000.
  150081. };
  150082. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  150083. ve_setup_data_template ve_setup_22_stereo={
  150084. 3,
  150085. rate_mapping_22,
  150086. quality_mapping_16,
  150087. 2,
  150088. 19000,
  150089. 26000,
  150090. blocksize_16_short,
  150091. blocksize_16_long,
  150092. _psy_tone_masteratt_16,
  150093. _psy_tone_0dB,
  150094. _psy_tone_suppress,
  150095. _vp_tonemask_adj_16,
  150096. _vp_tonemask_adj_16,
  150097. _vp_tonemask_adj_16,
  150098. _psy_noiseguards_8,
  150099. _psy_noisebias_16_impulse,
  150100. _psy_noisebias_16_short,
  150101. _psy_noisebias_16_short,
  150102. _psy_noisebias_16,
  150103. _psy_noise_suppress,
  150104. _psy_compand_8,
  150105. _psy_compand_8_mapping,
  150106. _psy_compand_8_mapping,
  150107. {_noise_start_16,_noise_start_16},
  150108. { _noise_part_16, _noise_part_16},
  150109. _noise_thresh_16,
  150110. _psy_ath_floater_16,
  150111. _psy_ath_abs_16,
  150112. _psy_lowpass_22,
  150113. _psy_global_44,
  150114. _global_mapping_16,
  150115. _psy_stereo_modes_16,
  150116. _floor_books,
  150117. _floor,
  150118. _floor_mapping_16_short,
  150119. _floor_mapping_16,
  150120. _mapres_template_16_stereo
  150121. };
  150122. ve_setup_data_template ve_setup_22_uncoupled={
  150123. 3,
  150124. rate_mapping_22_uncoupled,
  150125. quality_mapping_16,
  150126. -1,
  150127. 19000,
  150128. 26000,
  150129. blocksize_16_short,
  150130. blocksize_16_long,
  150131. _psy_tone_masteratt_16,
  150132. _psy_tone_0dB,
  150133. _psy_tone_suppress,
  150134. _vp_tonemask_adj_16,
  150135. _vp_tonemask_adj_16,
  150136. _vp_tonemask_adj_16,
  150137. _psy_noiseguards_8,
  150138. _psy_noisebias_16_impulse,
  150139. _psy_noisebias_16_short,
  150140. _psy_noisebias_16_short,
  150141. _psy_noisebias_16,
  150142. _psy_noise_suppress,
  150143. _psy_compand_8,
  150144. _psy_compand_8_mapping,
  150145. _psy_compand_8_mapping,
  150146. {_noise_start_16,_noise_start_16},
  150147. { _noise_part_16, _noise_part_16},
  150148. _noise_thresh_16,
  150149. _psy_ath_floater_16,
  150150. _psy_ath_abs_16,
  150151. _psy_lowpass_22,
  150152. _psy_global_44,
  150153. _global_mapping_16,
  150154. _psy_stereo_modes_16,
  150155. _floor_books,
  150156. _floor,
  150157. _floor_mapping_16_short,
  150158. _floor_mapping_16,
  150159. _mapres_template_16_uncoupled
  150160. };
  150161. /********* End of inlined file: setup_22.h *********/
  150162. /********* Start of inlined file: setup_X.h *********/
  150163. static double rate_mapping_X[12]={
  150164. -1.,-1.,-1.,-1.,-1.,-1.,
  150165. -1.,-1.,-1.,-1.,-1.,-1.
  150166. };
  150167. ve_setup_data_template ve_setup_X_stereo={
  150168. 11,
  150169. rate_mapping_X,
  150170. quality_mapping_44,
  150171. 2,
  150172. 50000,
  150173. 200000,
  150174. blocksize_short_44,
  150175. blocksize_long_44,
  150176. _psy_tone_masteratt_44,
  150177. _psy_tone_0dB,
  150178. _psy_tone_suppress,
  150179. _vp_tonemask_adj_otherblock,
  150180. _vp_tonemask_adj_longblock,
  150181. _vp_tonemask_adj_otherblock,
  150182. _psy_noiseguards_44,
  150183. _psy_noisebias_impulse,
  150184. _psy_noisebias_padding,
  150185. _psy_noisebias_trans,
  150186. _psy_noisebias_long,
  150187. _psy_noise_suppress,
  150188. _psy_compand_44,
  150189. _psy_compand_short_mapping,
  150190. _psy_compand_long_mapping,
  150191. {_noise_start_short_44,_noise_start_long_44},
  150192. {_noise_part_short_44,_noise_part_long_44},
  150193. _noise_thresh_44,
  150194. _psy_ath_floater,
  150195. _psy_ath_abs,
  150196. _psy_lowpass_44,
  150197. _psy_global_44,
  150198. _global_mapping_44,
  150199. _psy_stereo_modes_44,
  150200. _floor_books,
  150201. _floor,
  150202. _floor_short_mapping_44,
  150203. _floor_long_mapping_44,
  150204. _mapres_template_44_stereo
  150205. };
  150206. ve_setup_data_template ve_setup_X_uncoupled={
  150207. 11,
  150208. rate_mapping_X,
  150209. quality_mapping_44,
  150210. -1,
  150211. 50000,
  150212. 200000,
  150213. blocksize_short_44,
  150214. blocksize_long_44,
  150215. _psy_tone_masteratt_44,
  150216. _psy_tone_0dB,
  150217. _psy_tone_suppress,
  150218. _vp_tonemask_adj_otherblock,
  150219. _vp_tonemask_adj_longblock,
  150220. _vp_tonemask_adj_otherblock,
  150221. _psy_noiseguards_44,
  150222. _psy_noisebias_impulse,
  150223. _psy_noisebias_padding,
  150224. _psy_noisebias_trans,
  150225. _psy_noisebias_long,
  150226. _psy_noise_suppress,
  150227. _psy_compand_44,
  150228. _psy_compand_short_mapping,
  150229. _psy_compand_long_mapping,
  150230. {_noise_start_short_44,_noise_start_long_44},
  150231. {_noise_part_short_44,_noise_part_long_44},
  150232. _noise_thresh_44,
  150233. _psy_ath_floater,
  150234. _psy_ath_abs,
  150235. _psy_lowpass_44,
  150236. _psy_global_44,
  150237. _global_mapping_44,
  150238. NULL,
  150239. _floor_books,
  150240. _floor,
  150241. _floor_short_mapping_44,
  150242. _floor_long_mapping_44,
  150243. _mapres_template_44_uncoupled
  150244. };
  150245. ve_setup_data_template ve_setup_XX_stereo={
  150246. 2,
  150247. rate_mapping_X,
  150248. quality_mapping_8,
  150249. 2,
  150250. 0,
  150251. 8000,
  150252. blocksize_8,
  150253. blocksize_8,
  150254. _psy_tone_masteratt_8,
  150255. _psy_tone_0dB,
  150256. _psy_tone_suppress,
  150257. _vp_tonemask_adj_8,
  150258. NULL,
  150259. _vp_tonemask_adj_8,
  150260. _psy_noiseguards_8,
  150261. _psy_noisebias_8,
  150262. _psy_noisebias_8,
  150263. NULL,
  150264. NULL,
  150265. _psy_noise_suppress,
  150266. _psy_compand_8,
  150267. _psy_compand_8_mapping,
  150268. NULL,
  150269. {_noise_start_8,_noise_start_8},
  150270. {_noise_part_8,_noise_part_8},
  150271. _noise_thresh_5only,
  150272. _psy_ath_floater_8,
  150273. _psy_ath_abs_8,
  150274. _psy_lowpass_8,
  150275. _psy_global_44,
  150276. _global_mapping_8,
  150277. _psy_stereo_modes_8,
  150278. _floor_books,
  150279. _floor,
  150280. _floor_mapping_8,
  150281. NULL,
  150282. _mapres_template_8_stereo
  150283. };
  150284. ve_setup_data_template ve_setup_XX_uncoupled={
  150285. 2,
  150286. rate_mapping_X,
  150287. quality_mapping_8,
  150288. -1,
  150289. 0,
  150290. 8000,
  150291. blocksize_8,
  150292. blocksize_8,
  150293. _psy_tone_masteratt_8,
  150294. _psy_tone_0dB,
  150295. _psy_tone_suppress,
  150296. _vp_tonemask_adj_8,
  150297. NULL,
  150298. _vp_tonemask_adj_8,
  150299. _psy_noiseguards_8,
  150300. _psy_noisebias_8,
  150301. _psy_noisebias_8,
  150302. NULL,
  150303. NULL,
  150304. _psy_noise_suppress,
  150305. _psy_compand_8,
  150306. _psy_compand_8_mapping,
  150307. NULL,
  150308. {_noise_start_8,_noise_start_8},
  150309. {_noise_part_8,_noise_part_8},
  150310. _noise_thresh_5only,
  150311. _psy_ath_floater_8,
  150312. _psy_ath_abs_8,
  150313. _psy_lowpass_8,
  150314. _psy_global_44,
  150315. _global_mapping_8,
  150316. _psy_stereo_modes_8,
  150317. _floor_books,
  150318. _floor,
  150319. _floor_mapping_8,
  150320. NULL,
  150321. _mapres_template_8_uncoupled
  150322. };
  150323. /********* End of inlined file: setup_X.h *********/
  150324. static ve_setup_data_template *setup_list[]={
  150325. &ve_setup_44_stereo,
  150326. &ve_setup_44_uncoupled,
  150327. &ve_setup_32_stereo,
  150328. &ve_setup_32_uncoupled,
  150329. &ve_setup_22_stereo,
  150330. &ve_setup_22_uncoupled,
  150331. &ve_setup_16_stereo,
  150332. &ve_setup_16_uncoupled,
  150333. &ve_setup_11_stereo,
  150334. &ve_setup_11_uncoupled,
  150335. &ve_setup_8_stereo,
  150336. &ve_setup_8_uncoupled,
  150337. &ve_setup_X_stereo,
  150338. &ve_setup_X_uncoupled,
  150339. &ve_setup_XX_stereo,
  150340. &ve_setup_XX_uncoupled,
  150341. 0
  150342. };
  150343. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  150344. if(vi && vi->codec_setup){
  150345. vi->version=0;
  150346. vi->channels=ch;
  150347. vi->rate=rate;
  150348. return(0);
  150349. }
  150350. return(OV_EINVAL);
  150351. }
  150352. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  150353. static_codebook ***books,
  150354. vorbis_info_floor1 *in,
  150355. int *x){
  150356. int i,k,is=s;
  150357. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  150358. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150359. memcpy(f,in+x[is],sizeof(*f));
  150360. /* fill in the lowpass field, even if it's temporary */
  150361. f->n=ci->blocksizes[block]>>1;
  150362. /* books */
  150363. {
  150364. int partitions=f->partitions;
  150365. int maxclass=-1;
  150366. int maxbook=-1;
  150367. for(i=0;i<partitions;i++)
  150368. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  150369. for(i=0;i<=maxclass;i++){
  150370. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  150371. f->class_book[i]+=ci->books;
  150372. for(k=0;k<(1<<f->class_subs[i]);k++){
  150373. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  150374. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  150375. }
  150376. }
  150377. for(i=0;i<=maxbook;i++)
  150378. ci->book_param[ci->books++]=books[x[is]][i];
  150379. }
  150380. /* for now, we're only using floor 1 */
  150381. ci->floor_type[ci->floors]=1;
  150382. ci->floor_param[ci->floors]=f;
  150383. ci->floors++;
  150384. return;
  150385. }
  150386. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  150387. vorbis_info_psy_global *in,
  150388. double *x){
  150389. int i,is=s;
  150390. double ds=s-is;
  150391. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150392. vorbis_info_psy_global *g=&ci->psy_g_param;
  150393. memcpy(g,in+(int)x[is],sizeof(*g));
  150394. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150395. is=(int)ds;
  150396. ds-=is;
  150397. if(ds==0 && is>0){
  150398. is--;
  150399. ds=1.;
  150400. }
  150401. /* interpolate the trigger threshholds */
  150402. for(i=0;i<4;i++){
  150403. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  150404. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  150405. }
  150406. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  150407. return;
  150408. }
  150409. static void vorbis_encode_global_stereo(vorbis_info *vi,
  150410. highlevel_encode_setup *hi,
  150411. adj_stereo *p){
  150412. float s=hi->stereo_point_setting;
  150413. int i,is=s;
  150414. double ds=s-is;
  150415. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150416. vorbis_info_psy_global *g=&ci->psy_g_param;
  150417. if(p){
  150418. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  150419. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  150420. if(hi->managed){
  150421. /* interpolate the kHz threshholds */
  150422. for(i=0;i<PACKETBLOBS;i++){
  150423. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  150424. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150425. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150426. g->coupling_pkHz[i]=kHz;
  150427. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  150428. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150429. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150430. }
  150431. }else{
  150432. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  150433. for(i=0;i<PACKETBLOBS;i++){
  150434. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150435. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150436. g->coupling_pkHz[i]=kHz;
  150437. }
  150438. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  150439. for(i=0;i<PACKETBLOBS;i++){
  150440. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150441. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150442. }
  150443. }
  150444. }else{
  150445. for(i=0;i<PACKETBLOBS;i++){
  150446. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  150447. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  150448. }
  150449. }
  150450. return;
  150451. }
  150452. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  150453. int *nn_start,
  150454. int *nn_partition,
  150455. double *nn_thresh,
  150456. int block){
  150457. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150458. vorbis_info_psy *p=ci->psy_param[block];
  150459. highlevel_encode_setup *hi=&ci->hi;
  150460. int is=s;
  150461. if(block>=ci->psys)
  150462. ci->psys=block+1;
  150463. if(!p){
  150464. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  150465. ci->psy_param[block]=p;
  150466. }
  150467. memcpy(p,&_psy_info_template,sizeof(*p));
  150468. p->blockflag=block>>1;
  150469. if(hi->noise_normalize_p){
  150470. p->normal_channel_p=1;
  150471. p->normal_point_p=1;
  150472. p->normal_start=nn_start[is];
  150473. p->normal_partition=nn_partition[is];
  150474. p->normal_thresh=nn_thresh[is];
  150475. }
  150476. return;
  150477. }
  150478. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  150479. att3 *att,
  150480. int *max,
  150481. vp_adjblock *in){
  150482. int i,is=s;
  150483. double ds=s-is;
  150484. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150485. vorbis_info_psy *p=ci->psy_param[block];
  150486. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  150487. filling the values in here */
  150488. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  150489. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  150490. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  150491. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  150492. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  150493. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  150494. for(i=0;i<P_BANDS;i++)
  150495. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  150496. return;
  150497. }
  150498. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  150499. compandblock *in, double *x){
  150500. int i,is=s;
  150501. double ds=s-is;
  150502. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150503. vorbis_info_psy *p=ci->psy_param[block];
  150504. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150505. is=(int)ds;
  150506. ds-=is;
  150507. if(ds==0 && is>0){
  150508. is--;
  150509. ds=1.;
  150510. }
  150511. /* interpolate the compander settings */
  150512. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  150513. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  150514. return;
  150515. }
  150516. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  150517. int *suppress){
  150518. int is=s;
  150519. double ds=s-is;
  150520. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150521. vorbis_info_psy *p=ci->psy_param[block];
  150522. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150523. return;
  150524. }
  150525. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  150526. int *suppress,
  150527. noise3 *in,
  150528. noiseguard *guard,
  150529. double userbias){
  150530. int i,is=s,j;
  150531. double ds=s-is;
  150532. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150533. vorbis_info_psy *p=ci->psy_param[block];
  150534. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150535. p->noisewindowlomin=guard[block].lo;
  150536. p->noisewindowhimin=guard[block].hi;
  150537. p->noisewindowfixed=guard[block].fixed;
  150538. for(j=0;j<P_NOISECURVES;j++)
  150539. for(i=0;i<P_BANDS;i++)
  150540. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  150541. /* impulse blocks may take a user specified bias to boost the
  150542. nominal/high noise encoding depth */
  150543. for(j=0;j<P_NOISECURVES;j++){
  150544. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  150545. for(i=0;i<P_BANDS;i++){
  150546. p->noiseoff[j][i]+=userbias;
  150547. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  150548. }
  150549. }
  150550. return;
  150551. }
  150552. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  150553. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150554. vorbis_info_psy *p=ci->psy_param[block];
  150555. p->ath_adjatt=ci->hi.ath_floating_dB;
  150556. p->ath_maxatt=ci->hi.ath_absolute_dB;
  150557. return;
  150558. }
  150559. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  150560. int i;
  150561. for(i=0;i<ci->books;i++)
  150562. if(ci->book_param[i]==book)return(i);
  150563. return(ci->books++);
  150564. }
  150565. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  150566. int *shortb,int *longb){
  150567. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150568. int is=s;
  150569. int blockshort=shortb[is];
  150570. int blocklong=longb[is];
  150571. ci->blocksizes[0]=blockshort;
  150572. ci->blocksizes[1]=blocklong;
  150573. }
  150574. static void vorbis_encode_residue_setup(vorbis_info *vi,
  150575. int number, int block,
  150576. vorbis_residue_template *res){
  150577. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150578. int i,n;
  150579. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  150580. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  150581. memcpy(r,res->res,sizeof(*r));
  150582. if(ci->residues<=number)ci->residues=number+1;
  150583. switch(ci->blocksizes[block]){
  150584. case 64:case 128:case 256:
  150585. r->grouping=16;
  150586. break;
  150587. default:
  150588. r->grouping=32;
  150589. break;
  150590. }
  150591. ci->residue_type[number]=res->res_type;
  150592. /* to be adjusted by lowpass/pointlimit later */
  150593. n=r->end=ci->blocksizes[block]>>1;
  150594. if(res->res_type==2)
  150595. n=r->end*=vi->channels;
  150596. /* fill in all the books */
  150597. {
  150598. int booklist=0,k;
  150599. if(ci->hi.managed){
  150600. for(i=0;i<r->partitions;i++)
  150601. for(k=0;k<3;k++)
  150602. if(res->books_base_managed->books[i][k])
  150603. r->secondstages[i]|=(1<<k);
  150604. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  150605. ci->book_param[r->groupbook]=res->book_aux_managed;
  150606. for(i=0;i<r->partitions;i++){
  150607. for(k=0;k<3;k++){
  150608. if(res->books_base_managed->books[i][k]){
  150609. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  150610. r->booklist[booklist++]=bookid;
  150611. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  150612. }
  150613. }
  150614. }
  150615. }else{
  150616. for(i=0;i<r->partitions;i++)
  150617. for(k=0;k<3;k++)
  150618. if(res->books_base->books[i][k])
  150619. r->secondstages[i]|=(1<<k);
  150620. r->groupbook=book_dup_or_new(ci,res->book_aux);
  150621. ci->book_param[r->groupbook]=res->book_aux;
  150622. for(i=0;i<r->partitions;i++){
  150623. for(k=0;k<3;k++){
  150624. if(res->books_base->books[i][k]){
  150625. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  150626. r->booklist[booklist++]=bookid;
  150627. ci->book_param[bookid]=res->books_base->books[i][k];
  150628. }
  150629. }
  150630. }
  150631. }
  150632. }
  150633. /* lowpass setup/pointlimit */
  150634. {
  150635. double freq=ci->hi.lowpass_kHz*1000.;
  150636. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  150637. double nyq=vi->rate/2.;
  150638. long blocksize=ci->blocksizes[block]>>1;
  150639. /* lowpass needs to be set in the floor and the residue. */
  150640. if(freq>nyq)freq=nyq;
  150641. /* in the floor, the granularity can be very fine; it doesn't alter
  150642. the encoding structure, only the samples used to fit the floor
  150643. approximation */
  150644. f->n=freq/nyq*blocksize;
  150645. /* this res may by limited by the maximum pointlimit of the mode,
  150646. not the lowpass. the floor is always lowpass limited. */
  150647. if(res->limit_type){
  150648. if(ci->hi.managed)
  150649. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  150650. else
  150651. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  150652. if(freq>nyq)freq=nyq;
  150653. }
  150654. /* in the residue, we're constrained, physically, by partition
  150655. boundaries. We still lowpass 'wherever', but we have to round up
  150656. here to next boundary, or the vorbis spec will round it *down* to
  150657. previous boundary in encode/decode */
  150658. if(ci->residue_type[block]==2)
  150659. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  150660. r->grouping;
  150661. else
  150662. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  150663. r->grouping;
  150664. }
  150665. }
  150666. /* we assume two maps in this encoder */
  150667. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  150668. vorbis_mapping_template *maps){
  150669. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150670. int i,j,is=s,modes=2;
  150671. vorbis_info_mapping0 *map=maps[is].map;
  150672. vorbis_info_mode *mode=_mode_template;
  150673. vorbis_residue_template *res=maps[is].res;
  150674. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  150675. for(i=0;i<modes;i++){
  150676. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  150677. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  150678. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  150679. if(i>=ci->modes)ci->modes=i+1;
  150680. ci->map_type[i]=0;
  150681. memcpy(ci->map_param[i],map+i,sizeof(*map));
  150682. if(i>=ci->maps)ci->maps=i+1;
  150683. for(j=0;j<map[i].submaps;j++)
  150684. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  150685. ,res+map[i].residuesubmap[j]);
  150686. }
  150687. }
  150688. static double setting_to_approx_bitrate(vorbis_info *vi){
  150689. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150690. highlevel_encode_setup *hi=&ci->hi;
  150691. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  150692. int is=hi->base_setting;
  150693. double ds=hi->base_setting-is;
  150694. int ch=vi->channels;
  150695. double *r=setup->rate_mapping;
  150696. if(r==NULL)
  150697. return(-1);
  150698. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  150699. }
  150700. static void get_setup_template(vorbis_info *vi,
  150701. long ch,long srate,
  150702. double req,int q_or_bitrate){
  150703. int i=0,j;
  150704. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150705. highlevel_encode_setup *hi=&ci->hi;
  150706. if(q_or_bitrate)req/=ch;
  150707. while(setup_list[i]){
  150708. if(setup_list[i]->coupling_restriction==-1 ||
  150709. setup_list[i]->coupling_restriction==ch){
  150710. if(srate>=setup_list[i]->samplerate_min_restriction &&
  150711. srate<=setup_list[i]->samplerate_max_restriction){
  150712. int mappings=setup_list[i]->mappings;
  150713. double *map=(q_or_bitrate?
  150714. setup_list[i]->rate_mapping:
  150715. setup_list[i]->quality_mapping);
  150716. /* the template matches. Does the requested quality mode
  150717. fall within this template's modes? */
  150718. if(req<map[0]){++i;continue;}
  150719. if(req>map[setup_list[i]->mappings]){++i;continue;}
  150720. for(j=0;j<mappings;j++)
  150721. if(req>=map[j] && req<map[j+1])break;
  150722. /* an all-points match */
  150723. hi->setup=setup_list[i];
  150724. if(j==mappings)
  150725. hi->base_setting=j-.001;
  150726. else{
  150727. float low=map[j];
  150728. float high=map[j+1];
  150729. float del=(req-low)/(high-low);
  150730. hi->base_setting=j+del;
  150731. }
  150732. return;
  150733. }
  150734. }
  150735. i++;
  150736. }
  150737. hi->setup=NULL;
  150738. }
  150739. /* encoders will need to use vorbis_info_init beforehand and call
  150740. vorbis_info clear when all done */
  150741. /* two interfaces; this, more detailed one, and later a convenience
  150742. layer on top */
  150743. /* the final setup call */
  150744. int vorbis_encode_setup_init(vorbis_info *vi){
  150745. int i0=0,singleblock=0;
  150746. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150747. ve_setup_data_template *setup=NULL;
  150748. highlevel_encode_setup *hi=&ci->hi;
  150749. if(ci==NULL)return(OV_EINVAL);
  150750. if(!hi->impulse_block_p)i0=1;
  150751. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  150752. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  150753. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  150754. /* again, bound this to avoid the app shooting itself int he foot
  150755. too badly */
  150756. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  150757. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  150758. /* get the appropriate setup template; matches the fetch in previous
  150759. stages */
  150760. setup=(ve_setup_data_template *)hi->setup;
  150761. if(setup==NULL)return(OV_EINVAL);
  150762. hi->set_in_stone=1;
  150763. /* choose block sizes from configured sizes as well as paying
  150764. attention to long_block_p and short_block_p. If the configured
  150765. short and long blocks are the same length, we set long_block_p
  150766. and unset short_block_p */
  150767. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  150768. setup->blocksize_short,
  150769. setup->blocksize_long);
  150770. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  150771. /* floor setup; choose proper floor params. Allocated on the floor
  150772. stack in order; if we alloc only long floor, it's 0 */
  150773. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  150774. setup->floor_books,
  150775. setup->floor_params,
  150776. setup->floor_short_mapping);
  150777. if(!singleblock)
  150778. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  150779. setup->floor_books,
  150780. setup->floor_params,
  150781. setup->floor_long_mapping);
  150782. /* setup of [mostly] short block detection and stereo*/
  150783. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  150784. setup->global_params,
  150785. setup->global_mapping);
  150786. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  150787. /* basic psych setup and noise normalization */
  150788. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150789. setup->psy_noise_normal_start[0],
  150790. setup->psy_noise_normal_partition[0],
  150791. setup->psy_noise_normal_thresh,
  150792. 0);
  150793. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150794. setup->psy_noise_normal_start[0],
  150795. setup->psy_noise_normal_partition[0],
  150796. setup->psy_noise_normal_thresh,
  150797. 1);
  150798. if(!singleblock){
  150799. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150800. setup->psy_noise_normal_start[1],
  150801. setup->psy_noise_normal_partition[1],
  150802. setup->psy_noise_normal_thresh,
  150803. 2);
  150804. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150805. setup->psy_noise_normal_start[1],
  150806. setup->psy_noise_normal_partition[1],
  150807. setup->psy_noise_normal_thresh,
  150808. 3);
  150809. }
  150810. /* tone masking setup */
  150811. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  150812. setup->psy_tone_masteratt,
  150813. setup->psy_tone_0dB,
  150814. setup->psy_tone_adj_impulse);
  150815. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  150816. setup->psy_tone_masteratt,
  150817. setup->psy_tone_0dB,
  150818. setup->psy_tone_adj_other);
  150819. if(!singleblock){
  150820. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  150821. setup->psy_tone_masteratt,
  150822. setup->psy_tone_0dB,
  150823. setup->psy_tone_adj_other);
  150824. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  150825. setup->psy_tone_masteratt,
  150826. setup->psy_tone_0dB,
  150827. setup->psy_tone_adj_long);
  150828. }
  150829. /* noise companding setup */
  150830. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  150831. setup->psy_noise_compand,
  150832. setup->psy_noise_compand_short_mapping);
  150833. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  150834. setup->psy_noise_compand,
  150835. setup->psy_noise_compand_short_mapping);
  150836. if(!singleblock){
  150837. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  150838. setup->psy_noise_compand,
  150839. setup->psy_noise_compand_long_mapping);
  150840. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  150841. setup->psy_noise_compand,
  150842. setup->psy_noise_compand_long_mapping);
  150843. }
  150844. /* peak guarding setup */
  150845. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  150846. setup->psy_tone_dBsuppress);
  150847. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  150848. setup->psy_tone_dBsuppress);
  150849. if(!singleblock){
  150850. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  150851. setup->psy_tone_dBsuppress);
  150852. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  150853. setup->psy_tone_dBsuppress);
  150854. }
  150855. /* noise bias setup */
  150856. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  150857. setup->psy_noise_dBsuppress,
  150858. setup->psy_noise_bias_impulse,
  150859. setup->psy_noiseguards,
  150860. (i0==0?hi->impulse_noisetune:0.));
  150861. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  150862. setup->psy_noise_dBsuppress,
  150863. setup->psy_noise_bias_padding,
  150864. setup->psy_noiseguards,0.);
  150865. if(!singleblock){
  150866. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  150867. setup->psy_noise_dBsuppress,
  150868. setup->psy_noise_bias_trans,
  150869. setup->psy_noiseguards,0.);
  150870. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  150871. setup->psy_noise_dBsuppress,
  150872. setup->psy_noise_bias_long,
  150873. setup->psy_noiseguards,0.);
  150874. }
  150875. vorbis_encode_ath_setup(vi,0);
  150876. vorbis_encode_ath_setup(vi,1);
  150877. if(!singleblock){
  150878. vorbis_encode_ath_setup(vi,2);
  150879. vorbis_encode_ath_setup(vi,3);
  150880. }
  150881. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  150882. /* set bitrate readonlies and management */
  150883. if(hi->bitrate_av>0)
  150884. vi->bitrate_nominal=hi->bitrate_av;
  150885. else{
  150886. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  150887. }
  150888. vi->bitrate_lower=hi->bitrate_min;
  150889. vi->bitrate_upper=hi->bitrate_max;
  150890. if(hi->bitrate_av)
  150891. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  150892. else
  150893. vi->bitrate_window=0.;
  150894. if(hi->managed){
  150895. ci->bi.avg_rate=hi->bitrate_av;
  150896. ci->bi.min_rate=hi->bitrate_min;
  150897. ci->bi.max_rate=hi->bitrate_max;
  150898. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  150899. ci->bi.reservoir_bias=
  150900. hi->bitrate_reservoir_bias;
  150901. ci->bi.slew_damp=hi->bitrate_av_damp;
  150902. }
  150903. return(0);
  150904. }
  150905. static int vorbis_encode_setup_setting(vorbis_info *vi,
  150906. long channels,
  150907. long rate){
  150908. int ret=0,i,is;
  150909. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150910. highlevel_encode_setup *hi=&ci->hi;
  150911. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  150912. double ds;
  150913. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  150914. if(ret)return(ret);
  150915. is=hi->base_setting;
  150916. ds=hi->base_setting-is;
  150917. hi->short_setting=hi->base_setting;
  150918. hi->long_setting=hi->base_setting;
  150919. hi->managed=0;
  150920. hi->impulse_block_p=1;
  150921. hi->noise_normalize_p=1;
  150922. hi->stereo_point_setting=hi->base_setting;
  150923. hi->lowpass_kHz=
  150924. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  150925. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  150926. setup->psy_ath_float[is+1]*ds;
  150927. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  150928. setup->psy_ath_abs[is+1]*ds;
  150929. hi->amplitude_track_dBpersec=-6.;
  150930. hi->trigger_setting=hi->base_setting;
  150931. for(i=0;i<4;i++){
  150932. hi->block[i].tone_mask_setting=hi->base_setting;
  150933. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  150934. hi->block[i].noise_bias_setting=hi->base_setting;
  150935. hi->block[i].noise_compand_setting=hi->base_setting;
  150936. }
  150937. return(ret);
  150938. }
  150939. int vorbis_encode_setup_vbr(vorbis_info *vi,
  150940. long channels,
  150941. long rate,
  150942. float quality){
  150943. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150944. highlevel_encode_setup *hi=&ci->hi;
  150945. quality+=.0000001;
  150946. if(quality>=1.)quality=.9999;
  150947. get_setup_template(vi,channels,rate,quality,0);
  150948. if(!hi->setup)return OV_EIMPL;
  150949. return vorbis_encode_setup_setting(vi,channels,rate);
  150950. }
  150951. int vorbis_encode_init_vbr(vorbis_info *vi,
  150952. long channels,
  150953. long rate,
  150954. float base_quality /* 0. to 1. */
  150955. ){
  150956. int ret=0;
  150957. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  150958. if(ret){
  150959. vorbis_info_clear(vi);
  150960. return ret;
  150961. }
  150962. ret=vorbis_encode_setup_init(vi);
  150963. if(ret)
  150964. vorbis_info_clear(vi);
  150965. return(ret);
  150966. }
  150967. int vorbis_encode_setup_managed(vorbis_info *vi,
  150968. long channels,
  150969. long rate,
  150970. long max_bitrate,
  150971. long nominal_bitrate,
  150972. long min_bitrate){
  150973. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150974. highlevel_encode_setup *hi=&ci->hi;
  150975. double tnominal=nominal_bitrate;
  150976. int ret=0;
  150977. if(nominal_bitrate<=0.){
  150978. if(max_bitrate>0.){
  150979. if(min_bitrate>0.)
  150980. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  150981. else
  150982. nominal_bitrate=max_bitrate*.875;
  150983. }else{
  150984. if(min_bitrate>0.){
  150985. nominal_bitrate=min_bitrate;
  150986. }else{
  150987. return(OV_EINVAL);
  150988. }
  150989. }
  150990. }
  150991. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  150992. if(!hi->setup)return OV_EIMPL;
  150993. ret=vorbis_encode_setup_setting(vi,channels,rate);
  150994. if(ret){
  150995. vorbis_info_clear(vi);
  150996. return ret;
  150997. }
  150998. /* initialize management with sane defaults */
  150999. hi->managed=1;
  151000. hi->bitrate_min=min_bitrate;
  151001. hi->bitrate_max=max_bitrate;
  151002. hi->bitrate_av=tnominal;
  151003. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  151004. hi->bitrate_reservoir=nominal_bitrate*2;
  151005. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  151006. return(ret);
  151007. }
  151008. int vorbis_encode_init(vorbis_info *vi,
  151009. long channels,
  151010. long rate,
  151011. long max_bitrate,
  151012. long nominal_bitrate,
  151013. long min_bitrate){
  151014. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  151015. max_bitrate,
  151016. nominal_bitrate,
  151017. min_bitrate);
  151018. if(ret){
  151019. vorbis_info_clear(vi);
  151020. return(ret);
  151021. }
  151022. ret=vorbis_encode_setup_init(vi);
  151023. if(ret)
  151024. vorbis_info_clear(vi);
  151025. return(ret);
  151026. }
  151027. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  151028. if(vi){
  151029. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  151030. highlevel_encode_setup *hi=&ci->hi;
  151031. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  151032. if(setp && hi->set_in_stone)return(OV_EINVAL);
  151033. switch(number){
  151034. /* now deprecated *****************/
  151035. case OV_ECTL_RATEMANAGE_GET:
  151036. {
  151037. struct ovectl_ratemanage_arg *ai=
  151038. (struct ovectl_ratemanage_arg *)arg;
  151039. ai->management_active=hi->managed;
  151040. ai->bitrate_hard_window=ai->bitrate_av_window=
  151041. (double)hi->bitrate_reservoir/vi->rate;
  151042. ai->bitrate_av_window_center=1.;
  151043. ai->bitrate_hard_min=hi->bitrate_min;
  151044. ai->bitrate_hard_max=hi->bitrate_max;
  151045. ai->bitrate_av_lo=hi->bitrate_av;
  151046. ai->bitrate_av_hi=hi->bitrate_av;
  151047. }
  151048. return(0);
  151049. /* now deprecated *****************/
  151050. case OV_ECTL_RATEMANAGE_SET:
  151051. {
  151052. struct ovectl_ratemanage_arg *ai=
  151053. (struct ovectl_ratemanage_arg *)arg;
  151054. if(ai==NULL){
  151055. hi->managed=0;
  151056. }else{
  151057. hi->managed=ai->management_active;
  151058. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  151059. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  151060. }
  151061. }
  151062. return 0;
  151063. /* now deprecated *****************/
  151064. case OV_ECTL_RATEMANAGE_AVG:
  151065. {
  151066. struct ovectl_ratemanage_arg *ai=
  151067. (struct ovectl_ratemanage_arg *)arg;
  151068. if(ai==NULL){
  151069. hi->bitrate_av=0;
  151070. }else{
  151071. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  151072. }
  151073. }
  151074. return(0);
  151075. /* now deprecated *****************/
  151076. case OV_ECTL_RATEMANAGE_HARD:
  151077. {
  151078. struct ovectl_ratemanage_arg *ai=
  151079. (struct ovectl_ratemanage_arg *)arg;
  151080. if(ai==NULL){
  151081. hi->bitrate_min=0;
  151082. hi->bitrate_max=0;
  151083. }else{
  151084. hi->bitrate_min=ai->bitrate_hard_min;
  151085. hi->bitrate_max=ai->bitrate_hard_max;
  151086. hi->bitrate_reservoir=ai->bitrate_hard_window*
  151087. (hi->bitrate_max+hi->bitrate_min)*.5;
  151088. }
  151089. if(hi->bitrate_reservoir<128.)
  151090. hi->bitrate_reservoir=128.;
  151091. }
  151092. return(0);
  151093. /* replacement ratemanage interface */
  151094. case OV_ECTL_RATEMANAGE2_GET:
  151095. {
  151096. struct ovectl_ratemanage2_arg *ai=
  151097. (struct ovectl_ratemanage2_arg *)arg;
  151098. if(ai==NULL)return OV_EINVAL;
  151099. ai->management_active=hi->managed;
  151100. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  151101. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  151102. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  151103. ai->bitrate_average_damping=hi->bitrate_av_damp;
  151104. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  151105. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  151106. }
  151107. return (0);
  151108. case OV_ECTL_RATEMANAGE2_SET:
  151109. {
  151110. struct ovectl_ratemanage2_arg *ai=
  151111. (struct ovectl_ratemanage2_arg *)arg;
  151112. if(ai==NULL){
  151113. hi->managed=0;
  151114. }else{
  151115. /* sanity check; only catch invariant violations */
  151116. if(ai->bitrate_limit_min_kbps>0 &&
  151117. ai->bitrate_average_kbps>0 &&
  151118. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  151119. return OV_EINVAL;
  151120. if(ai->bitrate_limit_max_kbps>0 &&
  151121. ai->bitrate_average_kbps>0 &&
  151122. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  151123. return OV_EINVAL;
  151124. if(ai->bitrate_limit_min_kbps>0 &&
  151125. ai->bitrate_limit_max_kbps>0 &&
  151126. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  151127. return OV_EINVAL;
  151128. if(ai->bitrate_average_damping <= 0.)
  151129. return OV_EINVAL;
  151130. if(ai->bitrate_limit_reservoir_bits < 0)
  151131. return OV_EINVAL;
  151132. if(ai->bitrate_limit_reservoir_bias < 0.)
  151133. return OV_EINVAL;
  151134. if(ai->bitrate_limit_reservoir_bias > 1.)
  151135. return OV_EINVAL;
  151136. hi->managed=ai->management_active;
  151137. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  151138. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  151139. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  151140. hi->bitrate_av_damp=ai->bitrate_average_damping;
  151141. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  151142. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  151143. }
  151144. }
  151145. return 0;
  151146. case OV_ECTL_LOWPASS_GET:
  151147. {
  151148. double *farg=(double *)arg;
  151149. *farg=hi->lowpass_kHz;
  151150. }
  151151. return(0);
  151152. case OV_ECTL_LOWPASS_SET:
  151153. {
  151154. double *farg=(double *)arg;
  151155. hi->lowpass_kHz=*farg;
  151156. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  151157. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  151158. }
  151159. return(0);
  151160. case OV_ECTL_IBLOCK_GET:
  151161. {
  151162. double *farg=(double *)arg;
  151163. *farg=hi->impulse_noisetune;
  151164. }
  151165. return(0);
  151166. case OV_ECTL_IBLOCK_SET:
  151167. {
  151168. double *farg=(double *)arg;
  151169. hi->impulse_noisetune=*farg;
  151170. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  151171. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  151172. }
  151173. return(0);
  151174. }
  151175. return(OV_EIMPL);
  151176. }
  151177. return(OV_EINVAL);
  151178. }
  151179. #endif
  151180. /********* End of inlined file: vorbisenc.c *********/
  151181. /********* Start of inlined file: vorbisfile.c *********/
  151182. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  151183. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151184. // tasks..
  151185. #if JUCE_MSVC
  151186. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151187. #endif
  151188. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  151189. #if JUCE_USE_OGGVORBIS
  151190. #include <stdlib.h>
  151191. #include <stdio.h>
  151192. #include <errno.h>
  151193. #include <string.h>
  151194. #include <math.h>
  151195. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  151196. one logical bitstream arranged end to end (the only form of Ogg
  151197. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  151198. multiplexing] is not allowed in Vorbis) */
  151199. /* A Vorbis file can be played beginning to end (streamed) without
  151200. worrying ahead of time about chaining (see decoder_example.c). If
  151201. we have the whole file, however, and want random access
  151202. (seeking/scrubbing) or desire to know the total length/time of a
  151203. file, we need to account for the possibility of chaining. */
  151204. /* We can handle things a number of ways; we can determine the entire
  151205. bitstream structure right off the bat, or find pieces on demand.
  151206. This example determines and caches structure for the entire
  151207. bitstream, but builds a virtual decoder on the fly when moving
  151208. between links in the chain. */
  151209. /* There are also different ways to implement seeking. Enough
  151210. information exists in an Ogg bitstream to seek to
  151211. sample-granularity positions in the output. Or, one can seek by
  151212. picking some portion of the stream roughly in the desired area if
  151213. we only want coarse navigation through the stream. */
  151214. /*************************************************************************
  151215. * Many, many internal helpers. The intention is not to be confusing;
  151216. * rampant duplication and monolithic function implementation would be
  151217. * harder to understand anyway. The high level functions are last. Begin
  151218. * grokking near the end of the file */
  151219. /* read a little more data from the file/pipe into the ogg_sync framer
  151220. */
  151221. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  151222. over 8k gets what they deserve */
  151223. static long _get_data(OggVorbis_File *vf){
  151224. errno=0;
  151225. if(vf->datasource){
  151226. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  151227. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  151228. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  151229. if(bytes==0 && errno)return(-1);
  151230. return(bytes);
  151231. }else
  151232. return(0);
  151233. }
  151234. /* save a tiny smidge of verbosity to make the code more readable */
  151235. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  151236. if(vf->datasource){
  151237. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  151238. vf->offset=offset;
  151239. ogg_sync_reset(&vf->oy);
  151240. }else{
  151241. /* shouldn't happen unless someone writes a broken callback */
  151242. return;
  151243. }
  151244. }
  151245. /* The read/seek functions track absolute position within the stream */
  151246. /* from the head of the stream, get the next page. boundary specifies
  151247. if the function is allowed to fetch more data from the stream (and
  151248. how much) or only use internally buffered data.
  151249. boundary: -1) unbounded search
  151250. 0) read no additional data; use cached only
  151251. n) search for a new page beginning for n bytes
  151252. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  151253. n) found a page at absolute offset n */
  151254. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  151255. ogg_int64_t boundary){
  151256. if(boundary>0)boundary+=vf->offset;
  151257. while(1){
  151258. long more;
  151259. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  151260. more=ogg_sync_pageseek(&vf->oy,og);
  151261. if(more<0){
  151262. /* skipped n bytes */
  151263. vf->offset-=more;
  151264. }else{
  151265. if(more==0){
  151266. /* send more paramedics */
  151267. if(!boundary)return(OV_FALSE);
  151268. {
  151269. long ret=_get_data(vf);
  151270. if(ret==0)return(OV_EOF);
  151271. if(ret<0)return(OV_EREAD);
  151272. }
  151273. }else{
  151274. /* got a page. Return the offset at the page beginning,
  151275. advance the internal offset past the page end */
  151276. ogg_int64_t ret=vf->offset;
  151277. vf->offset+=more;
  151278. return(ret);
  151279. }
  151280. }
  151281. }
  151282. }
  151283. /* find the latest page beginning before the current stream cursor
  151284. position. Much dirtier than the above as Ogg doesn't have any
  151285. backward search linkage. no 'readp' as it will certainly have to
  151286. read. */
  151287. /* returns offset or OV_EREAD, OV_FAULT */
  151288. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  151289. ogg_int64_t begin=vf->offset;
  151290. ogg_int64_t end=begin;
  151291. ogg_int64_t ret;
  151292. ogg_int64_t offset=-1;
  151293. while(offset==-1){
  151294. begin-=CHUNKSIZE;
  151295. if(begin<0)
  151296. begin=0;
  151297. _seek_helper(vf,begin);
  151298. while(vf->offset<end){
  151299. ret=_get_next_page(vf,og,end-vf->offset);
  151300. if(ret==OV_EREAD)return(OV_EREAD);
  151301. if(ret<0){
  151302. break;
  151303. }else{
  151304. offset=ret;
  151305. }
  151306. }
  151307. }
  151308. /* we have the offset. Actually snork and hold the page now */
  151309. _seek_helper(vf,offset);
  151310. ret=_get_next_page(vf,og,CHUNKSIZE);
  151311. if(ret<0)
  151312. /* this shouldn't be possible */
  151313. return(OV_EFAULT);
  151314. return(offset);
  151315. }
  151316. /* finds each bitstream link one at a time using a bisection search
  151317. (has to begin by knowing the offset of the lb's initial page).
  151318. Recurses for each link so it can alloc the link storage after
  151319. finding them all, then unroll and fill the cache at the same time */
  151320. static int _bisect_forward_serialno(OggVorbis_File *vf,
  151321. ogg_int64_t begin,
  151322. ogg_int64_t searched,
  151323. ogg_int64_t end,
  151324. long currentno,
  151325. long m){
  151326. ogg_int64_t endsearched=end;
  151327. ogg_int64_t next=end;
  151328. ogg_page og;
  151329. ogg_int64_t ret;
  151330. /* the below guards against garbage seperating the last and
  151331. first pages of two links. */
  151332. while(searched<endsearched){
  151333. ogg_int64_t bisect;
  151334. if(endsearched-searched<CHUNKSIZE){
  151335. bisect=searched;
  151336. }else{
  151337. bisect=(searched+endsearched)/2;
  151338. }
  151339. _seek_helper(vf,bisect);
  151340. ret=_get_next_page(vf,&og,-1);
  151341. if(ret==OV_EREAD)return(OV_EREAD);
  151342. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  151343. endsearched=bisect;
  151344. if(ret>=0)next=ret;
  151345. }else{
  151346. searched=ret+og.header_len+og.body_len;
  151347. }
  151348. }
  151349. _seek_helper(vf,next);
  151350. ret=_get_next_page(vf,&og,-1);
  151351. if(ret==OV_EREAD)return(OV_EREAD);
  151352. if(searched>=end || ret<0){
  151353. vf->links=m+1;
  151354. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  151355. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  151356. vf->offsets[m+1]=searched;
  151357. }else{
  151358. ret=_bisect_forward_serialno(vf,next,vf->offset,
  151359. end,ogg_page_serialno(&og),m+1);
  151360. if(ret==OV_EREAD)return(OV_EREAD);
  151361. }
  151362. vf->offsets[m]=begin;
  151363. vf->serialnos[m]=currentno;
  151364. return(0);
  151365. }
  151366. /* uses the local ogg_stream storage in vf; this is important for
  151367. non-streaming input sources */
  151368. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  151369. long *serialno,ogg_page *og_ptr){
  151370. ogg_page og;
  151371. ogg_packet op;
  151372. int i,ret;
  151373. if(!og_ptr){
  151374. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  151375. if(llret==OV_EREAD)return(OV_EREAD);
  151376. if(llret<0)return OV_ENOTVORBIS;
  151377. og_ptr=&og;
  151378. }
  151379. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  151380. if(serialno)*serialno=vf->os.serialno;
  151381. vf->ready_state=STREAMSET;
  151382. /* extract the initial header from the first page and verify that the
  151383. Ogg bitstream is in fact Vorbis data */
  151384. vorbis_info_init(vi);
  151385. vorbis_comment_init(vc);
  151386. i=0;
  151387. while(i<3){
  151388. ogg_stream_pagein(&vf->os,og_ptr);
  151389. while(i<3){
  151390. int result=ogg_stream_packetout(&vf->os,&op);
  151391. if(result==0)break;
  151392. if(result==-1){
  151393. ret=OV_EBADHEADER;
  151394. goto bail_header;
  151395. }
  151396. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  151397. goto bail_header;
  151398. }
  151399. i++;
  151400. }
  151401. if(i<3)
  151402. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  151403. ret=OV_EBADHEADER;
  151404. goto bail_header;
  151405. }
  151406. }
  151407. return 0;
  151408. bail_header:
  151409. vorbis_info_clear(vi);
  151410. vorbis_comment_clear(vc);
  151411. vf->ready_state=OPENED;
  151412. return ret;
  151413. }
  151414. /* last step of the OggVorbis_File initialization; get all the
  151415. vorbis_info structs and PCM positions. Only called by the seekable
  151416. initialization (local stream storage is hacked slightly; pay
  151417. attention to how that's done) */
  151418. /* this is void and does not propogate errors up because we want to be
  151419. able to open and use damaged bitstreams as well as we can. Just
  151420. watch out for missing information for links in the OggVorbis_File
  151421. struct */
  151422. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  151423. ogg_page og;
  151424. int i;
  151425. ogg_int64_t ret;
  151426. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  151427. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  151428. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  151429. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  151430. for(i=0;i<vf->links;i++){
  151431. if(i==0){
  151432. /* we already grabbed the initial header earlier. Just set the offset */
  151433. vf->dataoffsets[i]=dataoffset;
  151434. _seek_helper(vf,dataoffset);
  151435. }else{
  151436. /* seek to the location of the initial header */
  151437. _seek_helper(vf,vf->offsets[i]);
  151438. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  151439. vf->dataoffsets[i]=-1;
  151440. }else{
  151441. vf->dataoffsets[i]=vf->offset;
  151442. }
  151443. }
  151444. /* fetch beginning PCM offset */
  151445. if(vf->dataoffsets[i]!=-1){
  151446. ogg_int64_t accumulated=0;
  151447. long lastblock=-1;
  151448. int result;
  151449. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  151450. while(1){
  151451. ogg_packet op;
  151452. ret=_get_next_page(vf,&og,-1);
  151453. if(ret<0)
  151454. /* this should not be possible unless the file is
  151455. truncated/mangled */
  151456. break;
  151457. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  151458. break;
  151459. /* count blocksizes of all frames in the page */
  151460. ogg_stream_pagein(&vf->os,&og);
  151461. while((result=ogg_stream_packetout(&vf->os,&op))){
  151462. if(result>0){ /* ignore holes */
  151463. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  151464. if(lastblock!=-1)
  151465. accumulated+=(lastblock+thisblock)>>2;
  151466. lastblock=thisblock;
  151467. }
  151468. }
  151469. if(ogg_page_granulepos(&og)!=-1){
  151470. /* pcm offset of last packet on the first audio page */
  151471. accumulated= ogg_page_granulepos(&og)-accumulated;
  151472. break;
  151473. }
  151474. }
  151475. /* less than zero? This is a stream with samples trimmed off
  151476. the beginning, a normal occurrence; set the offset to zero */
  151477. if(accumulated<0)accumulated=0;
  151478. vf->pcmlengths[i*2]=accumulated;
  151479. }
  151480. /* get the PCM length of this link. To do this,
  151481. get the last page of the stream */
  151482. {
  151483. ogg_int64_t end=vf->offsets[i+1];
  151484. _seek_helper(vf,end);
  151485. while(1){
  151486. ret=_get_prev_page(vf,&og);
  151487. if(ret<0){
  151488. /* this should not be possible */
  151489. vorbis_info_clear(vf->vi+i);
  151490. vorbis_comment_clear(vf->vc+i);
  151491. break;
  151492. }
  151493. if(ogg_page_granulepos(&og)!=-1){
  151494. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  151495. break;
  151496. }
  151497. vf->offset=ret;
  151498. }
  151499. }
  151500. }
  151501. }
  151502. static int _make_decode_ready(OggVorbis_File *vf){
  151503. if(vf->ready_state>STREAMSET)return 0;
  151504. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  151505. if(vf->seekable){
  151506. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  151507. return OV_EBADLINK;
  151508. }else{
  151509. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  151510. return OV_EBADLINK;
  151511. }
  151512. vorbis_block_init(&vf->vd,&vf->vb);
  151513. vf->ready_state=INITSET;
  151514. vf->bittrack=0.f;
  151515. vf->samptrack=0.f;
  151516. return 0;
  151517. }
  151518. static int _open_seekable2(OggVorbis_File *vf){
  151519. long serialno=vf->current_serialno;
  151520. ogg_int64_t dataoffset=vf->offset, end;
  151521. ogg_page og;
  151522. /* we're partially open and have a first link header state in
  151523. storage in vf */
  151524. /* we can seek, so set out learning all about this file */
  151525. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  151526. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  151527. /* We get the offset for the last page of the physical bitstream.
  151528. Most OggVorbis files will contain a single logical bitstream */
  151529. end=_get_prev_page(vf,&og);
  151530. if(end<0)return(end);
  151531. /* more than one logical bitstream? */
  151532. if(ogg_page_serialno(&og)!=serialno){
  151533. /* Chained bitstream. Bisect-search each logical bitstream
  151534. section. Do so based on serial number only */
  151535. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  151536. }else{
  151537. /* Only one logical bitstream */
  151538. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  151539. }
  151540. /* the initial header memory is referenced by vf after; don't free it */
  151541. _prefetch_all_headers(vf,dataoffset);
  151542. return(ov_raw_seek(vf,0));
  151543. }
  151544. /* clear out the current logical bitstream decoder */
  151545. static void _decode_clear(OggVorbis_File *vf){
  151546. vorbis_dsp_clear(&vf->vd);
  151547. vorbis_block_clear(&vf->vb);
  151548. vf->ready_state=OPENED;
  151549. }
  151550. /* fetch and process a packet. Handles the case where we're at a
  151551. bitstream boundary and dumps the decoding machine. If the decoding
  151552. machine is unloaded, it loads it. It also keeps pcm_offset up to
  151553. date (seek and read both use this. seek uses a special hack with
  151554. readp).
  151555. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  151556. 0) need more data (only if readp==0)
  151557. 1) got a packet
  151558. */
  151559. static int _fetch_and_process_packet(OggVorbis_File *vf,
  151560. ogg_packet *op_in,
  151561. int readp,
  151562. int spanp){
  151563. ogg_page og;
  151564. /* handle one packet. Try to fetch it from current stream state */
  151565. /* extract packets from page */
  151566. while(1){
  151567. /* process a packet if we can. If the machine isn't loaded,
  151568. neither is a page */
  151569. if(vf->ready_state==INITSET){
  151570. while(1) {
  151571. ogg_packet op;
  151572. ogg_packet *op_ptr=(op_in?op_in:&op);
  151573. int result=ogg_stream_packetout(&vf->os,op_ptr);
  151574. ogg_int64_t granulepos;
  151575. op_in=NULL;
  151576. if(result==-1)return(OV_HOLE); /* hole in the data. */
  151577. if(result>0){
  151578. /* got a packet. process it */
  151579. granulepos=op_ptr->granulepos;
  151580. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  151581. header handling. The
  151582. header packets aren't
  151583. audio, so if/when we
  151584. submit them,
  151585. vorbis_synthesis will
  151586. reject them */
  151587. /* suck in the synthesis data and track bitrate */
  151588. {
  151589. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151590. /* for proper use of libvorbis within libvorbisfile,
  151591. oldsamples will always be zero. */
  151592. if(oldsamples)return(OV_EFAULT);
  151593. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  151594. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  151595. vf->bittrack+=op_ptr->bytes*8;
  151596. }
  151597. /* update the pcm offset. */
  151598. if(granulepos!=-1 && !op_ptr->e_o_s){
  151599. int link=(vf->seekable?vf->current_link:0);
  151600. int i,samples;
  151601. /* this packet has a pcm_offset on it (the last packet
  151602. completed on a page carries the offset) After processing
  151603. (above), we know the pcm position of the *last* sample
  151604. ready to be returned. Find the offset of the *first*
  151605. As an aside, this trick is inaccurate if we begin
  151606. reading anew right at the last page; the end-of-stream
  151607. granulepos declares the last frame in the stream, and the
  151608. last packet of the last page may be a partial frame.
  151609. So, we need a previous granulepos from an in-sequence page
  151610. to have a reference point. Thus the !op_ptr->e_o_s clause
  151611. above */
  151612. if(vf->seekable && link>0)
  151613. granulepos-=vf->pcmlengths[link*2];
  151614. if(granulepos<0)granulepos=0; /* actually, this
  151615. shouldn't be possible
  151616. here unless the stream
  151617. is very broken */
  151618. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151619. granulepos-=samples;
  151620. for(i=0;i<link;i++)
  151621. granulepos+=vf->pcmlengths[i*2+1];
  151622. vf->pcm_offset=granulepos;
  151623. }
  151624. return(1);
  151625. }
  151626. }
  151627. else
  151628. break;
  151629. }
  151630. }
  151631. if(vf->ready_state>=OPENED){
  151632. ogg_int64_t ret;
  151633. if(!readp)return(0);
  151634. if((ret=_get_next_page(vf,&og,-1))<0){
  151635. return(OV_EOF); /* eof.
  151636. leave unitialized */
  151637. }
  151638. /* bitrate tracking; add the header's bytes here, the body bytes
  151639. are done by packet above */
  151640. vf->bittrack+=og.header_len*8;
  151641. /* has our decoding just traversed a bitstream boundary? */
  151642. if(vf->ready_state==INITSET){
  151643. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151644. if(!spanp)
  151645. return(OV_EOF);
  151646. _decode_clear(vf);
  151647. if(!vf->seekable){
  151648. vorbis_info_clear(vf->vi);
  151649. vorbis_comment_clear(vf->vc);
  151650. }
  151651. }
  151652. }
  151653. }
  151654. /* Do we need to load a new machine before submitting the page? */
  151655. /* This is different in the seekable and non-seekable cases.
  151656. In the seekable case, we already have all the header
  151657. information loaded and cached; we just initialize the machine
  151658. with it and continue on our merry way.
  151659. In the non-seekable (streaming) case, we'll only be at a
  151660. boundary if we just left the previous logical bitstream and
  151661. we're now nominally at the header of the next bitstream
  151662. */
  151663. if(vf->ready_state!=INITSET){
  151664. int link;
  151665. if(vf->ready_state<STREAMSET){
  151666. if(vf->seekable){
  151667. vf->current_serialno=ogg_page_serialno(&og);
  151668. /* match the serialno to bitstream section. We use this rather than
  151669. offset positions to avoid problems near logical bitstream
  151670. boundaries */
  151671. for(link=0;link<vf->links;link++)
  151672. if(vf->serialnos[link]==vf->current_serialno)break;
  151673. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  151674. stream. error out,
  151675. leave machine
  151676. uninitialized */
  151677. vf->current_link=link;
  151678. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151679. vf->ready_state=STREAMSET;
  151680. }else{
  151681. /* we're streaming */
  151682. /* fetch the three header packets, build the info struct */
  151683. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  151684. if(ret)return(ret);
  151685. vf->current_link++;
  151686. link=0;
  151687. }
  151688. }
  151689. {
  151690. int ret=_make_decode_ready(vf);
  151691. if(ret<0)return ret;
  151692. }
  151693. }
  151694. ogg_stream_pagein(&vf->os,&og);
  151695. }
  151696. }
  151697. /* if, eg, 64 bit stdio is configured by default, this will build with
  151698. fseek64 */
  151699. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  151700. if(f==NULL)return(-1);
  151701. return fseek(f,off,whence);
  151702. }
  151703. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  151704. long ibytes, ov_callbacks callbacks){
  151705. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  151706. int ret;
  151707. memset(vf,0,sizeof(*vf));
  151708. vf->datasource=f;
  151709. vf->callbacks = callbacks;
  151710. /* init the framing state */
  151711. ogg_sync_init(&vf->oy);
  151712. /* perhaps some data was previously read into a buffer for testing
  151713. against other stream types. Allow initialization from this
  151714. previously read data (as we may be reading from a non-seekable
  151715. stream) */
  151716. if(initial){
  151717. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  151718. memcpy(buffer,initial,ibytes);
  151719. ogg_sync_wrote(&vf->oy,ibytes);
  151720. }
  151721. /* can we seek? Stevens suggests the seek test was portable */
  151722. if(offsettest!=-1)vf->seekable=1;
  151723. /* No seeking yet; Set up a 'single' (current) logical bitstream
  151724. entry for partial open */
  151725. vf->links=1;
  151726. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  151727. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  151728. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  151729. /* Try to fetch the headers, maintaining all the storage */
  151730. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  151731. vf->datasource=NULL;
  151732. ov_clear(vf);
  151733. }else
  151734. vf->ready_state=PARTOPEN;
  151735. return(ret);
  151736. }
  151737. static int _ov_open2(OggVorbis_File *vf){
  151738. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  151739. vf->ready_state=OPENED;
  151740. if(vf->seekable){
  151741. int ret=_open_seekable2(vf);
  151742. if(ret){
  151743. vf->datasource=NULL;
  151744. ov_clear(vf);
  151745. }
  151746. return(ret);
  151747. }else
  151748. vf->ready_state=STREAMSET;
  151749. return 0;
  151750. }
  151751. /* clear out the OggVorbis_File struct */
  151752. int ov_clear(OggVorbis_File *vf){
  151753. if(vf){
  151754. vorbis_block_clear(&vf->vb);
  151755. vorbis_dsp_clear(&vf->vd);
  151756. ogg_stream_clear(&vf->os);
  151757. if(vf->vi && vf->links){
  151758. int i;
  151759. for(i=0;i<vf->links;i++){
  151760. vorbis_info_clear(vf->vi+i);
  151761. vorbis_comment_clear(vf->vc+i);
  151762. }
  151763. _ogg_free(vf->vi);
  151764. _ogg_free(vf->vc);
  151765. }
  151766. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  151767. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  151768. if(vf->serialnos)_ogg_free(vf->serialnos);
  151769. if(vf->offsets)_ogg_free(vf->offsets);
  151770. ogg_sync_clear(&vf->oy);
  151771. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  151772. memset(vf,0,sizeof(*vf));
  151773. }
  151774. #ifdef DEBUG_LEAKS
  151775. _VDBG_dump();
  151776. #endif
  151777. return(0);
  151778. }
  151779. /* inspects the OggVorbis file and finds/documents all the logical
  151780. bitstreams contained in it. Tries to be tolerant of logical
  151781. bitstream sections that are truncated/woogie.
  151782. return: -1) error
  151783. 0) OK
  151784. */
  151785. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151786. ov_callbacks callbacks){
  151787. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  151788. if(ret)return ret;
  151789. return _ov_open2(vf);
  151790. }
  151791. int ov_open(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_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151799. }
  151800. /* cheap hack for game usage where downsampling is desirable; there's
  151801. no need for SRC as we can just do it cheaply in libvorbis. */
  151802. int ov_halfrate(OggVorbis_File *vf,int flag){
  151803. int i;
  151804. if(vf->vi==NULL)return OV_EINVAL;
  151805. if(!vf->seekable)return OV_EINVAL;
  151806. if(vf->ready_state>=STREAMSET)
  151807. _decode_clear(vf); /* clear out stream state; later on libvorbis
  151808. will be able to swap this on the fly, but
  151809. for now dumping the decode machine is needed
  151810. to reinit the MDCT lookups. 1.1 libvorbis
  151811. is planned to be able to switch on the fly */
  151812. for(i=0;i<vf->links;i++){
  151813. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  151814. ov_halfrate(vf,0);
  151815. return OV_EINVAL;
  151816. }
  151817. }
  151818. return 0;
  151819. }
  151820. int ov_halfrate_p(OggVorbis_File *vf){
  151821. if(vf->vi==NULL)return OV_EINVAL;
  151822. return vorbis_synthesis_halfrate_p(vf->vi);
  151823. }
  151824. /* Only partially open the vorbis file; test for Vorbisness, and load
  151825. the headers for the first chain. Do not seek (although test for
  151826. seekability). Use ov_test_open to finish opening the file, else
  151827. ov_clear to close/free it. Same return codes as open. */
  151828. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151829. ov_callbacks callbacks)
  151830. {
  151831. return _ov_open1(f,vf,initial,ibytes,callbacks);
  151832. }
  151833. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151834. ov_callbacks callbacks = {
  151835. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151836. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151837. (int (*)(void *)) fclose,
  151838. (long (*)(void *)) ftell
  151839. };
  151840. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151841. }
  151842. int ov_test_open(OggVorbis_File *vf){
  151843. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  151844. return _ov_open2(vf);
  151845. }
  151846. /* How many logical bitstreams in this physical bitstream? */
  151847. long ov_streams(OggVorbis_File *vf){
  151848. return vf->links;
  151849. }
  151850. /* Is the FILE * associated with vf seekable? */
  151851. long ov_seekable(OggVorbis_File *vf){
  151852. return vf->seekable;
  151853. }
  151854. /* returns the bitrate for a given logical bitstream or the entire
  151855. physical bitstream. If the file is open for random access, it will
  151856. find the *actual* average bitrate. If the file is streaming, it
  151857. returns the nominal bitrate (if set) else the average of the
  151858. upper/lower bounds (if set) else -1 (unset).
  151859. If you want the actual bitrate field settings, get them from the
  151860. vorbis_info structs */
  151861. long ov_bitrate(OggVorbis_File *vf,int i){
  151862. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151863. if(i>=vf->links)return(OV_EINVAL);
  151864. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  151865. if(i<0){
  151866. ogg_int64_t bits=0;
  151867. int i;
  151868. float br;
  151869. for(i=0;i<vf->links;i++)
  151870. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  151871. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  151872. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  151873. * so this is slightly transformed to make it work.
  151874. */
  151875. br = bits/ov_time_total(vf,-1);
  151876. return(rint(br));
  151877. }else{
  151878. if(vf->seekable){
  151879. /* return the actual bitrate */
  151880. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  151881. }else{
  151882. /* return nominal if set */
  151883. if(vf->vi[i].bitrate_nominal>0){
  151884. return vf->vi[i].bitrate_nominal;
  151885. }else{
  151886. if(vf->vi[i].bitrate_upper>0){
  151887. if(vf->vi[i].bitrate_lower>0){
  151888. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  151889. }else{
  151890. return vf->vi[i].bitrate_upper;
  151891. }
  151892. }
  151893. return(OV_FALSE);
  151894. }
  151895. }
  151896. }
  151897. }
  151898. /* returns the actual bitrate since last call. returns -1 if no
  151899. additional data to offer since last call (or at beginning of stream),
  151900. EINVAL if stream is only partially open
  151901. */
  151902. long ov_bitrate_instant(OggVorbis_File *vf){
  151903. int link=(vf->seekable?vf->current_link:0);
  151904. long ret;
  151905. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151906. if(vf->samptrack==0)return(OV_FALSE);
  151907. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  151908. vf->bittrack=0.f;
  151909. vf->samptrack=0.f;
  151910. return(ret);
  151911. }
  151912. /* Guess */
  151913. long ov_serialnumber(OggVorbis_File *vf,int i){
  151914. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  151915. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  151916. if(i<0){
  151917. return(vf->current_serialno);
  151918. }else{
  151919. return(vf->serialnos[i]);
  151920. }
  151921. }
  151922. /* returns: total raw (compressed) length of content if i==-1
  151923. raw (compressed) length of that logical bitstream for i==0 to n
  151924. OV_EINVAL if the stream is not seekable (we can't know the length)
  151925. or if stream is only partially open
  151926. */
  151927. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  151928. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151929. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151930. if(i<0){
  151931. ogg_int64_t acc=0;
  151932. int i;
  151933. for(i=0;i<vf->links;i++)
  151934. acc+=ov_raw_total(vf,i);
  151935. return(acc);
  151936. }else{
  151937. return(vf->offsets[i+1]-vf->offsets[i]);
  151938. }
  151939. }
  151940. /* returns: total PCM length (samples) of content if i==-1 PCM length
  151941. (samples) of that logical bitstream for i==0 to n
  151942. OV_EINVAL if the stream is not seekable (we can't know the
  151943. length) or only partially open
  151944. */
  151945. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  151946. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151947. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151948. if(i<0){
  151949. ogg_int64_t acc=0;
  151950. int i;
  151951. for(i=0;i<vf->links;i++)
  151952. acc+=ov_pcm_total(vf,i);
  151953. return(acc);
  151954. }else{
  151955. return(vf->pcmlengths[i*2+1]);
  151956. }
  151957. }
  151958. /* returns: total seconds of content if i==-1
  151959. seconds in that logical bitstream for i==0 to n
  151960. OV_EINVAL if the stream is not seekable (we can't know the
  151961. length) or only partially open
  151962. */
  151963. double ov_time_total(OggVorbis_File *vf,int i){
  151964. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151965. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151966. if(i<0){
  151967. double acc=0;
  151968. int i;
  151969. for(i=0;i<vf->links;i++)
  151970. acc+=ov_time_total(vf,i);
  151971. return(acc);
  151972. }else{
  151973. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  151974. }
  151975. }
  151976. /* seek to an offset relative to the *compressed* data. This also
  151977. scans packets to update the PCM cursor. It will cross a logical
  151978. bitstream boundary, but only if it can't get any packets out of the
  151979. tail of the bitstream we seek to (so no surprises).
  151980. returns zero on success, nonzero on failure */
  151981. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151982. ogg_stream_state work_os;
  151983. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151984. if(!vf->seekable)
  151985. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  151986. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  151987. /* don't yet clear out decoding machine (if it's initialized), in
  151988. the case we're in the same link. Restart the decode lapping, and
  151989. let _fetch_and_process_packet deal with a potential bitstream
  151990. boundary */
  151991. vf->pcm_offset=-1;
  151992. ogg_stream_reset_serialno(&vf->os,
  151993. vf->current_serialno); /* must set serialno */
  151994. vorbis_synthesis_restart(&vf->vd);
  151995. _seek_helper(vf,pos);
  151996. /* we need to make sure the pcm_offset is set, but we don't want to
  151997. advance the raw cursor past good packets just to get to the first
  151998. with a granulepos. That's not equivalent behavior to beginning
  151999. decoding as immediately after the seek position as possible.
  152000. So, a hack. We use two stream states; a local scratch state and
  152001. the shared vf->os stream state. We use the local state to
  152002. scan, and the shared state as a buffer for later decode.
  152003. Unfortuantely, on the last page we still advance to last packet
  152004. because the granulepos on the last page is not necessarily on a
  152005. packet boundary, and we need to make sure the granpos is
  152006. correct.
  152007. */
  152008. {
  152009. ogg_page og;
  152010. ogg_packet op;
  152011. int lastblock=0;
  152012. int accblock=0;
  152013. int thisblock;
  152014. int eosflag;
  152015. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  152016. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  152017. return from not necessarily
  152018. starting from the beginning */
  152019. while(1){
  152020. if(vf->ready_state>=STREAMSET){
  152021. /* snarf/scan a packet if we can */
  152022. int result=ogg_stream_packetout(&work_os,&op);
  152023. if(result>0){
  152024. if(vf->vi[vf->current_link].codec_setup){
  152025. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152026. if(thisblock<0){
  152027. ogg_stream_packetout(&vf->os,NULL);
  152028. thisblock=0;
  152029. }else{
  152030. if(eosflag)
  152031. ogg_stream_packetout(&vf->os,NULL);
  152032. else
  152033. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  152034. }
  152035. if(op.granulepos!=-1){
  152036. int i,link=vf->current_link;
  152037. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  152038. if(granulepos<0)granulepos=0;
  152039. for(i=0;i<link;i++)
  152040. granulepos+=vf->pcmlengths[i*2+1];
  152041. vf->pcm_offset=granulepos-accblock;
  152042. break;
  152043. }
  152044. lastblock=thisblock;
  152045. continue;
  152046. }else
  152047. ogg_stream_packetout(&vf->os,NULL);
  152048. }
  152049. }
  152050. if(!lastblock){
  152051. if(_get_next_page(vf,&og,-1)<0){
  152052. vf->pcm_offset=ov_pcm_total(vf,-1);
  152053. break;
  152054. }
  152055. }else{
  152056. /* huh? Bogus stream with packets but no granulepos */
  152057. vf->pcm_offset=-1;
  152058. break;
  152059. }
  152060. /* has our decoding just traversed a bitstream boundary? */
  152061. if(vf->ready_state>=STREAMSET)
  152062. if(vf->current_serialno!=ogg_page_serialno(&og)){
  152063. _decode_clear(vf); /* clear out stream state */
  152064. ogg_stream_clear(&work_os);
  152065. }
  152066. if(vf->ready_state<STREAMSET){
  152067. int link;
  152068. vf->current_serialno=ogg_page_serialno(&og);
  152069. for(link=0;link<vf->links;link++)
  152070. if(vf->serialnos[link]==vf->current_serialno)break;
  152071. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  152072. error out, leave
  152073. machine uninitialized */
  152074. vf->current_link=link;
  152075. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152076. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  152077. vf->ready_state=STREAMSET;
  152078. }
  152079. ogg_stream_pagein(&vf->os,&og);
  152080. ogg_stream_pagein(&work_os,&og);
  152081. eosflag=ogg_page_eos(&og);
  152082. }
  152083. }
  152084. ogg_stream_clear(&work_os);
  152085. vf->bittrack=0.f;
  152086. vf->samptrack=0.f;
  152087. return(0);
  152088. seek_error:
  152089. /* dump the machine so we're in a known state */
  152090. vf->pcm_offset=-1;
  152091. ogg_stream_clear(&work_os);
  152092. _decode_clear(vf);
  152093. return OV_EBADLINK;
  152094. }
  152095. /* Page granularity seek (faster than sample granularity because we
  152096. don't do the last bit of decode to find a specific sample).
  152097. Seek to the last [granule marked] page preceeding the specified pos
  152098. location, such that decoding past the returned point will quickly
  152099. arrive at the requested position. */
  152100. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  152101. int link=-1;
  152102. ogg_int64_t result=0;
  152103. ogg_int64_t total=ov_pcm_total(vf,-1);
  152104. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152105. if(!vf->seekable)return(OV_ENOSEEK);
  152106. if(pos<0 || pos>total)return(OV_EINVAL);
  152107. /* which bitstream section does this pcm offset occur in? */
  152108. for(link=vf->links-1;link>=0;link--){
  152109. total-=vf->pcmlengths[link*2+1];
  152110. if(pos>=total)break;
  152111. }
  152112. /* search within the logical bitstream for the page with the highest
  152113. pcm_pos preceeding (or equal to) pos. There is a danger here;
  152114. missing pages or incorrect frame number information in the
  152115. bitstream could make our task impossible. Account for that (it
  152116. would be an error condition) */
  152117. /* new search algorithm by HB (Nicholas Vinen) */
  152118. {
  152119. ogg_int64_t end=vf->offsets[link+1];
  152120. ogg_int64_t begin=vf->offsets[link];
  152121. ogg_int64_t begintime = vf->pcmlengths[link*2];
  152122. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  152123. ogg_int64_t target=pos-total+begintime;
  152124. ogg_int64_t best=begin;
  152125. ogg_page og;
  152126. while(begin<end){
  152127. ogg_int64_t bisect;
  152128. if(end-begin<CHUNKSIZE){
  152129. bisect=begin;
  152130. }else{
  152131. /* take a (pretty decent) guess. */
  152132. bisect=begin +
  152133. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  152134. if(bisect<=begin)
  152135. bisect=begin+1;
  152136. }
  152137. _seek_helper(vf,bisect);
  152138. while(begin<end){
  152139. result=_get_next_page(vf,&og,end-vf->offset);
  152140. if(result==OV_EREAD) goto seek_error;
  152141. if(result<0){
  152142. if(bisect<=begin+1)
  152143. end=begin; /* found it */
  152144. else{
  152145. if(bisect==0) goto seek_error;
  152146. bisect-=CHUNKSIZE;
  152147. if(bisect<=begin)bisect=begin+1;
  152148. _seek_helper(vf,bisect);
  152149. }
  152150. }else{
  152151. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  152152. if(granulepos==-1)continue;
  152153. if(granulepos<target){
  152154. best=result; /* raw offset of packet with granulepos */
  152155. begin=vf->offset; /* raw offset of next page */
  152156. begintime=granulepos;
  152157. if(target-begintime>44100)break;
  152158. bisect=begin; /* *not* begin + 1 */
  152159. }else{
  152160. if(bisect<=begin+1)
  152161. end=begin; /* found it */
  152162. else{
  152163. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  152164. end=result;
  152165. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  152166. if(bisect<=begin)bisect=begin+1;
  152167. _seek_helper(vf,bisect);
  152168. }else{
  152169. end=result;
  152170. endtime=granulepos;
  152171. break;
  152172. }
  152173. }
  152174. }
  152175. }
  152176. }
  152177. }
  152178. /* found our page. seek to it, update pcm offset. Easier case than
  152179. raw_seek, don't keep packets preceeding granulepos. */
  152180. {
  152181. ogg_page og;
  152182. ogg_packet op;
  152183. /* seek */
  152184. _seek_helper(vf,best);
  152185. vf->pcm_offset=-1;
  152186. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  152187. if(link!=vf->current_link){
  152188. /* Different link; dump entire decode machine */
  152189. _decode_clear(vf);
  152190. vf->current_link=link;
  152191. vf->current_serialno=ogg_page_serialno(&og);
  152192. vf->ready_state=STREAMSET;
  152193. }else{
  152194. vorbis_synthesis_restart(&vf->vd);
  152195. }
  152196. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152197. ogg_stream_pagein(&vf->os,&og);
  152198. /* pull out all but last packet; the one with granulepos */
  152199. while(1){
  152200. result=ogg_stream_packetpeek(&vf->os,&op);
  152201. if(result==0){
  152202. /* !!! the packet finishing this page originated on a
  152203. preceeding page. Keep fetching previous pages until we
  152204. get one with a granulepos or without the 'continued' flag
  152205. set. Then just use raw_seek for simplicity. */
  152206. _seek_helper(vf,best);
  152207. while(1){
  152208. result=_get_prev_page(vf,&og);
  152209. if(result<0) goto seek_error;
  152210. if(ogg_page_granulepos(&og)>-1 ||
  152211. !ogg_page_continued(&og)){
  152212. return ov_raw_seek(vf,result);
  152213. }
  152214. vf->offset=result;
  152215. }
  152216. }
  152217. if(result<0){
  152218. result = OV_EBADPACKET;
  152219. goto seek_error;
  152220. }
  152221. if(op.granulepos!=-1){
  152222. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152223. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152224. vf->pcm_offset+=total;
  152225. break;
  152226. }else
  152227. result=ogg_stream_packetout(&vf->os,NULL);
  152228. }
  152229. }
  152230. }
  152231. /* verify result */
  152232. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  152233. result=OV_EFAULT;
  152234. goto seek_error;
  152235. }
  152236. vf->bittrack=0.f;
  152237. vf->samptrack=0.f;
  152238. return(0);
  152239. seek_error:
  152240. /* dump machine so we're in a known state */
  152241. vf->pcm_offset=-1;
  152242. _decode_clear(vf);
  152243. return (int)result;
  152244. }
  152245. /* seek to a sample offset relative to the decompressed pcm stream
  152246. returns zero on success, nonzero on failure */
  152247. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152248. int thisblock,lastblock=0;
  152249. int ret=ov_pcm_seek_page(vf,pos);
  152250. if(ret<0)return(ret);
  152251. if((ret=_make_decode_ready(vf)))return ret;
  152252. /* discard leading packets we don't need for the lapping of the
  152253. position we want; don't decode them */
  152254. while(1){
  152255. ogg_packet op;
  152256. ogg_page og;
  152257. int ret=ogg_stream_packetpeek(&vf->os,&op);
  152258. if(ret>0){
  152259. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152260. if(thisblock<0){
  152261. ogg_stream_packetout(&vf->os,NULL);
  152262. continue; /* non audio packet */
  152263. }
  152264. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  152265. if(vf->pcm_offset+((thisblock+
  152266. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  152267. /* remove the packet from packet queue and track its granulepos */
  152268. ogg_stream_packetout(&vf->os,NULL);
  152269. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  152270. only tracking, no
  152271. pcm_decode */
  152272. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152273. /* end of logical stream case is hard, especially with exact
  152274. length positioning. */
  152275. if(op.granulepos>-1){
  152276. int i;
  152277. /* always believe the stream markers */
  152278. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152279. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152280. for(i=0;i<vf->current_link;i++)
  152281. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  152282. }
  152283. lastblock=thisblock;
  152284. }else{
  152285. if(ret<0 && ret!=OV_HOLE)break;
  152286. /* suck in a new page */
  152287. if(_get_next_page(vf,&og,-1)<0)break;
  152288. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  152289. if(vf->ready_state<STREAMSET){
  152290. int link;
  152291. vf->current_serialno=ogg_page_serialno(&og);
  152292. for(link=0;link<vf->links;link++)
  152293. if(vf->serialnos[link]==vf->current_serialno)break;
  152294. if(link==vf->links)return(OV_EBADLINK);
  152295. vf->current_link=link;
  152296. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152297. vf->ready_state=STREAMSET;
  152298. ret=_make_decode_ready(vf);
  152299. if(ret)return ret;
  152300. lastblock=0;
  152301. }
  152302. ogg_stream_pagein(&vf->os,&og);
  152303. }
  152304. }
  152305. vf->bittrack=0.f;
  152306. vf->samptrack=0.f;
  152307. /* discard samples until we reach the desired position. Crossing a
  152308. logical bitstream boundary with abandon is OK. */
  152309. while(vf->pcm_offset<pos){
  152310. ogg_int64_t target=pos-vf->pcm_offset;
  152311. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152312. if(samples>target)samples=target;
  152313. vorbis_synthesis_read(&vf->vd,samples);
  152314. vf->pcm_offset+=samples;
  152315. if(samples<target)
  152316. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  152317. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  152318. }
  152319. return 0;
  152320. }
  152321. /* seek to a playback time relative to the decompressed pcm stream
  152322. returns zero on success, nonzero on failure */
  152323. int ov_time_seek(OggVorbis_File *vf,double seconds){
  152324. /* translate time to PCM position and call ov_pcm_seek */
  152325. int link=-1;
  152326. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  152327. double time_total=ov_time_total(vf,-1);
  152328. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152329. if(!vf->seekable)return(OV_ENOSEEK);
  152330. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  152331. /* which bitstream section does this time offset occur in? */
  152332. for(link=vf->links-1;link>=0;link--){
  152333. pcm_total-=vf->pcmlengths[link*2+1];
  152334. time_total-=ov_time_total(vf,link);
  152335. if(seconds>=time_total)break;
  152336. }
  152337. /* enough information to convert time offset to pcm offset */
  152338. {
  152339. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  152340. return(ov_pcm_seek(vf,target));
  152341. }
  152342. }
  152343. /* page-granularity version of ov_time_seek
  152344. returns zero on success, nonzero on failure */
  152345. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  152346. /* translate time to PCM position and call ov_pcm_seek */
  152347. int link=-1;
  152348. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  152349. double time_total=ov_time_total(vf,-1);
  152350. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152351. if(!vf->seekable)return(OV_ENOSEEK);
  152352. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  152353. /* which bitstream section does this time offset occur in? */
  152354. for(link=vf->links-1;link>=0;link--){
  152355. pcm_total-=vf->pcmlengths[link*2+1];
  152356. time_total-=ov_time_total(vf,link);
  152357. if(seconds>=time_total)break;
  152358. }
  152359. /* enough information to convert time offset to pcm offset */
  152360. {
  152361. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  152362. return(ov_pcm_seek_page(vf,target));
  152363. }
  152364. }
  152365. /* tell the current stream offset cursor. Note that seek followed by
  152366. tell will likely not give the set offset due to caching */
  152367. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  152368. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152369. return(vf->offset);
  152370. }
  152371. /* return PCM offset (sample) of next PCM sample to be read */
  152372. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  152373. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152374. return(vf->pcm_offset);
  152375. }
  152376. /* return time offset (seconds) of next PCM sample to be read */
  152377. double ov_time_tell(OggVorbis_File *vf){
  152378. int link=0;
  152379. ogg_int64_t pcm_total=0;
  152380. double time_total=0.f;
  152381. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152382. if(vf->seekable){
  152383. pcm_total=ov_pcm_total(vf,-1);
  152384. time_total=ov_time_total(vf,-1);
  152385. /* which bitstream section does this time offset occur in? */
  152386. for(link=vf->links-1;link>=0;link--){
  152387. pcm_total-=vf->pcmlengths[link*2+1];
  152388. time_total-=ov_time_total(vf,link);
  152389. if(vf->pcm_offset>=pcm_total)break;
  152390. }
  152391. }
  152392. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  152393. }
  152394. /* link: -1) return the vorbis_info struct for the bitstream section
  152395. currently being decoded
  152396. 0-n) to request information for a specific bitstream section
  152397. In the case of a non-seekable bitstream, any call returns the
  152398. current bitstream. NULL in the case that the machine is not
  152399. initialized */
  152400. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  152401. if(vf->seekable){
  152402. if(link<0)
  152403. if(vf->ready_state>=STREAMSET)
  152404. return vf->vi+vf->current_link;
  152405. else
  152406. return vf->vi;
  152407. else
  152408. if(link>=vf->links)
  152409. return NULL;
  152410. else
  152411. return vf->vi+link;
  152412. }else{
  152413. return vf->vi;
  152414. }
  152415. }
  152416. /* grr, strong typing, grr, no templates/inheritence, grr */
  152417. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  152418. if(vf->seekable){
  152419. if(link<0)
  152420. if(vf->ready_state>=STREAMSET)
  152421. return vf->vc+vf->current_link;
  152422. else
  152423. return vf->vc;
  152424. else
  152425. if(link>=vf->links)
  152426. return NULL;
  152427. else
  152428. return vf->vc+link;
  152429. }else{
  152430. return vf->vc;
  152431. }
  152432. }
  152433. static int host_is_big_endian() {
  152434. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  152435. unsigned char *bytewise = (unsigned char *)&pattern;
  152436. if (bytewise[0] == 0xfe) return 1;
  152437. return 0;
  152438. }
  152439. /* up to this point, everything could more or less hide the multiple
  152440. logical bitstream nature of chaining from the toplevel application
  152441. if the toplevel application didn't particularly care. However, at
  152442. the point that we actually read audio back, the multiple-section
  152443. nature must surface: Multiple bitstream sections do not necessarily
  152444. have to have the same number of channels or sampling rate.
  152445. ov_read returns the sequential logical bitstream number currently
  152446. being decoded along with the PCM data in order that the toplevel
  152447. application can take action on channel/sample rate changes. This
  152448. number will be incremented even for streamed (non-seekable) streams
  152449. (for seekable streams, it represents the actual logical bitstream
  152450. index within the physical bitstream. Note that the accessor
  152451. functions above are aware of this dichotomy).
  152452. input values: buffer) a buffer to hold packed PCM data for return
  152453. length) the byte length requested to be placed into buffer
  152454. bigendianp) should the data be packed LSB first (0) or
  152455. MSB first (1)
  152456. word) word size for output. currently 1 (byte) or
  152457. 2 (16 bit short)
  152458. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152459. 0) EOF
  152460. n) number of bytes of PCM actually returned. The
  152461. below works on a packet-by-packet basis, so the
  152462. return length is not related to the 'length' passed
  152463. in, just guaranteed to fit.
  152464. *section) set to the logical bitstream number */
  152465. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  152466. int bigendianp,int word,int sgned,int *bitstream){
  152467. int i,j;
  152468. int host_endian = host_is_big_endian();
  152469. float **pcm;
  152470. long samples;
  152471. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152472. while(1){
  152473. if(vf->ready_state==INITSET){
  152474. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152475. if(samples)break;
  152476. }
  152477. /* suck in another packet */
  152478. {
  152479. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152480. if(ret==OV_EOF)
  152481. return(0);
  152482. if(ret<=0)
  152483. return(ret);
  152484. }
  152485. }
  152486. if(samples>0){
  152487. /* yay! proceed to pack data into the byte buffer */
  152488. long channels=ov_info(vf,-1)->channels;
  152489. long bytespersample=word * channels;
  152490. vorbis_fpu_control fpu;
  152491. (void) fpu; // (to avoid a warning about it being unused)
  152492. if(samples>length/bytespersample)samples=length/bytespersample;
  152493. if(samples <= 0)
  152494. return OV_EINVAL;
  152495. /* a tight loop to pack each size */
  152496. {
  152497. int val;
  152498. if(word==1){
  152499. int off=(sgned?0:128);
  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]*128.f);
  152504. if(val>127)val=127;
  152505. else if(val<-128)val=-128;
  152506. *buffer++=val+off;
  152507. }
  152508. vorbis_fpu_restore(fpu);
  152509. }else{
  152510. int off=(sgned?0:32768);
  152511. if(host_endian==bigendianp){
  152512. if(sgned){
  152513. vorbis_fpu_setround(&fpu);
  152514. for(i=0;i<channels;i++) { /* It's faster in this order */
  152515. float *src=pcm[i];
  152516. short *dest=((short *)buffer)+i;
  152517. for(j=0;j<samples;j++) {
  152518. val=vorbis_ftoi(src[j]*32768.f);
  152519. if(val>32767)val=32767;
  152520. else if(val<-32768)val=-32768;
  152521. *dest=val;
  152522. dest+=channels;
  152523. }
  152524. }
  152525. vorbis_fpu_restore(fpu);
  152526. }else{
  152527. vorbis_fpu_setround(&fpu);
  152528. for(i=0;i<channels;i++) {
  152529. float *src=pcm[i];
  152530. short *dest=((short *)buffer)+i;
  152531. for(j=0;j<samples;j++) {
  152532. val=vorbis_ftoi(src[j]*32768.f);
  152533. if(val>32767)val=32767;
  152534. else if(val<-32768)val=-32768;
  152535. *dest=val+off;
  152536. dest+=channels;
  152537. }
  152538. }
  152539. vorbis_fpu_restore(fpu);
  152540. }
  152541. }else if(bigendianp){
  152542. vorbis_fpu_setround(&fpu);
  152543. for(j=0;j<samples;j++)
  152544. for(i=0;i<channels;i++){
  152545. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152546. if(val>32767)val=32767;
  152547. else if(val<-32768)val=-32768;
  152548. val+=off;
  152549. *buffer++=(val>>8);
  152550. *buffer++=(val&0xff);
  152551. }
  152552. vorbis_fpu_restore(fpu);
  152553. }else{
  152554. int val;
  152555. vorbis_fpu_setround(&fpu);
  152556. for(j=0;j<samples;j++)
  152557. for(i=0;i<channels;i++){
  152558. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152559. if(val>32767)val=32767;
  152560. else if(val<-32768)val=-32768;
  152561. val+=off;
  152562. *buffer++=(val&0xff);
  152563. *buffer++=(val>>8);
  152564. }
  152565. vorbis_fpu_restore(fpu);
  152566. }
  152567. }
  152568. }
  152569. vorbis_synthesis_read(&vf->vd,samples);
  152570. vf->pcm_offset+=samples;
  152571. if(bitstream)*bitstream=vf->current_link;
  152572. return(samples*bytespersample);
  152573. }else{
  152574. return(samples);
  152575. }
  152576. }
  152577. /* input values: pcm_channels) a float vector per channel of output
  152578. length) the sample length being read by the app
  152579. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152580. 0) EOF
  152581. n) number of samples of PCM actually returned. The
  152582. below works on a packet-by-packet basis, so the
  152583. return length is not related to the 'length' passed
  152584. in, just guaranteed to fit.
  152585. *section) set to the logical bitstream number */
  152586. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  152587. int *bitstream){
  152588. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152589. while(1){
  152590. if(vf->ready_state==INITSET){
  152591. float **pcm;
  152592. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152593. if(samples){
  152594. if(pcm_channels)*pcm_channels=pcm;
  152595. if(samples>length)samples=length;
  152596. vorbis_synthesis_read(&vf->vd,samples);
  152597. vf->pcm_offset+=samples;
  152598. if(bitstream)*bitstream=vf->current_link;
  152599. return samples;
  152600. }
  152601. }
  152602. /* suck in another packet */
  152603. {
  152604. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152605. if(ret==OV_EOF)return(0);
  152606. if(ret<=0)return(ret);
  152607. }
  152608. }
  152609. }
  152610. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  152611. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  152612. ogg_int64_t off);
  152613. static void _ov_splice(float **pcm,float **lappcm,
  152614. int n1, int n2,
  152615. int ch1, int ch2,
  152616. float *w1, float *w2){
  152617. int i,j;
  152618. float *w=w1;
  152619. int n=n1;
  152620. if(n1>n2){
  152621. n=n2;
  152622. w=w2;
  152623. }
  152624. /* splice */
  152625. for(j=0;j<ch1 && j<ch2;j++){
  152626. float *s=lappcm[j];
  152627. float *d=pcm[j];
  152628. for(i=0;i<n;i++){
  152629. float wd=w[i]*w[i];
  152630. float ws=1.-wd;
  152631. d[i]=d[i]*wd + s[i]*ws;
  152632. }
  152633. }
  152634. /* window from zero */
  152635. for(;j<ch2;j++){
  152636. float *d=pcm[j];
  152637. for(i=0;i<n;i++){
  152638. float wd=w[i]*w[i];
  152639. d[i]=d[i]*wd;
  152640. }
  152641. }
  152642. }
  152643. /* make sure vf is INITSET */
  152644. static int _ov_initset(OggVorbis_File *vf){
  152645. while(1){
  152646. if(vf->ready_state==INITSET)break;
  152647. /* suck in another packet */
  152648. {
  152649. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152650. if(ret<0 && ret!=OV_HOLE)return(ret);
  152651. }
  152652. }
  152653. return 0;
  152654. }
  152655. /* make sure vf is INITSET and that we have a primed buffer; if
  152656. we're crosslapping at a stream section boundary, this also makes
  152657. sure we're sanity checking against the right stream information */
  152658. static int _ov_initprime(OggVorbis_File *vf){
  152659. vorbis_dsp_state *vd=&vf->vd;
  152660. while(1){
  152661. if(vf->ready_state==INITSET)
  152662. if(vorbis_synthesis_pcmout(vd,NULL))break;
  152663. /* suck in another packet */
  152664. {
  152665. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152666. if(ret<0 && ret!=OV_HOLE)return(ret);
  152667. }
  152668. }
  152669. return 0;
  152670. }
  152671. /* grab enough data for lapping from vf; this may be in the form of
  152672. unreturned, already-decoded pcm, remaining PCM we will need to
  152673. decode, or synthetic postextrapolation from last packets. */
  152674. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  152675. float **lappcm,int lapsize){
  152676. int lapcount=0,i;
  152677. float **pcm;
  152678. /* try first to decode the lapping data */
  152679. while(lapcount<lapsize){
  152680. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  152681. if(samples){
  152682. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152683. for(i=0;i<vi->channels;i++)
  152684. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152685. lapcount+=samples;
  152686. vorbis_synthesis_read(vd,samples);
  152687. }else{
  152688. /* suck in another packet */
  152689. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  152690. if(ret==OV_EOF)break;
  152691. }
  152692. }
  152693. if(lapcount<lapsize){
  152694. /* failed to get lapping data from normal decode; pry it from the
  152695. postextrapolation buffering, or the second half of the MDCT
  152696. from the last packet */
  152697. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  152698. if(samples==0){
  152699. for(i=0;i<vi->channels;i++)
  152700. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  152701. lapcount=lapsize;
  152702. }else{
  152703. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152704. for(i=0;i<vi->channels;i++)
  152705. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152706. lapcount+=samples;
  152707. }
  152708. }
  152709. }
  152710. /* this sets up crosslapping of a sample by using trailing data from
  152711. sample 1 and lapping it into the windowing buffer of sample 2 */
  152712. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  152713. vorbis_info *vi1,*vi2;
  152714. float **lappcm;
  152715. float **pcm;
  152716. float *w1,*w2;
  152717. int n1,n2,i,ret,hs1,hs2;
  152718. if(vf1==vf2)return(0); /* degenerate case */
  152719. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  152720. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  152721. /* the relevant overlap buffers must be pre-checked and pre-primed
  152722. before looking at settings in the event that priming would cross
  152723. a bitstream boundary. So, do it now */
  152724. ret=_ov_initset(vf1);
  152725. if(ret)return(ret);
  152726. ret=_ov_initprime(vf2);
  152727. if(ret)return(ret);
  152728. vi1=ov_info(vf1,-1);
  152729. vi2=ov_info(vf2,-1);
  152730. hs1=ov_halfrate_p(vf1);
  152731. hs2=ov_halfrate_p(vf2);
  152732. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  152733. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  152734. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  152735. w1=vorbis_window(&vf1->vd,0);
  152736. w2=vorbis_window(&vf2->vd,0);
  152737. for(i=0;i<vi1->channels;i++)
  152738. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152739. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  152740. /* have a lapping buffer from vf1; now to splice it into the lapping
  152741. buffer of vf2 */
  152742. /* consolidate and expose the buffer. */
  152743. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  152744. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  152745. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  152746. /* splice */
  152747. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  152748. /* done */
  152749. return(0);
  152750. }
  152751. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  152752. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  152753. vorbis_info *vi;
  152754. float **lappcm;
  152755. float **pcm;
  152756. float *w1,*w2;
  152757. int n1,n2,ch1,ch2,hs;
  152758. int i,ret;
  152759. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152760. ret=_ov_initset(vf);
  152761. if(ret)return(ret);
  152762. vi=ov_info(vf,-1);
  152763. hs=ov_halfrate_p(vf);
  152764. ch1=vi->channels;
  152765. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152766. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152767. persistent; even if the decode state
  152768. from this link gets dumped, this
  152769. window array continues to exist */
  152770. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152771. for(i=0;i<ch1;i++)
  152772. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152773. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152774. /* have lapping data; seek and prime the buffer */
  152775. ret=localseek(vf,pos);
  152776. if(ret)return ret;
  152777. ret=_ov_initprime(vf);
  152778. if(ret)return(ret);
  152779. /* Guard against cross-link changes; they're perfectly legal */
  152780. vi=ov_info(vf,-1);
  152781. ch2=vi->channels;
  152782. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152783. w2=vorbis_window(&vf->vd,0);
  152784. /* consolidate and expose the buffer. */
  152785. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152786. /* splice */
  152787. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152788. /* done */
  152789. return(0);
  152790. }
  152791. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152792. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  152793. }
  152794. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152795. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  152796. }
  152797. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152798. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  152799. }
  152800. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  152801. int (*localseek)(OggVorbis_File *,double)){
  152802. vorbis_info *vi;
  152803. float **lappcm;
  152804. float **pcm;
  152805. float *w1,*w2;
  152806. int n1,n2,ch1,ch2,hs;
  152807. int i,ret;
  152808. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152809. ret=_ov_initset(vf);
  152810. if(ret)return(ret);
  152811. vi=ov_info(vf,-1);
  152812. hs=ov_halfrate_p(vf);
  152813. ch1=vi->channels;
  152814. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152815. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152816. persistent; even if the decode state
  152817. from this link gets dumped, this
  152818. window array continues to exist */
  152819. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152820. for(i=0;i<ch1;i++)
  152821. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152822. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152823. /* have lapping data; seek and prime the buffer */
  152824. ret=localseek(vf,pos);
  152825. if(ret)return ret;
  152826. ret=_ov_initprime(vf);
  152827. if(ret)return(ret);
  152828. /* Guard against cross-link changes; they're perfectly legal */
  152829. vi=ov_info(vf,-1);
  152830. ch2=vi->channels;
  152831. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152832. w2=vorbis_window(&vf->vd,0);
  152833. /* consolidate and expose the buffer. */
  152834. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152835. /* splice */
  152836. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152837. /* done */
  152838. return(0);
  152839. }
  152840. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  152841. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  152842. }
  152843. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  152844. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  152845. }
  152846. #endif
  152847. /********* End of inlined file: vorbisfile.c *********/
  152848. /********* Start of inlined file: window.c *********/
  152849. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  152850. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  152851. // tasks..
  152852. #if JUCE_MSVC
  152853. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  152854. #endif
  152855. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  152856. #if JUCE_USE_OGGVORBIS
  152857. #include <stdlib.h>
  152858. #include <math.h>
  152859. static float vwin64[32] = {
  152860. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  152861. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  152862. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  152863. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  152864. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  152865. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  152866. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  152867. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  152868. };
  152869. static float vwin128[64] = {
  152870. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  152871. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  152872. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  152873. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  152874. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  152875. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  152876. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  152877. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  152878. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  152879. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  152880. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  152881. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  152882. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  152883. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  152884. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  152885. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  152886. };
  152887. static float vwin256[128] = {
  152888. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  152889. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  152890. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  152891. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  152892. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  152893. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  152894. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  152895. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  152896. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  152897. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  152898. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  152899. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  152900. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  152901. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  152902. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  152903. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  152904. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  152905. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  152906. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  152907. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  152908. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  152909. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  152910. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  152911. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  152912. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  152913. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  152914. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  152915. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  152916. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  152917. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  152918. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  152919. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  152920. };
  152921. static float vwin512[256] = {
  152922. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  152923. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  152924. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  152925. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  152926. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  152927. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  152928. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  152929. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  152930. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  152931. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  152932. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  152933. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  152934. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  152935. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  152936. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  152937. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  152938. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  152939. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  152940. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  152941. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  152942. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  152943. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  152944. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  152945. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  152946. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  152947. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  152948. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  152949. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  152950. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  152951. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  152952. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  152953. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  152954. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  152955. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  152956. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  152957. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  152958. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  152959. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  152960. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  152961. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  152962. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  152963. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  152964. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  152965. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  152966. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  152967. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  152968. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  152969. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  152970. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  152971. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  152972. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  152973. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  152974. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  152975. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  152976. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  152977. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  152978. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  152979. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  152980. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  152981. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  152982. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  152983. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  152984. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  152985. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  152986. };
  152987. static float vwin1024[512] = {
  152988. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  152989. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  152990. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  152991. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  152992. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  152993. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  152994. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  152995. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  152996. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  152997. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  152998. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  152999. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  153000. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  153001. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  153002. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  153003. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  153004. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  153005. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  153006. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  153007. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  153008. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  153009. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  153010. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  153011. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  153012. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  153013. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  153014. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  153015. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  153016. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  153017. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  153018. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  153019. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  153020. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  153021. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  153022. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  153023. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  153024. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  153025. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  153026. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  153027. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  153028. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  153029. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  153030. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  153031. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  153032. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  153033. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  153034. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  153035. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  153036. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  153037. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  153038. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  153039. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  153040. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  153041. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  153042. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  153043. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  153044. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  153045. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  153046. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  153047. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  153048. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  153049. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  153050. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  153051. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  153052. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  153053. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  153054. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  153055. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  153056. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  153057. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  153058. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  153059. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  153060. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  153061. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  153062. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  153063. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  153064. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  153065. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  153066. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  153067. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  153068. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  153069. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  153070. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  153071. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  153072. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  153073. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  153074. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  153075. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  153076. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  153077. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  153078. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  153079. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  153080. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  153081. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  153082. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  153083. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  153084. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  153085. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  153086. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  153087. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  153088. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  153089. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  153090. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  153091. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  153092. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  153093. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  153094. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  153095. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  153096. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  153097. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  153098. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  153099. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  153100. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  153101. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  153102. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  153103. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  153104. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  153105. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  153106. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  153107. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  153108. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  153109. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  153110. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  153111. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  153112. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  153113. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  153114. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  153115. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  153116. };
  153117. static float vwin2048[1024] = {
  153118. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  153119. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  153120. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  153121. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  153122. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  153123. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  153124. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  153125. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  153126. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  153127. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  153128. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  153129. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  153130. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  153131. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  153132. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  153133. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  153134. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  153135. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  153136. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  153137. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  153138. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  153139. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  153140. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  153141. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  153142. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  153143. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  153144. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  153145. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  153146. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  153147. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  153148. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  153149. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  153150. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  153151. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  153152. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  153153. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  153154. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  153155. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  153156. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  153157. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  153158. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  153159. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  153160. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  153161. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  153162. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  153163. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  153164. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  153165. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  153166. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  153167. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  153168. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  153169. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  153170. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  153171. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  153172. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  153173. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  153174. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  153175. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  153176. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  153177. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  153178. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  153179. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  153180. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  153181. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  153182. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  153183. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  153184. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  153185. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  153186. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  153187. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  153188. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  153189. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  153190. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  153191. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  153192. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  153193. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  153194. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  153195. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  153196. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  153197. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  153198. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  153199. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  153200. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  153201. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  153202. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  153203. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  153204. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  153205. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  153206. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  153207. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  153208. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  153209. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  153210. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  153211. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  153212. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  153213. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  153214. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  153215. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  153216. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  153217. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  153218. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  153219. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  153220. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  153221. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  153222. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  153223. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  153224. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  153225. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  153226. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  153227. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  153228. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  153229. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  153230. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  153231. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  153232. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  153233. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  153234. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  153235. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  153236. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  153237. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  153238. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  153239. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  153240. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  153241. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  153242. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  153243. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  153244. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  153245. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  153246. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  153247. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  153248. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  153249. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  153250. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  153251. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  153252. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  153253. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  153254. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  153255. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  153256. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  153257. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  153258. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  153259. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  153260. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  153261. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  153262. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  153263. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  153264. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  153265. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  153266. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  153267. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  153268. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  153269. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  153270. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  153271. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  153272. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  153273. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  153274. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  153275. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  153276. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  153277. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  153278. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  153279. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  153280. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  153281. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  153282. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  153283. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  153284. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  153285. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  153286. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  153287. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  153288. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  153289. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  153290. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  153291. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  153292. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  153293. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  153294. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  153295. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  153296. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  153297. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  153298. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  153299. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  153300. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  153301. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  153302. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  153303. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  153304. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  153305. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  153306. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  153307. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  153308. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  153309. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  153310. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  153311. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  153312. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  153313. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  153314. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  153315. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  153316. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  153317. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  153318. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  153319. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  153320. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  153321. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  153322. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  153323. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  153324. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  153325. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  153326. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  153327. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  153328. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  153329. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  153330. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  153331. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  153332. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  153333. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  153334. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  153335. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  153336. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  153337. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  153338. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  153339. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  153340. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  153341. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  153342. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  153343. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  153344. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  153345. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  153346. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  153347. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  153348. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  153349. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  153350. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  153351. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  153352. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  153353. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  153354. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  153355. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  153356. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  153357. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  153358. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  153359. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  153360. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  153361. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  153362. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  153363. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  153364. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  153365. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  153366. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  153367. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  153368. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  153369. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  153370. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  153371. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  153372. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  153373. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  153374. };
  153375. static float vwin4096[2048] = {
  153376. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  153377. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  153378. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  153379. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  153380. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  153381. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  153382. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  153383. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  153384. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  153385. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  153386. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  153387. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  153388. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  153389. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  153390. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  153391. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  153392. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  153393. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  153394. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  153395. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  153396. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  153397. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  153398. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  153399. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  153400. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  153401. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  153402. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  153403. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  153404. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  153405. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  153406. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  153407. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  153408. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  153409. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  153410. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  153411. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  153412. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  153413. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  153414. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  153415. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  153416. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  153417. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  153418. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  153419. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  153420. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  153421. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  153422. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  153423. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  153424. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  153425. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  153426. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  153427. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  153428. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  153429. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  153430. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  153431. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  153432. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  153433. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  153434. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  153435. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  153436. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  153437. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  153438. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  153439. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  153440. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  153441. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  153442. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  153443. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  153444. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  153445. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  153446. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  153447. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  153448. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  153449. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  153450. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  153451. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  153452. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  153453. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  153454. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  153455. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  153456. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  153457. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  153458. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  153459. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  153460. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  153461. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  153462. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  153463. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  153464. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  153465. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  153466. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  153467. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  153468. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  153469. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  153470. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  153471. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  153472. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  153473. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  153474. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  153475. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  153476. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  153477. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  153478. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  153479. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  153480. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  153481. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  153482. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  153483. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  153484. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  153485. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  153486. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  153487. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  153488. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  153489. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  153490. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  153491. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  153492. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  153493. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  153494. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  153495. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  153496. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  153497. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  153498. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  153499. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  153500. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  153501. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  153502. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  153503. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  153504. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  153505. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  153506. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  153507. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  153508. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  153509. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  153510. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  153511. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  153512. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  153513. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  153514. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  153515. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  153516. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  153517. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  153518. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  153519. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  153520. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  153521. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  153522. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  153523. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  153524. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  153525. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  153526. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  153527. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  153528. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  153529. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  153530. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  153531. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  153532. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  153533. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  153534. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  153535. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  153536. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  153537. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  153538. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  153539. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  153540. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  153541. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  153542. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  153543. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  153544. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  153545. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  153546. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  153547. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  153548. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  153549. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  153550. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  153551. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  153552. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  153553. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  153554. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  153555. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  153556. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  153557. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  153558. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  153559. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  153560. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  153561. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  153562. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  153563. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  153564. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  153565. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  153566. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  153567. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  153568. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  153569. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  153570. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  153571. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  153572. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  153573. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  153574. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  153575. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  153576. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  153577. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  153578. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  153579. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  153580. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  153581. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  153582. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  153583. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  153584. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  153585. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  153586. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  153587. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  153588. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  153589. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  153590. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  153591. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  153592. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  153593. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  153594. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  153595. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  153596. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  153597. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  153598. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  153599. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  153600. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  153601. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  153602. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  153603. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  153604. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  153605. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  153606. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  153607. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  153608. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  153609. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  153610. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  153611. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  153612. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  153613. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  153614. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  153615. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  153616. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  153617. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  153618. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  153619. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  153620. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  153621. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  153622. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  153623. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  153624. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  153625. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  153626. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  153627. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  153628. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  153629. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  153630. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  153631. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  153632. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  153633. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  153634. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  153635. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  153636. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  153637. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  153638. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  153639. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  153640. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  153641. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  153642. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  153643. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  153644. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  153645. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  153646. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  153647. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  153648. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  153649. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  153650. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  153651. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  153652. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  153653. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  153654. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  153655. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  153656. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  153657. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  153658. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  153659. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  153660. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  153661. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  153662. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  153663. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  153664. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  153665. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  153666. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  153667. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  153668. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  153669. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  153670. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  153671. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  153672. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  153673. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  153674. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  153675. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  153676. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  153677. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  153678. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  153679. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  153680. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  153681. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  153682. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  153683. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  153684. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  153685. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  153686. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  153687. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  153688. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  153689. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  153690. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  153691. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  153692. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  153693. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  153694. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  153695. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  153696. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  153697. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  153698. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  153699. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  153700. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  153701. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  153702. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  153703. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  153704. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  153705. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  153706. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  153707. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  153708. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  153709. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  153710. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  153711. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  153712. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  153713. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  153714. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  153715. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  153716. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  153717. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  153718. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  153719. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  153720. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  153721. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  153722. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  153723. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  153724. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  153725. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  153726. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  153727. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  153728. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  153729. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  153730. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  153731. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  153732. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  153733. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  153734. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  153735. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  153736. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  153737. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  153738. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  153739. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  153740. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  153741. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  153742. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  153743. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  153744. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  153745. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  153746. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  153747. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  153748. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  153749. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  153750. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  153751. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  153752. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  153753. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  153754. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  153755. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  153756. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  153757. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  153758. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  153759. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  153760. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  153761. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  153762. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  153763. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  153764. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  153765. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  153766. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  153767. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  153768. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  153769. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  153770. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  153771. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  153772. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  153773. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  153774. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  153775. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  153776. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  153777. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  153778. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  153779. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  153780. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  153781. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  153782. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  153783. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  153784. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  153785. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  153786. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  153787. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  153788. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  153789. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  153790. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  153791. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  153792. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  153793. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  153794. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  153795. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  153796. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  153797. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  153798. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  153799. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  153800. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  153801. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  153802. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  153803. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  153804. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  153805. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  153806. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  153807. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  153808. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  153809. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  153810. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  153811. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  153812. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  153813. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  153814. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  153815. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  153816. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  153817. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  153818. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  153819. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  153820. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  153821. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  153822. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  153823. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  153824. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  153825. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  153826. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  153827. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  153828. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  153829. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  153830. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  153831. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  153832. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  153833. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  153834. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  153835. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  153836. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  153837. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  153838. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  153839. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  153840. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  153841. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  153842. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  153843. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  153844. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  153845. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  153846. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  153847. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  153848. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  153849. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  153850. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  153851. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  153852. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  153853. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  153854. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  153855. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  153856. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  153857. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  153858. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  153859. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  153860. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  153861. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  153862. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  153863. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  153864. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  153865. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  153866. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  153867. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  153868. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  153869. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  153870. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  153871. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  153872. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  153873. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  153874. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  153875. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  153876. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  153877. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  153878. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  153879. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  153880. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  153881. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  153882. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  153883. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  153884. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  153885. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  153886. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  153887. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153888. };
  153889. static float vwin8192[4096] = {
  153890. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  153891. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  153892. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  153893. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  153894. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  153895. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  153896. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  153897. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  153898. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  153899. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  153900. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  153901. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  153902. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  153903. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  153904. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  153905. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  153906. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  153907. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  153908. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  153909. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  153910. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  153911. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  153912. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  153913. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  153914. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  153915. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  153916. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  153917. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  153918. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  153919. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  153920. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  153921. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  153922. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  153923. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  153924. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  153925. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  153926. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  153927. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  153928. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  153929. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  153930. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  153931. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  153932. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  153933. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  153934. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  153935. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  153936. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  153937. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  153938. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  153939. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  153940. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  153941. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  153942. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  153943. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  153944. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  153945. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  153946. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  153947. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  153948. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  153949. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  153950. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  153951. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  153952. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  153953. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  153954. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  153955. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  153956. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  153957. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  153958. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  153959. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  153960. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  153961. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  153962. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  153963. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  153964. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  153965. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  153966. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  153967. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  153968. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  153969. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  153970. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  153971. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  153972. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  153973. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  153974. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  153975. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  153976. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  153977. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  153978. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  153979. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  153980. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  153981. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  153982. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  153983. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  153984. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  153985. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  153986. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  153987. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  153988. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  153989. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  153990. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  153991. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  153992. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  153993. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  153994. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  153995. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  153996. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  153997. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  153998. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  153999. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  154000. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  154001. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  154002. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  154003. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  154004. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  154005. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  154006. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  154007. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  154008. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  154009. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  154010. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  154011. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  154012. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  154013. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  154014. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  154015. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  154016. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  154017. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  154018. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  154019. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  154020. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  154021. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  154022. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  154023. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  154024. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  154025. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  154026. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  154027. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  154028. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  154029. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  154030. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  154031. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  154032. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  154033. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  154034. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  154035. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  154036. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  154037. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  154038. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  154039. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  154040. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  154041. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  154042. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  154043. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  154044. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  154045. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  154046. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  154047. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  154048. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  154049. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  154050. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  154051. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  154052. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  154053. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  154054. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  154055. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  154056. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  154057. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  154058. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  154059. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  154060. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  154061. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  154062. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  154063. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  154064. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  154065. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  154066. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  154067. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  154068. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  154069. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  154070. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  154071. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  154072. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  154073. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  154074. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  154075. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  154076. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  154077. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  154078. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  154079. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  154080. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  154081. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  154082. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  154083. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  154084. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  154085. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  154086. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  154087. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  154088. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  154089. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  154090. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  154091. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  154092. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  154093. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  154094. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  154095. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  154096. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  154097. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  154098. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  154099. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  154100. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  154101. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  154102. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  154103. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  154104. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  154105. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  154106. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  154107. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  154108. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  154109. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  154110. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  154111. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  154112. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  154113. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  154114. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  154115. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  154116. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  154117. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  154118. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  154119. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  154120. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  154121. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  154122. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  154123. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  154124. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  154125. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  154126. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  154127. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  154128. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  154129. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  154130. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  154131. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  154132. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  154133. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  154134. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  154135. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  154136. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  154137. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  154138. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  154139. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  154140. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  154141. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  154142. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  154143. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  154144. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  154145. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  154146. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  154147. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  154148. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  154149. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  154150. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  154151. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  154152. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  154153. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  154154. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  154155. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  154156. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  154157. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  154158. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  154159. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  154160. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  154161. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  154162. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  154163. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  154164. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  154165. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  154166. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  154167. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  154168. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  154169. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  154170. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  154171. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  154172. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  154173. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  154174. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  154175. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  154176. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  154177. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  154178. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  154179. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  154180. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  154181. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  154182. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  154183. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  154184. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  154185. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  154186. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  154187. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  154188. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  154189. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  154190. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  154191. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  154192. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  154193. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  154194. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  154195. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  154196. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  154197. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  154198. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  154199. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  154200. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  154201. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  154202. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  154203. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  154204. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  154205. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  154206. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  154207. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  154208. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  154209. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  154210. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  154211. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  154212. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  154213. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  154214. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  154215. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  154216. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  154217. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  154218. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  154219. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  154220. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  154221. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  154222. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  154223. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  154224. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  154225. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  154226. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  154227. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  154228. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  154229. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  154230. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  154231. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  154232. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  154233. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  154234. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  154235. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  154236. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  154237. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  154238. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  154239. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  154240. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  154241. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  154242. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  154243. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  154244. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  154245. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  154246. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  154247. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  154248. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  154249. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  154250. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  154251. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  154252. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  154253. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  154254. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  154255. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  154256. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  154257. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  154258. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  154259. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  154260. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  154261. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  154262. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  154263. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  154264. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  154265. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  154266. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  154267. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  154268. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  154269. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  154270. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  154271. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  154272. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  154273. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  154274. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  154275. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  154276. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  154277. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  154278. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  154279. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  154280. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  154281. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  154282. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  154283. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  154284. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  154285. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  154286. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  154287. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  154288. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  154289. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  154290. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  154291. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  154292. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  154293. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  154294. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  154295. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  154296. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  154297. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  154298. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  154299. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  154300. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  154301. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  154302. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  154303. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  154304. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  154305. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  154306. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  154307. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  154308. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  154309. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  154310. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  154311. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  154312. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  154313. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  154314. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  154315. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  154316. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  154317. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  154318. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  154319. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  154320. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  154321. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  154322. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  154323. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  154324. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  154325. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  154326. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  154327. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  154328. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  154329. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  154330. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  154331. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  154332. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  154333. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  154334. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  154335. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  154336. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  154337. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  154338. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  154339. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  154340. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  154341. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  154342. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  154343. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  154344. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  154345. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  154346. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  154347. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  154348. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  154349. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  154350. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  154351. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  154352. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  154353. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  154354. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  154355. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  154356. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  154357. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  154358. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  154359. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  154360. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  154361. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  154362. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  154363. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  154364. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  154365. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  154366. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  154367. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  154368. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  154369. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  154370. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  154371. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  154372. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  154373. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  154374. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  154375. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  154376. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  154377. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  154378. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  154379. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  154380. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  154381. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  154382. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  154383. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  154384. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  154385. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  154386. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  154387. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  154388. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  154389. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  154390. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  154391. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  154392. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  154393. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  154394. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  154395. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  154396. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  154397. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  154398. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  154399. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  154400. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  154401. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  154402. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  154403. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  154404. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  154405. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  154406. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  154407. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  154408. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  154409. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  154410. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  154411. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  154412. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  154413. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  154414. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  154415. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  154416. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  154417. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  154418. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  154419. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  154420. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  154421. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  154422. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  154423. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  154424. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  154425. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  154426. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  154427. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  154428. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  154429. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  154430. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  154431. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  154432. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  154433. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  154434. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  154435. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  154436. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  154437. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  154438. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  154439. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  154440. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  154441. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  154442. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  154443. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  154444. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  154445. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  154446. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  154447. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  154448. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  154449. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  154450. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  154451. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  154452. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  154453. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  154454. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  154455. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  154456. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  154457. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  154458. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  154459. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  154460. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  154461. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  154462. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  154463. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  154464. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  154465. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  154466. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  154467. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  154468. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  154469. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  154470. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  154471. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  154472. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  154473. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  154474. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  154475. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  154476. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  154477. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  154478. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  154479. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  154480. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  154481. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  154482. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  154483. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  154484. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  154485. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  154486. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  154487. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  154488. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  154489. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  154490. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  154491. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  154492. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  154493. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  154494. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  154495. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  154496. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  154497. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  154498. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  154499. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  154500. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  154501. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  154502. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  154503. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  154504. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  154505. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  154506. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  154507. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  154508. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  154509. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  154510. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  154511. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  154512. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  154513. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  154514. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  154515. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  154516. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  154517. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  154518. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  154519. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  154520. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  154521. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  154522. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  154523. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  154524. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  154525. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  154526. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  154527. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  154528. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  154529. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  154530. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  154531. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  154532. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  154533. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  154534. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  154535. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  154536. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  154537. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  154538. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  154539. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  154540. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  154541. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  154542. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  154543. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  154544. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  154545. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  154546. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  154547. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  154548. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  154549. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  154550. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  154551. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  154552. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  154553. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  154554. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  154555. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  154556. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  154557. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  154558. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  154559. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  154560. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  154561. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  154562. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  154563. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  154564. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  154565. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  154566. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  154567. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  154568. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  154569. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  154570. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  154571. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  154572. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  154573. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  154574. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  154575. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  154576. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  154577. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  154578. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  154579. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  154580. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  154581. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  154582. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  154583. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  154584. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  154585. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  154586. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  154587. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  154588. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  154589. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  154590. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  154591. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  154592. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  154593. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  154594. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  154595. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  154596. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  154597. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  154598. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  154599. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  154600. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  154601. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  154602. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  154603. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  154604. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  154605. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  154606. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  154607. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  154608. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  154609. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  154610. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  154611. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  154612. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  154613. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  154614. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  154615. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  154616. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  154617. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  154618. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  154619. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  154620. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  154621. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  154622. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  154623. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  154624. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  154625. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  154626. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  154627. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  154628. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  154629. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  154630. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  154631. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  154632. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  154633. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  154634. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  154635. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  154636. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  154637. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  154638. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  154639. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  154640. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  154641. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  154642. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  154643. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  154644. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  154645. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  154646. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  154647. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  154648. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  154649. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  154650. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  154651. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  154652. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  154653. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  154654. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  154655. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  154656. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  154657. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  154658. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  154659. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  154660. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  154661. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  154662. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  154663. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  154664. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  154665. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  154666. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  154667. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  154668. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  154669. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  154670. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  154671. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  154672. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  154673. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  154674. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  154675. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  154676. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  154677. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  154678. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  154679. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  154680. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  154681. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  154682. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  154683. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  154684. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  154685. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  154686. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  154687. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  154688. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  154689. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  154690. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  154691. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  154692. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  154693. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  154694. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  154695. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  154696. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  154697. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  154698. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  154699. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  154700. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  154701. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  154702. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  154703. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  154704. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  154705. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  154706. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  154707. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  154708. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  154709. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  154710. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  154711. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  154712. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  154713. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  154714. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  154715. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  154716. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  154717. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  154718. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  154719. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  154720. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  154721. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  154722. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  154723. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  154724. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  154725. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  154726. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  154727. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  154728. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  154729. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  154730. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  154731. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  154732. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  154733. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  154734. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  154735. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  154736. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  154737. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  154738. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  154739. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  154740. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  154741. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  154742. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  154743. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  154744. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  154745. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  154746. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  154747. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  154748. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  154749. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  154750. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  154751. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  154752. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  154753. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  154754. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  154755. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  154756. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  154757. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  154758. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  154759. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  154760. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  154761. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  154762. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  154763. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  154764. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  154765. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  154766. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  154767. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  154768. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  154769. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  154770. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  154771. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  154772. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  154773. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  154774. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  154775. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  154776. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  154777. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  154778. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  154779. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  154780. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  154781. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  154782. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  154783. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  154784. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  154785. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  154786. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  154787. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  154788. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  154789. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  154790. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  154791. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  154792. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  154793. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  154794. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  154795. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  154796. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  154797. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  154798. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  154799. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  154800. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  154801. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  154802. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  154803. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  154804. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  154805. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  154806. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  154807. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  154808. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  154809. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  154810. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  154811. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  154812. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  154813. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  154814. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  154815. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  154816. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  154817. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  154818. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  154819. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  154820. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  154821. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  154822. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  154823. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  154824. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  154825. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  154826. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  154827. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  154828. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  154829. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  154830. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  154831. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  154832. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  154833. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  154834. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  154835. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  154836. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  154837. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  154838. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  154839. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  154840. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  154841. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  154842. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  154843. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  154844. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  154845. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  154846. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  154847. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  154848. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  154849. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  154850. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  154851. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  154852. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  154853. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  154854. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  154855. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  154856. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  154857. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  154858. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  154859. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  154860. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  154861. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  154862. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  154863. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  154864. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  154865. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  154866. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  154867. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  154868. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  154869. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  154870. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  154871. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  154872. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  154873. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  154874. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  154875. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  154876. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  154877. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  154878. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  154879. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  154880. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  154881. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  154882. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  154883. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  154884. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  154885. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  154886. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  154887. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  154888. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  154889. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  154890. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  154891. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  154892. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  154893. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  154894. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  154895. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  154896. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  154897. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  154898. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  154899. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  154900. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  154901. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  154902. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  154903. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  154904. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  154905. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  154906. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  154907. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  154908. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  154909. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  154910. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  154911. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  154912. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154913. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154914. };
  154915. static float *vwin[8] = {
  154916. vwin64,
  154917. vwin128,
  154918. vwin256,
  154919. vwin512,
  154920. vwin1024,
  154921. vwin2048,
  154922. vwin4096,
  154923. vwin8192,
  154924. };
  154925. float *_vorbis_window_get(int n){
  154926. return vwin[n];
  154927. }
  154928. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  154929. int lW,int W,int nW){
  154930. lW=(W?lW:0);
  154931. nW=(W?nW:0);
  154932. {
  154933. float *windowLW=vwin[winno[lW]];
  154934. float *windowNW=vwin[winno[nW]];
  154935. long n=blocksizes[W];
  154936. long ln=blocksizes[lW];
  154937. long rn=blocksizes[nW];
  154938. long leftbegin=n/4-ln/4;
  154939. long leftend=leftbegin+ln/2;
  154940. long rightbegin=n/2+n/4-rn/4;
  154941. long rightend=rightbegin+rn/2;
  154942. int i,p;
  154943. for(i=0;i<leftbegin;i++)
  154944. d[i]=0.f;
  154945. for(p=0;i<leftend;i++,p++)
  154946. d[i]*=windowLW[p];
  154947. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  154948. d[i]*=windowNW[p];
  154949. for(;i<n;i++)
  154950. d[i]=0.f;
  154951. }
  154952. }
  154953. #endif
  154954. /********* End of inlined file: window.c *********/
  154955. #else
  154956. #include <vorbis/vorbisenc.h>
  154957. #include <vorbis/codec.h>
  154958. #include <vorbis/vorbisfile.h>
  154959. #endif
  154960. }
  154961. BEGIN_JUCE_NAMESPACE
  154962. using namespace OggVorbisNamespace;
  154963. #define oggFormatName TRANS("Ogg-Vorbis file")
  154964. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  154965. class OggReader : public AudioFormatReader
  154966. {
  154967. OggVorbis_File ovFile;
  154968. ov_callbacks callbacks;
  154969. AudioSampleBuffer reservoir;
  154970. int reservoirStart, samplesInReservoir;
  154971. public:
  154972. OggReader (InputStream* const inp)
  154973. : AudioFormatReader (inp, oggFormatName),
  154974. reservoir (2, 4096),
  154975. reservoirStart (0),
  154976. samplesInReservoir (0)
  154977. {
  154978. sampleRate = 0;
  154979. usesFloatingPointData = true;
  154980. callbacks.read_func = &oggReadCallback;
  154981. callbacks.seek_func = &oggSeekCallback;
  154982. callbacks.close_func = &oggCloseCallback;
  154983. callbacks.tell_func = &oggTellCallback;
  154984. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  154985. if (err == 0)
  154986. {
  154987. vorbis_info* info = ov_info (&ovFile, -1);
  154988. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  154989. numChannels = info->channels;
  154990. bitsPerSample = 16;
  154991. sampleRate = info->rate;
  154992. reservoir.setSize (numChannels,
  154993. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  154994. }
  154995. }
  154996. ~OggReader()
  154997. {
  154998. ov_clear (&ovFile);
  154999. }
  155000. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  155001. int64 startSampleInFile, int numSamples)
  155002. {
  155003. while (numSamples > 0)
  155004. {
  155005. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  155006. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  155007. {
  155008. // got a few samples overlapping, so use them before seeking..
  155009. const int numToUse = jmin (numSamples, numAvailable);
  155010. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  155011. if (destSamples[i] != 0)
  155012. memcpy (destSamples[i] + startOffsetInDestBuffer,
  155013. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  155014. sizeof (float) * numToUse);
  155015. startSampleInFile += numToUse;
  155016. numSamples -= numToUse;
  155017. startOffsetInDestBuffer += numToUse;
  155018. if (numSamples == 0)
  155019. break;
  155020. }
  155021. if (startSampleInFile < reservoirStart
  155022. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  155023. {
  155024. // buffer miss, so refill the reservoir
  155025. int bitStream = 0;
  155026. reservoirStart = jmax (0, (int) startSampleInFile);
  155027. samplesInReservoir = reservoir.getNumSamples();
  155028. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  155029. ov_pcm_seek (&ovFile, reservoirStart);
  155030. int offset = 0;
  155031. int numToRead = samplesInReservoir;
  155032. while (numToRead > 0)
  155033. {
  155034. float** dataIn = 0;
  155035. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  155036. if (samps == 0)
  155037. break;
  155038. jassert (samps <= numToRead);
  155039. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  155040. {
  155041. memcpy (reservoir.getSampleData (i, offset),
  155042. dataIn[i],
  155043. sizeof (float) * samps);
  155044. }
  155045. numToRead -= samps;
  155046. offset += samps;
  155047. }
  155048. if (numToRead > 0)
  155049. reservoir.clear (offset, numToRead);
  155050. }
  155051. }
  155052. if (numSamples > 0)
  155053. {
  155054. for (int i = numDestChannels; --i >= 0;)
  155055. if (destSamples[i] != 0)
  155056. zeromem (destSamples[i] + startOffsetInDestBuffer,
  155057. sizeof (int) * numSamples);
  155058. }
  155059. return true;
  155060. }
  155061. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  155062. {
  155063. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  155064. }
  155065. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  155066. {
  155067. InputStream* const in = (InputStream*) datasource;
  155068. if (whence == SEEK_CUR)
  155069. offset += in->getPosition();
  155070. else if (whence == SEEK_END)
  155071. offset += in->getTotalLength();
  155072. in->setPosition (offset);
  155073. return 0;
  155074. }
  155075. static int oggCloseCallback (void*)
  155076. {
  155077. return 0;
  155078. }
  155079. static long oggTellCallback (void* datasource)
  155080. {
  155081. return (long) ((InputStream*) datasource)->getPosition();
  155082. }
  155083. juce_UseDebuggingNewOperator
  155084. };
  155085. class OggWriter : public AudioFormatWriter
  155086. {
  155087. ogg_stream_state os;
  155088. ogg_page og;
  155089. ogg_packet op;
  155090. vorbis_info vi;
  155091. vorbis_comment vc;
  155092. vorbis_dsp_state vd;
  155093. vorbis_block vb;
  155094. public:
  155095. bool ok;
  155096. OggWriter (OutputStream* const out,
  155097. const double sampleRate,
  155098. const int numChannels,
  155099. const int bitsPerSample,
  155100. const int qualityIndex)
  155101. : AudioFormatWriter (out, oggFormatName,
  155102. sampleRate,
  155103. numChannels,
  155104. bitsPerSample)
  155105. {
  155106. ok = false;
  155107. vorbis_info_init (&vi);
  155108. if (vorbis_encode_init_vbr (&vi,
  155109. numChannels,
  155110. (int) sampleRate,
  155111. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  155112. {
  155113. vorbis_comment_init (&vc);
  155114. if (JUCEApplication::getInstance() != 0)
  155115. vorbis_comment_add_tag (&vc, "ENCODER",
  155116. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  155117. vorbis_analysis_init (&vd, &vi);
  155118. vorbis_block_init (&vd, &vb);
  155119. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  155120. ogg_packet header;
  155121. ogg_packet header_comm;
  155122. ogg_packet header_code;
  155123. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  155124. ogg_stream_packetin (&os, &header);
  155125. ogg_stream_packetin (&os, &header_comm);
  155126. ogg_stream_packetin (&os, &header_code);
  155127. for (;;)
  155128. {
  155129. if (ogg_stream_flush (&os, &og) == 0)
  155130. break;
  155131. output->write (og.header, og.header_len);
  155132. output->write (og.body, og.body_len);
  155133. }
  155134. ok = true;
  155135. }
  155136. }
  155137. ~OggWriter()
  155138. {
  155139. if (ok)
  155140. {
  155141. // write a zero-length packet to show ogg that we're finished..
  155142. write (0, 0);
  155143. ogg_stream_clear (&os);
  155144. vorbis_block_clear (&vb);
  155145. vorbis_dsp_clear (&vd);
  155146. vorbis_comment_clear (&vc);
  155147. vorbis_info_clear (&vi);
  155148. output->flush();
  155149. }
  155150. else
  155151. {
  155152. vorbis_info_clear (&vi);
  155153. output = 0; // to stop the base class deleting this, as it needs to be returned
  155154. // to the caller of createWriter()
  155155. }
  155156. }
  155157. bool write (const int** samplesToWrite, int numSamples)
  155158. {
  155159. if (! ok)
  155160. return false;
  155161. if (numSamples > 0)
  155162. {
  155163. const double gain = 1.0 / 0x80000000u;
  155164. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  155165. for (int i = numChannels; --i >= 0;)
  155166. {
  155167. float* const dst = vorbisBuffer[i];
  155168. const int* const src = samplesToWrite [i];
  155169. if (src != 0 && dst != 0)
  155170. {
  155171. for (int j = 0; j < numSamples; ++j)
  155172. dst[j] = (float) (src[j] * gain);
  155173. }
  155174. }
  155175. }
  155176. vorbis_analysis_wrote (&vd, numSamples);
  155177. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  155178. {
  155179. vorbis_analysis (&vb, 0);
  155180. vorbis_bitrate_addblock (&vb);
  155181. while (vorbis_bitrate_flushpacket (&vd, &op))
  155182. {
  155183. ogg_stream_packetin (&os, &op);
  155184. for (;;)
  155185. {
  155186. if (ogg_stream_pageout (&os, &og) == 0)
  155187. break;
  155188. output->write (og.header, og.header_len);
  155189. output->write (og.body, og.body_len);
  155190. if (ogg_page_eos (&og))
  155191. break;
  155192. }
  155193. }
  155194. }
  155195. return true;
  155196. }
  155197. juce_UseDebuggingNewOperator
  155198. };
  155199. OggVorbisAudioFormat::OggVorbisAudioFormat()
  155200. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  155201. {
  155202. }
  155203. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  155204. {
  155205. }
  155206. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  155207. {
  155208. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  155209. return Array <int> (rates);
  155210. }
  155211. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  155212. {
  155213. Array <int> depths;
  155214. depths.add (32);
  155215. return depths;
  155216. }
  155217. bool OggVorbisAudioFormat::canDoStereo()
  155218. {
  155219. return true;
  155220. }
  155221. bool OggVorbisAudioFormat::canDoMono()
  155222. {
  155223. return true;
  155224. }
  155225. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  155226. const bool deleteStreamIfOpeningFails)
  155227. {
  155228. OggReader* r = new OggReader (in);
  155229. if (r->sampleRate == 0)
  155230. {
  155231. if (! deleteStreamIfOpeningFails)
  155232. r->input = 0;
  155233. deleteAndZero (r);
  155234. }
  155235. return r;
  155236. }
  155237. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  155238. double sampleRate,
  155239. unsigned int numChannels,
  155240. int bitsPerSample,
  155241. const StringPairArray& /*metadataValues*/,
  155242. int qualityOptionIndex)
  155243. {
  155244. OggWriter* w = new OggWriter (out,
  155245. sampleRate,
  155246. numChannels,
  155247. bitsPerSample,
  155248. qualityOptionIndex);
  155249. if (! w->ok)
  155250. deleteAndZero (w);
  155251. return w;
  155252. }
  155253. bool OggVorbisAudioFormat::isCompressed()
  155254. {
  155255. return true;
  155256. }
  155257. const StringArray OggVorbisAudioFormat::getQualityOptions()
  155258. {
  155259. StringArray s;
  155260. s.add ("Low Quality");
  155261. s.add ("Medium Quality");
  155262. s.add ("High Quality");
  155263. return s;
  155264. }
  155265. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  155266. {
  155267. FileInputStream* const in = source.createInputStream();
  155268. if (in != 0)
  155269. {
  155270. AudioFormatReader* const r = createReaderFor (in, true);
  155271. if (r != 0)
  155272. {
  155273. const int64 numSamps = r->lengthInSamples;
  155274. delete r;
  155275. const int64 fileNumSamps = source.getSize() / 4;
  155276. const double ratio = numSamps / (double) fileNumSamps;
  155277. if (ratio > 12.0)
  155278. return 0;
  155279. else if (ratio > 6.0)
  155280. return 1;
  155281. else
  155282. return 2;
  155283. }
  155284. }
  155285. return 1;
  155286. }
  155287. END_JUCE_NAMESPACE
  155288. #endif
  155289. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  155290. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  155291. #if JUCE_MSVC
  155292. #pragma warning (push)
  155293. #endif
  155294. namespace jpeglibNamespace
  155295. {
  155296. #if JUCE_INCLUDE_JPEGLIB_CODE
  155297. extern "C"
  155298. {
  155299. #define JPEG_INTERNALS
  155300. #undef FAR
  155301. /********* Start of inlined file: jpeglib.h *********/
  155302. #ifndef JPEGLIB_H
  155303. #define JPEGLIB_H
  155304. /*
  155305. * First we include the configuration files that record how this
  155306. * installation of the JPEG library is set up. jconfig.h can be
  155307. * generated automatically for many systems. jmorecfg.h contains
  155308. * manual configuration options that most people need not worry about.
  155309. */
  155310. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  155311. /********* Start of inlined file: jconfig.h *********/
  155312. /* see jconfig.doc for explanations */
  155313. // disable all the warnings under MSVC
  155314. #ifdef _MSC_VER
  155315. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  155316. #endif
  155317. #ifdef __BORLANDC__
  155318. #pragma warn -8057
  155319. #pragma warn -8019
  155320. #pragma warn -8004
  155321. #pragma warn -8008
  155322. #endif
  155323. #define HAVE_PROTOTYPES
  155324. #define HAVE_UNSIGNED_CHAR
  155325. #define HAVE_UNSIGNED_SHORT
  155326. /* #define void char */
  155327. /* #define const */
  155328. #undef CHAR_IS_UNSIGNED
  155329. #define HAVE_STDDEF_H
  155330. #define HAVE_STDLIB_H
  155331. #undef NEED_BSD_STRINGS
  155332. #undef NEED_SYS_TYPES_H
  155333. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  155334. #undef NEED_SHORT_EXTERNAL_NAMES
  155335. #undef INCOMPLETE_TYPES_BROKEN
  155336. /* Define "boolean" as unsigned char, not int, per Windows custom */
  155337. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  155338. typedef unsigned char boolean;
  155339. #endif
  155340. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  155341. #ifdef JPEG_INTERNALS
  155342. #undef RIGHT_SHIFT_IS_UNSIGNED
  155343. #endif /* JPEG_INTERNALS */
  155344. #ifdef JPEG_CJPEG_DJPEG
  155345. #define BMP_SUPPORTED /* BMP image file format */
  155346. #define GIF_SUPPORTED /* GIF image file format */
  155347. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  155348. #undef RLE_SUPPORTED /* Utah RLE image file format */
  155349. #define TARGA_SUPPORTED /* Targa image file format */
  155350. #define TWO_FILE_COMMANDLINE /* optional */
  155351. #define USE_SETMODE /* Microsoft has setmode() */
  155352. #undef NEED_SIGNAL_CATCHER
  155353. #undef DONT_USE_B_MODE
  155354. #undef PROGRESS_REPORT /* optional */
  155355. #endif /* JPEG_CJPEG_DJPEG */
  155356. /********* End of inlined file: jconfig.h *********/
  155357. /* widely used configuration options */
  155358. #endif
  155359. /********* Start of inlined file: jmorecfg.h *********/
  155360. /*
  155361. * Define BITS_IN_JSAMPLE as either
  155362. * 8 for 8-bit sample values (the usual setting)
  155363. * 12 for 12-bit sample values
  155364. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  155365. * JPEG standard, and the IJG code does not support anything else!
  155366. * We do not support run-time selection of data precision, sorry.
  155367. */
  155368. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  155369. /*
  155370. * Maximum number of components (color channels) allowed in JPEG image.
  155371. * To meet the letter of the JPEG spec, set this to 255. However, darn
  155372. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  155373. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  155374. * really short on memory. (Each allowed component costs a hundred or so
  155375. * bytes of storage, whether actually used in an image or not.)
  155376. */
  155377. #define MAX_COMPONENTS 10 /* maximum number of image components */
  155378. /*
  155379. * Basic data types.
  155380. * You may need to change these if you have a machine with unusual data
  155381. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  155382. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  155383. * but it had better be at least 16.
  155384. */
  155385. /* Representation of a single sample (pixel element value).
  155386. * We frequently allocate large arrays of these, so it's important to keep
  155387. * them small. But if you have memory to burn and access to char or short
  155388. * arrays is very slow on your hardware, you might want to change these.
  155389. */
  155390. #if BITS_IN_JSAMPLE == 8
  155391. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  155392. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  155393. */
  155394. #ifdef HAVE_UNSIGNED_CHAR
  155395. typedef unsigned char JSAMPLE;
  155396. #define GETJSAMPLE(value) ((int) (value))
  155397. #else /* not HAVE_UNSIGNED_CHAR */
  155398. typedef char JSAMPLE;
  155399. #ifdef CHAR_IS_UNSIGNED
  155400. #define GETJSAMPLE(value) ((int) (value))
  155401. #else
  155402. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  155403. #endif /* CHAR_IS_UNSIGNED */
  155404. #endif /* HAVE_UNSIGNED_CHAR */
  155405. #define MAXJSAMPLE 255
  155406. #define CENTERJSAMPLE 128
  155407. #endif /* BITS_IN_JSAMPLE == 8 */
  155408. #if BITS_IN_JSAMPLE == 12
  155409. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  155410. * On nearly all machines "short" will do nicely.
  155411. */
  155412. typedef short JSAMPLE;
  155413. #define GETJSAMPLE(value) ((int) (value))
  155414. #define MAXJSAMPLE 4095
  155415. #define CENTERJSAMPLE 2048
  155416. #endif /* BITS_IN_JSAMPLE == 12 */
  155417. /* Representation of a DCT frequency coefficient.
  155418. * This should be a signed value of at least 16 bits; "short" is usually OK.
  155419. * Again, we allocate large arrays of these, but you can change to int
  155420. * if you have memory to burn and "short" is really slow.
  155421. */
  155422. typedef short JCOEF;
  155423. /* Compressed datastreams are represented as arrays of JOCTET.
  155424. * These must be EXACTLY 8 bits wide, at least once they are written to
  155425. * external storage. Note that when using the stdio data source/destination
  155426. * managers, this is also the data type passed to fread/fwrite.
  155427. */
  155428. #ifdef HAVE_UNSIGNED_CHAR
  155429. typedef unsigned char JOCTET;
  155430. #define GETJOCTET(value) (value)
  155431. #else /* not HAVE_UNSIGNED_CHAR */
  155432. typedef char JOCTET;
  155433. #ifdef CHAR_IS_UNSIGNED
  155434. #define GETJOCTET(value) (value)
  155435. #else
  155436. #define GETJOCTET(value) ((value) & 0xFF)
  155437. #endif /* CHAR_IS_UNSIGNED */
  155438. #endif /* HAVE_UNSIGNED_CHAR */
  155439. /* These typedefs are used for various table entries and so forth.
  155440. * They must be at least as wide as specified; but making them too big
  155441. * won't cost a huge amount of memory, so we don't provide special
  155442. * extraction code like we did for JSAMPLE. (In other words, these
  155443. * typedefs live at a different point on the speed/space tradeoff curve.)
  155444. */
  155445. /* UINT8 must hold at least the values 0..255. */
  155446. #ifdef HAVE_UNSIGNED_CHAR
  155447. typedef unsigned char UINT8;
  155448. #else /* not HAVE_UNSIGNED_CHAR */
  155449. #ifdef CHAR_IS_UNSIGNED
  155450. typedef char UINT8;
  155451. #else /* not CHAR_IS_UNSIGNED */
  155452. typedef short UINT8;
  155453. #endif /* CHAR_IS_UNSIGNED */
  155454. #endif /* HAVE_UNSIGNED_CHAR */
  155455. /* UINT16 must hold at least the values 0..65535. */
  155456. #ifdef HAVE_UNSIGNED_SHORT
  155457. typedef unsigned short UINT16;
  155458. #else /* not HAVE_UNSIGNED_SHORT */
  155459. typedef unsigned int UINT16;
  155460. #endif /* HAVE_UNSIGNED_SHORT */
  155461. /* INT16 must hold at least the values -32768..32767. */
  155462. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  155463. typedef short INT16;
  155464. #endif
  155465. /* INT32 must hold at least signed 32-bit values. */
  155466. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  155467. typedef long INT32;
  155468. #endif
  155469. /* Datatype used for image dimensions. The JPEG standard only supports
  155470. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  155471. * "unsigned int" is sufficient on all machines. However, if you need to
  155472. * handle larger images and you don't mind deviating from the spec, you
  155473. * can change this datatype.
  155474. */
  155475. typedef unsigned int JDIMENSION;
  155476. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  155477. /* These macros are used in all function definitions and extern declarations.
  155478. * You could modify them if you need to change function linkage conventions;
  155479. * in particular, you'll need to do that to make the library a Windows DLL.
  155480. * Another application is to make all functions global for use with debuggers
  155481. * or code profilers that require it.
  155482. */
  155483. /* a function called through method pointers: */
  155484. #define METHODDEF(type) static type
  155485. /* a function used only in its module: */
  155486. #define LOCAL(type) static type
  155487. /* a function referenced thru EXTERNs: */
  155488. #define GLOBAL(type) type
  155489. /* a reference to a GLOBAL function: */
  155490. #define EXTERN(type) extern type
  155491. /* This macro is used to declare a "method", that is, a function pointer.
  155492. * We want to supply prototype parameters if the compiler can cope.
  155493. * Note that the arglist parameter must be parenthesized!
  155494. * Again, you can customize this if you need special linkage keywords.
  155495. */
  155496. #ifdef HAVE_PROTOTYPES
  155497. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  155498. #else
  155499. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  155500. #endif
  155501. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  155502. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  155503. * by just saying "FAR *" where such a pointer is needed. In a few places
  155504. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  155505. */
  155506. #ifdef NEED_FAR_POINTERS
  155507. #define FAR far
  155508. #else
  155509. #define FAR
  155510. #endif
  155511. /*
  155512. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  155513. * in standard header files. Or you may have conflicts with application-
  155514. * specific header files that you want to include together with these files.
  155515. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  155516. */
  155517. #ifndef HAVE_BOOLEAN
  155518. typedef int boolean;
  155519. #endif
  155520. #ifndef FALSE /* in case these macros already exist */
  155521. #define FALSE 0 /* values of boolean */
  155522. #endif
  155523. #ifndef TRUE
  155524. #define TRUE 1
  155525. #endif
  155526. /*
  155527. * The remaining options affect code selection within the JPEG library,
  155528. * but they don't need to be visible to most applications using the library.
  155529. * To minimize application namespace pollution, the symbols won't be
  155530. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  155531. */
  155532. #ifdef JPEG_INTERNALS
  155533. #define JPEG_INTERNAL_OPTIONS
  155534. #endif
  155535. #ifdef JPEG_INTERNAL_OPTIONS
  155536. /*
  155537. * These defines indicate whether to include various optional functions.
  155538. * Undefining some of these symbols will produce a smaller but less capable
  155539. * library. Note that you can leave certain source files out of the
  155540. * compilation/linking process if you've #undef'd the corresponding symbols.
  155541. * (You may HAVE to do that if your compiler doesn't like null source files.)
  155542. */
  155543. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  155544. /* Capability options common to encoder and decoder: */
  155545. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  155546. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  155547. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  155548. /* Encoder capability options: */
  155549. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155550. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155551. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155552. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  155553. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  155554. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  155555. * precision, so jchuff.c normally uses entropy optimization to compute
  155556. * usable tables for higher precision. If you don't want to do optimization,
  155557. * you'll have to supply different default Huffman tables.
  155558. * The exact same statements apply for progressive JPEG: the default tables
  155559. * don't work for progressive mode. (This may get fixed, however.)
  155560. */
  155561. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  155562. /* Decoder capability options: */
  155563. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155564. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155565. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155566. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  155567. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  155568. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  155569. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  155570. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  155571. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  155572. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  155573. /* more capability options later, no doubt */
  155574. /*
  155575. * Ordering of RGB data in scanlines passed to or from the application.
  155576. * If your application wants to deal with data in the order B,G,R, just
  155577. * change these macros. You can also deal with formats such as R,G,B,X
  155578. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  155579. * the offsets will also change the order in which colormap data is organized.
  155580. * RESTRICTIONS:
  155581. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  155582. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  155583. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  155584. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  155585. * is not 3 (they don't understand about dummy color components!). So you
  155586. * can't use color quantization if you change that value.
  155587. */
  155588. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  155589. #define RGB_GREEN 1 /* Offset of Green */
  155590. #define RGB_BLUE 2 /* Offset of Blue */
  155591. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  155592. /* Definitions for speed-related optimizations. */
  155593. /* If your compiler supports inline functions, define INLINE
  155594. * as the inline keyword; otherwise define it as empty.
  155595. */
  155596. #ifndef INLINE
  155597. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  155598. #define INLINE __inline__
  155599. #endif
  155600. #ifndef INLINE
  155601. #define INLINE /* default is to define it as empty */
  155602. #endif
  155603. #endif
  155604. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  155605. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  155606. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  155607. */
  155608. #ifndef MULTIPLIER
  155609. #define MULTIPLIER int /* type for fastest integer multiply */
  155610. #endif
  155611. /* FAST_FLOAT should be either float or double, whichever is done faster
  155612. * by your compiler. (Note that this type is only used in the floating point
  155613. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  155614. * Typically, float is faster in ANSI C compilers, while double is faster in
  155615. * pre-ANSI compilers (because they insist on converting to double anyway).
  155616. * The code below therefore chooses float if we have ANSI-style prototypes.
  155617. */
  155618. #ifndef FAST_FLOAT
  155619. #ifdef HAVE_PROTOTYPES
  155620. #define FAST_FLOAT float
  155621. #else
  155622. #define FAST_FLOAT double
  155623. #endif
  155624. #endif
  155625. #endif /* JPEG_INTERNAL_OPTIONS */
  155626. /********* End of inlined file: jmorecfg.h *********/
  155627. /* seldom changed options */
  155628. /* Version ID for the JPEG library.
  155629. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  155630. */
  155631. #define JPEG_LIB_VERSION 62 /* Version 6b */
  155632. /* Various constants determining the sizes of things.
  155633. * All of these are specified by the JPEG standard, so don't change them
  155634. * if you want to be compatible.
  155635. */
  155636. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  155637. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  155638. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  155639. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  155640. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  155641. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  155642. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  155643. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  155644. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  155645. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  155646. * to handle it. We even let you do this from the jconfig.h file. However,
  155647. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  155648. * sometimes emits noncompliant files doesn't mean you should too.
  155649. */
  155650. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  155651. #ifndef D_MAX_BLOCKS_IN_MCU
  155652. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  155653. #endif
  155654. /* Data structures for images (arrays of samples and of DCT coefficients).
  155655. * On 80x86 machines, the image arrays are too big for near pointers,
  155656. * but the pointer arrays can fit in near memory.
  155657. */
  155658. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  155659. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  155660. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  155661. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  155662. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  155663. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  155664. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  155665. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  155666. /* Types for JPEG compression parameters and working tables. */
  155667. /* DCT coefficient quantization tables. */
  155668. typedef struct {
  155669. /* This array gives the coefficient quantizers in natural array order
  155670. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  155671. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  155672. */
  155673. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  155674. /* This field is used only during compression. It's initialized FALSE when
  155675. * the table is created, and set TRUE when it's been output to the file.
  155676. * You could suppress output of a table by setting this to TRUE.
  155677. * (See jpeg_suppress_tables for an example.)
  155678. */
  155679. boolean sent_table; /* TRUE when table has been output */
  155680. } JQUANT_TBL;
  155681. /* Huffman coding tables. */
  155682. typedef struct {
  155683. /* These two fields directly represent the contents of a JPEG DHT marker */
  155684. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  155685. /* length k bits; bits[0] is unused */
  155686. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  155687. /* This field is used only during compression. It's initialized FALSE when
  155688. * the table is created, and set TRUE when it's been output to the file.
  155689. * You could suppress output of a table by setting this to TRUE.
  155690. * (See jpeg_suppress_tables for an example.)
  155691. */
  155692. boolean sent_table; /* TRUE when table has been output */
  155693. } JHUFF_TBL;
  155694. /* Basic info about one component (color channel). */
  155695. typedef struct {
  155696. /* These values are fixed over the whole image. */
  155697. /* For compression, they must be supplied by parameter setup; */
  155698. /* for decompression, they are read from the SOF marker. */
  155699. int component_id; /* identifier for this component (0..255) */
  155700. int component_index; /* its index in SOF or cinfo->comp_info[] */
  155701. int h_samp_factor; /* horizontal sampling factor (1..4) */
  155702. int v_samp_factor; /* vertical sampling factor (1..4) */
  155703. int quant_tbl_no; /* quantization table selector (0..3) */
  155704. /* These values may vary between scans. */
  155705. /* For compression, they must be supplied by parameter setup; */
  155706. /* for decompression, they are read from the SOS marker. */
  155707. /* The decompressor output side may not use these variables. */
  155708. int dc_tbl_no; /* DC entropy table selector (0..3) */
  155709. int ac_tbl_no; /* AC entropy table selector (0..3) */
  155710. /* Remaining fields should be treated as private by applications. */
  155711. /* These values are computed during compression or decompression startup: */
  155712. /* Component's size in DCT blocks.
  155713. * Any dummy blocks added to complete an MCU are not counted; therefore
  155714. * these values do not depend on whether a scan is interleaved or not.
  155715. */
  155716. JDIMENSION width_in_blocks;
  155717. JDIMENSION height_in_blocks;
  155718. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  155719. * For decompression this is the size of the output from one DCT block,
  155720. * reflecting any scaling we choose to apply during the IDCT step.
  155721. * Values of 1,2,4,8 are likely to be supported. Note that different
  155722. * components may receive different IDCT scalings.
  155723. */
  155724. int DCT_scaled_size;
  155725. /* The downsampled dimensions are the component's actual, unpadded number
  155726. * of samples at the main buffer (preprocessing/compression interface), thus
  155727. * downsampled_width = ceil(image_width * Hi/Hmax)
  155728. * and similarly for height. For decompression, IDCT scaling is included, so
  155729. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  155730. */
  155731. JDIMENSION downsampled_width; /* actual width in samples */
  155732. JDIMENSION downsampled_height; /* actual height in samples */
  155733. /* This flag is used only for decompression. In cases where some of the
  155734. * components will be ignored (eg grayscale output from YCbCr image),
  155735. * we can skip most computations for the unused components.
  155736. */
  155737. boolean component_needed; /* do we need the value of this component? */
  155738. /* These values are computed before starting a scan of the component. */
  155739. /* The decompressor output side may not use these variables. */
  155740. int MCU_width; /* number of blocks per MCU, horizontally */
  155741. int MCU_height; /* number of blocks per MCU, vertically */
  155742. int MCU_blocks; /* MCU_width * MCU_height */
  155743. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  155744. int last_col_width; /* # of non-dummy blocks across in last MCU */
  155745. int last_row_height; /* # of non-dummy blocks down in last MCU */
  155746. /* Saved quantization table for component; NULL if none yet saved.
  155747. * See jdinput.c comments about the need for this information.
  155748. * This field is currently used only for decompression.
  155749. */
  155750. JQUANT_TBL * quant_table;
  155751. /* Private per-component storage for DCT or IDCT subsystem. */
  155752. void * dct_table;
  155753. } jpeg_component_info;
  155754. /* The script for encoding a multiple-scan file is an array of these: */
  155755. typedef struct {
  155756. int comps_in_scan; /* number of components encoded in this scan */
  155757. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  155758. int Ss, Se; /* progressive JPEG spectral selection parms */
  155759. int Ah, Al; /* progressive JPEG successive approx. parms */
  155760. } jpeg_scan_info;
  155761. /* The decompressor can save APPn and COM markers in a list of these: */
  155762. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  155763. struct jpeg_marker_struct {
  155764. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  155765. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  155766. unsigned int original_length; /* # bytes of data in the file */
  155767. unsigned int data_length; /* # bytes of data saved at data[] */
  155768. JOCTET FAR * data; /* the data contained in the marker */
  155769. /* the marker length word is not counted in data_length or original_length */
  155770. };
  155771. /* Known color spaces. */
  155772. typedef enum {
  155773. JCS_UNKNOWN, /* error/unspecified */
  155774. JCS_GRAYSCALE, /* monochrome */
  155775. JCS_RGB, /* red/green/blue */
  155776. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  155777. JCS_CMYK, /* C/M/Y/K */
  155778. JCS_YCCK /* Y/Cb/Cr/K */
  155779. } J_COLOR_SPACE;
  155780. /* DCT/IDCT algorithm options. */
  155781. typedef enum {
  155782. JDCT_ISLOW, /* slow but accurate integer algorithm */
  155783. JDCT_IFAST, /* faster, less accurate integer method */
  155784. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  155785. } J_DCT_METHOD;
  155786. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  155787. #define JDCT_DEFAULT JDCT_ISLOW
  155788. #endif
  155789. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  155790. #define JDCT_FASTEST JDCT_IFAST
  155791. #endif
  155792. /* Dithering options for decompression. */
  155793. typedef enum {
  155794. JDITHER_NONE, /* no dithering */
  155795. JDITHER_ORDERED, /* simple ordered dither */
  155796. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  155797. } J_DITHER_MODE;
  155798. /* Common fields between JPEG compression and decompression master structs. */
  155799. #define jpeg_common_fields \
  155800. struct jpeg_error_mgr * err; /* Error handler module */\
  155801. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  155802. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  155803. void * client_data; /* Available for use by application */\
  155804. boolean is_decompressor; /* So common code can tell which is which */\
  155805. int global_state /* For checking call sequence validity */
  155806. /* Routines that are to be used by both halves of the library are declared
  155807. * to receive a pointer to this structure. There are no actual instances of
  155808. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  155809. */
  155810. struct jpeg_common_struct {
  155811. jpeg_common_fields; /* Fields common to both master struct types */
  155812. /* Additional fields follow in an actual jpeg_compress_struct or
  155813. * jpeg_decompress_struct. All three structs must agree on these
  155814. * initial fields! (This would be a lot cleaner in C++.)
  155815. */
  155816. };
  155817. typedef struct jpeg_common_struct * j_common_ptr;
  155818. typedef struct jpeg_compress_struct * j_compress_ptr;
  155819. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  155820. /* Master record for a compression instance */
  155821. struct jpeg_compress_struct {
  155822. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  155823. /* Destination for compressed data */
  155824. struct jpeg_destination_mgr * dest;
  155825. /* Description of source image --- these fields must be filled in by
  155826. * outer application before starting compression. in_color_space must
  155827. * be correct before you can even call jpeg_set_defaults().
  155828. */
  155829. JDIMENSION image_width; /* input image width */
  155830. JDIMENSION image_height; /* input image height */
  155831. int input_components; /* # of color components in input image */
  155832. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  155833. double input_gamma; /* image gamma of input image */
  155834. /* Compression parameters --- these fields must be set before calling
  155835. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  155836. * initialize everything to reasonable defaults, then changing anything
  155837. * the application specifically wants to change. That way you won't get
  155838. * burnt when new parameters are added. Also note that there are several
  155839. * helper routines to simplify changing parameters.
  155840. */
  155841. int data_precision; /* bits of precision in image data */
  155842. int num_components; /* # of color components in JPEG image */
  155843. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155844. jpeg_component_info * comp_info;
  155845. /* comp_info[i] describes component that appears i'th in SOF */
  155846. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155847. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155848. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155849. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155850. /* ptrs to Huffman coding tables, or NULL if not defined */
  155851. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155852. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155853. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155854. int num_scans; /* # of entries in scan_info array */
  155855. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  155856. /* The default value of scan_info is NULL, which causes a single-scan
  155857. * sequential JPEG file to be emitted. To create a multi-scan file,
  155858. * set num_scans and scan_info to point to an array of scan definitions.
  155859. */
  155860. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  155861. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155862. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  155863. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155864. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  155865. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  155866. /* The restart interval can be specified in absolute MCUs by setting
  155867. * restart_interval, or in MCU rows by setting restart_in_rows
  155868. * (in which case the correct restart_interval will be figured
  155869. * for each scan).
  155870. */
  155871. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  155872. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  155873. /* Parameters controlling emission of special markers. */
  155874. boolean write_JFIF_header; /* should a JFIF marker be written? */
  155875. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  155876. UINT8 JFIF_minor_version;
  155877. /* These three values are not used by the JPEG code, merely copied */
  155878. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  155879. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  155880. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  155881. UINT8 density_unit; /* JFIF code for pixel size units */
  155882. UINT16 X_density; /* Horizontal pixel density */
  155883. UINT16 Y_density; /* Vertical pixel density */
  155884. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  155885. /* State variable: index of next scanline to be written to
  155886. * jpeg_write_scanlines(). Application may use this to control its
  155887. * processing loop, e.g., "while (next_scanline < image_height)".
  155888. */
  155889. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  155890. /* Remaining fields are known throughout compressor, but generally
  155891. * should not be touched by a surrounding application.
  155892. */
  155893. /*
  155894. * These fields are computed during compression startup
  155895. */
  155896. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  155897. int max_h_samp_factor; /* largest h_samp_factor */
  155898. int max_v_samp_factor; /* largest v_samp_factor */
  155899. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  155900. /* The coefficient controller receives data in units of MCU rows as defined
  155901. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  155902. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  155903. * "iMCU" (interleaved MCU) row.
  155904. */
  155905. /*
  155906. * These fields are valid during any one scan.
  155907. * They describe the components and MCUs actually appearing in the scan.
  155908. */
  155909. int comps_in_scan; /* # of JPEG components in this scan */
  155910. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155911. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155912. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155913. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155914. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155915. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  155916. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155917. /* i'th block in an MCU */
  155918. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155919. /*
  155920. * Links to compression subobjects (methods and private variables of modules)
  155921. */
  155922. struct jpeg_comp_master * master;
  155923. struct jpeg_c_main_controller * main;
  155924. struct jpeg_c_prep_controller * prep;
  155925. struct jpeg_c_coef_controller * coef;
  155926. struct jpeg_marker_writer * marker;
  155927. struct jpeg_color_converter * cconvert;
  155928. struct jpeg_downsampler * downsample;
  155929. struct jpeg_forward_dct * fdct;
  155930. struct jpeg_entropy_encoder * entropy;
  155931. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  155932. int script_space_size;
  155933. };
  155934. /* Master record for a decompression instance */
  155935. struct jpeg_decompress_struct {
  155936. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  155937. /* Source of compressed data */
  155938. struct jpeg_source_mgr * src;
  155939. /* Basic description of image --- filled in by jpeg_read_header(). */
  155940. /* Application may inspect these values to decide how to process image. */
  155941. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  155942. JDIMENSION image_height; /* nominal image height */
  155943. int num_components; /* # of color components in JPEG image */
  155944. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155945. /* Decompression processing parameters --- these fields must be set before
  155946. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  155947. * them to default values.
  155948. */
  155949. J_COLOR_SPACE out_color_space; /* colorspace for output */
  155950. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  155951. double output_gamma; /* image gamma wanted in output */
  155952. boolean buffered_image; /* TRUE=multiple output passes */
  155953. boolean raw_data_out; /* TRUE=downsampled data wanted */
  155954. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  155955. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  155956. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  155957. boolean quantize_colors; /* TRUE=colormapped output wanted */
  155958. /* the following are ignored if not quantize_colors: */
  155959. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  155960. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  155961. int desired_number_of_colors; /* max # colors to use in created colormap */
  155962. /* these are significant only in buffered-image mode: */
  155963. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  155964. boolean enable_external_quant;/* enable future use of external colormap */
  155965. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  155966. /* Description of actual output image that will be returned to application.
  155967. * These fields are computed by jpeg_start_decompress().
  155968. * You can also use jpeg_calc_output_dimensions() to determine these values
  155969. * in advance of calling jpeg_start_decompress().
  155970. */
  155971. JDIMENSION output_width; /* scaled image width */
  155972. JDIMENSION output_height; /* scaled image height */
  155973. int out_color_components; /* # of color components in out_color_space */
  155974. int output_components; /* # of color components returned */
  155975. /* output_components is 1 (a colormap index) when quantizing colors;
  155976. * otherwise it equals out_color_components.
  155977. */
  155978. int rec_outbuf_height; /* min recommended height of scanline buffer */
  155979. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  155980. * high, space and time will be wasted due to unnecessary data copying.
  155981. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  155982. */
  155983. /* When quantizing colors, the output colormap is described by these fields.
  155984. * The application can supply a colormap by setting colormap non-NULL before
  155985. * calling jpeg_start_decompress; otherwise a colormap is created during
  155986. * jpeg_start_decompress or jpeg_start_output.
  155987. * The map has out_color_components rows and actual_number_of_colors columns.
  155988. */
  155989. int actual_number_of_colors; /* number of entries in use */
  155990. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  155991. /* State variables: these variables indicate the progress of decompression.
  155992. * The application may examine these but must not modify them.
  155993. */
  155994. /* Row index of next scanline to be read from jpeg_read_scanlines().
  155995. * Application may use this to control its processing loop, e.g.,
  155996. * "while (output_scanline < output_height)".
  155997. */
  155998. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  155999. /* Current input scan number and number of iMCU rows completed in scan.
  156000. * These indicate the progress of the decompressor input side.
  156001. */
  156002. int input_scan_number; /* Number of SOS markers seen so far */
  156003. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  156004. /* The "output scan number" is the notional scan being displayed by the
  156005. * output side. The decompressor will not allow output scan/row number
  156006. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  156007. */
  156008. int output_scan_number; /* Nominal scan number being displayed */
  156009. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  156010. /* Current progression status. coef_bits[c][i] indicates the precision
  156011. * with which component c's DCT coefficient i (in zigzag order) is known.
  156012. * It is -1 when no data has yet been received, otherwise it is the point
  156013. * transform (shift) value for the most recent scan of the coefficient
  156014. * (thus, 0 at completion of the progression).
  156015. * This pointer is NULL when reading a non-progressive file.
  156016. */
  156017. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  156018. /* Internal JPEG parameters --- the application usually need not look at
  156019. * these fields. Note that the decompressor output side may not use
  156020. * any parameters that can change between scans.
  156021. */
  156022. /* Quantization and Huffman tables are carried forward across input
  156023. * datastreams when processing abbreviated JPEG datastreams.
  156024. */
  156025. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  156026. /* ptrs to coefficient quantization tables, or NULL if not defined */
  156027. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156028. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  156029. /* ptrs to Huffman coding tables, or NULL if not defined */
  156030. /* These parameters are never carried across datastreams, since they
  156031. * are given in SOF/SOS markers or defined to be reset by SOI.
  156032. */
  156033. int data_precision; /* bits of precision in image data */
  156034. jpeg_component_info * comp_info;
  156035. /* comp_info[i] describes component that appears i'th in SOF */
  156036. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  156037. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  156038. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  156039. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  156040. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  156041. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  156042. /* These fields record data obtained from optional markers recognized by
  156043. * the JPEG library.
  156044. */
  156045. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  156046. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  156047. UINT8 JFIF_major_version; /* JFIF version number */
  156048. UINT8 JFIF_minor_version;
  156049. UINT8 density_unit; /* JFIF code for pixel size units */
  156050. UINT16 X_density; /* Horizontal pixel density */
  156051. UINT16 Y_density; /* Vertical pixel density */
  156052. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  156053. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  156054. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  156055. /* Aside from the specific data retained from APPn markers known to the
  156056. * library, the uninterpreted contents of any or all APPn and COM markers
  156057. * can be saved in a list for examination by the application.
  156058. */
  156059. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  156060. /* Remaining fields are known throughout decompressor, but generally
  156061. * should not be touched by a surrounding application.
  156062. */
  156063. /*
  156064. * These fields are computed during decompression startup
  156065. */
  156066. int max_h_samp_factor; /* largest h_samp_factor */
  156067. int max_v_samp_factor; /* largest v_samp_factor */
  156068. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  156069. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  156070. /* The coefficient controller's input and output progress is measured in
  156071. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  156072. * in fully interleaved JPEG scans, but are used whether the scan is
  156073. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  156074. * rows of each component. Therefore, the IDCT output contains
  156075. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  156076. */
  156077. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  156078. /*
  156079. * These fields are valid during any one scan.
  156080. * They describe the components and MCUs actually appearing in the scan.
  156081. * Note that the decompressor output side must not use these fields.
  156082. */
  156083. int comps_in_scan; /* # of JPEG components in this scan */
  156084. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  156085. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  156086. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  156087. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  156088. int blocks_in_MCU; /* # of DCT blocks per MCU */
  156089. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  156090. /* MCU_membership[i] is index in cur_comp_info of component owning */
  156091. /* i'th block in an MCU */
  156092. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  156093. /* This field is shared between entropy decoder and marker parser.
  156094. * It is either zero or the code of a JPEG marker that has been
  156095. * read from the data source, but has not yet been processed.
  156096. */
  156097. int unread_marker;
  156098. /*
  156099. * Links to decompression subobjects (methods, private variables of modules)
  156100. */
  156101. struct jpeg_decomp_master * master;
  156102. struct jpeg_d_main_controller * main;
  156103. struct jpeg_d_coef_controller * coef;
  156104. struct jpeg_d_post_controller * post;
  156105. struct jpeg_input_controller * inputctl;
  156106. struct jpeg_marker_reader * marker;
  156107. struct jpeg_entropy_decoder * entropy;
  156108. struct jpeg_inverse_dct * idct;
  156109. struct jpeg_upsampler * upsample;
  156110. struct jpeg_color_deconverter * cconvert;
  156111. struct jpeg_color_quantizer * cquantize;
  156112. };
  156113. /* "Object" declarations for JPEG modules that may be supplied or called
  156114. * directly by the surrounding application.
  156115. * As with all objects in the JPEG library, these structs only define the
  156116. * publicly visible methods and state variables of a module. Additional
  156117. * private fields may exist after the public ones.
  156118. */
  156119. /* Error handler object */
  156120. struct jpeg_error_mgr {
  156121. /* Error exit handler: does not return to caller */
  156122. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  156123. /* Conditionally emit a trace or warning message */
  156124. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  156125. /* Routine that actually outputs a trace or error message */
  156126. JMETHOD(void, output_message, (j_common_ptr cinfo));
  156127. /* Format a message string for the most recent JPEG error or message */
  156128. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  156129. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  156130. /* Reset error state variables at start of a new image */
  156131. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  156132. /* The message ID code and any parameters are saved here.
  156133. * A message can have one string parameter or up to 8 int parameters.
  156134. */
  156135. int msg_code;
  156136. #define JMSG_STR_PARM_MAX 80
  156137. union {
  156138. int i[8];
  156139. char s[JMSG_STR_PARM_MAX];
  156140. } msg_parm;
  156141. /* Standard state variables for error facility */
  156142. int trace_level; /* max msg_level that will be displayed */
  156143. /* For recoverable corrupt-data errors, we emit a warning message,
  156144. * but keep going unless emit_message chooses to abort. emit_message
  156145. * should count warnings in num_warnings. The surrounding application
  156146. * can check for bad data by seeing if num_warnings is nonzero at the
  156147. * end of processing.
  156148. */
  156149. long num_warnings; /* number of corrupt-data warnings */
  156150. /* These fields point to the table(s) of error message strings.
  156151. * An application can change the table pointer to switch to a different
  156152. * message list (typically, to change the language in which errors are
  156153. * reported). Some applications may wish to add additional error codes
  156154. * that will be handled by the JPEG library error mechanism; the second
  156155. * table pointer is used for this purpose.
  156156. *
  156157. * First table includes all errors generated by JPEG library itself.
  156158. * Error code 0 is reserved for a "no such error string" message.
  156159. */
  156160. const char * const * jpeg_message_table; /* Library errors */
  156161. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  156162. /* Second table can be added by application (see cjpeg/djpeg for example).
  156163. * It contains strings numbered first_addon_message..last_addon_message.
  156164. */
  156165. const char * const * addon_message_table; /* Non-library errors */
  156166. int first_addon_message; /* code for first string in addon table */
  156167. int last_addon_message; /* code for last string in addon table */
  156168. };
  156169. /* Progress monitor object */
  156170. struct jpeg_progress_mgr {
  156171. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  156172. long pass_counter; /* work units completed in this pass */
  156173. long pass_limit; /* total number of work units in this pass */
  156174. int completed_passes; /* passes completed so far */
  156175. int total_passes; /* total number of passes expected */
  156176. };
  156177. /* Data destination object for compression */
  156178. struct jpeg_destination_mgr {
  156179. JOCTET * next_output_byte; /* => next byte to write in buffer */
  156180. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  156181. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  156182. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  156183. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  156184. };
  156185. /* Data source object for decompression */
  156186. struct jpeg_source_mgr {
  156187. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  156188. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  156189. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  156190. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  156191. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  156192. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  156193. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  156194. };
  156195. /* Memory manager object.
  156196. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  156197. * and "really big" objects (virtual arrays with backing store if needed).
  156198. * The memory manager does not allow individual objects to be freed; rather,
  156199. * each created object is assigned to a pool, and whole pools can be freed
  156200. * at once. This is faster and more convenient than remembering exactly what
  156201. * to free, especially where malloc()/free() are not too speedy.
  156202. * NB: alloc routines never return NULL. They exit to error_exit if not
  156203. * successful.
  156204. */
  156205. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  156206. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  156207. #define JPOOL_NUMPOOLS 2
  156208. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  156209. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  156210. struct jpeg_memory_mgr {
  156211. /* Method pointers */
  156212. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  156213. size_t sizeofobject));
  156214. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  156215. size_t sizeofobject));
  156216. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  156217. JDIMENSION samplesperrow,
  156218. JDIMENSION numrows));
  156219. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  156220. JDIMENSION blocksperrow,
  156221. JDIMENSION numrows));
  156222. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  156223. int pool_id,
  156224. boolean pre_zero,
  156225. JDIMENSION samplesperrow,
  156226. JDIMENSION numrows,
  156227. JDIMENSION maxaccess));
  156228. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  156229. int pool_id,
  156230. boolean pre_zero,
  156231. JDIMENSION blocksperrow,
  156232. JDIMENSION numrows,
  156233. JDIMENSION maxaccess));
  156234. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  156235. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  156236. jvirt_sarray_ptr ptr,
  156237. JDIMENSION start_row,
  156238. JDIMENSION num_rows,
  156239. boolean writable));
  156240. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  156241. jvirt_barray_ptr ptr,
  156242. JDIMENSION start_row,
  156243. JDIMENSION num_rows,
  156244. boolean writable));
  156245. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  156246. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  156247. /* Limit on memory allocation for this JPEG object. (Note that this is
  156248. * merely advisory, not a guaranteed maximum; it only affects the space
  156249. * used for virtual-array buffers.) May be changed by outer application
  156250. * after creating the JPEG object.
  156251. */
  156252. long max_memory_to_use;
  156253. /* Maximum allocation request accepted by alloc_large. */
  156254. long max_alloc_chunk;
  156255. };
  156256. /* Routine signature for application-supplied marker processing methods.
  156257. * Need not pass marker code since it is stored in cinfo->unread_marker.
  156258. */
  156259. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  156260. /* Declarations for routines called by application.
  156261. * The JPP macro hides prototype parameters from compilers that can't cope.
  156262. * Note JPP requires double parentheses.
  156263. */
  156264. #ifdef HAVE_PROTOTYPES
  156265. #define JPP(arglist) arglist
  156266. #else
  156267. #define JPP(arglist) ()
  156268. #endif
  156269. /* Short forms of external names for systems with brain-damaged linkers.
  156270. * We shorten external names to be unique in the first six letters, which
  156271. * is good enough for all known systems.
  156272. * (If your compiler itself needs names to be unique in less than 15
  156273. * characters, you are out of luck. Get a better compiler.)
  156274. */
  156275. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156276. #define jpeg_std_error jStdError
  156277. #define jpeg_CreateCompress jCreaCompress
  156278. #define jpeg_CreateDecompress jCreaDecompress
  156279. #define jpeg_destroy_compress jDestCompress
  156280. #define jpeg_destroy_decompress jDestDecompress
  156281. #define jpeg_stdio_dest jStdDest
  156282. #define jpeg_stdio_src jStdSrc
  156283. #define jpeg_set_defaults jSetDefaults
  156284. #define jpeg_set_colorspace jSetColorspace
  156285. #define jpeg_default_colorspace jDefColorspace
  156286. #define jpeg_set_quality jSetQuality
  156287. #define jpeg_set_linear_quality jSetLQuality
  156288. #define jpeg_add_quant_table jAddQuantTable
  156289. #define jpeg_quality_scaling jQualityScaling
  156290. #define jpeg_simple_progression jSimProgress
  156291. #define jpeg_suppress_tables jSuppressTables
  156292. #define jpeg_alloc_quant_table jAlcQTable
  156293. #define jpeg_alloc_huff_table jAlcHTable
  156294. #define jpeg_start_compress jStrtCompress
  156295. #define jpeg_write_scanlines jWrtScanlines
  156296. #define jpeg_finish_compress jFinCompress
  156297. #define jpeg_write_raw_data jWrtRawData
  156298. #define jpeg_write_marker jWrtMarker
  156299. #define jpeg_write_m_header jWrtMHeader
  156300. #define jpeg_write_m_byte jWrtMByte
  156301. #define jpeg_write_tables jWrtTables
  156302. #define jpeg_read_header jReadHeader
  156303. #define jpeg_start_decompress jStrtDecompress
  156304. #define jpeg_read_scanlines jReadScanlines
  156305. #define jpeg_finish_decompress jFinDecompress
  156306. #define jpeg_read_raw_data jReadRawData
  156307. #define jpeg_has_multiple_scans jHasMultScn
  156308. #define jpeg_start_output jStrtOutput
  156309. #define jpeg_finish_output jFinOutput
  156310. #define jpeg_input_complete jInComplete
  156311. #define jpeg_new_colormap jNewCMap
  156312. #define jpeg_consume_input jConsumeInput
  156313. #define jpeg_calc_output_dimensions jCalcDimensions
  156314. #define jpeg_save_markers jSaveMarkers
  156315. #define jpeg_set_marker_processor jSetMarker
  156316. #define jpeg_read_coefficients jReadCoefs
  156317. #define jpeg_write_coefficients jWrtCoefs
  156318. #define jpeg_copy_critical_parameters jCopyCrit
  156319. #define jpeg_abort_compress jAbrtCompress
  156320. #define jpeg_abort_decompress jAbrtDecompress
  156321. #define jpeg_abort jAbort
  156322. #define jpeg_destroy jDestroy
  156323. #define jpeg_resync_to_restart jResyncRestart
  156324. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156325. /* Default error-management setup */
  156326. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  156327. JPP((struct jpeg_error_mgr * err));
  156328. /* Initialization of JPEG compression objects.
  156329. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  156330. * names that applications should call. These expand to calls on
  156331. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  156332. * passed for version mismatch checking.
  156333. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  156334. */
  156335. #define jpeg_create_compress(cinfo) \
  156336. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  156337. (size_t) sizeof(struct jpeg_compress_struct))
  156338. #define jpeg_create_decompress(cinfo) \
  156339. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  156340. (size_t) sizeof(struct jpeg_decompress_struct))
  156341. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  156342. int version, size_t structsize));
  156343. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  156344. int version, size_t structsize));
  156345. /* Destruction of JPEG compression objects */
  156346. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  156347. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  156348. /* Standard data source and destination managers: stdio streams. */
  156349. /* Caller is responsible for opening the file before and closing after. */
  156350. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  156351. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  156352. /* Default parameter setup for compression */
  156353. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  156354. /* Compression parameter setup aids */
  156355. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  156356. J_COLOR_SPACE colorspace));
  156357. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  156358. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  156359. boolean force_baseline));
  156360. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  156361. int scale_factor,
  156362. boolean force_baseline));
  156363. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  156364. const unsigned int *basic_table,
  156365. int scale_factor,
  156366. boolean force_baseline));
  156367. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  156368. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  156369. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  156370. boolean suppress));
  156371. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  156372. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  156373. /* Main entry points for compression */
  156374. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  156375. boolean write_all_tables));
  156376. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  156377. JSAMPARRAY scanlines,
  156378. JDIMENSION num_lines));
  156379. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  156380. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  156381. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  156382. JSAMPIMAGE data,
  156383. JDIMENSION num_lines));
  156384. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  156385. EXTERN(void) jpeg_write_marker
  156386. JPP((j_compress_ptr cinfo, int marker,
  156387. const JOCTET * dataptr, unsigned int datalen));
  156388. /* Same, but piecemeal. */
  156389. EXTERN(void) jpeg_write_m_header
  156390. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  156391. EXTERN(void) jpeg_write_m_byte
  156392. JPP((j_compress_ptr cinfo, int val));
  156393. /* Alternate compression function: just write an abbreviated table file */
  156394. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  156395. /* Decompression startup: read start of JPEG datastream to see what's there */
  156396. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  156397. boolean require_image));
  156398. /* Return value is one of: */
  156399. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  156400. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  156401. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  156402. /* If you pass require_image = TRUE (normal case), you need not check for
  156403. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  156404. * JPEG_SUSPENDED is only possible if you use a data source module that can
  156405. * give a suspension return (the stdio source module doesn't).
  156406. */
  156407. /* Main entry points for decompression */
  156408. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  156409. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  156410. JSAMPARRAY scanlines,
  156411. JDIMENSION max_lines));
  156412. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  156413. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  156414. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  156415. JSAMPIMAGE data,
  156416. JDIMENSION max_lines));
  156417. /* Additional entry points for buffered-image mode. */
  156418. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  156419. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  156420. int scan_number));
  156421. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  156422. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  156423. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  156424. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  156425. /* Return value is one of: */
  156426. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  156427. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  156428. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  156429. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  156430. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  156431. /* Precalculate output dimensions for current decompression parameters. */
  156432. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  156433. /* Control saving of COM and APPn markers into marker_list. */
  156434. EXTERN(void) jpeg_save_markers
  156435. JPP((j_decompress_ptr cinfo, int marker_code,
  156436. unsigned int length_limit));
  156437. /* Install a special processing method for COM or APPn markers. */
  156438. EXTERN(void) jpeg_set_marker_processor
  156439. JPP((j_decompress_ptr cinfo, int marker_code,
  156440. jpeg_marker_parser_method routine));
  156441. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  156442. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  156443. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  156444. jvirt_barray_ptr * coef_arrays));
  156445. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  156446. j_compress_ptr dstinfo));
  156447. /* If you choose to abort compression or decompression before completing
  156448. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  156449. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  156450. * if you're done with the JPEG object, but if you want to clean it up and
  156451. * reuse it, call this:
  156452. */
  156453. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  156454. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  156455. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  156456. * flavor of JPEG object. These may be more convenient in some places.
  156457. */
  156458. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  156459. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  156460. /* Default restart-marker-resync procedure for use by data source modules */
  156461. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  156462. int desired));
  156463. /* These marker codes are exported since applications and data source modules
  156464. * are likely to want to use them.
  156465. */
  156466. #define JPEG_RST0 0xD0 /* RST0 marker code */
  156467. #define JPEG_EOI 0xD9 /* EOI marker code */
  156468. #define JPEG_APP0 0xE0 /* APP0 marker code */
  156469. #define JPEG_COM 0xFE /* COM marker code */
  156470. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  156471. * for structure definitions that are never filled in, keep it quiet by
  156472. * supplying dummy definitions for the various substructures.
  156473. */
  156474. #ifdef INCOMPLETE_TYPES_BROKEN
  156475. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  156476. struct jvirt_sarray_control { long dummy; };
  156477. struct jvirt_barray_control { long dummy; };
  156478. struct jpeg_comp_master { long dummy; };
  156479. struct jpeg_c_main_controller { long dummy; };
  156480. struct jpeg_c_prep_controller { long dummy; };
  156481. struct jpeg_c_coef_controller { long dummy; };
  156482. struct jpeg_marker_writer { long dummy; };
  156483. struct jpeg_color_converter { long dummy; };
  156484. struct jpeg_downsampler { long dummy; };
  156485. struct jpeg_forward_dct { long dummy; };
  156486. struct jpeg_entropy_encoder { long dummy; };
  156487. struct jpeg_decomp_master { long dummy; };
  156488. struct jpeg_d_main_controller { long dummy; };
  156489. struct jpeg_d_coef_controller { long dummy; };
  156490. struct jpeg_d_post_controller { long dummy; };
  156491. struct jpeg_input_controller { long dummy; };
  156492. struct jpeg_marker_reader { long dummy; };
  156493. struct jpeg_entropy_decoder { long dummy; };
  156494. struct jpeg_inverse_dct { long dummy; };
  156495. struct jpeg_upsampler { long dummy; };
  156496. struct jpeg_color_deconverter { long dummy; };
  156497. struct jpeg_color_quantizer { long dummy; };
  156498. #endif /* JPEG_INTERNALS */
  156499. #endif /* INCOMPLETE_TYPES_BROKEN */
  156500. /*
  156501. * The JPEG library modules define JPEG_INTERNALS before including this file.
  156502. * The internal structure declarations are read only when that is true.
  156503. * Applications using the library should not include jpegint.h, but may wish
  156504. * to include jerror.h.
  156505. */
  156506. #ifdef JPEG_INTERNALS
  156507. /********* Start of inlined file: jpegint.h *********/
  156508. /* Declarations for both compression & decompression */
  156509. typedef enum { /* Operating modes for buffer controllers */
  156510. JBUF_PASS_THRU, /* Plain stripwise operation */
  156511. /* Remaining modes require a full-image buffer to have been created */
  156512. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  156513. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  156514. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  156515. } J_BUF_MODE;
  156516. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  156517. #define CSTATE_START 100 /* after create_compress */
  156518. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  156519. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  156520. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  156521. #define DSTATE_START 200 /* after create_decompress */
  156522. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  156523. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  156524. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  156525. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  156526. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  156527. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  156528. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  156529. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  156530. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  156531. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  156532. /* Declarations for compression modules */
  156533. /* Master control module */
  156534. struct jpeg_comp_master {
  156535. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  156536. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  156537. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156538. /* State variables made visible to other modules */
  156539. boolean call_pass_startup; /* True if pass_startup must be called */
  156540. boolean is_last_pass; /* True during last pass */
  156541. };
  156542. /* Main buffer control (downsampled-data buffer) */
  156543. struct jpeg_c_main_controller {
  156544. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156545. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  156546. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  156547. JDIMENSION in_rows_avail));
  156548. };
  156549. /* Compression preprocessing (downsampling input buffer control) */
  156550. struct jpeg_c_prep_controller {
  156551. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156552. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  156553. JSAMPARRAY input_buf,
  156554. JDIMENSION *in_row_ctr,
  156555. JDIMENSION in_rows_avail,
  156556. JSAMPIMAGE output_buf,
  156557. JDIMENSION *out_row_group_ctr,
  156558. JDIMENSION out_row_groups_avail));
  156559. };
  156560. /* Coefficient buffer control */
  156561. struct jpeg_c_coef_controller {
  156562. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156563. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  156564. JSAMPIMAGE input_buf));
  156565. };
  156566. /* Colorspace conversion */
  156567. struct jpeg_color_converter {
  156568. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156569. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  156570. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156571. JDIMENSION output_row, int num_rows));
  156572. };
  156573. /* Downsampling */
  156574. struct jpeg_downsampler {
  156575. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156576. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  156577. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  156578. JSAMPIMAGE output_buf,
  156579. JDIMENSION out_row_group_index));
  156580. boolean need_context_rows; /* TRUE if need rows above & below */
  156581. };
  156582. /* Forward DCT (also controls coefficient quantization) */
  156583. struct jpeg_forward_dct {
  156584. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156585. /* perhaps this should be an array??? */
  156586. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  156587. jpeg_component_info * compptr,
  156588. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156589. JDIMENSION start_row, JDIMENSION start_col,
  156590. JDIMENSION num_blocks));
  156591. };
  156592. /* Entropy encoding */
  156593. struct jpeg_entropy_encoder {
  156594. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  156595. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  156596. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156597. };
  156598. /* Marker writing */
  156599. struct jpeg_marker_writer {
  156600. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  156601. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  156602. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  156603. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  156604. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  156605. /* These routines are exported to allow insertion of extra markers */
  156606. /* Probably only COM and APPn markers should be written this way */
  156607. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  156608. unsigned int datalen));
  156609. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  156610. };
  156611. /* Declarations for decompression modules */
  156612. /* Master control module */
  156613. struct jpeg_decomp_master {
  156614. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  156615. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  156616. /* State variables made visible to other modules */
  156617. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  156618. };
  156619. /* Input control module */
  156620. struct jpeg_input_controller {
  156621. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  156622. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  156623. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156624. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  156625. /* State variables made visible to other modules */
  156626. boolean has_multiple_scans; /* True if file has multiple scans */
  156627. boolean eoi_reached; /* True when EOI has been consumed */
  156628. };
  156629. /* Main buffer control (downsampled-data buffer) */
  156630. struct jpeg_d_main_controller {
  156631. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156632. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  156633. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  156634. JDIMENSION out_rows_avail));
  156635. };
  156636. /* Coefficient buffer control */
  156637. struct jpeg_d_coef_controller {
  156638. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156639. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  156640. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  156641. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  156642. JSAMPIMAGE output_buf));
  156643. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  156644. jvirt_barray_ptr *coef_arrays;
  156645. };
  156646. /* Decompression postprocessing (color quantization buffer control) */
  156647. struct jpeg_d_post_controller {
  156648. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156649. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  156650. JSAMPIMAGE input_buf,
  156651. JDIMENSION *in_row_group_ctr,
  156652. JDIMENSION in_row_groups_avail,
  156653. JSAMPARRAY output_buf,
  156654. JDIMENSION *out_row_ctr,
  156655. JDIMENSION out_rows_avail));
  156656. };
  156657. /* Marker reading & parsing */
  156658. struct jpeg_marker_reader {
  156659. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  156660. /* Read markers until SOS or EOI.
  156661. * Returns same codes as are defined for jpeg_consume_input:
  156662. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  156663. */
  156664. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  156665. /* Read a restart marker --- exported for use by entropy decoder only */
  156666. jpeg_marker_parser_method read_restart_marker;
  156667. /* State of marker reader --- nominally internal, but applications
  156668. * supplying COM or APPn handlers might like to know the state.
  156669. */
  156670. boolean saw_SOI; /* found SOI? */
  156671. boolean saw_SOF; /* found SOF? */
  156672. int next_restart_num; /* next restart number expected (0-7) */
  156673. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  156674. };
  156675. /* Entropy decoding */
  156676. struct jpeg_entropy_decoder {
  156677. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156678. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  156679. JBLOCKROW *MCU_data));
  156680. /* This is here to share code between baseline and progressive decoders; */
  156681. /* other modules probably should not use it */
  156682. boolean insufficient_data; /* set TRUE after emitting warning */
  156683. };
  156684. /* Inverse DCT (also performs dequantization) */
  156685. typedef JMETHOD(void, inverse_DCT_method_ptr,
  156686. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156687. JCOEFPTR coef_block,
  156688. JSAMPARRAY output_buf, JDIMENSION output_col));
  156689. struct jpeg_inverse_dct {
  156690. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156691. /* It is useful to allow each component to have a separate IDCT method. */
  156692. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  156693. };
  156694. /* Upsampling (note that upsampler must also call color converter) */
  156695. struct jpeg_upsampler {
  156696. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156697. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  156698. JSAMPIMAGE input_buf,
  156699. JDIMENSION *in_row_group_ctr,
  156700. JDIMENSION in_row_groups_avail,
  156701. JSAMPARRAY output_buf,
  156702. JDIMENSION *out_row_ctr,
  156703. JDIMENSION out_rows_avail));
  156704. boolean need_context_rows; /* TRUE if need rows above & below */
  156705. };
  156706. /* Colorspace conversion */
  156707. struct jpeg_color_deconverter {
  156708. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156709. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  156710. JSAMPIMAGE input_buf, JDIMENSION input_row,
  156711. JSAMPARRAY output_buf, int num_rows));
  156712. };
  156713. /* Color quantization or color precision reduction */
  156714. struct jpeg_color_quantizer {
  156715. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  156716. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  156717. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  156718. int num_rows));
  156719. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  156720. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  156721. };
  156722. /* Miscellaneous useful macros */
  156723. #undef MAX
  156724. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  156725. #undef MIN
  156726. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  156727. /* We assume that right shift corresponds to signed division by 2 with
  156728. * rounding towards minus infinity. This is correct for typical "arithmetic
  156729. * shift" instructions that shift in copies of the sign bit. But some
  156730. * C compilers implement >> with an unsigned shift. For these machines you
  156731. * must define RIGHT_SHIFT_IS_UNSIGNED.
  156732. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  156733. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  156734. * included in the variables of any routine using RIGHT_SHIFT.
  156735. */
  156736. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  156737. #define SHIFT_TEMPS INT32 shift_temp;
  156738. #define RIGHT_SHIFT(x,shft) \
  156739. ((shift_temp = (x)) < 0 ? \
  156740. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  156741. (shift_temp >> (shft)))
  156742. #else
  156743. #define SHIFT_TEMPS
  156744. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  156745. #endif
  156746. /* Short forms of external names for systems with brain-damaged linkers. */
  156747. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156748. #define jinit_compress_master jICompress
  156749. #define jinit_c_master_control jICMaster
  156750. #define jinit_c_main_controller jICMainC
  156751. #define jinit_c_prep_controller jICPrepC
  156752. #define jinit_c_coef_controller jICCoefC
  156753. #define jinit_color_converter jICColor
  156754. #define jinit_downsampler jIDownsampler
  156755. #define jinit_forward_dct jIFDCT
  156756. #define jinit_huff_encoder jIHEncoder
  156757. #define jinit_phuff_encoder jIPHEncoder
  156758. #define jinit_marker_writer jIMWriter
  156759. #define jinit_master_decompress jIDMaster
  156760. #define jinit_d_main_controller jIDMainC
  156761. #define jinit_d_coef_controller jIDCoefC
  156762. #define jinit_d_post_controller jIDPostC
  156763. #define jinit_input_controller jIInCtlr
  156764. #define jinit_marker_reader jIMReader
  156765. #define jinit_huff_decoder jIHDecoder
  156766. #define jinit_phuff_decoder jIPHDecoder
  156767. #define jinit_inverse_dct jIIDCT
  156768. #define jinit_upsampler jIUpsampler
  156769. #define jinit_color_deconverter jIDColor
  156770. #define jinit_1pass_quantizer jI1Quant
  156771. #define jinit_2pass_quantizer jI2Quant
  156772. #define jinit_merged_upsampler jIMUpsampler
  156773. #define jinit_memory_mgr jIMemMgr
  156774. #define jdiv_round_up jDivRound
  156775. #define jround_up jRound
  156776. #define jcopy_sample_rows jCopySamples
  156777. #define jcopy_block_row jCopyBlocks
  156778. #define jzero_far jZeroFar
  156779. #define jpeg_zigzag_order jZIGTable
  156780. #define jpeg_natural_order jZAGTable
  156781. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156782. /* Compression module initialization routines */
  156783. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  156784. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  156785. boolean transcode_only));
  156786. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  156787. boolean need_full_buffer));
  156788. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  156789. boolean need_full_buffer));
  156790. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  156791. boolean need_full_buffer));
  156792. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  156793. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  156794. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  156795. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  156796. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  156797. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  156798. /* Decompression module initialization routines */
  156799. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  156800. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  156801. boolean need_full_buffer));
  156802. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  156803. boolean need_full_buffer));
  156804. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  156805. boolean need_full_buffer));
  156806. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  156807. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  156808. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  156809. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  156810. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  156811. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  156812. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  156813. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  156814. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  156815. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  156816. /* Memory manager initialization */
  156817. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  156818. /* Utility routines in jutils.c */
  156819. EXTERN(long) jdiv_round_up JPP((long a, long b));
  156820. EXTERN(long) jround_up JPP((long a, long b));
  156821. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  156822. JSAMPARRAY output_array, int dest_row,
  156823. int num_rows, JDIMENSION num_cols));
  156824. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  156825. JDIMENSION num_blocks));
  156826. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  156827. /* Constant tables in jutils.c */
  156828. #if 0 /* This table is not actually needed in v6a */
  156829. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  156830. #endif
  156831. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  156832. /* Suppress undefined-structure complaints if necessary. */
  156833. #ifdef INCOMPLETE_TYPES_BROKEN
  156834. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  156835. struct jvirt_sarray_control { long dummy; };
  156836. struct jvirt_barray_control { long dummy; };
  156837. #endif
  156838. #endif /* INCOMPLETE_TYPES_BROKEN */
  156839. /********* End of inlined file: jpegint.h *********/
  156840. /* fetch private declarations */
  156841. /********* Start of inlined file: jerror.h *********/
  156842. /*
  156843. * To define the enum list of message codes, include this file without
  156844. * defining macro JMESSAGE. To create a message string table, include it
  156845. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  156846. */
  156847. #ifndef JMESSAGE
  156848. #ifndef JERROR_H
  156849. /* First time through, define the enum list */
  156850. #define JMAKE_ENUM_LIST
  156851. #else
  156852. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  156853. #define JMESSAGE(code,string)
  156854. #endif /* JERROR_H */
  156855. #endif /* JMESSAGE */
  156856. #ifdef JMAKE_ENUM_LIST
  156857. typedef enum {
  156858. #define JMESSAGE(code,string) code ,
  156859. #endif /* JMAKE_ENUM_LIST */
  156860. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  156861. /* For maintenance convenience, list is alphabetical by message code name */
  156862. JMESSAGE(JERR_ARITH_NOTIMPL,
  156863. "Sorry, there are legal restrictions on arithmetic coding")
  156864. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  156865. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  156866. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  156867. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  156868. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  156869. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  156870. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  156871. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  156872. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  156873. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  156874. JMESSAGE(JERR_BAD_LIB_VERSION,
  156875. "Wrong JPEG library version: library is %d, caller expects %d")
  156876. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  156877. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  156878. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  156879. JMESSAGE(JERR_BAD_PROGRESSION,
  156880. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  156881. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  156882. "Invalid progressive parameters at scan script entry %d")
  156883. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  156884. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  156885. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  156886. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  156887. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  156888. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  156889. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  156890. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  156891. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  156892. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  156893. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  156894. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  156895. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  156896. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  156897. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  156898. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  156899. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  156900. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  156901. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  156902. JMESSAGE(JERR_FILE_READ, "Input file read error")
  156903. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  156904. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  156905. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  156906. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  156907. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  156908. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  156909. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  156910. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  156911. "Cannot transcode due to multiple use of quantization table %d")
  156912. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  156913. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  156914. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  156915. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  156916. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  156917. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  156918. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  156919. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  156920. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  156921. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  156922. JMESSAGE(JERR_QUANT_COMPONENTS,
  156923. "Cannot quantize more than %d color components")
  156924. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  156925. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  156926. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  156927. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  156928. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  156929. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  156930. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  156931. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  156932. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  156933. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  156934. JMESSAGE(JERR_TFILE_WRITE,
  156935. "Write failed on temporary file --- out of disk space?")
  156936. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  156937. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  156938. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  156939. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  156940. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  156941. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  156942. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  156943. JMESSAGE(JMSG_VERSION, JVERSION)
  156944. JMESSAGE(JTRC_16BIT_TABLES,
  156945. "Caution: quantization tables are too coarse for baseline JPEG")
  156946. JMESSAGE(JTRC_ADOBE,
  156947. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  156948. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  156949. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  156950. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  156951. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  156952. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  156953. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  156954. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  156955. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  156956. JMESSAGE(JTRC_EOI, "End Of Image")
  156957. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  156958. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  156959. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  156960. "Warning: thumbnail image size does not match data length %u")
  156961. JMESSAGE(JTRC_JFIF_EXTENSION,
  156962. "JFIF extension marker: type 0x%02x, length %u")
  156963. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  156964. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  156965. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  156966. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  156967. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  156968. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  156969. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  156970. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  156971. JMESSAGE(JTRC_RST, "RST%d")
  156972. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  156973. "Smoothing not supported with nonstandard sampling ratios")
  156974. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  156975. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  156976. JMESSAGE(JTRC_SOI, "Start of Image")
  156977. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  156978. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  156979. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  156980. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  156981. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  156982. JMESSAGE(JTRC_THUMB_JPEG,
  156983. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  156984. JMESSAGE(JTRC_THUMB_PALETTE,
  156985. "JFIF extension marker: palette thumbnail image, length %u")
  156986. JMESSAGE(JTRC_THUMB_RGB,
  156987. "JFIF extension marker: RGB thumbnail image, length %u")
  156988. JMESSAGE(JTRC_UNKNOWN_IDS,
  156989. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  156990. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  156991. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  156992. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  156993. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  156994. "Inconsistent progression sequence for component %d coefficient %d")
  156995. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  156996. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  156997. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  156998. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  156999. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  157000. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  157001. JMESSAGE(JWRN_MUST_RESYNC,
  157002. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  157003. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  157004. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  157005. #ifdef JMAKE_ENUM_LIST
  157006. JMSG_LASTMSGCODE
  157007. } J_MESSAGE_CODE;
  157008. #undef JMAKE_ENUM_LIST
  157009. #endif /* JMAKE_ENUM_LIST */
  157010. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  157011. #undef JMESSAGE
  157012. #ifndef JERROR_H
  157013. #define JERROR_H
  157014. /* Macros to simplify using the error and trace message stuff */
  157015. /* The first parameter is either type of cinfo pointer */
  157016. /* Fatal errors (print message and exit) */
  157017. #define ERREXIT(cinfo,code) \
  157018. ((cinfo)->err->msg_code = (code), \
  157019. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157020. #define ERREXIT1(cinfo,code,p1) \
  157021. ((cinfo)->err->msg_code = (code), \
  157022. (cinfo)->err->msg_parm.i[0] = (p1), \
  157023. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157024. #define ERREXIT2(cinfo,code,p1,p2) \
  157025. ((cinfo)->err->msg_code = (code), \
  157026. (cinfo)->err->msg_parm.i[0] = (p1), \
  157027. (cinfo)->err->msg_parm.i[1] = (p2), \
  157028. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157029. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  157030. ((cinfo)->err->msg_code = (code), \
  157031. (cinfo)->err->msg_parm.i[0] = (p1), \
  157032. (cinfo)->err->msg_parm.i[1] = (p2), \
  157033. (cinfo)->err->msg_parm.i[2] = (p3), \
  157034. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157035. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  157036. ((cinfo)->err->msg_code = (code), \
  157037. (cinfo)->err->msg_parm.i[0] = (p1), \
  157038. (cinfo)->err->msg_parm.i[1] = (p2), \
  157039. (cinfo)->err->msg_parm.i[2] = (p3), \
  157040. (cinfo)->err->msg_parm.i[3] = (p4), \
  157041. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157042. #define ERREXITS(cinfo,code,str) \
  157043. ((cinfo)->err->msg_code = (code), \
  157044. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157045. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  157046. #define MAKESTMT(stuff) do { stuff } while (0)
  157047. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  157048. #define WARNMS(cinfo,code) \
  157049. ((cinfo)->err->msg_code = (code), \
  157050. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157051. #define WARNMS1(cinfo,code,p1) \
  157052. ((cinfo)->err->msg_code = (code), \
  157053. (cinfo)->err->msg_parm.i[0] = (p1), \
  157054. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157055. #define WARNMS2(cinfo,code,p1,p2) \
  157056. ((cinfo)->err->msg_code = (code), \
  157057. (cinfo)->err->msg_parm.i[0] = (p1), \
  157058. (cinfo)->err->msg_parm.i[1] = (p2), \
  157059. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  157060. /* Informational/debugging messages */
  157061. #define TRACEMS(cinfo,lvl,code) \
  157062. ((cinfo)->err->msg_code = (code), \
  157063. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157064. #define TRACEMS1(cinfo,lvl,code,p1) \
  157065. ((cinfo)->err->msg_code = (code), \
  157066. (cinfo)->err->msg_parm.i[0] = (p1), \
  157067. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157068. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  157069. ((cinfo)->err->msg_code = (code), \
  157070. (cinfo)->err->msg_parm.i[0] = (p1), \
  157071. (cinfo)->err->msg_parm.i[1] = (p2), \
  157072. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157073. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  157074. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157075. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  157076. (cinfo)->err->msg_code = (code); \
  157077. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157078. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  157079. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157080. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157081. (cinfo)->err->msg_code = (code); \
  157082. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157083. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  157084. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157085. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157086. _mp[4] = (p5); \
  157087. (cinfo)->err->msg_code = (code); \
  157088. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157089. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  157090. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  157091. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  157092. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  157093. (cinfo)->err->msg_code = (code); \
  157094. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  157095. #define TRACEMSS(cinfo,lvl,code,str) \
  157096. ((cinfo)->err->msg_code = (code), \
  157097. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  157098. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  157099. #endif /* JERROR_H */
  157100. /********* End of inlined file: jerror.h *********/
  157101. /* fetch error codes too */
  157102. #endif
  157103. #endif /* JPEGLIB_H */
  157104. /********* End of inlined file: jpeglib.h *********/
  157105. /********* Start of inlined file: jcapimin.c *********/
  157106. #define JPEG_INTERNALS
  157107. /********* Start of inlined file: jinclude.h *********/
  157108. /* Include auto-config file to find out which system include files we need. */
  157109. #ifndef __jinclude_h__
  157110. #define __jinclude_h__
  157111. /********* Start of inlined file: jconfig.h *********/
  157112. /* see jconfig.doc for explanations */
  157113. // disable all the warnings under MSVC
  157114. #ifdef _MSC_VER
  157115. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  157116. #endif
  157117. #ifdef __BORLANDC__
  157118. #pragma warn -8057
  157119. #pragma warn -8019
  157120. #pragma warn -8004
  157121. #pragma warn -8008
  157122. #endif
  157123. #define HAVE_PROTOTYPES
  157124. #define HAVE_UNSIGNED_CHAR
  157125. #define HAVE_UNSIGNED_SHORT
  157126. /* #define void char */
  157127. /* #define const */
  157128. #undef CHAR_IS_UNSIGNED
  157129. #define HAVE_STDDEF_H
  157130. #define HAVE_STDLIB_H
  157131. #undef NEED_BSD_STRINGS
  157132. #undef NEED_SYS_TYPES_H
  157133. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  157134. #undef NEED_SHORT_EXTERNAL_NAMES
  157135. #undef INCOMPLETE_TYPES_BROKEN
  157136. /* Define "boolean" as unsigned char, not int, per Windows custom */
  157137. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  157138. typedef unsigned char boolean;
  157139. #endif
  157140. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  157141. #ifdef JPEG_INTERNALS
  157142. #undef RIGHT_SHIFT_IS_UNSIGNED
  157143. #endif /* JPEG_INTERNALS */
  157144. #ifdef JPEG_CJPEG_DJPEG
  157145. #define BMP_SUPPORTED /* BMP image file format */
  157146. #define GIF_SUPPORTED /* GIF image file format */
  157147. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  157148. #undef RLE_SUPPORTED /* Utah RLE image file format */
  157149. #define TARGA_SUPPORTED /* Targa image file format */
  157150. #define TWO_FILE_COMMANDLINE /* optional */
  157151. #define USE_SETMODE /* Microsoft has setmode() */
  157152. #undef NEED_SIGNAL_CATCHER
  157153. #undef DONT_USE_B_MODE
  157154. #undef PROGRESS_REPORT /* optional */
  157155. #endif /* JPEG_CJPEG_DJPEG */
  157156. /********* End of inlined file: jconfig.h *********/
  157157. /* auto configuration options */
  157158. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  157159. /*
  157160. * We need the NULL macro and size_t typedef.
  157161. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  157162. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  157163. * pull in <sys/types.h> as well.
  157164. * Note that the core JPEG library does not require <stdio.h>;
  157165. * only the default error handler and data source/destination modules do.
  157166. * But we must pull it in because of the references to FILE in jpeglib.h.
  157167. * You can remove those references if you want to compile without <stdio.h>.
  157168. */
  157169. #ifdef HAVE_STDDEF_H
  157170. #include <stddef.h>
  157171. #endif
  157172. #ifdef HAVE_STDLIB_H
  157173. #include <stdlib.h>
  157174. #endif
  157175. #ifdef NEED_SYS_TYPES_H
  157176. #include <sys/types.h>
  157177. #endif
  157178. #include <stdio.h>
  157179. /*
  157180. * We need memory copying and zeroing functions, plus strncpy().
  157181. * ANSI and System V implementations declare these in <string.h>.
  157182. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  157183. * Some systems may declare memset and memcpy in <memory.h>.
  157184. *
  157185. * NOTE: we assume the size parameters to these functions are of type size_t.
  157186. * Change the casts in these macros if not!
  157187. */
  157188. #ifdef NEED_BSD_STRINGS
  157189. #include <strings.h>
  157190. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  157191. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  157192. #else /* not BSD, assume ANSI/SysV string lib */
  157193. #include <string.h>
  157194. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  157195. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  157196. #endif
  157197. /*
  157198. * In ANSI C, and indeed any rational implementation, size_t is also the
  157199. * type returned by sizeof(). However, it seems there are some irrational
  157200. * implementations out there, in which sizeof() returns an int even though
  157201. * size_t is defined as long or unsigned long. To ensure consistent results
  157202. * we always use this SIZEOF() macro in place of using sizeof() directly.
  157203. */
  157204. #define SIZEOF(object) ((size_t) sizeof(object))
  157205. /*
  157206. * The modules that use fread() and fwrite() always invoke them through
  157207. * these macros. On some systems you may need to twiddle the argument casts.
  157208. * CAUTION: argument order is different from underlying functions!
  157209. */
  157210. #define JFREAD(file,buf,sizeofbuf) \
  157211. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157212. #define JFWRITE(file,buf,sizeofbuf) \
  157213. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157214. typedef enum { /* JPEG marker codes */
  157215. M_SOF0 = 0xc0,
  157216. M_SOF1 = 0xc1,
  157217. M_SOF2 = 0xc2,
  157218. M_SOF3 = 0xc3,
  157219. M_SOF5 = 0xc5,
  157220. M_SOF6 = 0xc6,
  157221. M_SOF7 = 0xc7,
  157222. M_JPG = 0xc8,
  157223. M_SOF9 = 0xc9,
  157224. M_SOF10 = 0xca,
  157225. M_SOF11 = 0xcb,
  157226. M_SOF13 = 0xcd,
  157227. M_SOF14 = 0xce,
  157228. M_SOF15 = 0xcf,
  157229. M_DHT = 0xc4,
  157230. M_DAC = 0xcc,
  157231. M_RST0 = 0xd0,
  157232. M_RST1 = 0xd1,
  157233. M_RST2 = 0xd2,
  157234. M_RST3 = 0xd3,
  157235. M_RST4 = 0xd4,
  157236. M_RST5 = 0xd5,
  157237. M_RST6 = 0xd6,
  157238. M_RST7 = 0xd7,
  157239. M_SOI = 0xd8,
  157240. M_EOI = 0xd9,
  157241. M_SOS = 0xda,
  157242. M_DQT = 0xdb,
  157243. M_DNL = 0xdc,
  157244. M_DRI = 0xdd,
  157245. M_DHP = 0xde,
  157246. M_EXP = 0xdf,
  157247. M_APP0 = 0xe0,
  157248. M_APP1 = 0xe1,
  157249. M_APP2 = 0xe2,
  157250. M_APP3 = 0xe3,
  157251. M_APP4 = 0xe4,
  157252. M_APP5 = 0xe5,
  157253. M_APP6 = 0xe6,
  157254. M_APP7 = 0xe7,
  157255. M_APP8 = 0xe8,
  157256. M_APP9 = 0xe9,
  157257. M_APP10 = 0xea,
  157258. M_APP11 = 0xeb,
  157259. M_APP12 = 0xec,
  157260. M_APP13 = 0xed,
  157261. M_APP14 = 0xee,
  157262. M_APP15 = 0xef,
  157263. M_JPG0 = 0xf0,
  157264. M_JPG13 = 0xfd,
  157265. M_COM = 0xfe,
  157266. M_TEM = 0x01,
  157267. M_ERROR = 0x100
  157268. } JPEG_MARKER;
  157269. /*
  157270. * Figure F.12: extend sign bit.
  157271. * On some machines, a shift and add will be faster than a table lookup.
  157272. */
  157273. #ifdef AVOID_TABLES
  157274. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  157275. #else
  157276. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  157277. static const int extend_test[16] = /* entry n is 2**(n-1) */
  157278. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  157279. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  157280. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  157281. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  157282. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  157283. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  157284. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  157285. #endif /* AVOID_TABLES */
  157286. #endif
  157287. /********* End of inlined file: jinclude.h *********/
  157288. /*
  157289. * Initialization of a JPEG compression object.
  157290. * The error manager must already be set up (in case memory manager fails).
  157291. */
  157292. GLOBAL(void)
  157293. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  157294. {
  157295. int i;
  157296. /* Guard against version mismatches between library and caller. */
  157297. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  157298. if (version != JPEG_LIB_VERSION)
  157299. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  157300. if (structsize != SIZEOF(struct jpeg_compress_struct))
  157301. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  157302. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  157303. /* For debugging purposes, we zero the whole master structure.
  157304. * But the application has already set the err pointer, and may have set
  157305. * client_data, so we have to save and restore those fields.
  157306. * Note: if application hasn't set client_data, tools like Purify may
  157307. * complain here.
  157308. */
  157309. {
  157310. struct jpeg_error_mgr * err = cinfo->err;
  157311. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  157312. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  157313. cinfo->err = err;
  157314. cinfo->client_data = client_data;
  157315. }
  157316. cinfo->is_decompressor = FALSE;
  157317. /* Initialize a memory manager instance for this object */
  157318. jinit_memory_mgr((j_common_ptr) cinfo);
  157319. /* Zero out pointers to permanent structures. */
  157320. cinfo->progress = NULL;
  157321. cinfo->dest = NULL;
  157322. cinfo->comp_info = NULL;
  157323. for (i = 0; i < NUM_QUANT_TBLS; i++)
  157324. cinfo->quant_tbl_ptrs[i] = NULL;
  157325. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157326. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  157327. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  157328. }
  157329. cinfo->script_space = NULL;
  157330. cinfo->input_gamma = 1.0; /* in case application forgets */
  157331. /* OK, I'm ready */
  157332. cinfo->global_state = CSTATE_START;
  157333. }
  157334. /*
  157335. * Destruction of a JPEG compression object
  157336. */
  157337. GLOBAL(void)
  157338. jpeg_destroy_compress (j_compress_ptr cinfo)
  157339. {
  157340. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  157341. }
  157342. /*
  157343. * Abort processing of a JPEG compression operation,
  157344. * but don't destroy the object itself.
  157345. */
  157346. GLOBAL(void)
  157347. jpeg_abort_compress (j_compress_ptr cinfo)
  157348. {
  157349. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  157350. }
  157351. /*
  157352. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  157353. * Marks all currently defined tables as already written (if suppress)
  157354. * or not written (if !suppress). This will control whether they get emitted
  157355. * by a subsequent jpeg_start_compress call.
  157356. *
  157357. * This routine is exported for use by applications that want to produce
  157358. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  157359. * since it is called by jpeg_start_compress, we put it here --- otherwise
  157360. * jcparam.o would be linked whether the application used it or not.
  157361. */
  157362. GLOBAL(void)
  157363. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  157364. {
  157365. int i;
  157366. JQUANT_TBL * qtbl;
  157367. JHUFF_TBL * htbl;
  157368. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157369. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  157370. qtbl->sent_table = suppress;
  157371. }
  157372. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157373. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  157374. htbl->sent_table = suppress;
  157375. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  157376. htbl->sent_table = suppress;
  157377. }
  157378. }
  157379. /*
  157380. * Finish JPEG compression.
  157381. *
  157382. * If a multipass operating mode was selected, this may do a great deal of
  157383. * work including most of the actual output.
  157384. */
  157385. GLOBAL(void)
  157386. jpeg_finish_compress (j_compress_ptr cinfo)
  157387. {
  157388. JDIMENSION iMCU_row;
  157389. if (cinfo->global_state == CSTATE_SCANNING ||
  157390. cinfo->global_state == CSTATE_RAW_OK) {
  157391. /* Terminate first pass */
  157392. if (cinfo->next_scanline < cinfo->image_height)
  157393. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  157394. (*cinfo->master->finish_pass) (cinfo);
  157395. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  157396. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157397. /* Perform any remaining passes */
  157398. while (! cinfo->master->is_last_pass) {
  157399. (*cinfo->master->prepare_for_pass) (cinfo);
  157400. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  157401. if (cinfo->progress != NULL) {
  157402. cinfo->progress->pass_counter = (long) iMCU_row;
  157403. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  157404. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157405. }
  157406. /* We bypass the main controller and invoke coef controller directly;
  157407. * all work is being done from the coefficient buffer.
  157408. */
  157409. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  157410. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157411. }
  157412. (*cinfo->master->finish_pass) (cinfo);
  157413. }
  157414. /* Write EOI, do final cleanup */
  157415. (*cinfo->marker->write_file_trailer) (cinfo);
  157416. (*cinfo->dest->term_destination) (cinfo);
  157417. /* We can use jpeg_abort to release memory and reset global_state */
  157418. jpeg_abort((j_common_ptr) cinfo);
  157419. }
  157420. /*
  157421. * Write a special marker.
  157422. * This is only recommended for writing COM or APPn markers.
  157423. * Must be called after jpeg_start_compress() and before
  157424. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  157425. */
  157426. GLOBAL(void)
  157427. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  157428. const JOCTET *dataptr, unsigned int datalen)
  157429. {
  157430. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  157431. if (cinfo->next_scanline != 0 ||
  157432. (cinfo->global_state != CSTATE_SCANNING &&
  157433. cinfo->global_state != CSTATE_RAW_OK &&
  157434. cinfo->global_state != CSTATE_WRCOEFS))
  157435. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157436. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157437. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  157438. while (datalen--) {
  157439. (*write_marker_byte) (cinfo, *dataptr);
  157440. dataptr++;
  157441. }
  157442. }
  157443. /* Same, but piecemeal. */
  157444. GLOBAL(void)
  157445. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  157446. {
  157447. if (cinfo->next_scanline != 0 ||
  157448. (cinfo->global_state != CSTATE_SCANNING &&
  157449. cinfo->global_state != CSTATE_RAW_OK &&
  157450. cinfo->global_state != CSTATE_WRCOEFS))
  157451. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157452. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157453. }
  157454. GLOBAL(void)
  157455. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  157456. {
  157457. (*cinfo->marker->write_marker_byte) (cinfo, val);
  157458. }
  157459. /*
  157460. * Alternate compression function: just write an abbreviated table file.
  157461. * Before calling this, all parameters and a data destination must be set up.
  157462. *
  157463. * To produce a pair of files containing abbreviated tables and abbreviated
  157464. * image data, one would proceed as follows:
  157465. *
  157466. * initialize JPEG object
  157467. * set JPEG parameters
  157468. * set destination to table file
  157469. * jpeg_write_tables(cinfo);
  157470. * set destination to image file
  157471. * jpeg_start_compress(cinfo, FALSE);
  157472. * write data...
  157473. * jpeg_finish_compress(cinfo);
  157474. *
  157475. * jpeg_write_tables has the side effect of marking all tables written
  157476. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  157477. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  157478. */
  157479. GLOBAL(void)
  157480. jpeg_write_tables (j_compress_ptr cinfo)
  157481. {
  157482. if (cinfo->global_state != CSTATE_START)
  157483. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157484. /* (Re)initialize error mgr and destination modules */
  157485. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157486. (*cinfo->dest->init_destination) (cinfo);
  157487. /* Initialize the marker writer ... bit of a crock to do it here. */
  157488. jinit_marker_writer(cinfo);
  157489. /* Write them tables! */
  157490. (*cinfo->marker->write_tables_only) (cinfo);
  157491. /* And clean up. */
  157492. (*cinfo->dest->term_destination) (cinfo);
  157493. /*
  157494. * In library releases up through v6a, we called jpeg_abort() here to free
  157495. * any working memory allocated by the destination manager and marker
  157496. * writer. Some applications had a problem with that: they allocated space
  157497. * of their own from the library memory manager, and didn't want it to go
  157498. * away during write_tables. So now we do nothing. This will cause a
  157499. * memory leak if an app calls write_tables repeatedly without doing a full
  157500. * compression cycle or otherwise resetting the JPEG object. However, that
  157501. * seems less bad than unexpectedly freeing memory in the normal case.
  157502. * An app that prefers the old behavior can call jpeg_abort for itself after
  157503. * each call to jpeg_write_tables().
  157504. */
  157505. }
  157506. /********* End of inlined file: jcapimin.c *********/
  157507. /********* Start of inlined file: jcapistd.c *********/
  157508. #define JPEG_INTERNALS
  157509. /*
  157510. * Compression initialization.
  157511. * Before calling this, all parameters and a data destination must be set up.
  157512. *
  157513. * We require a write_all_tables parameter as a failsafe check when writing
  157514. * multiple datastreams from the same compression object. Since prior runs
  157515. * will have left all the tables marked sent_table=TRUE, a subsequent run
  157516. * would emit an abbreviated stream (no tables) by default. This may be what
  157517. * is wanted, but for safety's sake it should not be the default behavior:
  157518. * programmers should have to make a deliberate choice to emit abbreviated
  157519. * images. Therefore the documentation and examples should encourage people
  157520. * to pass write_all_tables=TRUE; then it will take active thought to do the
  157521. * wrong thing.
  157522. */
  157523. GLOBAL(void)
  157524. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  157525. {
  157526. if (cinfo->global_state != CSTATE_START)
  157527. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157528. if (write_all_tables)
  157529. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  157530. /* (Re)initialize error mgr and destination modules */
  157531. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157532. (*cinfo->dest->init_destination) (cinfo);
  157533. /* Perform master selection of active modules */
  157534. jinit_compress_master(cinfo);
  157535. /* Set up for the first pass */
  157536. (*cinfo->master->prepare_for_pass) (cinfo);
  157537. /* Ready for application to drive first pass through jpeg_write_scanlines
  157538. * or jpeg_write_raw_data.
  157539. */
  157540. cinfo->next_scanline = 0;
  157541. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  157542. }
  157543. /*
  157544. * Write some scanlines of data to the JPEG compressor.
  157545. *
  157546. * The return value will be the number of lines actually written.
  157547. * This should be less than the supplied num_lines only in case that
  157548. * the data destination module has requested suspension of the compressor,
  157549. * or if more than image_height scanlines are passed in.
  157550. *
  157551. * Note: we warn about excess calls to jpeg_write_scanlines() since
  157552. * this likely signals an application programmer error. However,
  157553. * excess scanlines passed in the last valid call are *silently* ignored,
  157554. * so that the application need not adjust num_lines for end-of-image
  157555. * when using a multiple-scanline buffer.
  157556. */
  157557. GLOBAL(JDIMENSION)
  157558. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  157559. JDIMENSION num_lines)
  157560. {
  157561. JDIMENSION row_ctr, rows_left;
  157562. if (cinfo->global_state != CSTATE_SCANNING)
  157563. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157564. if (cinfo->next_scanline >= cinfo->image_height)
  157565. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157566. /* Call progress monitor hook if present */
  157567. if (cinfo->progress != NULL) {
  157568. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157569. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157570. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157571. }
  157572. /* Give master control module another chance if this is first call to
  157573. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  157574. * delayed so that application can write COM, etc, markers between
  157575. * jpeg_start_compress and jpeg_write_scanlines.
  157576. */
  157577. if (cinfo->master->call_pass_startup)
  157578. (*cinfo->master->pass_startup) (cinfo);
  157579. /* Ignore any extra scanlines at bottom of image. */
  157580. rows_left = cinfo->image_height - cinfo->next_scanline;
  157581. if (num_lines > rows_left)
  157582. num_lines = rows_left;
  157583. row_ctr = 0;
  157584. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  157585. cinfo->next_scanline += row_ctr;
  157586. return row_ctr;
  157587. }
  157588. /*
  157589. * Alternate entry point to write raw data.
  157590. * Processes exactly one iMCU row per call, unless suspended.
  157591. */
  157592. GLOBAL(JDIMENSION)
  157593. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  157594. JDIMENSION num_lines)
  157595. {
  157596. JDIMENSION lines_per_iMCU_row;
  157597. if (cinfo->global_state != CSTATE_RAW_OK)
  157598. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157599. if (cinfo->next_scanline >= cinfo->image_height) {
  157600. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157601. return 0;
  157602. }
  157603. /* Call progress monitor hook if present */
  157604. if (cinfo->progress != NULL) {
  157605. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157606. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157607. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157608. }
  157609. /* Give master control module another chance if this is first call to
  157610. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  157611. * delayed so that application can write COM, etc, markers between
  157612. * jpeg_start_compress and jpeg_write_raw_data.
  157613. */
  157614. if (cinfo->master->call_pass_startup)
  157615. (*cinfo->master->pass_startup) (cinfo);
  157616. /* Verify that at least one iMCU row has been passed. */
  157617. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  157618. if (num_lines < lines_per_iMCU_row)
  157619. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  157620. /* Directly compress the row. */
  157621. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  157622. /* If compressor did not consume the whole row, suspend processing. */
  157623. return 0;
  157624. }
  157625. /* OK, we processed one iMCU row. */
  157626. cinfo->next_scanline += lines_per_iMCU_row;
  157627. return lines_per_iMCU_row;
  157628. }
  157629. /********* End of inlined file: jcapistd.c *********/
  157630. /********* Start of inlined file: jccoefct.c *********/
  157631. #define JPEG_INTERNALS
  157632. /* We use a full-image coefficient buffer when doing Huffman optimization,
  157633. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  157634. * step is run during the first pass, and subsequent passes need only read
  157635. * the buffered coefficients.
  157636. */
  157637. #ifdef ENTROPY_OPT_SUPPORTED
  157638. #define FULL_COEF_BUFFER_SUPPORTED
  157639. #else
  157640. #ifdef C_MULTISCAN_FILES_SUPPORTED
  157641. #define FULL_COEF_BUFFER_SUPPORTED
  157642. #endif
  157643. #endif
  157644. /* Private buffer controller object */
  157645. typedef struct {
  157646. struct jpeg_c_coef_controller pub; /* public fields */
  157647. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  157648. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  157649. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  157650. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  157651. /* For single-pass compression, it's sufficient to buffer just one MCU
  157652. * (although this may prove a bit slow in practice). We allocate a
  157653. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  157654. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  157655. * it's not really very big; this is to keep the module interfaces unchanged
  157656. * when a large coefficient buffer is necessary.)
  157657. * In multi-pass modes, this array points to the current MCU's blocks
  157658. * within the virtual arrays.
  157659. */
  157660. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  157661. /* In multi-pass modes, we need a virtual block array for each component. */
  157662. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  157663. } my_coef_controller;
  157664. typedef my_coef_controller * my_coef_ptr;
  157665. /* Forward declarations */
  157666. METHODDEF(boolean) compress_data
  157667. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157668. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157669. METHODDEF(boolean) compress_first_pass
  157670. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157671. METHODDEF(boolean) compress_output
  157672. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157673. #endif
  157674. LOCAL(void)
  157675. start_iMCU_row (j_compress_ptr cinfo)
  157676. /* Reset within-iMCU-row counters for a new row */
  157677. {
  157678. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157679. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  157680. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  157681. * But at the bottom of the image, process only what's left.
  157682. */
  157683. if (cinfo->comps_in_scan > 1) {
  157684. coef->MCU_rows_per_iMCU_row = 1;
  157685. } else {
  157686. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  157687. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  157688. else
  157689. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  157690. }
  157691. coef->mcu_ctr = 0;
  157692. coef->MCU_vert_offset = 0;
  157693. }
  157694. /*
  157695. * Initialize for a processing pass.
  157696. */
  157697. METHODDEF(void)
  157698. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  157699. {
  157700. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157701. coef->iMCU_row_num = 0;
  157702. start_iMCU_row(cinfo);
  157703. switch (pass_mode) {
  157704. case JBUF_PASS_THRU:
  157705. if (coef->whole_image[0] != NULL)
  157706. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157707. coef->pub.compress_data = compress_data;
  157708. break;
  157709. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157710. case JBUF_SAVE_AND_PASS:
  157711. if (coef->whole_image[0] == NULL)
  157712. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157713. coef->pub.compress_data = compress_first_pass;
  157714. break;
  157715. case JBUF_CRANK_DEST:
  157716. if (coef->whole_image[0] == NULL)
  157717. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157718. coef->pub.compress_data = compress_output;
  157719. break;
  157720. #endif
  157721. default:
  157722. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157723. break;
  157724. }
  157725. }
  157726. /*
  157727. * Process some data in the single-pass case.
  157728. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157729. * per call, ie, v_samp_factor block rows for each component in the image.
  157730. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157731. *
  157732. * NB: input_buf contains a plane for each component in image,
  157733. * which we index according to the component's SOF position.
  157734. */
  157735. METHODDEF(boolean)
  157736. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157737. {
  157738. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157739. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157740. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  157741. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157742. int blkn, bi, ci, yindex, yoffset, blockcnt;
  157743. JDIMENSION ypos, xpos;
  157744. jpeg_component_info *compptr;
  157745. /* Loop to write as much as one whole iMCU row */
  157746. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157747. yoffset++) {
  157748. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  157749. MCU_col_num++) {
  157750. /* Determine where data comes from in input_buf and do the DCT thing.
  157751. * Each call on forward_DCT processes a horizontal row of DCT blocks
  157752. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  157753. * sequentially. Dummy blocks at the right or bottom edge are filled in
  157754. * specially. The data in them does not matter for image reconstruction,
  157755. * so we fill them with values that will encode to the smallest amount of
  157756. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  157757. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  157758. */
  157759. blkn = 0;
  157760. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157761. compptr = cinfo->cur_comp_info[ci];
  157762. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  157763. : compptr->last_col_width;
  157764. xpos = MCU_col_num * compptr->MCU_sample_width;
  157765. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  157766. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157767. if (coef->iMCU_row_num < last_iMCU_row ||
  157768. yoffset+yindex < compptr->last_row_height) {
  157769. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157770. input_buf[compptr->component_index],
  157771. coef->MCU_buffer[blkn],
  157772. ypos, xpos, (JDIMENSION) blockcnt);
  157773. if (blockcnt < compptr->MCU_width) {
  157774. /* Create some dummy blocks at the right edge of the image. */
  157775. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  157776. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  157777. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  157778. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  157779. }
  157780. }
  157781. } else {
  157782. /* Create a row of dummy blocks at the bottom of the image. */
  157783. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  157784. compptr->MCU_width * SIZEOF(JBLOCK));
  157785. for (bi = 0; bi < compptr->MCU_width; bi++) {
  157786. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  157787. }
  157788. }
  157789. blkn += compptr->MCU_width;
  157790. ypos += DCTSIZE;
  157791. }
  157792. }
  157793. /* Try to write the MCU. In event of a suspension failure, we will
  157794. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  157795. */
  157796. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157797. /* Suspension forced; update state counters and exit */
  157798. coef->MCU_vert_offset = yoffset;
  157799. coef->mcu_ctr = MCU_col_num;
  157800. return FALSE;
  157801. }
  157802. }
  157803. /* Completed an MCU row, but perhaps not an iMCU row */
  157804. coef->mcu_ctr = 0;
  157805. }
  157806. /* Completed the iMCU row, advance counters for next one */
  157807. coef->iMCU_row_num++;
  157808. start_iMCU_row(cinfo);
  157809. return TRUE;
  157810. }
  157811. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157812. /*
  157813. * Process some data in the first pass of a multi-pass case.
  157814. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157815. * per call, ie, v_samp_factor block rows for each component in the image.
  157816. * This amount of data is read from the source buffer, DCT'd and quantized,
  157817. * and saved into the virtual arrays. We also generate suitable dummy blocks
  157818. * as needed at the right and lower edges. (The dummy blocks are constructed
  157819. * in the virtual arrays, which have been padded appropriately.) This makes
  157820. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  157821. *
  157822. * We must also emit the data to the entropy encoder. This is conveniently
  157823. * done by calling compress_output() after we've loaded the current strip
  157824. * of the virtual arrays.
  157825. *
  157826. * NB: input_buf contains a plane for each component in image. All
  157827. * components are DCT'd and loaded into the virtual arrays in this pass.
  157828. * However, it may be that only a subset of the components are emitted to
  157829. * the entropy encoder during this first pass; be careful about looking
  157830. * at the scan-dependent variables (MCU dimensions, etc).
  157831. */
  157832. METHODDEF(boolean)
  157833. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157834. {
  157835. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157836. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157837. JDIMENSION blocks_across, MCUs_across, MCUindex;
  157838. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  157839. JCOEF lastDC;
  157840. jpeg_component_info *compptr;
  157841. JBLOCKARRAY buffer;
  157842. JBLOCKROW thisblockrow, lastblockrow;
  157843. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157844. ci++, compptr++) {
  157845. /* Align the virtual buffer for this component. */
  157846. buffer = (*cinfo->mem->access_virt_barray)
  157847. ((j_common_ptr) cinfo, coef->whole_image[ci],
  157848. coef->iMCU_row_num * compptr->v_samp_factor,
  157849. (JDIMENSION) compptr->v_samp_factor, TRUE);
  157850. /* Count non-dummy DCT block rows in this iMCU row. */
  157851. if (coef->iMCU_row_num < last_iMCU_row)
  157852. block_rows = compptr->v_samp_factor;
  157853. else {
  157854. /* NB: can't use last_row_height here, since may not be set! */
  157855. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  157856. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  157857. }
  157858. blocks_across = compptr->width_in_blocks;
  157859. h_samp_factor = compptr->h_samp_factor;
  157860. /* Count number of dummy blocks to be added at the right margin. */
  157861. ndummy = (int) (blocks_across % h_samp_factor);
  157862. if (ndummy > 0)
  157863. ndummy = h_samp_factor - ndummy;
  157864. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  157865. * on forward_DCT processes a complete horizontal row of DCT blocks.
  157866. */
  157867. for (block_row = 0; block_row < block_rows; block_row++) {
  157868. thisblockrow = buffer[block_row];
  157869. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157870. input_buf[ci], thisblockrow,
  157871. (JDIMENSION) (block_row * DCTSIZE),
  157872. (JDIMENSION) 0, blocks_across);
  157873. if (ndummy > 0) {
  157874. /* Create dummy blocks at the right edge of the image. */
  157875. thisblockrow += blocks_across; /* => first dummy block */
  157876. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  157877. lastDC = thisblockrow[-1][0];
  157878. for (bi = 0; bi < ndummy; bi++) {
  157879. thisblockrow[bi][0] = lastDC;
  157880. }
  157881. }
  157882. }
  157883. /* If at end of image, create dummy block rows as needed.
  157884. * The tricky part here is that within each MCU, we want the DC values
  157885. * of the dummy blocks to match the last real block's DC value.
  157886. * This squeezes a few more bytes out of the resulting file...
  157887. */
  157888. if (coef->iMCU_row_num == last_iMCU_row) {
  157889. blocks_across += ndummy; /* include lower right corner */
  157890. MCUs_across = blocks_across / h_samp_factor;
  157891. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  157892. block_row++) {
  157893. thisblockrow = buffer[block_row];
  157894. lastblockrow = buffer[block_row-1];
  157895. jzero_far((void FAR *) thisblockrow,
  157896. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  157897. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  157898. lastDC = lastblockrow[h_samp_factor-1][0];
  157899. for (bi = 0; bi < h_samp_factor; bi++) {
  157900. thisblockrow[bi][0] = lastDC;
  157901. }
  157902. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  157903. lastblockrow += h_samp_factor;
  157904. }
  157905. }
  157906. }
  157907. }
  157908. /* NB: compress_output will increment iMCU_row_num if successful.
  157909. * A suspension return will result in redoing all the work above next time.
  157910. */
  157911. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  157912. return compress_output(cinfo, input_buf);
  157913. }
  157914. /*
  157915. * Process some data in subsequent passes of a multi-pass case.
  157916. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157917. * per call, ie, v_samp_factor block rows for each component in the scan.
  157918. * The data is obtained from the virtual arrays and fed to the entropy coder.
  157919. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157920. *
  157921. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  157922. */
  157923. METHODDEF(boolean)
  157924. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157925. {
  157926. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157927. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157928. int blkn, ci, xindex, yindex, yoffset;
  157929. JDIMENSION start_col;
  157930. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  157931. JBLOCKROW buffer_ptr;
  157932. jpeg_component_info *compptr;
  157933. /* Align the virtual buffers for the components used in this scan.
  157934. * NB: during first pass, this is safe only because the buffers will
  157935. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  157936. */
  157937. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157938. compptr = cinfo->cur_comp_info[ci];
  157939. buffer[ci] = (*cinfo->mem->access_virt_barray)
  157940. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  157941. coef->iMCU_row_num * compptr->v_samp_factor,
  157942. (JDIMENSION) compptr->v_samp_factor, FALSE);
  157943. }
  157944. /* Loop to process one whole iMCU row */
  157945. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157946. yoffset++) {
  157947. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  157948. MCU_col_num++) {
  157949. /* Construct list of pointers to DCT blocks belonging to this MCU */
  157950. blkn = 0; /* index of current DCT block within MCU */
  157951. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157952. compptr = cinfo->cur_comp_info[ci];
  157953. start_col = MCU_col_num * compptr->MCU_width;
  157954. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157955. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  157956. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  157957. coef->MCU_buffer[blkn++] = buffer_ptr++;
  157958. }
  157959. }
  157960. }
  157961. /* Try to write the MCU. */
  157962. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157963. /* Suspension forced; update state counters and exit */
  157964. coef->MCU_vert_offset = yoffset;
  157965. coef->mcu_ctr = MCU_col_num;
  157966. return FALSE;
  157967. }
  157968. }
  157969. /* Completed an MCU row, but perhaps not an iMCU row */
  157970. coef->mcu_ctr = 0;
  157971. }
  157972. /* Completed the iMCU row, advance counters for next one */
  157973. coef->iMCU_row_num++;
  157974. start_iMCU_row(cinfo);
  157975. return TRUE;
  157976. }
  157977. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  157978. /*
  157979. * Initialize coefficient buffer controller.
  157980. */
  157981. GLOBAL(void)
  157982. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157983. {
  157984. my_coef_ptr coef;
  157985. coef = (my_coef_ptr)
  157986. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157987. SIZEOF(my_coef_controller));
  157988. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  157989. coef->pub.start_pass = start_pass_coef;
  157990. /* Create the coefficient buffer. */
  157991. if (need_full_buffer) {
  157992. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157993. /* Allocate a full-image virtual array for each component, */
  157994. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  157995. int ci;
  157996. jpeg_component_info *compptr;
  157997. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157998. ci++, compptr++) {
  157999. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  158000. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  158001. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  158002. (long) compptr->h_samp_factor),
  158003. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  158004. (long) compptr->v_samp_factor),
  158005. (JDIMENSION) compptr->v_samp_factor);
  158006. }
  158007. #else
  158008. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158009. #endif
  158010. } else {
  158011. /* We only need a single-MCU buffer. */
  158012. JBLOCKROW buffer;
  158013. int i;
  158014. buffer = (JBLOCKROW)
  158015. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158016. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  158017. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  158018. coef->MCU_buffer[i] = buffer + i;
  158019. }
  158020. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  158021. }
  158022. }
  158023. /********* End of inlined file: jccoefct.c *********/
  158024. /********* Start of inlined file: jccolor.c *********/
  158025. #define JPEG_INTERNALS
  158026. /* Private subobject */
  158027. typedef struct {
  158028. struct jpeg_color_converter pub; /* public fields */
  158029. /* Private state for RGB->YCC conversion */
  158030. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  158031. } my_color_converter;
  158032. typedef my_color_converter * my_cconvert_ptr;
  158033. /**************** RGB -> YCbCr conversion: most common case **************/
  158034. /*
  158035. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  158036. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  158037. * The conversion equations to be implemented are therefore
  158038. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  158039. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  158040. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  158041. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  158042. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  158043. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  158044. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  158045. * were not represented exactly. Now we sacrifice exact representation of
  158046. * maximum red and maximum blue in order to get exact grayscales.
  158047. *
  158048. * To avoid floating-point arithmetic, we represent the fractional constants
  158049. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  158050. * the products by 2^16, with appropriate rounding, to get the correct answer.
  158051. *
  158052. * For even more speed, we avoid doing any multiplications in the inner loop
  158053. * by precalculating the constants times R,G,B for all possible values.
  158054. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  158055. * for 12-bit samples it is still acceptable. It's not very reasonable for
  158056. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  158057. * colorspace anyway.
  158058. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  158059. * in the tables to save adding them separately in the inner loop.
  158060. */
  158061. #define SCALEBITS 16 /* speediest right-shift on some machines */
  158062. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  158063. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  158064. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  158065. /* We allocate one big table and divide it up into eight parts, instead of
  158066. * doing eight alloc_small requests. This lets us use a single table base
  158067. * address, which can be held in a register in the inner loops on many
  158068. * machines (more than can hold all eight addresses, anyway).
  158069. */
  158070. #define R_Y_OFF 0 /* offset to R => Y section */
  158071. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  158072. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  158073. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  158074. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  158075. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  158076. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  158077. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  158078. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  158079. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  158080. /*
  158081. * Initialize for RGB->YCC colorspace conversion.
  158082. */
  158083. METHODDEF(void)
  158084. rgb_ycc_start (j_compress_ptr cinfo)
  158085. {
  158086. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158087. INT32 * rgb_ycc_tab;
  158088. INT32 i;
  158089. /* Allocate and fill in the conversion tables. */
  158090. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  158091. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158092. (TABLE_SIZE * SIZEOF(INT32)));
  158093. for (i = 0; i <= MAXJSAMPLE; i++) {
  158094. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  158095. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  158096. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  158097. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  158098. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  158099. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  158100. * This ensures that the maximum output will round to MAXJSAMPLE
  158101. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  158102. */
  158103. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158104. /* B=>Cb and R=>Cr tables are the same
  158105. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  158106. */
  158107. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  158108. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  158109. }
  158110. }
  158111. /*
  158112. * Convert some rows of samples to the JPEG colorspace.
  158113. *
  158114. * Note that we change from the application's interleaved-pixel format
  158115. * to our internal noninterleaved, one-plane-per-component format.
  158116. * The input buffer is therefore three times as wide as the output buffer.
  158117. *
  158118. * A starting row offset is provided only for the output buffer. The caller
  158119. * can easily adjust the passed input_buf value to accommodate any row
  158120. * offset required on that side.
  158121. */
  158122. METHODDEF(void)
  158123. rgb_ycc_convert (j_compress_ptr cinfo,
  158124. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158125. JDIMENSION output_row, int num_rows)
  158126. {
  158127. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158128. register int r, g, b;
  158129. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158130. register JSAMPROW inptr;
  158131. register JSAMPROW outptr0, outptr1, outptr2;
  158132. register JDIMENSION col;
  158133. JDIMENSION num_cols = cinfo->image_width;
  158134. while (--num_rows >= 0) {
  158135. inptr = *input_buf++;
  158136. outptr0 = output_buf[0][output_row];
  158137. outptr1 = output_buf[1][output_row];
  158138. outptr2 = output_buf[2][output_row];
  158139. output_row++;
  158140. for (col = 0; col < num_cols; col++) {
  158141. r = GETJSAMPLE(inptr[RGB_RED]);
  158142. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158143. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158144. inptr += RGB_PIXELSIZE;
  158145. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158146. * must be too; we do not need an explicit range-limiting operation.
  158147. * Hence the value being shifted is never negative, and we don't
  158148. * need the general RIGHT_SHIFT macro.
  158149. */
  158150. /* Y */
  158151. outptr0[col] = (JSAMPLE)
  158152. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158153. >> SCALEBITS);
  158154. /* Cb */
  158155. outptr1[col] = (JSAMPLE)
  158156. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158157. >> SCALEBITS);
  158158. /* Cr */
  158159. outptr2[col] = (JSAMPLE)
  158160. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158161. >> SCALEBITS);
  158162. }
  158163. }
  158164. }
  158165. /**************** Cases other than RGB -> YCbCr **************/
  158166. /*
  158167. * Convert some rows of samples to the JPEG colorspace.
  158168. * This version handles RGB->grayscale conversion, which is the same
  158169. * as the RGB->Y portion of RGB->YCbCr.
  158170. * We assume rgb_ycc_start has been called (we only use the Y tables).
  158171. */
  158172. METHODDEF(void)
  158173. rgb_gray_convert (j_compress_ptr cinfo,
  158174. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158175. JDIMENSION output_row, int num_rows)
  158176. {
  158177. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158178. register int r, g, b;
  158179. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158180. register JSAMPROW inptr;
  158181. register JSAMPROW outptr;
  158182. register JDIMENSION col;
  158183. JDIMENSION num_cols = cinfo->image_width;
  158184. while (--num_rows >= 0) {
  158185. inptr = *input_buf++;
  158186. outptr = output_buf[0][output_row];
  158187. output_row++;
  158188. for (col = 0; col < num_cols; col++) {
  158189. r = GETJSAMPLE(inptr[RGB_RED]);
  158190. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158191. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158192. inptr += RGB_PIXELSIZE;
  158193. /* Y */
  158194. outptr[col] = (JSAMPLE)
  158195. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158196. >> SCALEBITS);
  158197. }
  158198. }
  158199. }
  158200. /*
  158201. * Convert some rows of samples to the JPEG colorspace.
  158202. * This version handles Adobe-style CMYK->YCCK conversion,
  158203. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  158204. * conversion as above, while passing K (black) unchanged.
  158205. * We assume rgb_ycc_start has been called.
  158206. */
  158207. METHODDEF(void)
  158208. cmyk_ycck_convert (j_compress_ptr cinfo,
  158209. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158210. JDIMENSION output_row, int num_rows)
  158211. {
  158212. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158213. register int r, g, b;
  158214. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158215. register JSAMPROW inptr;
  158216. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  158217. register JDIMENSION col;
  158218. JDIMENSION num_cols = cinfo->image_width;
  158219. while (--num_rows >= 0) {
  158220. inptr = *input_buf++;
  158221. outptr0 = output_buf[0][output_row];
  158222. outptr1 = output_buf[1][output_row];
  158223. outptr2 = output_buf[2][output_row];
  158224. outptr3 = output_buf[3][output_row];
  158225. output_row++;
  158226. for (col = 0; col < num_cols; col++) {
  158227. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  158228. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  158229. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  158230. /* K passes through as-is */
  158231. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  158232. inptr += 4;
  158233. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158234. * must be too; we do not need an explicit range-limiting operation.
  158235. * Hence the value being shifted is never negative, and we don't
  158236. * need the general RIGHT_SHIFT macro.
  158237. */
  158238. /* Y */
  158239. outptr0[col] = (JSAMPLE)
  158240. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158241. >> SCALEBITS);
  158242. /* Cb */
  158243. outptr1[col] = (JSAMPLE)
  158244. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158245. >> SCALEBITS);
  158246. /* Cr */
  158247. outptr2[col] = (JSAMPLE)
  158248. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158249. >> SCALEBITS);
  158250. }
  158251. }
  158252. }
  158253. /*
  158254. * Convert some rows of samples to the JPEG colorspace.
  158255. * This version handles grayscale output with no conversion.
  158256. * The source can be either plain grayscale or YCbCr (since Y == gray).
  158257. */
  158258. METHODDEF(void)
  158259. grayscale_convert (j_compress_ptr cinfo,
  158260. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158261. JDIMENSION output_row, int num_rows)
  158262. {
  158263. register JSAMPROW inptr;
  158264. register JSAMPROW outptr;
  158265. register JDIMENSION col;
  158266. JDIMENSION num_cols = cinfo->image_width;
  158267. int instride = cinfo->input_components;
  158268. while (--num_rows >= 0) {
  158269. inptr = *input_buf++;
  158270. outptr = output_buf[0][output_row];
  158271. output_row++;
  158272. for (col = 0; col < num_cols; col++) {
  158273. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  158274. inptr += instride;
  158275. }
  158276. }
  158277. }
  158278. /*
  158279. * Convert some rows of samples to the JPEG colorspace.
  158280. * This version handles multi-component colorspaces without conversion.
  158281. * We assume input_components == num_components.
  158282. */
  158283. METHODDEF(void)
  158284. null_convert (j_compress_ptr cinfo,
  158285. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158286. JDIMENSION output_row, int num_rows)
  158287. {
  158288. register JSAMPROW inptr;
  158289. register JSAMPROW outptr;
  158290. register JDIMENSION col;
  158291. register int ci;
  158292. int nc = cinfo->num_components;
  158293. JDIMENSION num_cols = cinfo->image_width;
  158294. while (--num_rows >= 0) {
  158295. /* It seems fastest to make a separate pass for each component. */
  158296. for (ci = 0; ci < nc; ci++) {
  158297. inptr = *input_buf;
  158298. outptr = output_buf[ci][output_row];
  158299. for (col = 0; col < num_cols; col++) {
  158300. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  158301. inptr += nc;
  158302. }
  158303. }
  158304. input_buf++;
  158305. output_row++;
  158306. }
  158307. }
  158308. /*
  158309. * Empty method for start_pass.
  158310. */
  158311. METHODDEF(void)
  158312. null_method (j_compress_ptr cinfo)
  158313. {
  158314. /* no work needed */
  158315. }
  158316. /*
  158317. * Module initialization routine for input colorspace conversion.
  158318. */
  158319. GLOBAL(void)
  158320. jinit_color_converter (j_compress_ptr cinfo)
  158321. {
  158322. my_cconvert_ptr cconvert;
  158323. cconvert = (my_cconvert_ptr)
  158324. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158325. SIZEOF(my_color_converter));
  158326. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  158327. /* set start_pass to null method until we find out differently */
  158328. cconvert->pub.start_pass = null_method;
  158329. /* Make sure input_components agrees with in_color_space */
  158330. switch (cinfo->in_color_space) {
  158331. case JCS_GRAYSCALE:
  158332. if (cinfo->input_components != 1)
  158333. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158334. break;
  158335. case JCS_RGB:
  158336. #if RGB_PIXELSIZE != 3
  158337. if (cinfo->input_components != RGB_PIXELSIZE)
  158338. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158339. break;
  158340. #endif /* else share code with YCbCr */
  158341. case JCS_YCbCr:
  158342. if (cinfo->input_components != 3)
  158343. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158344. break;
  158345. case JCS_CMYK:
  158346. case JCS_YCCK:
  158347. if (cinfo->input_components != 4)
  158348. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158349. break;
  158350. default: /* JCS_UNKNOWN can be anything */
  158351. if (cinfo->input_components < 1)
  158352. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158353. break;
  158354. }
  158355. /* Check num_components, set conversion method based on requested space */
  158356. switch (cinfo->jpeg_color_space) {
  158357. case JCS_GRAYSCALE:
  158358. if (cinfo->num_components != 1)
  158359. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158360. if (cinfo->in_color_space == JCS_GRAYSCALE)
  158361. cconvert->pub.color_convert = grayscale_convert;
  158362. else if (cinfo->in_color_space == JCS_RGB) {
  158363. cconvert->pub.start_pass = rgb_ycc_start;
  158364. cconvert->pub.color_convert = rgb_gray_convert;
  158365. } else if (cinfo->in_color_space == JCS_YCbCr)
  158366. cconvert->pub.color_convert = grayscale_convert;
  158367. else
  158368. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158369. break;
  158370. case JCS_RGB:
  158371. if (cinfo->num_components != 3)
  158372. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158373. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  158374. cconvert->pub.color_convert = null_convert;
  158375. else
  158376. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158377. break;
  158378. case JCS_YCbCr:
  158379. if (cinfo->num_components != 3)
  158380. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158381. if (cinfo->in_color_space == JCS_RGB) {
  158382. cconvert->pub.start_pass = rgb_ycc_start;
  158383. cconvert->pub.color_convert = rgb_ycc_convert;
  158384. } else if (cinfo->in_color_space == JCS_YCbCr)
  158385. cconvert->pub.color_convert = null_convert;
  158386. else
  158387. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158388. break;
  158389. case JCS_CMYK:
  158390. if (cinfo->num_components != 4)
  158391. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158392. if (cinfo->in_color_space == JCS_CMYK)
  158393. cconvert->pub.color_convert = null_convert;
  158394. else
  158395. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158396. break;
  158397. case JCS_YCCK:
  158398. if (cinfo->num_components != 4)
  158399. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158400. if (cinfo->in_color_space == JCS_CMYK) {
  158401. cconvert->pub.start_pass = rgb_ycc_start;
  158402. cconvert->pub.color_convert = cmyk_ycck_convert;
  158403. } else if (cinfo->in_color_space == JCS_YCCK)
  158404. cconvert->pub.color_convert = null_convert;
  158405. else
  158406. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158407. break;
  158408. default: /* allow null conversion of JCS_UNKNOWN */
  158409. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  158410. cinfo->num_components != cinfo->input_components)
  158411. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158412. cconvert->pub.color_convert = null_convert;
  158413. break;
  158414. }
  158415. }
  158416. /********* End of inlined file: jccolor.c *********/
  158417. #undef FIX
  158418. /********* Start of inlined file: jcdctmgr.c *********/
  158419. #define JPEG_INTERNALS
  158420. /********* Start of inlined file: jdct.h *********/
  158421. /*
  158422. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  158423. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  158424. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  158425. * implementations use an array of type FAST_FLOAT, instead.)
  158426. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  158427. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  158428. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  158429. * convention improves accuracy in integer implementations and saves some
  158430. * work in floating-point ones.
  158431. * Quantization of the output coefficients is done by jcdctmgr.c.
  158432. */
  158433. #ifndef __jdct_h__
  158434. #define __jdct_h__
  158435. #if BITS_IN_JSAMPLE == 8
  158436. typedef int DCTELEM; /* 16 or 32 bits is fine */
  158437. #else
  158438. typedef INT32 DCTELEM; /* must have 32 bits */
  158439. #endif
  158440. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  158441. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  158442. /*
  158443. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  158444. * to an output sample array. The routine must dequantize the input data as
  158445. * well as perform the IDCT; for dequantization, it uses the multiplier table
  158446. * pointed to by compptr->dct_table. The output data is to be placed into the
  158447. * sample array starting at a specified column. (Any row offset needed will
  158448. * be applied to the array pointer before it is passed to the IDCT code.)
  158449. * Note that the number of samples emitted by the IDCT routine is
  158450. * DCT_scaled_size * DCT_scaled_size.
  158451. */
  158452. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  158453. /*
  158454. * Each IDCT routine has its own ideas about the best dct_table element type.
  158455. */
  158456. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  158457. #if BITS_IN_JSAMPLE == 8
  158458. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  158459. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  158460. #else
  158461. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  158462. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  158463. #endif
  158464. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  158465. /*
  158466. * Each IDCT routine is responsible for range-limiting its results and
  158467. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  158468. * be quite far out of range if the input data is corrupt, so a bulletproof
  158469. * range-limiting step is required. We use a mask-and-table-lookup method
  158470. * to do the combined operations quickly. See the comments with
  158471. * prepare_range_limit_table (in jdmaster.c) for more info.
  158472. */
  158473. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  158474. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  158475. /* Short forms of external names for systems with brain-damaged linkers. */
  158476. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158477. #define jpeg_fdct_islow jFDislow
  158478. #define jpeg_fdct_ifast jFDifast
  158479. #define jpeg_fdct_float jFDfloat
  158480. #define jpeg_idct_islow jRDislow
  158481. #define jpeg_idct_ifast jRDifast
  158482. #define jpeg_idct_float jRDfloat
  158483. #define jpeg_idct_4x4 jRD4x4
  158484. #define jpeg_idct_2x2 jRD2x2
  158485. #define jpeg_idct_1x1 jRD1x1
  158486. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158487. /* Extern declarations for the forward and inverse DCT routines. */
  158488. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  158489. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  158490. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  158491. EXTERN(void) jpeg_idct_islow
  158492. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158493. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158494. EXTERN(void) jpeg_idct_ifast
  158495. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158496. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158497. EXTERN(void) jpeg_idct_float
  158498. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158499. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158500. EXTERN(void) jpeg_idct_4x4
  158501. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158502. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158503. EXTERN(void) jpeg_idct_2x2
  158504. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158505. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158506. EXTERN(void) jpeg_idct_1x1
  158507. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158508. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158509. /*
  158510. * Macros for handling fixed-point arithmetic; these are used by many
  158511. * but not all of the DCT/IDCT modules.
  158512. *
  158513. * All values are expected to be of type INT32.
  158514. * Fractional constants are scaled left by CONST_BITS bits.
  158515. * CONST_BITS is defined within each module using these macros,
  158516. * and may differ from one module to the next.
  158517. */
  158518. #define ONE ((INT32) 1)
  158519. #define CONST_SCALE (ONE << CONST_BITS)
  158520. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  158521. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  158522. * thus causing a lot of useless floating-point operations at run time.
  158523. */
  158524. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  158525. /* Descale and correctly round an INT32 value that's scaled by N bits.
  158526. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  158527. * the fudge factor is correct for either sign of X.
  158528. */
  158529. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  158530. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  158531. * This macro is used only when the two inputs will actually be no more than
  158532. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  158533. * full 32x32 multiply. This provides a useful speedup on many machines.
  158534. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  158535. * in C, but some C compilers will do the right thing if you provide the
  158536. * correct combination of casts.
  158537. */
  158538. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158539. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  158540. #endif
  158541. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  158542. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  158543. #endif
  158544. #ifndef MULTIPLY16C16 /* default definition */
  158545. #define MULTIPLY16C16(var,const) ((var) * (const))
  158546. #endif
  158547. /* Same except both inputs are variables. */
  158548. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158549. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  158550. #endif
  158551. #ifndef MULTIPLY16V16 /* default definition */
  158552. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  158553. #endif
  158554. #endif
  158555. /********* End of inlined file: jdct.h *********/
  158556. /* Private declarations for DCT subsystem */
  158557. /* Private subobject for this module */
  158558. typedef struct {
  158559. struct jpeg_forward_dct pub; /* public fields */
  158560. /* Pointer to the DCT routine actually in use */
  158561. forward_DCT_method_ptr do_dct;
  158562. /* The actual post-DCT divisors --- not identical to the quant table
  158563. * entries, because of scaling (especially for an unnormalized DCT).
  158564. * Each table is given in normal array order.
  158565. */
  158566. DCTELEM * divisors[NUM_QUANT_TBLS];
  158567. #ifdef DCT_FLOAT_SUPPORTED
  158568. /* Same as above for the floating-point case. */
  158569. float_DCT_method_ptr do_float_dct;
  158570. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  158571. #endif
  158572. } my_fdct_controller;
  158573. typedef my_fdct_controller * my_fdct_ptr;
  158574. /*
  158575. * Initialize for a processing pass.
  158576. * Verify that all referenced Q-tables are present, and set up
  158577. * the divisor table for each one.
  158578. * In the current implementation, DCT of all components is done during
  158579. * the first pass, even if only some components will be output in the
  158580. * first scan. Hence all components should be examined here.
  158581. */
  158582. METHODDEF(void)
  158583. start_pass_fdctmgr (j_compress_ptr cinfo)
  158584. {
  158585. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158586. int ci, qtblno, i;
  158587. jpeg_component_info *compptr;
  158588. JQUANT_TBL * qtbl;
  158589. DCTELEM * dtbl;
  158590. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158591. ci++, compptr++) {
  158592. qtblno = compptr->quant_tbl_no;
  158593. /* Make sure specified quantization table is present */
  158594. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  158595. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  158596. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  158597. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  158598. /* Compute divisors for this quant table */
  158599. /* We may do this more than once for same table, but it's not a big deal */
  158600. switch (cinfo->dct_method) {
  158601. #ifdef DCT_ISLOW_SUPPORTED
  158602. case JDCT_ISLOW:
  158603. /* For LL&M IDCT method, divisors are equal to raw quantization
  158604. * coefficients multiplied by 8 (to counteract scaling).
  158605. */
  158606. if (fdct->divisors[qtblno] == NULL) {
  158607. fdct->divisors[qtblno] = (DCTELEM *)
  158608. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158609. DCTSIZE2 * SIZEOF(DCTELEM));
  158610. }
  158611. dtbl = fdct->divisors[qtblno];
  158612. for (i = 0; i < DCTSIZE2; i++) {
  158613. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  158614. }
  158615. break;
  158616. #endif
  158617. #ifdef DCT_IFAST_SUPPORTED
  158618. case JDCT_IFAST:
  158619. {
  158620. /* For AA&N IDCT method, divisors are equal to quantization
  158621. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158622. * scalefactor[0] = 1
  158623. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158624. * We apply a further scale factor of 8.
  158625. */
  158626. #define CONST_BITS 14
  158627. static const INT16 aanscales[DCTSIZE2] = {
  158628. /* precomputed values scaled up by 14 bits */
  158629. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158630. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  158631. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  158632. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  158633. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158634. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  158635. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  158636. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  158637. };
  158638. SHIFT_TEMPS
  158639. if (fdct->divisors[qtblno] == NULL) {
  158640. fdct->divisors[qtblno] = (DCTELEM *)
  158641. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158642. DCTSIZE2 * SIZEOF(DCTELEM));
  158643. }
  158644. dtbl = fdct->divisors[qtblno];
  158645. for (i = 0; i < DCTSIZE2; i++) {
  158646. dtbl[i] = (DCTELEM)
  158647. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  158648. (INT32) aanscales[i]),
  158649. CONST_BITS-3);
  158650. }
  158651. }
  158652. break;
  158653. #endif
  158654. #ifdef DCT_FLOAT_SUPPORTED
  158655. case JDCT_FLOAT:
  158656. {
  158657. /* For float AA&N IDCT method, divisors are equal to quantization
  158658. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158659. * scalefactor[0] = 1
  158660. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158661. * We apply a further scale factor of 8.
  158662. * What's actually stored is 1/divisor so that the inner loop can
  158663. * use a multiplication rather than a division.
  158664. */
  158665. FAST_FLOAT * fdtbl;
  158666. int row, col;
  158667. static const double aanscalefactor[DCTSIZE] = {
  158668. 1.0, 1.387039845, 1.306562965, 1.175875602,
  158669. 1.0, 0.785694958, 0.541196100, 0.275899379
  158670. };
  158671. if (fdct->float_divisors[qtblno] == NULL) {
  158672. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  158673. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158674. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  158675. }
  158676. fdtbl = fdct->float_divisors[qtblno];
  158677. i = 0;
  158678. for (row = 0; row < DCTSIZE; row++) {
  158679. for (col = 0; col < DCTSIZE; col++) {
  158680. fdtbl[i] = (FAST_FLOAT)
  158681. (1.0 / (((double) qtbl->quantval[i] *
  158682. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  158683. i++;
  158684. }
  158685. }
  158686. }
  158687. break;
  158688. #endif
  158689. default:
  158690. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158691. break;
  158692. }
  158693. }
  158694. }
  158695. /*
  158696. * Perform forward DCT on one or more blocks of a component.
  158697. *
  158698. * The input samples are taken from the sample_data[] array starting at
  158699. * position start_row/start_col, and moving to the right for any additional
  158700. * blocks. The quantized coefficients are returned in coef_blocks[].
  158701. */
  158702. METHODDEF(void)
  158703. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158704. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158705. JDIMENSION start_row, JDIMENSION start_col,
  158706. JDIMENSION num_blocks)
  158707. /* This version is used for integer DCT implementations. */
  158708. {
  158709. /* This routine is heavily used, so it's worth coding it tightly. */
  158710. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158711. forward_DCT_method_ptr do_dct = fdct->do_dct;
  158712. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  158713. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158714. JDIMENSION bi;
  158715. sample_data += start_row; /* fold in the vertical offset once */
  158716. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158717. /* Load data into workspace, applying unsigned->signed conversion */
  158718. { register DCTELEM *workspaceptr;
  158719. register JSAMPROW elemptr;
  158720. register int elemr;
  158721. workspaceptr = workspace;
  158722. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158723. elemptr = sample_data[elemr] + start_col;
  158724. #if DCTSIZE == 8 /* unroll the inner loop */
  158725. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158726. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158727. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158728. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158729. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158730. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158731. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158732. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158733. #else
  158734. { register int elemc;
  158735. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158736. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158737. }
  158738. }
  158739. #endif
  158740. }
  158741. }
  158742. /* Perform the DCT */
  158743. (*do_dct) (workspace);
  158744. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158745. { register DCTELEM temp, qval;
  158746. register int i;
  158747. register JCOEFPTR output_ptr = coef_blocks[bi];
  158748. for (i = 0; i < DCTSIZE2; i++) {
  158749. qval = divisors[i];
  158750. temp = workspace[i];
  158751. /* Divide the coefficient value by qval, ensuring proper rounding.
  158752. * Since C does not specify the direction of rounding for negative
  158753. * quotients, we have to force the dividend positive for portability.
  158754. *
  158755. * In most files, at least half of the output values will be zero
  158756. * (at default quantization settings, more like three-quarters...)
  158757. * so we should ensure that this case is fast. On many machines,
  158758. * a comparison is enough cheaper than a divide to make a special test
  158759. * a win. Since both inputs will be nonnegative, we need only test
  158760. * for a < b to discover whether a/b is 0.
  158761. * If your machine's division is fast enough, define FAST_DIVIDE.
  158762. */
  158763. #ifdef FAST_DIVIDE
  158764. #define DIVIDE_BY(a,b) a /= b
  158765. #else
  158766. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  158767. #endif
  158768. if (temp < 0) {
  158769. temp = -temp;
  158770. temp += qval>>1; /* for rounding */
  158771. DIVIDE_BY(temp, qval);
  158772. temp = -temp;
  158773. } else {
  158774. temp += qval>>1; /* for rounding */
  158775. DIVIDE_BY(temp, qval);
  158776. }
  158777. output_ptr[i] = (JCOEF) temp;
  158778. }
  158779. }
  158780. }
  158781. }
  158782. #ifdef DCT_FLOAT_SUPPORTED
  158783. METHODDEF(void)
  158784. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158785. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158786. JDIMENSION start_row, JDIMENSION start_col,
  158787. JDIMENSION num_blocks)
  158788. /* This version is used for floating-point DCT implementations. */
  158789. {
  158790. /* This routine is heavily used, so it's worth coding it tightly. */
  158791. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158792. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  158793. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  158794. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158795. JDIMENSION bi;
  158796. sample_data += start_row; /* fold in the vertical offset once */
  158797. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158798. /* Load data into workspace, applying unsigned->signed conversion */
  158799. { register FAST_FLOAT *workspaceptr;
  158800. register JSAMPROW elemptr;
  158801. register int elemr;
  158802. workspaceptr = workspace;
  158803. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158804. elemptr = sample_data[elemr] + start_col;
  158805. #if DCTSIZE == 8 /* unroll the inner loop */
  158806. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158807. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158808. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158809. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158810. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158811. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158812. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158813. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158814. #else
  158815. { register int elemc;
  158816. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158817. *workspaceptr++ = (FAST_FLOAT)
  158818. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158819. }
  158820. }
  158821. #endif
  158822. }
  158823. }
  158824. /* Perform the DCT */
  158825. (*do_dct) (workspace);
  158826. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158827. { register FAST_FLOAT temp;
  158828. register int i;
  158829. register JCOEFPTR output_ptr = coef_blocks[bi];
  158830. for (i = 0; i < DCTSIZE2; i++) {
  158831. /* Apply the quantization and scaling factor */
  158832. temp = workspace[i] * divisors[i];
  158833. /* Round to nearest integer.
  158834. * Since C does not specify the direction of rounding for negative
  158835. * quotients, we have to force the dividend positive for portability.
  158836. * The maximum coefficient size is +-16K (for 12-bit data), so this
  158837. * code should work for either 16-bit or 32-bit ints.
  158838. */
  158839. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  158840. }
  158841. }
  158842. }
  158843. }
  158844. #endif /* DCT_FLOAT_SUPPORTED */
  158845. /*
  158846. * Initialize FDCT manager.
  158847. */
  158848. GLOBAL(void)
  158849. jinit_forward_dct (j_compress_ptr cinfo)
  158850. {
  158851. my_fdct_ptr fdct;
  158852. int i;
  158853. fdct = (my_fdct_ptr)
  158854. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158855. SIZEOF(my_fdct_controller));
  158856. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  158857. fdct->pub.start_pass = start_pass_fdctmgr;
  158858. switch (cinfo->dct_method) {
  158859. #ifdef DCT_ISLOW_SUPPORTED
  158860. case JDCT_ISLOW:
  158861. fdct->pub.forward_DCT = forward_DCT;
  158862. fdct->do_dct = jpeg_fdct_islow;
  158863. break;
  158864. #endif
  158865. #ifdef DCT_IFAST_SUPPORTED
  158866. case JDCT_IFAST:
  158867. fdct->pub.forward_DCT = forward_DCT;
  158868. fdct->do_dct = jpeg_fdct_ifast;
  158869. break;
  158870. #endif
  158871. #ifdef DCT_FLOAT_SUPPORTED
  158872. case JDCT_FLOAT:
  158873. fdct->pub.forward_DCT = forward_DCT_float;
  158874. fdct->do_float_dct = jpeg_fdct_float;
  158875. break;
  158876. #endif
  158877. default:
  158878. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158879. break;
  158880. }
  158881. /* Mark divisor tables unallocated */
  158882. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158883. fdct->divisors[i] = NULL;
  158884. #ifdef DCT_FLOAT_SUPPORTED
  158885. fdct->float_divisors[i] = NULL;
  158886. #endif
  158887. }
  158888. }
  158889. /********* End of inlined file: jcdctmgr.c *********/
  158890. #undef CONST_BITS
  158891. /********* Start of inlined file: jchuff.c *********/
  158892. #define JPEG_INTERNALS
  158893. /********* Start of inlined file: jchuff.h *********/
  158894. /* The legal range of a DCT coefficient is
  158895. * -1024 .. +1023 for 8-bit data;
  158896. * -16384 .. +16383 for 12-bit data.
  158897. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  158898. */
  158899. #ifndef _jchuff_h_
  158900. #define _jchuff_h_
  158901. #if BITS_IN_JSAMPLE == 8
  158902. #define MAX_COEF_BITS 10
  158903. #else
  158904. #define MAX_COEF_BITS 14
  158905. #endif
  158906. /* Derived data constructed for each Huffman table */
  158907. typedef struct {
  158908. unsigned int ehufco[256]; /* code for each symbol */
  158909. char ehufsi[256]; /* length of code for each symbol */
  158910. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  158911. } c_derived_tbl;
  158912. /* Short forms of external names for systems with brain-damaged linkers. */
  158913. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158914. #define jpeg_make_c_derived_tbl jMkCDerived
  158915. #define jpeg_gen_optimal_table jGenOptTbl
  158916. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158917. /* Expand a Huffman table definition into the derived format */
  158918. EXTERN(void) jpeg_make_c_derived_tbl
  158919. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  158920. c_derived_tbl ** pdtbl));
  158921. /* Generate an optimal table definition given the specified counts */
  158922. EXTERN(void) jpeg_gen_optimal_table
  158923. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  158924. #endif
  158925. /********* End of inlined file: jchuff.h *********/
  158926. /* Declarations shared with jcphuff.c */
  158927. /* Expanded entropy encoder object for Huffman encoding.
  158928. *
  158929. * The savable_state subrecord contains fields that change within an MCU,
  158930. * but must not be updated permanently until we complete the MCU.
  158931. */
  158932. typedef struct {
  158933. INT32 put_buffer; /* current bit-accumulation buffer */
  158934. int put_bits; /* # of bits now in it */
  158935. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  158936. } savable_state;
  158937. /* This macro is to work around compilers with missing or broken
  158938. * structure assignment. You'll need to fix this code if you have
  158939. * such a compiler and you change MAX_COMPS_IN_SCAN.
  158940. */
  158941. #ifndef NO_STRUCT_ASSIGN
  158942. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  158943. #else
  158944. #if MAX_COMPS_IN_SCAN == 4
  158945. #define ASSIGN_STATE(dest,src) \
  158946. ((dest).put_buffer = (src).put_buffer, \
  158947. (dest).put_bits = (src).put_bits, \
  158948. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  158949. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  158950. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  158951. (dest).last_dc_val[3] = (src).last_dc_val[3])
  158952. #endif
  158953. #endif
  158954. typedef struct {
  158955. struct jpeg_entropy_encoder pub; /* public fields */
  158956. savable_state saved; /* Bit buffer & DC state at start of MCU */
  158957. /* These fields are NOT loaded into local working state. */
  158958. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  158959. int next_restart_num; /* next restart number to write (0-7) */
  158960. /* Pointers to derived tables (these workspaces have image lifespan) */
  158961. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  158962. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  158963. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  158964. long * dc_count_ptrs[NUM_HUFF_TBLS];
  158965. long * ac_count_ptrs[NUM_HUFF_TBLS];
  158966. #endif
  158967. } huff_entropy_encoder;
  158968. typedef huff_entropy_encoder * huff_entropy_ptr;
  158969. /* Working state while writing an MCU.
  158970. * This struct contains all the fields that are needed by subroutines.
  158971. */
  158972. typedef struct {
  158973. JOCTET * next_output_byte; /* => next byte to write in buffer */
  158974. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  158975. savable_state cur; /* Current bit buffer & DC state */
  158976. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  158977. } working_state;
  158978. /* Forward declarations */
  158979. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  158980. JBLOCKROW *MCU_data));
  158981. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  158982. #ifdef ENTROPY_OPT_SUPPORTED
  158983. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  158984. JBLOCKROW *MCU_data));
  158985. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  158986. #endif
  158987. /*
  158988. * Initialize for a Huffman-compressed scan.
  158989. * If gather_statistics is TRUE, we do not output anything during the scan,
  158990. * just count the Huffman symbols used and generate Huffman code tables.
  158991. */
  158992. METHODDEF(void)
  158993. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  158994. {
  158995. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158996. int ci, dctbl, actbl;
  158997. jpeg_component_info * compptr;
  158998. if (gather_statistics) {
  158999. #ifdef ENTROPY_OPT_SUPPORTED
  159000. entropy->pub.encode_mcu = encode_mcu_gather;
  159001. entropy->pub.finish_pass = finish_pass_gather;
  159002. #else
  159003. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159004. #endif
  159005. } else {
  159006. entropy->pub.encode_mcu = encode_mcu_huff;
  159007. entropy->pub.finish_pass = finish_pass_huff;
  159008. }
  159009. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159010. compptr = cinfo->cur_comp_info[ci];
  159011. dctbl = compptr->dc_tbl_no;
  159012. actbl = compptr->ac_tbl_no;
  159013. if (gather_statistics) {
  159014. #ifdef ENTROPY_OPT_SUPPORTED
  159015. /* Check for invalid table indexes */
  159016. /* (make_c_derived_tbl does this in the other path) */
  159017. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  159018. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  159019. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  159020. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  159021. /* Allocate and zero the statistics tables */
  159022. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  159023. if (entropy->dc_count_ptrs[dctbl] == NULL)
  159024. entropy->dc_count_ptrs[dctbl] = (long *)
  159025. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159026. 257 * SIZEOF(long));
  159027. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  159028. if (entropy->ac_count_ptrs[actbl] == NULL)
  159029. entropy->ac_count_ptrs[actbl] = (long *)
  159030. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159031. 257 * SIZEOF(long));
  159032. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  159033. #endif
  159034. } else {
  159035. /* Compute derived values for Huffman tables */
  159036. /* We may do this more than once for a table, but it's not expensive */
  159037. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  159038. & entropy->dc_derived_tbls[dctbl]);
  159039. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  159040. & entropy->ac_derived_tbls[actbl]);
  159041. }
  159042. /* Initialize DC predictions to 0 */
  159043. entropy->saved.last_dc_val[ci] = 0;
  159044. }
  159045. /* Initialize bit buffer to empty */
  159046. entropy->saved.put_buffer = 0;
  159047. entropy->saved.put_bits = 0;
  159048. /* Initialize restart stuff */
  159049. entropy->restarts_to_go = cinfo->restart_interval;
  159050. entropy->next_restart_num = 0;
  159051. }
  159052. /*
  159053. * Compute the derived values for a Huffman table.
  159054. * This routine also performs some validation checks on the table.
  159055. *
  159056. * Note this is also used by jcphuff.c.
  159057. */
  159058. GLOBAL(void)
  159059. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  159060. c_derived_tbl ** pdtbl)
  159061. {
  159062. JHUFF_TBL *htbl;
  159063. c_derived_tbl *dtbl;
  159064. int p, i, l, lastp, si, maxsymbol;
  159065. char huffsize[257];
  159066. unsigned int huffcode[257];
  159067. unsigned int code;
  159068. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  159069. * paralleling the order of the symbols themselves in htbl->huffval[].
  159070. */
  159071. /* Find the input Huffman table */
  159072. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  159073. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159074. htbl =
  159075. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  159076. if (htbl == NULL)
  159077. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  159078. /* Allocate a workspace if we haven't already done so. */
  159079. if (*pdtbl == NULL)
  159080. *pdtbl = (c_derived_tbl *)
  159081. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159082. SIZEOF(c_derived_tbl));
  159083. dtbl = *pdtbl;
  159084. /* Figure C.1: make table of Huffman code length for each symbol */
  159085. p = 0;
  159086. for (l = 1; l <= 16; l++) {
  159087. i = (int) htbl->bits[l];
  159088. if (i < 0 || p + i > 256) /* protect against table overrun */
  159089. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159090. while (i--)
  159091. huffsize[p++] = (char) l;
  159092. }
  159093. huffsize[p] = 0;
  159094. lastp = p;
  159095. /* Figure C.2: generate the codes themselves */
  159096. /* We also validate that the counts represent a legal Huffman code tree. */
  159097. code = 0;
  159098. si = huffsize[0];
  159099. p = 0;
  159100. while (huffsize[p]) {
  159101. while (((int) huffsize[p]) == si) {
  159102. huffcode[p++] = code;
  159103. code++;
  159104. }
  159105. /* code is now 1 more than the last code used for codelength si; but
  159106. * it must still fit in si bits, since no code is allowed to be all ones.
  159107. */
  159108. if (((INT32) code) >= (((INT32) 1) << si))
  159109. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159110. code <<= 1;
  159111. si++;
  159112. }
  159113. /* Figure C.3: generate encoding tables */
  159114. /* These are code and size indexed by symbol value */
  159115. /* Set all codeless symbols to have code length 0;
  159116. * this lets us detect duplicate VAL entries here, and later
  159117. * allows emit_bits to detect any attempt to emit such symbols.
  159118. */
  159119. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  159120. /* This is also a convenient place to check for out-of-range
  159121. * and duplicated VAL entries. We allow 0..255 for AC symbols
  159122. * but only 0..15 for DC. (We could constrain them further
  159123. * based on data depth and mode, but this seems enough.)
  159124. */
  159125. maxsymbol = isDC ? 15 : 255;
  159126. for (p = 0; p < lastp; p++) {
  159127. i = htbl->huffval[p];
  159128. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  159129. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159130. dtbl->ehufco[i] = huffcode[p];
  159131. dtbl->ehufsi[i] = huffsize[p];
  159132. }
  159133. }
  159134. /* Outputting bytes to the file */
  159135. /* Emit a byte, taking 'action' if must suspend. */
  159136. #define emit_byte(state,val,action) \
  159137. { *(state)->next_output_byte++ = (JOCTET) (val); \
  159138. if (--(state)->free_in_buffer == 0) \
  159139. if (! dump_buffer(state)) \
  159140. { action; } }
  159141. LOCAL(boolean)
  159142. dump_buffer (working_state * state)
  159143. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  159144. {
  159145. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  159146. if (! (*dest->empty_output_buffer) (state->cinfo))
  159147. return FALSE;
  159148. /* After a successful buffer dump, must reset buffer pointers */
  159149. state->next_output_byte = dest->next_output_byte;
  159150. state->free_in_buffer = dest->free_in_buffer;
  159151. return TRUE;
  159152. }
  159153. /* Outputting bits to the file */
  159154. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159155. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159156. * in one call, and we never retain more than 7 bits in put_buffer
  159157. * between calls, so 24 bits are sufficient.
  159158. */
  159159. INLINE
  159160. LOCAL(boolean)
  159161. emit_bits (working_state * state, unsigned int code, int size)
  159162. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  159163. {
  159164. /* This routine is heavily used, so it's worth coding tightly. */
  159165. register INT32 put_buffer = (INT32) code;
  159166. register int put_bits = state->cur.put_bits;
  159167. /* if size is 0, caller used an invalid Huffman table entry */
  159168. if (size == 0)
  159169. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  159170. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  159171. put_bits += size; /* new number of bits in buffer */
  159172. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159173. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  159174. while (put_bits >= 8) {
  159175. int c = (int) ((put_buffer >> 16) & 0xFF);
  159176. emit_byte(state, c, return FALSE);
  159177. if (c == 0xFF) { /* need to stuff a zero byte? */
  159178. emit_byte(state, 0, return FALSE);
  159179. }
  159180. put_buffer <<= 8;
  159181. put_bits -= 8;
  159182. }
  159183. state->cur.put_buffer = put_buffer; /* update state variables */
  159184. state->cur.put_bits = put_bits;
  159185. return TRUE;
  159186. }
  159187. LOCAL(boolean)
  159188. flush_bits (working_state * state)
  159189. {
  159190. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  159191. return FALSE;
  159192. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  159193. state->cur.put_bits = 0;
  159194. return TRUE;
  159195. }
  159196. /* Encode a single block's worth of coefficients */
  159197. LOCAL(boolean)
  159198. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  159199. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  159200. {
  159201. register int temp, temp2;
  159202. register int nbits;
  159203. register int k, r, i;
  159204. /* Encode the DC coefficient difference per section F.1.2.1 */
  159205. temp = temp2 = block[0] - last_dc_val;
  159206. if (temp < 0) {
  159207. temp = -temp; /* temp is abs value of input */
  159208. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159209. /* This code assumes we are on a two's complement machine */
  159210. temp2--;
  159211. }
  159212. /* Find the number of bits needed for the magnitude of the coefficient */
  159213. nbits = 0;
  159214. while (temp) {
  159215. nbits++;
  159216. temp >>= 1;
  159217. }
  159218. /* Check for out-of-range coefficient values.
  159219. * Since we're encoding a difference, the range limit is twice as much.
  159220. */
  159221. if (nbits > MAX_COEF_BITS+1)
  159222. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159223. /* Emit the Huffman-coded symbol for the number of bits */
  159224. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  159225. return FALSE;
  159226. /* Emit that number of bits of the value, if positive, */
  159227. /* or the complement of its magnitude, if negative. */
  159228. if (nbits) /* emit_bits rejects calls with size 0 */
  159229. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159230. return FALSE;
  159231. /* Encode the AC coefficients per section F.1.2.2 */
  159232. r = 0; /* r = run length of zeros */
  159233. for (k = 1; k < DCTSIZE2; k++) {
  159234. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159235. r++;
  159236. } else {
  159237. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159238. while (r > 15) {
  159239. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  159240. return FALSE;
  159241. r -= 16;
  159242. }
  159243. temp2 = temp;
  159244. if (temp < 0) {
  159245. temp = -temp; /* temp is abs value of input */
  159246. /* This code assumes we are on a two's complement machine */
  159247. temp2--;
  159248. }
  159249. /* Find the number of bits needed for the magnitude of the coefficient */
  159250. nbits = 1; /* there must be at least one 1 bit */
  159251. while ((temp >>= 1))
  159252. nbits++;
  159253. /* Check for out-of-range coefficient values */
  159254. if (nbits > MAX_COEF_BITS)
  159255. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159256. /* Emit Huffman symbol for run length / number of bits */
  159257. i = (r << 4) + nbits;
  159258. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  159259. return FALSE;
  159260. /* Emit that number of bits of the value, if positive, */
  159261. /* or the complement of its magnitude, if negative. */
  159262. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159263. return FALSE;
  159264. r = 0;
  159265. }
  159266. }
  159267. /* If the last coef(s) were zero, emit an end-of-block code */
  159268. if (r > 0)
  159269. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  159270. return FALSE;
  159271. return TRUE;
  159272. }
  159273. /*
  159274. * Emit a restart marker & resynchronize predictions.
  159275. */
  159276. LOCAL(boolean)
  159277. emit_restart (working_state * state, int restart_num)
  159278. {
  159279. int ci;
  159280. if (! flush_bits(state))
  159281. return FALSE;
  159282. emit_byte(state, 0xFF, return FALSE);
  159283. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  159284. /* Re-initialize DC predictions to 0 */
  159285. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  159286. state->cur.last_dc_val[ci] = 0;
  159287. /* The restart counter is not updated until we successfully write the MCU. */
  159288. return TRUE;
  159289. }
  159290. /*
  159291. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  159292. */
  159293. METHODDEF(boolean)
  159294. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159295. {
  159296. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159297. working_state state;
  159298. int blkn, ci;
  159299. jpeg_component_info * compptr;
  159300. /* Load up working state */
  159301. state.next_output_byte = cinfo->dest->next_output_byte;
  159302. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159303. ASSIGN_STATE(state.cur, entropy->saved);
  159304. state.cinfo = cinfo;
  159305. /* Emit restart marker if needed */
  159306. if (cinfo->restart_interval) {
  159307. if (entropy->restarts_to_go == 0)
  159308. if (! emit_restart(&state, entropy->next_restart_num))
  159309. return FALSE;
  159310. }
  159311. /* Encode the MCU data blocks */
  159312. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159313. ci = cinfo->MCU_membership[blkn];
  159314. compptr = cinfo->cur_comp_info[ci];
  159315. if (! encode_one_block(&state,
  159316. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  159317. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  159318. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  159319. return FALSE;
  159320. /* Update last_dc_val */
  159321. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  159322. }
  159323. /* Completed MCU, so update state */
  159324. cinfo->dest->next_output_byte = state.next_output_byte;
  159325. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159326. ASSIGN_STATE(entropy->saved, state.cur);
  159327. /* Update restart-interval state too */
  159328. if (cinfo->restart_interval) {
  159329. if (entropy->restarts_to_go == 0) {
  159330. entropy->restarts_to_go = cinfo->restart_interval;
  159331. entropy->next_restart_num++;
  159332. entropy->next_restart_num &= 7;
  159333. }
  159334. entropy->restarts_to_go--;
  159335. }
  159336. return TRUE;
  159337. }
  159338. /*
  159339. * Finish up at the end of a Huffman-compressed scan.
  159340. */
  159341. METHODDEF(void)
  159342. finish_pass_huff (j_compress_ptr cinfo)
  159343. {
  159344. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159345. working_state state;
  159346. /* Load up working state ... flush_bits needs it */
  159347. state.next_output_byte = cinfo->dest->next_output_byte;
  159348. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159349. ASSIGN_STATE(state.cur, entropy->saved);
  159350. state.cinfo = cinfo;
  159351. /* Flush out the last data */
  159352. if (! flush_bits(&state))
  159353. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159354. /* Update state */
  159355. cinfo->dest->next_output_byte = state.next_output_byte;
  159356. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159357. ASSIGN_STATE(entropy->saved, state.cur);
  159358. }
  159359. /*
  159360. * Huffman coding optimization.
  159361. *
  159362. * We first scan the supplied data and count the number of uses of each symbol
  159363. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  159364. * Then we build a Huffman coding tree for the observed counts.
  159365. * Symbols which are not needed at all for the particular image are not
  159366. * assigned any code, which saves space in the DHT marker as well as in
  159367. * the compressed data.
  159368. */
  159369. #ifdef ENTROPY_OPT_SUPPORTED
  159370. /* Process a single block's worth of coefficients */
  159371. LOCAL(void)
  159372. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  159373. long dc_counts[], long ac_counts[])
  159374. {
  159375. register int temp;
  159376. register int nbits;
  159377. register int k, r;
  159378. /* Encode the DC coefficient difference per section F.1.2.1 */
  159379. temp = block[0] - last_dc_val;
  159380. if (temp < 0)
  159381. temp = -temp;
  159382. /* Find the number of bits needed for the magnitude of the coefficient */
  159383. nbits = 0;
  159384. while (temp) {
  159385. nbits++;
  159386. temp >>= 1;
  159387. }
  159388. /* Check for out-of-range coefficient values.
  159389. * Since we're encoding a difference, the range limit is twice as much.
  159390. */
  159391. if (nbits > MAX_COEF_BITS+1)
  159392. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159393. /* Count the Huffman symbol for the number of bits */
  159394. dc_counts[nbits]++;
  159395. /* Encode the AC coefficients per section F.1.2.2 */
  159396. r = 0; /* r = run length of zeros */
  159397. for (k = 1; k < DCTSIZE2; k++) {
  159398. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159399. r++;
  159400. } else {
  159401. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159402. while (r > 15) {
  159403. ac_counts[0xF0]++;
  159404. r -= 16;
  159405. }
  159406. /* Find the number of bits needed for the magnitude of the coefficient */
  159407. if (temp < 0)
  159408. temp = -temp;
  159409. /* Find the number of bits needed for the magnitude of the coefficient */
  159410. nbits = 1; /* there must be at least one 1 bit */
  159411. while ((temp >>= 1))
  159412. nbits++;
  159413. /* Check for out-of-range coefficient values */
  159414. if (nbits > MAX_COEF_BITS)
  159415. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159416. /* Count Huffman symbol for run length / number of bits */
  159417. ac_counts[(r << 4) + nbits]++;
  159418. r = 0;
  159419. }
  159420. }
  159421. /* If the last coef(s) were zero, emit an end-of-block code */
  159422. if (r > 0)
  159423. ac_counts[0]++;
  159424. }
  159425. /*
  159426. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  159427. * No data is actually output, so no suspension return is possible.
  159428. */
  159429. METHODDEF(boolean)
  159430. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159431. {
  159432. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159433. int blkn, ci;
  159434. jpeg_component_info * compptr;
  159435. /* Take care of restart intervals if needed */
  159436. if (cinfo->restart_interval) {
  159437. if (entropy->restarts_to_go == 0) {
  159438. /* Re-initialize DC predictions to 0 */
  159439. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  159440. entropy->saved.last_dc_val[ci] = 0;
  159441. /* Update restart state */
  159442. entropy->restarts_to_go = cinfo->restart_interval;
  159443. }
  159444. entropy->restarts_to_go--;
  159445. }
  159446. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159447. ci = cinfo->MCU_membership[blkn];
  159448. compptr = cinfo->cur_comp_info[ci];
  159449. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  159450. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  159451. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  159452. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  159453. }
  159454. return TRUE;
  159455. }
  159456. /*
  159457. * Generate the best Huffman code table for the given counts, fill htbl.
  159458. * Note this is also used by jcphuff.c.
  159459. *
  159460. * The JPEG standard requires that no symbol be assigned a codeword of all
  159461. * one bits (so that padding bits added at the end of a compressed segment
  159462. * can't look like a valid code). Because of the canonical ordering of
  159463. * codewords, this just means that there must be an unused slot in the
  159464. * longest codeword length category. Section K.2 of the JPEG spec suggests
  159465. * reserving such a slot by pretending that symbol 256 is a valid symbol
  159466. * with count 1. In theory that's not optimal; giving it count zero but
  159467. * including it in the symbol set anyway should give a better Huffman code.
  159468. * But the theoretically better code actually seems to come out worse in
  159469. * practice, because it produces more all-ones bytes (which incur stuffed
  159470. * zero bytes in the final file). In any case the difference is tiny.
  159471. *
  159472. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  159473. * If some symbols have a very small but nonzero probability, the Huffman tree
  159474. * must be adjusted to meet the code length restriction. We currently use
  159475. * the adjustment method suggested in JPEG section K.2. This method is *not*
  159476. * optimal; it may not choose the best possible limited-length code. But
  159477. * typically only very-low-frequency symbols will be given less-than-optimal
  159478. * lengths, so the code is almost optimal. Experimental comparisons against
  159479. * an optimal limited-length-code algorithm indicate that the difference is
  159480. * microscopic --- usually less than a hundredth of a percent of total size.
  159481. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  159482. */
  159483. GLOBAL(void)
  159484. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  159485. {
  159486. #define MAX_CLEN 32 /* assumed maximum initial code length */
  159487. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  159488. int codesize[257]; /* codesize[k] = code length of symbol k */
  159489. int others[257]; /* next symbol in current branch of tree */
  159490. int c1, c2;
  159491. int p, i, j;
  159492. long v;
  159493. /* This algorithm is explained in section K.2 of the JPEG standard */
  159494. MEMZERO(bits, SIZEOF(bits));
  159495. MEMZERO(codesize, SIZEOF(codesize));
  159496. for (i = 0; i < 257; i++)
  159497. others[i] = -1; /* init links to empty */
  159498. freq[256] = 1; /* make sure 256 has a nonzero count */
  159499. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  159500. * that no real symbol is given code-value of all ones, because 256
  159501. * will be placed last in the largest codeword category.
  159502. */
  159503. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  159504. for (;;) {
  159505. /* Find the smallest nonzero frequency, set c1 = its symbol */
  159506. /* In case of ties, take the larger symbol number */
  159507. c1 = -1;
  159508. v = 1000000000L;
  159509. for (i = 0; i <= 256; i++) {
  159510. if (freq[i] && freq[i] <= v) {
  159511. v = freq[i];
  159512. c1 = i;
  159513. }
  159514. }
  159515. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  159516. /* In case of ties, take the larger symbol number */
  159517. c2 = -1;
  159518. v = 1000000000L;
  159519. for (i = 0; i <= 256; i++) {
  159520. if (freq[i] && freq[i] <= v && i != c1) {
  159521. v = freq[i];
  159522. c2 = i;
  159523. }
  159524. }
  159525. /* Done if we've merged everything into one frequency */
  159526. if (c2 < 0)
  159527. break;
  159528. /* Else merge the two counts/trees */
  159529. freq[c1] += freq[c2];
  159530. freq[c2] = 0;
  159531. /* Increment the codesize of everything in c1's tree branch */
  159532. codesize[c1]++;
  159533. while (others[c1] >= 0) {
  159534. c1 = others[c1];
  159535. codesize[c1]++;
  159536. }
  159537. others[c1] = c2; /* chain c2 onto c1's tree branch */
  159538. /* Increment the codesize of everything in c2's tree branch */
  159539. codesize[c2]++;
  159540. while (others[c2] >= 0) {
  159541. c2 = others[c2];
  159542. codesize[c2]++;
  159543. }
  159544. }
  159545. /* Now count the number of symbols of each code length */
  159546. for (i = 0; i <= 256; i++) {
  159547. if (codesize[i]) {
  159548. /* The JPEG standard seems to think that this can't happen, */
  159549. /* but I'm paranoid... */
  159550. if (codesize[i] > MAX_CLEN)
  159551. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  159552. bits[codesize[i]]++;
  159553. }
  159554. }
  159555. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  159556. * Huffman procedure assigned any such lengths, we must adjust the coding.
  159557. * Here is what the JPEG spec says about how this next bit works:
  159558. * Since symbols are paired for the longest Huffman code, the symbols are
  159559. * removed from this length category two at a time. The prefix for the pair
  159560. * (which is one bit shorter) is allocated to one of the pair; then,
  159561. * skipping the BITS entry for that prefix length, a code word from the next
  159562. * shortest nonzero BITS entry is converted into a prefix for two code words
  159563. * one bit longer.
  159564. */
  159565. for (i = MAX_CLEN; i > 16; i--) {
  159566. while (bits[i] > 0) {
  159567. j = i - 2; /* find length of new prefix to be used */
  159568. while (bits[j] == 0)
  159569. j--;
  159570. bits[i] -= 2; /* remove two symbols */
  159571. bits[i-1]++; /* one goes in this length */
  159572. bits[j+1] += 2; /* two new symbols in this length */
  159573. bits[j]--; /* symbol of this length is now a prefix */
  159574. }
  159575. }
  159576. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  159577. while (bits[i] == 0) /* find largest codelength still in use */
  159578. i--;
  159579. bits[i]--;
  159580. /* Return final symbol counts (only for lengths 0..16) */
  159581. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  159582. /* Return a list of the symbols sorted by code length */
  159583. /* It's not real clear to me why we don't need to consider the codelength
  159584. * changes made above, but the JPEG spec seems to think this works.
  159585. */
  159586. p = 0;
  159587. for (i = 1; i <= MAX_CLEN; i++) {
  159588. for (j = 0; j <= 255; j++) {
  159589. if (codesize[j] == i) {
  159590. htbl->huffval[p] = (UINT8) j;
  159591. p++;
  159592. }
  159593. }
  159594. }
  159595. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  159596. htbl->sent_table = FALSE;
  159597. }
  159598. /*
  159599. * Finish up a statistics-gathering pass and create the new Huffman tables.
  159600. */
  159601. METHODDEF(void)
  159602. finish_pass_gather (j_compress_ptr cinfo)
  159603. {
  159604. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159605. int ci, dctbl, actbl;
  159606. jpeg_component_info * compptr;
  159607. JHUFF_TBL **htblptr;
  159608. boolean did_dc[NUM_HUFF_TBLS];
  159609. boolean did_ac[NUM_HUFF_TBLS];
  159610. /* It's important not to apply jpeg_gen_optimal_table more than once
  159611. * per table, because it clobbers the input frequency counts!
  159612. */
  159613. MEMZERO(did_dc, SIZEOF(did_dc));
  159614. MEMZERO(did_ac, SIZEOF(did_ac));
  159615. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159616. compptr = cinfo->cur_comp_info[ci];
  159617. dctbl = compptr->dc_tbl_no;
  159618. actbl = compptr->ac_tbl_no;
  159619. if (! did_dc[dctbl]) {
  159620. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  159621. if (*htblptr == NULL)
  159622. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159623. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  159624. did_dc[dctbl] = TRUE;
  159625. }
  159626. if (! did_ac[actbl]) {
  159627. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  159628. if (*htblptr == NULL)
  159629. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159630. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  159631. did_ac[actbl] = TRUE;
  159632. }
  159633. }
  159634. }
  159635. #endif /* ENTROPY_OPT_SUPPORTED */
  159636. /*
  159637. * Module initialization routine for Huffman entropy encoding.
  159638. */
  159639. GLOBAL(void)
  159640. jinit_huff_encoder (j_compress_ptr cinfo)
  159641. {
  159642. huff_entropy_ptr entropy;
  159643. int i;
  159644. entropy = (huff_entropy_ptr)
  159645. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159646. SIZEOF(huff_entropy_encoder));
  159647. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  159648. entropy->pub.start_pass = start_pass_huff;
  159649. /* Mark tables unallocated */
  159650. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159651. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  159652. #ifdef ENTROPY_OPT_SUPPORTED
  159653. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  159654. #endif
  159655. }
  159656. }
  159657. /********* End of inlined file: jchuff.c *********/
  159658. #undef emit_byte
  159659. /********* Start of inlined file: jcinit.c *********/
  159660. #define JPEG_INTERNALS
  159661. /*
  159662. * Master selection of compression modules.
  159663. * This is done once at the start of processing an image. We determine
  159664. * which modules will be used and give them appropriate initialization calls.
  159665. */
  159666. GLOBAL(void)
  159667. jinit_compress_master (j_compress_ptr cinfo)
  159668. {
  159669. /* Initialize master control (includes parameter checking/processing) */
  159670. jinit_c_master_control(cinfo, FALSE /* full compression */);
  159671. /* Preprocessing */
  159672. if (! cinfo->raw_data_in) {
  159673. jinit_color_converter(cinfo);
  159674. jinit_downsampler(cinfo);
  159675. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  159676. }
  159677. /* Forward DCT */
  159678. jinit_forward_dct(cinfo);
  159679. /* Entropy encoding: either Huffman or arithmetic coding. */
  159680. if (cinfo->arith_code) {
  159681. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  159682. } else {
  159683. if (cinfo->progressive_mode) {
  159684. #ifdef C_PROGRESSIVE_SUPPORTED
  159685. jinit_phuff_encoder(cinfo);
  159686. #else
  159687. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159688. #endif
  159689. } else
  159690. jinit_huff_encoder(cinfo);
  159691. }
  159692. /* Need a full-image coefficient buffer in any multi-pass mode. */
  159693. jinit_c_coef_controller(cinfo,
  159694. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  159695. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  159696. jinit_marker_writer(cinfo);
  159697. /* We can now tell the memory manager to allocate virtual arrays. */
  159698. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  159699. /* Write the datastream header (SOI) immediately.
  159700. * Frame and scan headers are postponed till later.
  159701. * This lets application insert special markers after the SOI.
  159702. */
  159703. (*cinfo->marker->write_file_header) (cinfo);
  159704. }
  159705. /********* End of inlined file: jcinit.c *********/
  159706. /********* Start of inlined file: jcmainct.c *********/
  159707. #define JPEG_INTERNALS
  159708. /* Note: currently, there is no operating mode in which a full-image buffer
  159709. * is needed at this step. If there were, that mode could not be used with
  159710. * "raw data" input, since this module is bypassed in that case. However,
  159711. * we've left the code here for possible use in special applications.
  159712. */
  159713. #undef FULL_MAIN_BUFFER_SUPPORTED
  159714. /* Private buffer controller object */
  159715. typedef struct {
  159716. struct jpeg_c_main_controller pub; /* public fields */
  159717. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  159718. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  159719. boolean suspended; /* remember if we suspended output */
  159720. J_BUF_MODE pass_mode; /* current operating mode */
  159721. /* If using just a strip buffer, this points to the entire set of buffers
  159722. * (we allocate one for each component). In the full-image case, this
  159723. * points to the currently accessible strips of the virtual arrays.
  159724. */
  159725. JSAMPARRAY buffer[MAX_COMPONENTS];
  159726. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159727. /* If using full-image storage, this array holds pointers to virtual-array
  159728. * control blocks for each component. Unused if not full-image storage.
  159729. */
  159730. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  159731. #endif
  159732. } my_main_controller;
  159733. typedef my_main_controller * my_main_ptr;
  159734. /* Forward declarations */
  159735. METHODDEF(void) process_data_simple_main
  159736. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159737. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159738. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159739. METHODDEF(void) process_data_buffer_main
  159740. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159741. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159742. #endif
  159743. /*
  159744. * Initialize for a processing pass.
  159745. */
  159746. METHODDEF(void)
  159747. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159748. {
  159749. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159750. /* Do nothing in raw-data mode. */
  159751. if (cinfo->raw_data_in)
  159752. return;
  159753. main_->cur_iMCU_row = 0; /* initialize counters */
  159754. main_->rowgroup_ctr = 0;
  159755. main_->suspended = FALSE;
  159756. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  159757. switch (pass_mode) {
  159758. case JBUF_PASS_THRU:
  159759. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159760. if (main_->whole_image[0] != NULL)
  159761. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159762. #endif
  159763. main_->pub.process_data = process_data_simple_main;
  159764. break;
  159765. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159766. case JBUF_SAVE_SOURCE:
  159767. case JBUF_CRANK_DEST:
  159768. case JBUF_SAVE_AND_PASS:
  159769. if (main_->whole_image[0] == NULL)
  159770. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159771. main_->pub.process_data = process_data_buffer_main;
  159772. break;
  159773. #endif
  159774. default:
  159775. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159776. break;
  159777. }
  159778. }
  159779. /*
  159780. * Process some data.
  159781. * This routine handles the simple pass-through mode,
  159782. * where we have only a strip buffer.
  159783. */
  159784. METHODDEF(void)
  159785. process_data_simple_main (j_compress_ptr cinfo,
  159786. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159787. JDIMENSION in_rows_avail)
  159788. {
  159789. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159790. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159791. /* Read input data if we haven't filled the main buffer yet */
  159792. if (main_->rowgroup_ctr < DCTSIZE)
  159793. (*cinfo->prep->pre_process_data) (cinfo,
  159794. input_buf, in_row_ctr, in_rows_avail,
  159795. main_->buffer, &main_->rowgroup_ctr,
  159796. (JDIMENSION) DCTSIZE);
  159797. /* If we don't have a full iMCU row buffered, return to application for
  159798. * more data. Note that preprocessor will always pad to fill the iMCU row
  159799. * at the bottom of the image.
  159800. */
  159801. if (main_->rowgroup_ctr != DCTSIZE)
  159802. return;
  159803. /* Send the completed row to the compressor */
  159804. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  159805. /* If compressor did not consume the whole row, then we must need to
  159806. * suspend processing and return to the application. In this situation
  159807. * we pretend we didn't yet consume the last input row; otherwise, if
  159808. * it happened to be the last row of the image, the application would
  159809. * think we were done.
  159810. */
  159811. if (! main_->suspended) {
  159812. (*in_row_ctr)--;
  159813. main_->suspended = TRUE;
  159814. }
  159815. return;
  159816. }
  159817. /* We did finish the row. Undo our little suspension hack if a previous
  159818. * call suspended; then mark the main buffer empty.
  159819. */
  159820. if (main_->suspended) {
  159821. (*in_row_ctr)++;
  159822. main_->suspended = FALSE;
  159823. }
  159824. main_->rowgroup_ctr = 0;
  159825. main_->cur_iMCU_row++;
  159826. }
  159827. }
  159828. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159829. /*
  159830. * Process some data.
  159831. * This routine handles all of the modes that use a full-size buffer.
  159832. */
  159833. METHODDEF(void)
  159834. process_data_buffer_main (j_compress_ptr cinfo,
  159835. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159836. JDIMENSION in_rows_avail)
  159837. {
  159838. my_main_ptr main = (my_main_ptr) cinfo->main;
  159839. int ci;
  159840. jpeg_component_info *compptr;
  159841. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  159842. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159843. /* Realign the virtual buffers if at the start of an iMCU row. */
  159844. if (main->rowgroup_ctr == 0) {
  159845. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159846. ci++, compptr++) {
  159847. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  159848. ((j_common_ptr) cinfo, main->whole_image[ci],
  159849. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  159850. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  159851. }
  159852. /* In a read pass, pretend we just read some source data. */
  159853. if (! writing) {
  159854. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  159855. main->rowgroup_ctr = DCTSIZE;
  159856. }
  159857. }
  159858. /* If a write pass, read input data until the current iMCU row is full. */
  159859. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  159860. if (writing) {
  159861. (*cinfo->prep->pre_process_data) (cinfo,
  159862. input_buf, in_row_ctr, in_rows_avail,
  159863. main->buffer, &main->rowgroup_ctr,
  159864. (JDIMENSION) DCTSIZE);
  159865. /* Return to application if we need more data to fill the iMCU row. */
  159866. if (main->rowgroup_ctr < DCTSIZE)
  159867. return;
  159868. }
  159869. /* Emit data, unless this is a sink-only pass. */
  159870. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  159871. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  159872. /* If compressor did not consume the whole row, then we must need to
  159873. * suspend processing and return to the application. In this situation
  159874. * we pretend we didn't yet consume the last input row; otherwise, if
  159875. * it happened to be the last row of the image, the application would
  159876. * think we were done.
  159877. */
  159878. if (! main->suspended) {
  159879. (*in_row_ctr)--;
  159880. main->suspended = TRUE;
  159881. }
  159882. return;
  159883. }
  159884. /* We did finish the row. Undo our little suspension hack if a previous
  159885. * call suspended; then mark the main buffer empty.
  159886. */
  159887. if (main->suspended) {
  159888. (*in_row_ctr)++;
  159889. main->suspended = FALSE;
  159890. }
  159891. }
  159892. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  159893. main->rowgroup_ctr = 0;
  159894. main->cur_iMCU_row++;
  159895. }
  159896. }
  159897. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  159898. /*
  159899. * Initialize main buffer controller.
  159900. */
  159901. GLOBAL(void)
  159902. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159903. {
  159904. my_main_ptr main_;
  159905. int ci;
  159906. jpeg_component_info *compptr;
  159907. main_ = (my_main_ptr)
  159908. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159909. SIZEOF(my_main_controller));
  159910. cinfo->main = (struct jpeg_c_main_controller *) main_;
  159911. main_->pub.start_pass = start_pass_main;
  159912. /* We don't need to create a buffer in raw-data mode. */
  159913. if (cinfo->raw_data_in)
  159914. return;
  159915. /* Create the buffer. It holds downsampled data, so each component
  159916. * may be of a different size.
  159917. */
  159918. if (need_full_buffer) {
  159919. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159920. /* Allocate a full-image virtual array for each component */
  159921. /* Note we pad the bottom to a multiple of the iMCU height */
  159922. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159923. ci++, compptr++) {
  159924. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  159925. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159926. compptr->width_in_blocks * DCTSIZE,
  159927. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159928. (long) compptr->v_samp_factor) * DCTSIZE,
  159929. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159930. }
  159931. #else
  159932. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159933. #endif
  159934. } else {
  159935. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159936. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  159937. #endif
  159938. /* Allocate a strip buffer for each component */
  159939. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159940. ci++, compptr++) {
  159941. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  159942. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159943. compptr->width_in_blocks * DCTSIZE,
  159944. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159945. }
  159946. }
  159947. }
  159948. /********* End of inlined file: jcmainct.c *********/
  159949. /********* Start of inlined file: jcmarker.c *********/
  159950. #define JPEG_INTERNALS
  159951. /* Private state */
  159952. typedef struct {
  159953. struct jpeg_marker_writer pub; /* public fields */
  159954. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  159955. } my_marker_writer;
  159956. typedef my_marker_writer * my_marker_ptr;
  159957. /*
  159958. * Basic output routines.
  159959. *
  159960. * Note that we do not support suspension while writing a marker.
  159961. * Therefore, an application using suspension must ensure that there is
  159962. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  159963. * calling jpeg_start_compress, and enough space to write the trailing EOI
  159964. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  159965. * modes are not supported at all with suspension, so those two are the only
  159966. * points where markers will be written.
  159967. */
  159968. LOCAL(void)
  159969. emit_byte (j_compress_ptr cinfo, int val)
  159970. /* Emit a byte */
  159971. {
  159972. struct jpeg_destination_mgr * dest = cinfo->dest;
  159973. *(dest->next_output_byte)++ = (JOCTET) val;
  159974. if (--dest->free_in_buffer == 0) {
  159975. if (! (*dest->empty_output_buffer) (cinfo))
  159976. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159977. }
  159978. }
  159979. LOCAL(void)
  159980. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  159981. /* Emit a marker code */
  159982. {
  159983. emit_byte(cinfo, 0xFF);
  159984. emit_byte(cinfo, (int) mark);
  159985. }
  159986. LOCAL(void)
  159987. emit_2bytes (j_compress_ptr cinfo, int value)
  159988. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  159989. {
  159990. emit_byte(cinfo, (value >> 8) & 0xFF);
  159991. emit_byte(cinfo, value & 0xFF);
  159992. }
  159993. /*
  159994. * Routines to write specific marker types.
  159995. */
  159996. LOCAL(int)
  159997. emit_dqt (j_compress_ptr cinfo, int index)
  159998. /* Emit a DQT marker */
  159999. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  160000. {
  160001. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  160002. int prec;
  160003. int i;
  160004. if (qtbl == NULL)
  160005. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  160006. prec = 0;
  160007. for (i = 0; i < DCTSIZE2; i++) {
  160008. if (qtbl->quantval[i] > 255)
  160009. prec = 1;
  160010. }
  160011. if (! qtbl->sent_table) {
  160012. emit_marker(cinfo, M_DQT);
  160013. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  160014. emit_byte(cinfo, index + (prec<<4));
  160015. for (i = 0; i < DCTSIZE2; i++) {
  160016. /* The table entries must be emitted in zigzag order. */
  160017. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  160018. if (prec)
  160019. emit_byte(cinfo, (int) (qval >> 8));
  160020. emit_byte(cinfo, (int) (qval & 0xFF));
  160021. }
  160022. qtbl->sent_table = TRUE;
  160023. }
  160024. return prec;
  160025. }
  160026. LOCAL(void)
  160027. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  160028. /* Emit a DHT marker */
  160029. {
  160030. JHUFF_TBL * htbl;
  160031. int length, i;
  160032. if (is_ac) {
  160033. htbl = cinfo->ac_huff_tbl_ptrs[index];
  160034. index += 0x10; /* output index has AC bit set */
  160035. } else {
  160036. htbl = cinfo->dc_huff_tbl_ptrs[index];
  160037. }
  160038. if (htbl == NULL)
  160039. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  160040. if (! htbl->sent_table) {
  160041. emit_marker(cinfo, M_DHT);
  160042. length = 0;
  160043. for (i = 1; i <= 16; i++)
  160044. length += htbl->bits[i];
  160045. emit_2bytes(cinfo, length + 2 + 1 + 16);
  160046. emit_byte(cinfo, index);
  160047. for (i = 1; i <= 16; i++)
  160048. emit_byte(cinfo, htbl->bits[i]);
  160049. for (i = 0; i < length; i++)
  160050. emit_byte(cinfo, htbl->huffval[i]);
  160051. htbl->sent_table = TRUE;
  160052. }
  160053. }
  160054. LOCAL(void)
  160055. emit_dac (j_compress_ptr cinfo)
  160056. /* Emit a DAC marker */
  160057. /* Since the useful info is so small, we want to emit all the tables in */
  160058. /* one DAC marker. Therefore this routine does its own scan of the table. */
  160059. {
  160060. #ifdef C_ARITH_CODING_SUPPORTED
  160061. char dc_in_use[NUM_ARITH_TBLS];
  160062. char ac_in_use[NUM_ARITH_TBLS];
  160063. int length, i;
  160064. jpeg_component_info *compptr;
  160065. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160066. dc_in_use[i] = ac_in_use[i] = 0;
  160067. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160068. compptr = cinfo->cur_comp_info[i];
  160069. dc_in_use[compptr->dc_tbl_no] = 1;
  160070. ac_in_use[compptr->ac_tbl_no] = 1;
  160071. }
  160072. length = 0;
  160073. for (i = 0; i < NUM_ARITH_TBLS; i++)
  160074. length += dc_in_use[i] + ac_in_use[i];
  160075. emit_marker(cinfo, M_DAC);
  160076. emit_2bytes(cinfo, length*2 + 2);
  160077. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  160078. if (dc_in_use[i]) {
  160079. emit_byte(cinfo, i);
  160080. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  160081. }
  160082. if (ac_in_use[i]) {
  160083. emit_byte(cinfo, i + 0x10);
  160084. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  160085. }
  160086. }
  160087. #endif /* C_ARITH_CODING_SUPPORTED */
  160088. }
  160089. LOCAL(void)
  160090. emit_dri (j_compress_ptr cinfo)
  160091. /* Emit a DRI marker */
  160092. {
  160093. emit_marker(cinfo, M_DRI);
  160094. emit_2bytes(cinfo, 4); /* fixed length */
  160095. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  160096. }
  160097. LOCAL(void)
  160098. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  160099. /* Emit a SOF marker */
  160100. {
  160101. int ci;
  160102. jpeg_component_info *compptr;
  160103. emit_marker(cinfo, code);
  160104. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  160105. /* Make sure image isn't bigger than SOF field can handle */
  160106. if ((long) cinfo->image_height > 65535L ||
  160107. (long) cinfo->image_width > 65535L)
  160108. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  160109. emit_byte(cinfo, cinfo->data_precision);
  160110. emit_2bytes(cinfo, (int) cinfo->image_height);
  160111. emit_2bytes(cinfo, (int) cinfo->image_width);
  160112. emit_byte(cinfo, cinfo->num_components);
  160113. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160114. ci++, compptr++) {
  160115. emit_byte(cinfo, compptr->component_id);
  160116. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  160117. emit_byte(cinfo, compptr->quant_tbl_no);
  160118. }
  160119. }
  160120. LOCAL(void)
  160121. emit_sos (j_compress_ptr cinfo)
  160122. /* Emit a SOS marker */
  160123. {
  160124. int i, td, ta;
  160125. jpeg_component_info *compptr;
  160126. emit_marker(cinfo, M_SOS);
  160127. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  160128. emit_byte(cinfo, cinfo->comps_in_scan);
  160129. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160130. compptr = cinfo->cur_comp_info[i];
  160131. emit_byte(cinfo, compptr->component_id);
  160132. td = compptr->dc_tbl_no;
  160133. ta = compptr->ac_tbl_no;
  160134. if (cinfo->progressive_mode) {
  160135. /* Progressive mode: only DC or only AC tables are used in one scan;
  160136. * furthermore, Huffman coding of DC refinement uses no table at all.
  160137. * We emit 0 for unused field(s); this is recommended by the P&M text
  160138. * but does not seem to be specified in the standard.
  160139. */
  160140. if (cinfo->Ss == 0) {
  160141. ta = 0; /* DC scan */
  160142. if (cinfo->Ah != 0 && !cinfo->arith_code)
  160143. td = 0; /* no DC table either */
  160144. } else {
  160145. td = 0; /* AC scan */
  160146. }
  160147. }
  160148. emit_byte(cinfo, (td << 4) + ta);
  160149. }
  160150. emit_byte(cinfo, cinfo->Ss);
  160151. emit_byte(cinfo, cinfo->Se);
  160152. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  160153. }
  160154. LOCAL(void)
  160155. emit_jfif_app0 (j_compress_ptr cinfo)
  160156. /* Emit a JFIF-compliant APP0 marker */
  160157. {
  160158. /*
  160159. * Length of APP0 block (2 bytes)
  160160. * Block ID (4 bytes - ASCII "JFIF")
  160161. * Zero byte (1 byte to terminate the ID string)
  160162. * Version Major, Minor (2 bytes - major first)
  160163. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  160164. * Xdpu (2 bytes - dots per unit horizontal)
  160165. * Ydpu (2 bytes - dots per unit vertical)
  160166. * Thumbnail X size (1 byte)
  160167. * Thumbnail Y size (1 byte)
  160168. */
  160169. emit_marker(cinfo, M_APP0);
  160170. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  160171. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  160172. emit_byte(cinfo, 0x46);
  160173. emit_byte(cinfo, 0x49);
  160174. emit_byte(cinfo, 0x46);
  160175. emit_byte(cinfo, 0);
  160176. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  160177. emit_byte(cinfo, cinfo->JFIF_minor_version);
  160178. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  160179. emit_2bytes(cinfo, (int) cinfo->X_density);
  160180. emit_2bytes(cinfo, (int) cinfo->Y_density);
  160181. emit_byte(cinfo, 0); /* No thumbnail image */
  160182. emit_byte(cinfo, 0);
  160183. }
  160184. LOCAL(void)
  160185. emit_adobe_app14 (j_compress_ptr cinfo)
  160186. /* Emit an Adobe APP14 marker */
  160187. {
  160188. /*
  160189. * Length of APP14 block (2 bytes)
  160190. * Block ID (5 bytes - ASCII "Adobe")
  160191. * Version Number (2 bytes - currently 100)
  160192. * Flags0 (2 bytes - currently 0)
  160193. * Flags1 (2 bytes - currently 0)
  160194. * Color transform (1 byte)
  160195. *
  160196. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  160197. * now in circulation seem to use Version = 100, so that's what we write.
  160198. *
  160199. * We write the color transform byte as 1 if the JPEG color space is
  160200. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  160201. * whether the encoder performed a transformation, which is pretty useless.
  160202. */
  160203. emit_marker(cinfo, M_APP14);
  160204. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  160205. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  160206. emit_byte(cinfo, 0x64);
  160207. emit_byte(cinfo, 0x6F);
  160208. emit_byte(cinfo, 0x62);
  160209. emit_byte(cinfo, 0x65);
  160210. emit_2bytes(cinfo, 100); /* Version */
  160211. emit_2bytes(cinfo, 0); /* Flags0 */
  160212. emit_2bytes(cinfo, 0); /* Flags1 */
  160213. switch (cinfo->jpeg_color_space) {
  160214. case JCS_YCbCr:
  160215. emit_byte(cinfo, 1); /* Color transform = 1 */
  160216. break;
  160217. case JCS_YCCK:
  160218. emit_byte(cinfo, 2); /* Color transform = 2 */
  160219. break;
  160220. default:
  160221. emit_byte(cinfo, 0); /* Color transform = 0 */
  160222. break;
  160223. }
  160224. }
  160225. /*
  160226. * These routines allow writing an arbitrary marker with parameters.
  160227. * The only intended use is to emit COM or APPn markers after calling
  160228. * write_file_header and before calling write_frame_header.
  160229. * Other uses are not guaranteed to produce desirable results.
  160230. * Counting the parameter bytes properly is the caller's responsibility.
  160231. */
  160232. METHODDEF(void)
  160233. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160234. /* Emit an arbitrary marker header */
  160235. {
  160236. if (datalen > (unsigned int) 65533) /* safety check */
  160237. ERREXIT(cinfo, JERR_BAD_LENGTH);
  160238. emit_marker(cinfo, (JPEG_MARKER) marker);
  160239. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  160240. }
  160241. METHODDEF(void)
  160242. write_marker_byte (j_compress_ptr cinfo, int val)
  160243. /* Emit one byte of marker parameters following write_marker_header */
  160244. {
  160245. emit_byte(cinfo, val);
  160246. }
  160247. /*
  160248. * Write datastream header.
  160249. * This consists of an SOI and optional APPn markers.
  160250. * We recommend use of the JFIF marker, but not the Adobe marker,
  160251. * when using YCbCr or grayscale data. The JFIF marker should NOT
  160252. * be used for any other JPEG colorspace. The Adobe marker is helpful
  160253. * to distinguish RGB, CMYK, and YCCK colorspaces.
  160254. * Note that an application can write additional header markers after
  160255. * jpeg_start_compress returns.
  160256. */
  160257. METHODDEF(void)
  160258. write_file_header (j_compress_ptr cinfo)
  160259. {
  160260. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160261. emit_marker(cinfo, M_SOI); /* first the SOI */
  160262. /* SOI is defined to reset restart interval to 0 */
  160263. marker->last_restart_interval = 0;
  160264. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  160265. emit_jfif_app0(cinfo);
  160266. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  160267. emit_adobe_app14(cinfo);
  160268. }
  160269. /*
  160270. * Write frame header.
  160271. * This consists of DQT and SOFn markers.
  160272. * Note that we do not emit the SOF until we have emitted the DQT(s).
  160273. * This avoids compatibility problems with incorrect implementations that
  160274. * try to error-check the quant table numbers as soon as they see the SOF.
  160275. */
  160276. METHODDEF(void)
  160277. write_frame_header (j_compress_ptr cinfo)
  160278. {
  160279. int ci, prec;
  160280. boolean is_baseline;
  160281. jpeg_component_info *compptr;
  160282. /* Emit DQT for each quantization table.
  160283. * Note that emit_dqt() suppresses any duplicate tables.
  160284. */
  160285. prec = 0;
  160286. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160287. ci++, compptr++) {
  160288. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  160289. }
  160290. /* now prec is nonzero iff there are any 16-bit quant tables. */
  160291. /* Check for a non-baseline specification.
  160292. * Note we assume that Huffman table numbers won't be changed later.
  160293. */
  160294. if (cinfo->arith_code || cinfo->progressive_mode ||
  160295. cinfo->data_precision != 8) {
  160296. is_baseline = FALSE;
  160297. } else {
  160298. is_baseline = TRUE;
  160299. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160300. ci++, compptr++) {
  160301. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  160302. is_baseline = FALSE;
  160303. }
  160304. if (prec && is_baseline) {
  160305. is_baseline = FALSE;
  160306. /* If it's baseline except for quantizer size, warn the user */
  160307. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  160308. }
  160309. }
  160310. /* Emit the proper SOF marker */
  160311. if (cinfo->arith_code) {
  160312. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  160313. } else {
  160314. if (cinfo->progressive_mode)
  160315. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  160316. else if (is_baseline)
  160317. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  160318. else
  160319. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  160320. }
  160321. }
  160322. /*
  160323. * Write scan header.
  160324. * This consists of DHT or DAC markers, optional DRI, and SOS.
  160325. * Compressed data will be written following the SOS.
  160326. */
  160327. METHODDEF(void)
  160328. write_scan_header (j_compress_ptr cinfo)
  160329. {
  160330. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160331. int i;
  160332. jpeg_component_info *compptr;
  160333. if (cinfo->arith_code) {
  160334. /* Emit arith conditioning info. We may have some duplication
  160335. * if the file has multiple scans, but it's so small it's hardly
  160336. * worth worrying about.
  160337. */
  160338. emit_dac(cinfo);
  160339. } else {
  160340. /* Emit Huffman tables.
  160341. * Note that emit_dht() suppresses any duplicate tables.
  160342. */
  160343. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160344. compptr = cinfo->cur_comp_info[i];
  160345. if (cinfo->progressive_mode) {
  160346. /* Progressive mode: only DC or only AC tables are used in one scan */
  160347. if (cinfo->Ss == 0) {
  160348. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  160349. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160350. } else {
  160351. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160352. }
  160353. } else {
  160354. /* Sequential mode: need both DC and AC tables */
  160355. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160356. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160357. }
  160358. }
  160359. }
  160360. /* Emit DRI if required --- note that DRI value could change for each scan.
  160361. * We avoid wasting space with unnecessary DRIs, however.
  160362. */
  160363. if (cinfo->restart_interval != marker->last_restart_interval) {
  160364. emit_dri(cinfo);
  160365. marker->last_restart_interval = cinfo->restart_interval;
  160366. }
  160367. emit_sos(cinfo);
  160368. }
  160369. /*
  160370. * Write datastream trailer.
  160371. */
  160372. METHODDEF(void)
  160373. write_file_trailer (j_compress_ptr cinfo)
  160374. {
  160375. emit_marker(cinfo, M_EOI);
  160376. }
  160377. /*
  160378. * Write an abbreviated table-specification datastream.
  160379. * This consists of SOI, DQT and DHT tables, and EOI.
  160380. * Any table that is defined and not marked sent_table = TRUE will be
  160381. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  160382. */
  160383. METHODDEF(void)
  160384. write_tables_only (j_compress_ptr cinfo)
  160385. {
  160386. int i;
  160387. emit_marker(cinfo, M_SOI);
  160388. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160389. if (cinfo->quant_tbl_ptrs[i] != NULL)
  160390. (void) emit_dqt(cinfo, i);
  160391. }
  160392. if (! cinfo->arith_code) {
  160393. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160394. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  160395. emit_dht(cinfo, i, FALSE);
  160396. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  160397. emit_dht(cinfo, i, TRUE);
  160398. }
  160399. }
  160400. emit_marker(cinfo, M_EOI);
  160401. }
  160402. /*
  160403. * Initialize the marker writer module.
  160404. */
  160405. GLOBAL(void)
  160406. jinit_marker_writer (j_compress_ptr cinfo)
  160407. {
  160408. my_marker_ptr marker;
  160409. /* Create the subobject */
  160410. marker = (my_marker_ptr)
  160411. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160412. SIZEOF(my_marker_writer));
  160413. cinfo->marker = (struct jpeg_marker_writer *) marker;
  160414. /* Initialize method pointers */
  160415. marker->pub.write_file_header = write_file_header;
  160416. marker->pub.write_frame_header = write_frame_header;
  160417. marker->pub.write_scan_header = write_scan_header;
  160418. marker->pub.write_file_trailer = write_file_trailer;
  160419. marker->pub.write_tables_only = write_tables_only;
  160420. marker->pub.write_marker_header = write_marker_header;
  160421. marker->pub.write_marker_byte = write_marker_byte;
  160422. /* Initialize private state */
  160423. marker->last_restart_interval = 0;
  160424. }
  160425. /********* End of inlined file: jcmarker.c *********/
  160426. /********* Start of inlined file: jcmaster.c *********/
  160427. #define JPEG_INTERNALS
  160428. /* Private state */
  160429. typedef enum {
  160430. main_pass, /* input data, also do first output step */
  160431. huff_opt_pass, /* Huffman code optimization pass */
  160432. output_pass /* data output pass */
  160433. } c_pass_type;
  160434. typedef struct {
  160435. struct jpeg_comp_master pub; /* public fields */
  160436. c_pass_type pass_type; /* the type of the current pass */
  160437. int pass_number; /* # of passes completed */
  160438. int total_passes; /* total # of passes needed */
  160439. int scan_number; /* current index in scan_info[] */
  160440. } my_comp_master;
  160441. typedef my_comp_master * my_master_ptr;
  160442. /*
  160443. * Support routines that do various essential calculations.
  160444. */
  160445. LOCAL(void)
  160446. initial_setup (j_compress_ptr cinfo)
  160447. /* Do computations that are needed before master selection phase */
  160448. {
  160449. int ci;
  160450. jpeg_component_info *compptr;
  160451. long samplesperrow;
  160452. JDIMENSION jd_samplesperrow;
  160453. /* Sanity check on image dimensions */
  160454. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  160455. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  160456. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  160457. /* Make sure image isn't bigger than I can handle */
  160458. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  160459. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  160460. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  160461. /* Width of an input scanline must be representable as JDIMENSION. */
  160462. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  160463. jd_samplesperrow = (JDIMENSION) samplesperrow;
  160464. if ((long) jd_samplesperrow != samplesperrow)
  160465. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  160466. /* For now, precision must match compiled-in value... */
  160467. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  160468. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  160469. /* Check that number of components won't exceed internal array sizes */
  160470. if (cinfo->num_components > MAX_COMPONENTS)
  160471. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160472. MAX_COMPONENTS);
  160473. /* Compute maximum sampling factors; check factor validity */
  160474. cinfo->max_h_samp_factor = 1;
  160475. cinfo->max_v_samp_factor = 1;
  160476. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160477. ci++, compptr++) {
  160478. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  160479. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  160480. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  160481. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  160482. compptr->h_samp_factor);
  160483. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  160484. compptr->v_samp_factor);
  160485. }
  160486. /* Compute dimensions of components */
  160487. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160488. ci++, compptr++) {
  160489. /* Fill in the correct component_index value; don't rely on application */
  160490. compptr->component_index = ci;
  160491. /* For compression, we never do DCT scaling. */
  160492. compptr->DCT_scaled_size = DCTSIZE;
  160493. /* Size in DCT blocks */
  160494. compptr->width_in_blocks = (JDIMENSION)
  160495. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160496. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  160497. compptr->height_in_blocks = (JDIMENSION)
  160498. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160499. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  160500. /* Size in samples */
  160501. compptr->downsampled_width = (JDIMENSION)
  160502. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160503. (long) cinfo->max_h_samp_factor);
  160504. compptr->downsampled_height = (JDIMENSION)
  160505. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160506. (long) cinfo->max_v_samp_factor);
  160507. /* Mark component needed (this flag isn't actually used for compression) */
  160508. compptr->component_needed = TRUE;
  160509. }
  160510. /* Compute number of fully interleaved MCU rows (number of times that
  160511. * main controller will call coefficient controller).
  160512. */
  160513. cinfo->total_iMCU_rows = (JDIMENSION)
  160514. jdiv_round_up((long) cinfo->image_height,
  160515. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160516. }
  160517. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160518. LOCAL(void)
  160519. validate_script (j_compress_ptr cinfo)
  160520. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  160521. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  160522. */
  160523. {
  160524. const jpeg_scan_info * scanptr;
  160525. int scanno, ncomps, ci, coefi, thisi;
  160526. int Ss, Se, Ah, Al;
  160527. boolean component_sent[MAX_COMPONENTS];
  160528. #ifdef C_PROGRESSIVE_SUPPORTED
  160529. int * last_bitpos_ptr;
  160530. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  160531. /* -1 until that coefficient has been seen; then last Al for it */
  160532. #endif
  160533. if (cinfo->num_scans <= 0)
  160534. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  160535. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  160536. * for progressive JPEG, no scan can have this.
  160537. */
  160538. scanptr = cinfo->scan_info;
  160539. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  160540. #ifdef C_PROGRESSIVE_SUPPORTED
  160541. cinfo->progressive_mode = TRUE;
  160542. last_bitpos_ptr = & last_bitpos[0][0];
  160543. for (ci = 0; ci < cinfo->num_components; ci++)
  160544. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  160545. *last_bitpos_ptr++ = -1;
  160546. #else
  160547. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160548. #endif
  160549. } else {
  160550. cinfo->progressive_mode = FALSE;
  160551. for (ci = 0; ci < cinfo->num_components; ci++)
  160552. component_sent[ci] = FALSE;
  160553. }
  160554. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  160555. /* Validate component indexes */
  160556. ncomps = scanptr->comps_in_scan;
  160557. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  160558. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  160559. for (ci = 0; ci < ncomps; ci++) {
  160560. thisi = scanptr->component_index[ci];
  160561. if (thisi < 0 || thisi >= cinfo->num_components)
  160562. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160563. /* Components must appear in SOF order within each scan */
  160564. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  160565. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160566. }
  160567. /* Validate progression parameters */
  160568. Ss = scanptr->Ss;
  160569. Se = scanptr->Se;
  160570. Ah = scanptr->Ah;
  160571. Al = scanptr->Al;
  160572. if (cinfo->progressive_mode) {
  160573. #ifdef C_PROGRESSIVE_SUPPORTED
  160574. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  160575. * seems wrong: the upper bound ought to depend on data precision.
  160576. * Perhaps they really meant 0..N+1 for N-bit precision.
  160577. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  160578. * out-of-range reconstructed DC values during the first DC scan,
  160579. * which might cause problems for some decoders.
  160580. */
  160581. #if BITS_IN_JSAMPLE == 8
  160582. #define MAX_AH_AL 10
  160583. #else
  160584. #define MAX_AH_AL 13
  160585. #endif
  160586. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  160587. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  160588. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160589. if (Ss == 0) {
  160590. if (Se != 0) /* DC and AC together not OK */
  160591. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160592. } else {
  160593. if (ncomps != 1) /* AC scans must be for only one component */
  160594. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160595. }
  160596. for (ci = 0; ci < ncomps; ci++) {
  160597. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  160598. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  160599. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160600. for (coefi = Ss; coefi <= Se; coefi++) {
  160601. if (last_bitpos_ptr[coefi] < 0) {
  160602. /* first scan of this coefficient */
  160603. if (Ah != 0)
  160604. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160605. } else {
  160606. /* not first scan */
  160607. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  160608. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160609. }
  160610. last_bitpos_ptr[coefi] = Al;
  160611. }
  160612. }
  160613. #endif
  160614. } else {
  160615. /* For sequential JPEG, all progression parameters must be these: */
  160616. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  160617. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160618. /* Make sure components are not sent twice */
  160619. for (ci = 0; ci < ncomps; ci++) {
  160620. thisi = scanptr->component_index[ci];
  160621. if (component_sent[thisi])
  160622. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160623. component_sent[thisi] = TRUE;
  160624. }
  160625. }
  160626. }
  160627. /* Now verify that everything got sent. */
  160628. if (cinfo->progressive_mode) {
  160629. #ifdef C_PROGRESSIVE_SUPPORTED
  160630. /* For progressive mode, we only check that at least some DC data
  160631. * got sent for each component; the spec does not require that all bits
  160632. * of all coefficients be transmitted. Would it be wiser to enforce
  160633. * transmission of all coefficient bits??
  160634. */
  160635. for (ci = 0; ci < cinfo->num_components; ci++) {
  160636. if (last_bitpos[ci][0] < 0)
  160637. ERREXIT(cinfo, JERR_MISSING_DATA);
  160638. }
  160639. #endif
  160640. } else {
  160641. for (ci = 0; ci < cinfo->num_components; ci++) {
  160642. if (! component_sent[ci])
  160643. ERREXIT(cinfo, JERR_MISSING_DATA);
  160644. }
  160645. }
  160646. }
  160647. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  160648. LOCAL(void)
  160649. select_scan_parameters (j_compress_ptr cinfo)
  160650. /* Set up the scan parameters for the current scan */
  160651. {
  160652. int ci;
  160653. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160654. if (cinfo->scan_info != NULL) {
  160655. /* Prepare for current scan --- the script is already validated */
  160656. my_master_ptr master = (my_master_ptr) cinfo->master;
  160657. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  160658. cinfo->comps_in_scan = scanptr->comps_in_scan;
  160659. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  160660. cinfo->cur_comp_info[ci] =
  160661. &cinfo->comp_info[scanptr->component_index[ci]];
  160662. }
  160663. cinfo->Ss = scanptr->Ss;
  160664. cinfo->Se = scanptr->Se;
  160665. cinfo->Ah = scanptr->Ah;
  160666. cinfo->Al = scanptr->Al;
  160667. }
  160668. else
  160669. #endif
  160670. {
  160671. /* Prepare for single sequential-JPEG scan containing all components */
  160672. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  160673. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160674. MAX_COMPS_IN_SCAN);
  160675. cinfo->comps_in_scan = cinfo->num_components;
  160676. for (ci = 0; ci < cinfo->num_components; ci++) {
  160677. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  160678. }
  160679. cinfo->Ss = 0;
  160680. cinfo->Se = DCTSIZE2-1;
  160681. cinfo->Ah = 0;
  160682. cinfo->Al = 0;
  160683. }
  160684. }
  160685. LOCAL(void)
  160686. per_scan_setup (j_compress_ptr cinfo)
  160687. /* Do computations that are needed before processing a JPEG scan */
  160688. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  160689. {
  160690. int ci, mcublks, tmp;
  160691. jpeg_component_info *compptr;
  160692. if (cinfo->comps_in_scan == 1) {
  160693. /* Noninterleaved (single-component) scan */
  160694. compptr = cinfo->cur_comp_info[0];
  160695. /* Overall image size in MCUs */
  160696. cinfo->MCUs_per_row = compptr->width_in_blocks;
  160697. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  160698. /* For noninterleaved scan, always one block per MCU */
  160699. compptr->MCU_width = 1;
  160700. compptr->MCU_height = 1;
  160701. compptr->MCU_blocks = 1;
  160702. compptr->MCU_sample_width = DCTSIZE;
  160703. compptr->last_col_width = 1;
  160704. /* For noninterleaved scans, it is convenient to define last_row_height
  160705. * as the number of block rows present in the last iMCU row.
  160706. */
  160707. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  160708. if (tmp == 0) tmp = compptr->v_samp_factor;
  160709. compptr->last_row_height = tmp;
  160710. /* Prepare array describing MCU composition */
  160711. cinfo->blocks_in_MCU = 1;
  160712. cinfo->MCU_membership[0] = 0;
  160713. } else {
  160714. /* Interleaved (multi-component) scan */
  160715. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  160716. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  160717. MAX_COMPS_IN_SCAN);
  160718. /* Overall image size in MCUs */
  160719. cinfo->MCUs_per_row = (JDIMENSION)
  160720. jdiv_round_up((long) cinfo->image_width,
  160721. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  160722. cinfo->MCU_rows_in_scan = (JDIMENSION)
  160723. jdiv_round_up((long) cinfo->image_height,
  160724. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160725. cinfo->blocks_in_MCU = 0;
  160726. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160727. compptr = cinfo->cur_comp_info[ci];
  160728. /* Sampling factors give # of blocks of component in each MCU */
  160729. compptr->MCU_width = compptr->h_samp_factor;
  160730. compptr->MCU_height = compptr->v_samp_factor;
  160731. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  160732. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  160733. /* Figure number of non-dummy blocks in last MCU column & row */
  160734. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  160735. if (tmp == 0) tmp = compptr->MCU_width;
  160736. compptr->last_col_width = tmp;
  160737. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  160738. if (tmp == 0) tmp = compptr->MCU_height;
  160739. compptr->last_row_height = tmp;
  160740. /* Prepare array describing MCU composition */
  160741. mcublks = compptr->MCU_blocks;
  160742. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  160743. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  160744. while (mcublks-- > 0) {
  160745. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  160746. }
  160747. }
  160748. }
  160749. /* Convert restart specified in rows to actual MCU count. */
  160750. /* Note that count must fit in 16 bits, so we provide limiting. */
  160751. if (cinfo->restart_in_rows > 0) {
  160752. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  160753. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  160754. }
  160755. }
  160756. /*
  160757. * Per-pass setup.
  160758. * This is called at the beginning of each pass. We determine which modules
  160759. * will be active during this pass and give them appropriate start_pass calls.
  160760. * We also set is_last_pass to indicate whether any more passes will be
  160761. * required.
  160762. */
  160763. METHODDEF(void)
  160764. prepare_for_pass (j_compress_ptr cinfo)
  160765. {
  160766. my_master_ptr master = (my_master_ptr) cinfo->master;
  160767. switch (master->pass_type) {
  160768. case main_pass:
  160769. /* Initial pass: will collect input data, and do either Huffman
  160770. * optimization or data output for the first scan.
  160771. */
  160772. select_scan_parameters(cinfo);
  160773. per_scan_setup(cinfo);
  160774. if (! cinfo->raw_data_in) {
  160775. (*cinfo->cconvert->start_pass) (cinfo);
  160776. (*cinfo->downsample->start_pass) (cinfo);
  160777. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  160778. }
  160779. (*cinfo->fdct->start_pass) (cinfo);
  160780. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  160781. (*cinfo->coef->start_pass) (cinfo,
  160782. (master->total_passes > 1 ?
  160783. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  160784. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  160785. if (cinfo->optimize_coding) {
  160786. /* No immediate data output; postpone writing frame/scan headers */
  160787. master->pub.call_pass_startup = FALSE;
  160788. } else {
  160789. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  160790. master->pub.call_pass_startup = TRUE;
  160791. }
  160792. break;
  160793. #ifdef ENTROPY_OPT_SUPPORTED
  160794. case huff_opt_pass:
  160795. /* Do Huffman optimization for a scan after the first one. */
  160796. select_scan_parameters(cinfo);
  160797. per_scan_setup(cinfo);
  160798. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  160799. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  160800. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160801. master->pub.call_pass_startup = FALSE;
  160802. break;
  160803. }
  160804. /* Special case: Huffman DC refinement scans need no Huffman table
  160805. * and therefore we can skip the optimization pass for them.
  160806. */
  160807. master->pass_type = output_pass;
  160808. master->pass_number++;
  160809. /*FALLTHROUGH*/
  160810. #endif
  160811. case output_pass:
  160812. /* Do a data-output pass. */
  160813. /* We need not repeat per-scan setup if prior optimization pass did it. */
  160814. if (! cinfo->optimize_coding) {
  160815. select_scan_parameters(cinfo);
  160816. per_scan_setup(cinfo);
  160817. }
  160818. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  160819. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160820. /* We emit frame/scan headers now */
  160821. if (master->scan_number == 0)
  160822. (*cinfo->marker->write_frame_header) (cinfo);
  160823. (*cinfo->marker->write_scan_header) (cinfo);
  160824. master->pub.call_pass_startup = FALSE;
  160825. break;
  160826. default:
  160827. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160828. }
  160829. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  160830. /* Set up progress monitor's pass info if present */
  160831. if (cinfo->progress != NULL) {
  160832. cinfo->progress->completed_passes = master->pass_number;
  160833. cinfo->progress->total_passes = master->total_passes;
  160834. }
  160835. }
  160836. /*
  160837. * Special start-of-pass hook.
  160838. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  160839. * In single-pass processing, we need this hook because we don't want to
  160840. * write frame/scan headers during jpeg_start_compress; we want to let the
  160841. * application write COM markers etc. between jpeg_start_compress and the
  160842. * jpeg_write_scanlines loop.
  160843. * In multi-pass processing, this routine is not used.
  160844. */
  160845. METHODDEF(void)
  160846. pass_startup (j_compress_ptr cinfo)
  160847. {
  160848. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  160849. (*cinfo->marker->write_frame_header) (cinfo);
  160850. (*cinfo->marker->write_scan_header) (cinfo);
  160851. }
  160852. /*
  160853. * Finish up at end of pass.
  160854. */
  160855. METHODDEF(void)
  160856. finish_pass_master (j_compress_ptr cinfo)
  160857. {
  160858. my_master_ptr master = (my_master_ptr) cinfo->master;
  160859. /* The entropy coder always needs an end-of-pass call,
  160860. * either to analyze statistics or to flush its output buffer.
  160861. */
  160862. (*cinfo->entropy->finish_pass) (cinfo);
  160863. /* Update state for next pass */
  160864. switch (master->pass_type) {
  160865. case main_pass:
  160866. /* next pass is either output of scan 0 (after optimization)
  160867. * or output of scan 1 (if no optimization).
  160868. */
  160869. master->pass_type = output_pass;
  160870. if (! cinfo->optimize_coding)
  160871. master->scan_number++;
  160872. break;
  160873. case huff_opt_pass:
  160874. /* next pass is always output of current scan */
  160875. master->pass_type = output_pass;
  160876. break;
  160877. case output_pass:
  160878. /* next pass is either optimization or output of next scan */
  160879. if (cinfo->optimize_coding)
  160880. master->pass_type = huff_opt_pass;
  160881. master->scan_number++;
  160882. break;
  160883. }
  160884. master->pass_number++;
  160885. }
  160886. /*
  160887. * Initialize master compression control.
  160888. */
  160889. GLOBAL(void)
  160890. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  160891. {
  160892. my_master_ptr master;
  160893. master = (my_master_ptr)
  160894. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160895. SIZEOF(my_comp_master));
  160896. cinfo->master = (struct jpeg_comp_master *) master;
  160897. master->pub.prepare_for_pass = prepare_for_pass;
  160898. master->pub.pass_startup = pass_startup;
  160899. master->pub.finish_pass = finish_pass_master;
  160900. master->pub.is_last_pass = FALSE;
  160901. /* Validate parameters, determine derived values */
  160902. initial_setup(cinfo);
  160903. if (cinfo->scan_info != NULL) {
  160904. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160905. validate_script(cinfo);
  160906. #else
  160907. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160908. #endif
  160909. } else {
  160910. cinfo->progressive_mode = FALSE;
  160911. cinfo->num_scans = 1;
  160912. }
  160913. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  160914. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  160915. /* Initialize my private state */
  160916. if (transcode_only) {
  160917. /* no main pass in transcoding */
  160918. if (cinfo->optimize_coding)
  160919. master->pass_type = huff_opt_pass;
  160920. else
  160921. master->pass_type = output_pass;
  160922. } else {
  160923. /* for normal compression, first pass is always this type: */
  160924. master->pass_type = main_pass;
  160925. }
  160926. master->scan_number = 0;
  160927. master->pass_number = 0;
  160928. if (cinfo->optimize_coding)
  160929. master->total_passes = cinfo->num_scans * 2;
  160930. else
  160931. master->total_passes = cinfo->num_scans;
  160932. }
  160933. /********* End of inlined file: jcmaster.c *********/
  160934. /********* Start of inlined file: jcomapi.c *********/
  160935. #define JPEG_INTERNALS
  160936. /*
  160937. * Abort processing of a JPEG compression or decompression operation,
  160938. * but don't destroy the object itself.
  160939. *
  160940. * For this, we merely clean up all the nonpermanent memory pools.
  160941. * Note that temp files (virtual arrays) are not allowed to belong to
  160942. * the permanent pool, so we will be able to close all temp files here.
  160943. * Closing a data source or destination, if necessary, is the application's
  160944. * responsibility.
  160945. */
  160946. GLOBAL(void)
  160947. jpeg_abort (j_common_ptr cinfo)
  160948. {
  160949. int pool;
  160950. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  160951. if (cinfo->mem == NULL)
  160952. return;
  160953. /* Releasing pools in reverse order might help avoid fragmentation
  160954. * with some (brain-damaged) malloc libraries.
  160955. */
  160956. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  160957. (*cinfo->mem->free_pool) (cinfo, pool);
  160958. }
  160959. /* Reset overall state for possible reuse of object */
  160960. if (cinfo->is_decompressor) {
  160961. cinfo->global_state = DSTATE_START;
  160962. /* Try to keep application from accessing now-deleted marker list.
  160963. * A bit kludgy to do it here, but this is the most central place.
  160964. */
  160965. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  160966. } else {
  160967. cinfo->global_state = CSTATE_START;
  160968. }
  160969. }
  160970. /*
  160971. * Destruction of a JPEG object.
  160972. *
  160973. * Everything gets deallocated except the master jpeg_compress_struct itself
  160974. * and the error manager struct. Both of these are supplied by the application
  160975. * and must be freed, if necessary, by the application. (Often they are on
  160976. * the stack and so don't need to be freed anyway.)
  160977. * Closing a data source or destination, if necessary, is the application's
  160978. * responsibility.
  160979. */
  160980. GLOBAL(void)
  160981. jpeg_destroy (j_common_ptr cinfo)
  160982. {
  160983. /* We need only tell the memory manager to release everything. */
  160984. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  160985. if (cinfo->mem != NULL)
  160986. (*cinfo->mem->self_destruct) (cinfo);
  160987. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  160988. cinfo->global_state = 0; /* mark it destroyed */
  160989. }
  160990. /*
  160991. * Convenience routines for allocating quantization and Huffman tables.
  160992. * (Would jutils.c be a more reasonable place to put these?)
  160993. */
  160994. GLOBAL(JQUANT_TBL *)
  160995. jpeg_alloc_quant_table (j_common_ptr cinfo)
  160996. {
  160997. JQUANT_TBL *tbl;
  160998. tbl = (JQUANT_TBL *)
  160999. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  161000. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  161001. return tbl;
  161002. }
  161003. GLOBAL(JHUFF_TBL *)
  161004. jpeg_alloc_huff_table (j_common_ptr cinfo)
  161005. {
  161006. JHUFF_TBL *tbl;
  161007. tbl = (JHUFF_TBL *)
  161008. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  161009. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  161010. return tbl;
  161011. }
  161012. /********* End of inlined file: jcomapi.c *********/
  161013. /********* Start of inlined file: jcparam.c *********/
  161014. #define JPEG_INTERNALS
  161015. /*
  161016. * Quantization table setup routines
  161017. */
  161018. GLOBAL(void)
  161019. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  161020. const unsigned int *basic_table,
  161021. int scale_factor, boolean force_baseline)
  161022. /* Define a quantization table equal to the basic_table times
  161023. * a scale factor (given as a percentage).
  161024. * If force_baseline is TRUE, the computed quantization table entries
  161025. * are limited to 1..255 for JPEG baseline compatibility.
  161026. */
  161027. {
  161028. JQUANT_TBL ** qtblptr;
  161029. int i;
  161030. long temp;
  161031. /* Safety check to ensure start_compress not called yet. */
  161032. if (cinfo->global_state != CSTATE_START)
  161033. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161034. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  161035. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  161036. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  161037. if (*qtblptr == NULL)
  161038. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  161039. for (i = 0; i < DCTSIZE2; i++) {
  161040. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  161041. /* limit the values to the valid range */
  161042. if (temp <= 0L) temp = 1L;
  161043. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  161044. if (force_baseline && temp > 255L)
  161045. temp = 255L; /* limit to baseline range if requested */
  161046. (*qtblptr)->quantval[i] = (UINT16) temp;
  161047. }
  161048. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161049. (*qtblptr)->sent_table = FALSE;
  161050. }
  161051. GLOBAL(void)
  161052. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  161053. boolean force_baseline)
  161054. /* Set or change the 'quality' (quantization) setting, using default tables
  161055. * and a straight percentage-scaling quality scale. In most cases it's better
  161056. * to use jpeg_set_quality (below); this entry point is provided for
  161057. * applications that insist on a linear percentage scaling.
  161058. */
  161059. {
  161060. /* These are the sample quantization tables given in JPEG spec section K.1.
  161061. * The spec says that the values given produce "good" quality, and
  161062. * when divided by 2, "very good" quality.
  161063. */
  161064. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  161065. 16, 11, 10, 16, 24, 40, 51, 61,
  161066. 12, 12, 14, 19, 26, 58, 60, 55,
  161067. 14, 13, 16, 24, 40, 57, 69, 56,
  161068. 14, 17, 22, 29, 51, 87, 80, 62,
  161069. 18, 22, 37, 56, 68, 109, 103, 77,
  161070. 24, 35, 55, 64, 81, 104, 113, 92,
  161071. 49, 64, 78, 87, 103, 121, 120, 101,
  161072. 72, 92, 95, 98, 112, 100, 103, 99
  161073. };
  161074. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  161075. 17, 18, 24, 47, 99, 99, 99, 99,
  161076. 18, 21, 26, 66, 99, 99, 99, 99,
  161077. 24, 26, 56, 99, 99, 99, 99, 99,
  161078. 47, 66, 99, 99, 99, 99, 99, 99,
  161079. 99, 99, 99, 99, 99, 99, 99, 99,
  161080. 99, 99, 99, 99, 99, 99, 99, 99,
  161081. 99, 99, 99, 99, 99, 99, 99, 99,
  161082. 99, 99, 99, 99, 99, 99, 99, 99
  161083. };
  161084. /* Set up two quantization tables using the specified scaling */
  161085. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  161086. scale_factor, force_baseline);
  161087. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  161088. scale_factor, force_baseline);
  161089. }
  161090. GLOBAL(int)
  161091. jpeg_quality_scaling (int quality)
  161092. /* Convert a user-specified quality rating to a percentage scaling factor
  161093. * for an underlying quantization table, using our recommended scaling curve.
  161094. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  161095. */
  161096. {
  161097. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  161098. if (quality <= 0) quality = 1;
  161099. if (quality > 100) quality = 100;
  161100. /* The basic table is used as-is (scaling 100) for a quality of 50.
  161101. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  161102. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  161103. * to make all the table entries 1 (hence, minimum quantization loss).
  161104. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  161105. */
  161106. if (quality < 50)
  161107. quality = 5000 / quality;
  161108. else
  161109. quality = 200 - quality*2;
  161110. return quality;
  161111. }
  161112. GLOBAL(void)
  161113. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  161114. /* Set or change the 'quality' (quantization) setting, using default tables.
  161115. * This is the standard quality-adjusting entry point for typical user
  161116. * interfaces; only those who want detailed control over quantization tables
  161117. * would use the preceding three routines directly.
  161118. */
  161119. {
  161120. /* Convert user 0-100 rating to percentage scaling */
  161121. quality = jpeg_quality_scaling(quality);
  161122. /* Set up standard quality tables */
  161123. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  161124. }
  161125. /*
  161126. * Huffman table setup routines
  161127. */
  161128. LOCAL(void)
  161129. add_huff_table (j_compress_ptr cinfo,
  161130. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  161131. /* Define a Huffman table */
  161132. {
  161133. int nsymbols, len;
  161134. if (*htblptr == NULL)
  161135. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161136. /* Copy the number-of-symbols-of-each-code-length counts */
  161137. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  161138. /* Validate the counts. We do this here mainly so we can copy the right
  161139. * number of symbols from the val[] array, without risking marching off
  161140. * the end of memory. jchuff.c will do a more thorough test later.
  161141. */
  161142. nsymbols = 0;
  161143. for (len = 1; len <= 16; len++)
  161144. nsymbols += bits[len];
  161145. if (nsymbols < 1 || nsymbols > 256)
  161146. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  161147. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  161148. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  161149. (*htblptr)->sent_table = FALSE;
  161150. }
  161151. LOCAL(void)
  161152. std_huff_tables (j_compress_ptr cinfo)
  161153. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  161154. /* IMPORTANT: these are only valid for 8-bit data precision! */
  161155. {
  161156. static const UINT8 bits_dc_luminance[17] =
  161157. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  161158. static const UINT8 val_dc_luminance[] =
  161159. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161160. static const UINT8 bits_dc_chrominance[17] =
  161161. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  161162. static const UINT8 val_dc_chrominance[] =
  161163. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  161164. static const UINT8 bits_ac_luminance[17] =
  161165. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  161166. static const UINT8 val_ac_luminance[] =
  161167. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  161168. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  161169. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  161170. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  161171. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  161172. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  161173. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  161174. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  161175. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  161176. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  161177. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  161178. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  161179. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  161180. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  161181. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  161182. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  161183. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  161184. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  161185. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  161186. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161187. 0xf9, 0xfa };
  161188. static const UINT8 bits_ac_chrominance[17] =
  161189. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  161190. static const UINT8 val_ac_chrominance[] =
  161191. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  161192. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  161193. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  161194. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  161195. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  161196. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  161197. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  161198. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  161199. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  161200. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  161201. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  161202. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  161203. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  161204. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  161205. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  161206. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  161207. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  161208. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  161209. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  161210. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161211. 0xf9, 0xfa };
  161212. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  161213. bits_dc_luminance, val_dc_luminance);
  161214. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  161215. bits_ac_luminance, val_ac_luminance);
  161216. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  161217. bits_dc_chrominance, val_dc_chrominance);
  161218. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  161219. bits_ac_chrominance, val_ac_chrominance);
  161220. }
  161221. /*
  161222. * Default parameter setup for compression.
  161223. *
  161224. * Applications that don't choose to use this routine must do their
  161225. * own setup of all these parameters. Alternately, you can call this
  161226. * to establish defaults and then alter parameters selectively. This
  161227. * is the recommended approach since, if we add any new parameters,
  161228. * your code will still work (they'll be set to reasonable defaults).
  161229. */
  161230. GLOBAL(void)
  161231. jpeg_set_defaults (j_compress_ptr cinfo)
  161232. {
  161233. int i;
  161234. /* Safety check to ensure start_compress not called yet. */
  161235. if (cinfo->global_state != CSTATE_START)
  161236. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161237. /* Allocate comp_info array large enough for maximum component count.
  161238. * Array is made permanent in case application wants to compress
  161239. * multiple images at same param settings.
  161240. */
  161241. if (cinfo->comp_info == NULL)
  161242. cinfo->comp_info = (jpeg_component_info *)
  161243. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161244. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  161245. /* Initialize everything not dependent on the color space */
  161246. cinfo->data_precision = BITS_IN_JSAMPLE;
  161247. /* Set up two quantization tables using default quality of 75 */
  161248. jpeg_set_quality(cinfo, 75, TRUE);
  161249. /* Set up two Huffman tables */
  161250. std_huff_tables(cinfo);
  161251. /* Initialize default arithmetic coding conditioning */
  161252. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161253. cinfo->arith_dc_L[i] = 0;
  161254. cinfo->arith_dc_U[i] = 1;
  161255. cinfo->arith_ac_K[i] = 5;
  161256. }
  161257. /* Default is no multiple-scan output */
  161258. cinfo->scan_info = NULL;
  161259. cinfo->num_scans = 0;
  161260. /* Expect normal source image, not raw downsampled data */
  161261. cinfo->raw_data_in = FALSE;
  161262. /* Use Huffman coding, not arithmetic coding, by default */
  161263. cinfo->arith_code = FALSE;
  161264. /* By default, don't do extra passes to optimize entropy coding */
  161265. cinfo->optimize_coding = FALSE;
  161266. /* The standard Huffman tables are only valid for 8-bit data precision.
  161267. * If the precision is higher, force optimization on so that usable
  161268. * tables will be computed. This test can be removed if default tables
  161269. * are supplied that are valid for the desired precision.
  161270. */
  161271. if (cinfo->data_precision > 8)
  161272. cinfo->optimize_coding = TRUE;
  161273. /* By default, use the simpler non-cosited sampling alignment */
  161274. cinfo->CCIR601_sampling = FALSE;
  161275. /* No input smoothing */
  161276. cinfo->smoothing_factor = 0;
  161277. /* DCT algorithm preference */
  161278. cinfo->dct_method = JDCT_DEFAULT;
  161279. /* No restart markers */
  161280. cinfo->restart_interval = 0;
  161281. cinfo->restart_in_rows = 0;
  161282. /* Fill in default JFIF marker parameters. Note that whether the marker
  161283. * will actually be written is determined by jpeg_set_colorspace.
  161284. *
  161285. * By default, the library emits JFIF version code 1.01.
  161286. * An application that wants to emit JFIF 1.02 extension markers should set
  161287. * JFIF_minor_version to 2. We could probably get away with just defaulting
  161288. * to 1.02, but there may still be some decoders in use that will complain
  161289. * about that; saying 1.01 should minimize compatibility problems.
  161290. */
  161291. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  161292. cinfo->JFIF_minor_version = 1;
  161293. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  161294. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  161295. cinfo->Y_density = 1;
  161296. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  161297. jpeg_default_colorspace(cinfo);
  161298. }
  161299. /*
  161300. * Select an appropriate JPEG colorspace for in_color_space.
  161301. */
  161302. GLOBAL(void)
  161303. jpeg_default_colorspace (j_compress_ptr cinfo)
  161304. {
  161305. switch (cinfo->in_color_space) {
  161306. case JCS_GRAYSCALE:
  161307. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  161308. break;
  161309. case JCS_RGB:
  161310. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161311. break;
  161312. case JCS_YCbCr:
  161313. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161314. break;
  161315. case JCS_CMYK:
  161316. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  161317. break;
  161318. case JCS_YCCK:
  161319. jpeg_set_colorspace(cinfo, JCS_YCCK);
  161320. break;
  161321. case JCS_UNKNOWN:
  161322. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  161323. break;
  161324. default:
  161325. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161326. }
  161327. }
  161328. /*
  161329. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  161330. */
  161331. GLOBAL(void)
  161332. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  161333. {
  161334. jpeg_component_info * compptr;
  161335. int ci;
  161336. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  161337. (compptr = &cinfo->comp_info[index], \
  161338. compptr->component_id = (id), \
  161339. compptr->h_samp_factor = (hsamp), \
  161340. compptr->v_samp_factor = (vsamp), \
  161341. compptr->quant_tbl_no = (quant), \
  161342. compptr->dc_tbl_no = (dctbl), \
  161343. compptr->ac_tbl_no = (actbl) )
  161344. /* Safety check to ensure start_compress not called yet. */
  161345. if (cinfo->global_state != CSTATE_START)
  161346. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161347. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  161348. * tables 1 for chrominance components.
  161349. */
  161350. cinfo->jpeg_color_space = colorspace;
  161351. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  161352. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  161353. switch (colorspace) {
  161354. case JCS_GRAYSCALE:
  161355. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161356. cinfo->num_components = 1;
  161357. /* JFIF specifies component ID 1 */
  161358. SET_COMP(0, 1, 1,1, 0, 0,0);
  161359. break;
  161360. case JCS_RGB:
  161361. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  161362. cinfo->num_components = 3;
  161363. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  161364. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  161365. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  161366. break;
  161367. case JCS_YCbCr:
  161368. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161369. cinfo->num_components = 3;
  161370. /* JFIF specifies component IDs 1,2,3 */
  161371. /* We default to 2x2 subsamples of chrominance */
  161372. SET_COMP(0, 1, 2,2, 0, 0,0);
  161373. SET_COMP(1, 2, 1,1, 1, 1,1);
  161374. SET_COMP(2, 3, 1,1, 1, 1,1);
  161375. break;
  161376. case JCS_CMYK:
  161377. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  161378. cinfo->num_components = 4;
  161379. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  161380. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  161381. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  161382. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  161383. break;
  161384. case JCS_YCCK:
  161385. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  161386. cinfo->num_components = 4;
  161387. SET_COMP(0, 1, 2,2, 0, 0,0);
  161388. SET_COMP(1, 2, 1,1, 1, 1,1);
  161389. SET_COMP(2, 3, 1,1, 1, 1,1);
  161390. SET_COMP(3, 4, 2,2, 0, 0,0);
  161391. break;
  161392. case JCS_UNKNOWN:
  161393. cinfo->num_components = cinfo->input_components;
  161394. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  161395. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161396. MAX_COMPONENTS);
  161397. for (ci = 0; ci < cinfo->num_components; ci++) {
  161398. SET_COMP(ci, ci, 1,1, 0, 0,0);
  161399. }
  161400. break;
  161401. default:
  161402. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161403. }
  161404. }
  161405. #ifdef C_PROGRESSIVE_SUPPORTED
  161406. LOCAL(jpeg_scan_info *)
  161407. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  161408. int Ss, int Se, int Ah, int Al)
  161409. /* Support routine: generate one scan for specified component */
  161410. {
  161411. scanptr->comps_in_scan = 1;
  161412. scanptr->component_index[0] = ci;
  161413. scanptr->Ss = Ss;
  161414. scanptr->Se = Se;
  161415. scanptr->Ah = Ah;
  161416. scanptr->Al = Al;
  161417. scanptr++;
  161418. return scanptr;
  161419. }
  161420. LOCAL(jpeg_scan_info *)
  161421. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  161422. int Ss, int Se, int Ah, int Al)
  161423. /* Support routine: generate one scan for each component */
  161424. {
  161425. int ci;
  161426. for (ci = 0; ci < ncomps; ci++) {
  161427. scanptr->comps_in_scan = 1;
  161428. scanptr->component_index[0] = ci;
  161429. scanptr->Ss = Ss;
  161430. scanptr->Se = Se;
  161431. scanptr->Ah = Ah;
  161432. scanptr->Al = Al;
  161433. scanptr++;
  161434. }
  161435. return scanptr;
  161436. }
  161437. LOCAL(jpeg_scan_info *)
  161438. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  161439. /* Support routine: generate interleaved DC scan if possible, else N scans */
  161440. {
  161441. int ci;
  161442. if (ncomps <= MAX_COMPS_IN_SCAN) {
  161443. /* Single interleaved DC scan */
  161444. scanptr->comps_in_scan = ncomps;
  161445. for (ci = 0; ci < ncomps; ci++)
  161446. scanptr->component_index[ci] = ci;
  161447. scanptr->Ss = scanptr->Se = 0;
  161448. scanptr->Ah = Ah;
  161449. scanptr->Al = Al;
  161450. scanptr++;
  161451. } else {
  161452. /* Noninterleaved DC scan for each component */
  161453. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  161454. }
  161455. return scanptr;
  161456. }
  161457. /*
  161458. * Create a recommended progressive-JPEG script.
  161459. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  161460. */
  161461. GLOBAL(void)
  161462. jpeg_simple_progression (j_compress_ptr cinfo)
  161463. {
  161464. int ncomps = cinfo->num_components;
  161465. int nscans;
  161466. jpeg_scan_info * scanptr;
  161467. /* Safety check to ensure start_compress not called yet. */
  161468. if (cinfo->global_state != CSTATE_START)
  161469. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161470. /* Figure space needed for script. Calculation must match code below! */
  161471. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161472. /* Custom script for YCbCr color images. */
  161473. nscans = 10;
  161474. } else {
  161475. /* All-purpose script for other color spaces. */
  161476. if (ncomps > MAX_COMPS_IN_SCAN)
  161477. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  161478. else
  161479. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  161480. }
  161481. /* Allocate space for script.
  161482. * We need to put it in the permanent pool in case the application performs
  161483. * multiple compressions without changing the settings. To avoid a memory
  161484. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  161485. * object, we try to re-use previously allocated space, and we allocate
  161486. * enough space to handle YCbCr even if initially asked for grayscale.
  161487. */
  161488. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  161489. cinfo->script_space_size = MAX(nscans, 10);
  161490. cinfo->script_space = (jpeg_scan_info *)
  161491. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161492. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  161493. }
  161494. scanptr = cinfo->script_space;
  161495. cinfo->scan_info = scanptr;
  161496. cinfo->num_scans = nscans;
  161497. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161498. /* Custom script for YCbCr color images. */
  161499. /* Initial DC scan */
  161500. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161501. /* Initial AC scan: get some luma data out in a hurry */
  161502. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  161503. /* Chroma data is too small to be worth expending many scans on */
  161504. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  161505. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  161506. /* Complete spectral selection for luma AC */
  161507. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  161508. /* Refine next bit of luma AC */
  161509. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  161510. /* Finish DC successive approximation */
  161511. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161512. /* Finish AC successive approximation */
  161513. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  161514. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  161515. /* Luma bottom bit comes last since it's usually largest scan */
  161516. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  161517. } else {
  161518. /* All-purpose script for other color spaces. */
  161519. /* Successive approximation first pass */
  161520. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161521. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  161522. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  161523. /* Successive approximation second pass */
  161524. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  161525. /* Successive approximation final pass */
  161526. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161527. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  161528. }
  161529. }
  161530. #endif /* C_PROGRESSIVE_SUPPORTED */
  161531. /********* End of inlined file: jcparam.c *********/
  161532. /********* Start of inlined file: jcphuff.c *********/
  161533. #define JPEG_INTERNALS
  161534. #ifdef C_PROGRESSIVE_SUPPORTED
  161535. /* Expanded entropy encoder object for progressive Huffman encoding. */
  161536. typedef struct {
  161537. struct jpeg_entropy_encoder pub; /* public fields */
  161538. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  161539. boolean gather_statistics;
  161540. /* Bit-level coding status.
  161541. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  161542. */
  161543. JOCTET * next_output_byte; /* => next byte to write in buffer */
  161544. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  161545. INT32 put_buffer; /* current bit-accumulation buffer */
  161546. int put_bits; /* # of bits now in it */
  161547. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  161548. /* Coding status for DC components */
  161549. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  161550. /* Coding status for AC components */
  161551. int ac_tbl_no; /* the table number of the single component */
  161552. unsigned int EOBRUN; /* run length of EOBs */
  161553. unsigned int BE; /* # of buffered correction bits before MCU */
  161554. char * bit_buffer; /* buffer for correction bits (1 per char) */
  161555. /* packing correction bits tightly would save some space but cost time... */
  161556. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  161557. int next_restart_num; /* next restart number to write (0-7) */
  161558. /* Pointers to derived tables (these workspaces have image lifespan).
  161559. * Since any one scan codes only DC or only AC, we only need one set
  161560. * of tables, not one for DC and one for AC.
  161561. */
  161562. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  161563. /* Statistics tables for optimization; again, one set is enough */
  161564. long * count_ptrs[NUM_HUFF_TBLS];
  161565. } phuff_entropy_encoder;
  161566. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  161567. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  161568. * buffer can hold. Larger sizes may slightly improve compression, but
  161569. * 1000 is already well into the realm of overkill.
  161570. * The minimum safe size is 64 bits.
  161571. */
  161572. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  161573. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  161574. * We assume that int right shift is unsigned if INT32 right shift is,
  161575. * which should be safe.
  161576. */
  161577. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161578. #define ISHIFT_TEMPS int ishift_temp;
  161579. #define IRIGHT_SHIFT(x,shft) \
  161580. ((ishift_temp = (x)) < 0 ? \
  161581. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  161582. (ishift_temp >> (shft)))
  161583. #else
  161584. #define ISHIFT_TEMPS
  161585. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  161586. #endif
  161587. /* Forward declarations */
  161588. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  161589. JBLOCKROW *MCU_data));
  161590. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  161591. JBLOCKROW *MCU_data));
  161592. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  161593. JBLOCKROW *MCU_data));
  161594. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  161595. JBLOCKROW *MCU_data));
  161596. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  161597. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  161598. /*
  161599. * Initialize for a Huffman-compressed scan using progressive JPEG.
  161600. */
  161601. METHODDEF(void)
  161602. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  161603. {
  161604. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161605. boolean is_DC_band;
  161606. int ci, tbl;
  161607. jpeg_component_info * compptr;
  161608. entropy->cinfo = cinfo;
  161609. entropy->gather_statistics = gather_statistics;
  161610. is_DC_band = (cinfo->Ss == 0);
  161611. /* We assume jcmaster.c already validated the scan parameters. */
  161612. /* Select execution routines */
  161613. if (cinfo->Ah == 0) {
  161614. if (is_DC_band)
  161615. entropy->pub.encode_mcu = encode_mcu_DC_first;
  161616. else
  161617. entropy->pub.encode_mcu = encode_mcu_AC_first;
  161618. } else {
  161619. if (is_DC_band)
  161620. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  161621. else {
  161622. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  161623. /* AC refinement needs a correction bit buffer */
  161624. if (entropy->bit_buffer == NULL)
  161625. entropy->bit_buffer = (char *)
  161626. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161627. MAX_CORR_BITS * SIZEOF(char));
  161628. }
  161629. }
  161630. if (gather_statistics)
  161631. entropy->pub.finish_pass = finish_pass_gather_phuff;
  161632. else
  161633. entropy->pub.finish_pass = finish_pass_phuff;
  161634. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  161635. * for AC coefficients.
  161636. */
  161637. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161638. compptr = cinfo->cur_comp_info[ci];
  161639. /* Initialize DC predictions to 0 */
  161640. entropy->last_dc_val[ci] = 0;
  161641. /* Get table index */
  161642. if (is_DC_band) {
  161643. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161644. continue;
  161645. tbl = compptr->dc_tbl_no;
  161646. } else {
  161647. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  161648. }
  161649. if (gather_statistics) {
  161650. /* Check for invalid table index */
  161651. /* (make_c_derived_tbl does this in the other path) */
  161652. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  161653. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  161654. /* Allocate and zero the statistics tables */
  161655. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  161656. if (entropy->count_ptrs[tbl] == NULL)
  161657. entropy->count_ptrs[tbl] = (long *)
  161658. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161659. 257 * SIZEOF(long));
  161660. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  161661. } else {
  161662. /* Compute derived values for Huffman table */
  161663. /* We may do this more than once for a table, but it's not expensive */
  161664. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  161665. & entropy->derived_tbls[tbl]);
  161666. }
  161667. }
  161668. /* Initialize AC stuff */
  161669. entropy->EOBRUN = 0;
  161670. entropy->BE = 0;
  161671. /* Initialize bit buffer to empty */
  161672. entropy->put_buffer = 0;
  161673. entropy->put_bits = 0;
  161674. /* Initialize restart stuff */
  161675. entropy->restarts_to_go = cinfo->restart_interval;
  161676. entropy->next_restart_num = 0;
  161677. }
  161678. /* Outputting bytes to the file.
  161679. * NB: these must be called only when actually outputting,
  161680. * that is, entropy->gather_statistics == FALSE.
  161681. */
  161682. /* Emit a byte */
  161683. #define emit_byte(entropy,val) \
  161684. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  161685. if (--(entropy)->free_in_buffer == 0) \
  161686. dump_buffer_p(entropy); }
  161687. LOCAL(void)
  161688. dump_buffer_p (phuff_entropy_ptr entropy)
  161689. /* Empty the output buffer; we do not support suspension in this module. */
  161690. {
  161691. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  161692. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  161693. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  161694. /* After a successful buffer dump, must reset buffer pointers */
  161695. entropy->next_output_byte = dest->next_output_byte;
  161696. entropy->free_in_buffer = dest->free_in_buffer;
  161697. }
  161698. /* Outputting bits to the file */
  161699. /* Only the right 24 bits of put_buffer are used; the valid bits are
  161700. * left-justified in this part. At most 16 bits can be passed to emit_bits
  161701. * in one call, and we never retain more than 7 bits in put_buffer
  161702. * between calls, so 24 bits are sufficient.
  161703. */
  161704. INLINE
  161705. LOCAL(void)
  161706. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  161707. /* Emit some bits, unless we are in gather mode */
  161708. {
  161709. /* This routine is heavily used, so it's worth coding tightly. */
  161710. register INT32 put_buffer = (INT32) code;
  161711. register int put_bits = entropy->put_bits;
  161712. /* if size is 0, caller used an invalid Huffman table entry */
  161713. if (size == 0)
  161714. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161715. if (entropy->gather_statistics)
  161716. return; /* do nothing if we're only getting stats */
  161717. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  161718. put_bits += size; /* new number of bits in buffer */
  161719. put_buffer <<= 24 - put_bits; /* align incoming bits */
  161720. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  161721. while (put_bits >= 8) {
  161722. int c = (int) ((put_buffer >> 16) & 0xFF);
  161723. emit_byte(entropy, c);
  161724. if (c == 0xFF) { /* need to stuff a zero byte? */
  161725. emit_byte(entropy, 0);
  161726. }
  161727. put_buffer <<= 8;
  161728. put_bits -= 8;
  161729. }
  161730. entropy->put_buffer = put_buffer; /* update variables */
  161731. entropy->put_bits = put_bits;
  161732. }
  161733. LOCAL(void)
  161734. flush_bits_p (phuff_entropy_ptr entropy)
  161735. {
  161736. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  161737. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  161738. entropy->put_bits = 0;
  161739. }
  161740. /*
  161741. * Emit (or just count) a Huffman symbol.
  161742. */
  161743. INLINE
  161744. LOCAL(void)
  161745. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  161746. {
  161747. if (entropy->gather_statistics)
  161748. entropy->count_ptrs[tbl_no][symbol]++;
  161749. else {
  161750. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  161751. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  161752. }
  161753. }
  161754. /*
  161755. * Emit bits from a correction bit buffer.
  161756. */
  161757. LOCAL(void)
  161758. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  161759. unsigned int nbits)
  161760. {
  161761. if (entropy->gather_statistics)
  161762. return; /* no real work */
  161763. while (nbits > 0) {
  161764. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  161765. bufstart++;
  161766. nbits--;
  161767. }
  161768. }
  161769. /*
  161770. * Emit any pending EOBRUN symbol.
  161771. */
  161772. LOCAL(void)
  161773. emit_eobrun (phuff_entropy_ptr entropy)
  161774. {
  161775. register int temp, nbits;
  161776. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  161777. temp = entropy->EOBRUN;
  161778. nbits = 0;
  161779. while ((temp >>= 1))
  161780. nbits++;
  161781. /* safety check: shouldn't happen given limited correction-bit buffer */
  161782. if (nbits > 14)
  161783. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161784. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  161785. if (nbits)
  161786. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  161787. entropy->EOBRUN = 0;
  161788. /* Emit any buffered correction bits */
  161789. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  161790. entropy->BE = 0;
  161791. }
  161792. }
  161793. /*
  161794. * Emit a restart marker & resynchronize predictions.
  161795. */
  161796. LOCAL(void)
  161797. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  161798. {
  161799. int ci;
  161800. emit_eobrun(entropy);
  161801. if (! entropy->gather_statistics) {
  161802. flush_bits_p(entropy);
  161803. emit_byte(entropy, 0xFF);
  161804. emit_byte(entropy, JPEG_RST0 + restart_num);
  161805. }
  161806. if (entropy->cinfo->Ss == 0) {
  161807. /* Re-initialize DC predictions to 0 */
  161808. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  161809. entropy->last_dc_val[ci] = 0;
  161810. } else {
  161811. /* Re-initialize all AC-related fields to 0 */
  161812. entropy->EOBRUN = 0;
  161813. entropy->BE = 0;
  161814. }
  161815. }
  161816. /*
  161817. * MCU encoding for DC initial scan (either spectral selection,
  161818. * or first pass of successive approximation).
  161819. */
  161820. METHODDEF(boolean)
  161821. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161822. {
  161823. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161824. register int temp, temp2;
  161825. register int nbits;
  161826. int blkn, ci;
  161827. int Al = cinfo->Al;
  161828. JBLOCKROW block;
  161829. jpeg_component_info * compptr;
  161830. ISHIFT_TEMPS
  161831. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161832. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161833. /* Emit restart marker if needed */
  161834. if (cinfo->restart_interval)
  161835. if (entropy->restarts_to_go == 0)
  161836. emit_restart_p(entropy, entropy->next_restart_num);
  161837. /* Encode the MCU data blocks */
  161838. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161839. block = MCU_data[blkn];
  161840. ci = cinfo->MCU_membership[blkn];
  161841. compptr = cinfo->cur_comp_info[ci];
  161842. /* Compute the DC value after the required point transform by Al.
  161843. * This is simply an arithmetic right shift.
  161844. */
  161845. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  161846. /* DC differences are figured on the point-transformed values. */
  161847. temp = temp2 - entropy->last_dc_val[ci];
  161848. entropy->last_dc_val[ci] = temp2;
  161849. /* Encode the DC coefficient difference per section G.1.2.1 */
  161850. temp2 = temp;
  161851. if (temp < 0) {
  161852. temp = -temp; /* temp is abs value of input */
  161853. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  161854. /* This code assumes we are on a two's complement machine */
  161855. temp2--;
  161856. }
  161857. /* Find the number of bits needed for the magnitude of the coefficient */
  161858. nbits = 0;
  161859. while (temp) {
  161860. nbits++;
  161861. temp >>= 1;
  161862. }
  161863. /* Check for out-of-range coefficient values.
  161864. * Since we're encoding a difference, the range limit is twice as much.
  161865. */
  161866. if (nbits > MAX_COEF_BITS+1)
  161867. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161868. /* Count/emit the Huffman-coded symbol for the number of bits */
  161869. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  161870. /* Emit that number of bits of the value, if positive, */
  161871. /* or the complement of its magnitude, if negative. */
  161872. if (nbits) /* emit_bits rejects calls with size 0 */
  161873. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161874. }
  161875. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161876. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161877. /* Update restart-interval state too */
  161878. if (cinfo->restart_interval) {
  161879. if (entropy->restarts_to_go == 0) {
  161880. entropy->restarts_to_go = cinfo->restart_interval;
  161881. entropy->next_restart_num++;
  161882. entropy->next_restart_num &= 7;
  161883. }
  161884. entropy->restarts_to_go--;
  161885. }
  161886. return TRUE;
  161887. }
  161888. /*
  161889. * MCU encoding for AC initial scan (either spectral selection,
  161890. * or first pass of successive approximation).
  161891. */
  161892. METHODDEF(boolean)
  161893. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161894. {
  161895. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161896. register int temp, temp2;
  161897. register int nbits;
  161898. register int r, k;
  161899. int Se = cinfo->Se;
  161900. int Al = cinfo->Al;
  161901. JBLOCKROW block;
  161902. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161903. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161904. /* Emit restart marker if needed */
  161905. if (cinfo->restart_interval)
  161906. if (entropy->restarts_to_go == 0)
  161907. emit_restart_p(entropy, entropy->next_restart_num);
  161908. /* Encode the MCU data block */
  161909. block = MCU_data[0];
  161910. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  161911. r = 0; /* r = run length of zeros */
  161912. for (k = cinfo->Ss; k <= Se; k++) {
  161913. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  161914. r++;
  161915. continue;
  161916. }
  161917. /* We must apply the point transform by Al. For AC coefficients this
  161918. * is an integer division with rounding towards 0. To do this portably
  161919. * in C, we shift after obtaining the absolute value; so the code is
  161920. * interwoven with finding the abs value (temp) and output bits (temp2).
  161921. */
  161922. if (temp < 0) {
  161923. temp = -temp; /* temp is abs value of input */
  161924. temp >>= Al; /* apply the point transform */
  161925. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  161926. temp2 = ~temp;
  161927. } else {
  161928. temp >>= Al; /* apply the point transform */
  161929. temp2 = temp;
  161930. }
  161931. /* Watch out for case that nonzero coef is zero after point transform */
  161932. if (temp == 0) {
  161933. r++;
  161934. continue;
  161935. }
  161936. /* Emit any pending EOBRUN */
  161937. if (entropy->EOBRUN > 0)
  161938. emit_eobrun(entropy);
  161939. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  161940. while (r > 15) {
  161941. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161942. r -= 16;
  161943. }
  161944. /* Find the number of bits needed for the magnitude of the coefficient */
  161945. nbits = 1; /* there must be at least one 1 bit */
  161946. while ((temp >>= 1))
  161947. nbits++;
  161948. /* Check for out-of-range coefficient values */
  161949. if (nbits > MAX_COEF_BITS)
  161950. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161951. /* Count/emit Huffman symbol for run length / number of bits */
  161952. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  161953. /* Emit that number of bits of the value, if positive, */
  161954. /* or the complement of its magnitude, if negative. */
  161955. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161956. r = 0; /* reset zero run length */
  161957. }
  161958. if (r > 0) { /* If there are trailing zeroes, */
  161959. entropy->EOBRUN++; /* count an EOB */
  161960. if (entropy->EOBRUN == 0x7FFF)
  161961. emit_eobrun(entropy); /* force it out to avoid overflow */
  161962. }
  161963. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161964. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161965. /* Update restart-interval state too */
  161966. if (cinfo->restart_interval) {
  161967. if (entropy->restarts_to_go == 0) {
  161968. entropy->restarts_to_go = cinfo->restart_interval;
  161969. entropy->next_restart_num++;
  161970. entropy->next_restart_num &= 7;
  161971. }
  161972. entropy->restarts_to_go--;
  161973. }
  161974. return TRUE;
  161975. }
  161976. /*
  161977. * MCU encoding for DC successive approximation refinement scan.
  161978. * Note: we assume such scans can be multi-component, although the spec
  161979. * is not very clear on the point.
  161980. */
  161981. METHODDEF(boolean)
  161982. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161983. {
  161984. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161985. register int temp;
  161986. int blkn;
  161987. int Al = cinfo->Al;
  161988. JBLOCKROW block;
  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 blocks */
  161996. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161997. block = MCU_data[blkn];
  161998. /* We simply emit the Al'th bit of the DC coefficient value. */
  161999. temp = (*block)[0];
  162000. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  162001. }
  162002. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162003. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162004. /* Update restart-interval state too */
  162005. if (cinfo->restart_interval) {
  162006. if (entropy->restarts_to_go == 0) {
  162007. entropy->restarts_to_go = cinfo->restart_interval;
  162008. entropy->next_restart_num++;
  162009. entropy->next_restart_num &= 7;
  162010. }
  162011. entropy->restarts_to_go--;
  162012. }
  162013. return TRUE;
  162014. }
  162015. /*
  162016. * MCU encoding for AC successive approximation refinement scan.
  162017. */
  162018. METHODDEF(boolean)
  162019. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162020. {
  162021. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162022. register int temp;
  162023. register int r, k;
  162024. int EOB;
  162025. char *BR_buffer;
  162026. unsigned int BR;
  162027. int Se = cinfo->Se;
  162028. int Al = cinfo->Al;
  162029. JBLOCKROW block;
  162030. int absvalues[DCTSIZE2];
  162031. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162032. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162033. /* Emit restart marker if needed */
  162034. if (cinfo->restart_interval)
  162035. if (entropy->restarts_to_go == 0)
  162036. emit_restart_p(entropy, entropy->next_restart_num);
  162037. /* Encode the MCU data block */
  162038. block = MCU_data[0];
  162039. /* It is convenient to make a pre-pass to determine the transformed
  162040. * coefficients' absolute values and the EOB position.
  162041. */
  162042. EOB = 0;
  162043. for (k = cinfo->Ss; k <= Se; k++) {
  162044. temp = (*block)[jpeg_natural_order[k]];
  162045. /* We must apply the point transform by Al. For AC coefficients this
  162046. * is an integer division with rounding towards 0. To do this portably
  162047. * in C, we shift after obtaining the absolute value.
  162048. */
  162049. if (temp < 0)
  162050. temp = -temp; /* temp is abs value of input */
  162051. temp >>= Al; /* apply the point transform */
  162052. absvalues[k] = temp; /* save abs value for main pass */
  162053. if (temp == 1)
  162054. EOB = k; /* EOB = index of last newly-nonzero coef */
  162055. }
  162056. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  162057. r = 0; /* r = run length of zeros */
  162058. BR = 0; /* BR = count of buffered bits added now */
  162059. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  162060. for (k = cinfo->Ss; k <= Se; k++) {
  162061. if ((temp = absvalues[k]) == 0) {
  162062. r++;
  162063. continue;
  162064. }
  162065. /* Emit any required ZRLs, but not if they can be folded into EOB */
  162066. while (r > 15 && k <= EOB) {
  162067. /* emit any pending EOBRUN and the BE correction bits */
  162068. emit_eobrun(entropy);
  162069. /* Emit ZRL */
  162070. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  162071. r -= 16;
  162072. /* Emit buffered correction bits that must be associated with ZRL */
  162073. emit_buffered_bits(entropy, BR_buffer, BR);
  162074. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162075. BR = 0;
  162076. }
  162077. /* If the coef was previously nonzero, it only needs a correction bit.
  162078. * NOTE: a straight translation of the spec's figure G.7 would suggest
  162079. * that we also need to test r > 15. But if r > 15, we can only get here
  162080. * if k > EOB, which implies that this coefficient is not 1.
  162081. */
  162082. if (temp > 1) {
  162083. /* The correction bit is the next bit of the absolute value. */
  162084. BR_buffer[BR++] = (char) (temp & 1);
  162085. continue;
  162086. }
  162087. /* Emit any pending EOBRUN and the BE correction bits */
  162088. emit_eobrun(entropy);
  162089. /* Count/emit Huffman symbol for run length / number of bits */
  162090. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  162091. /* Emit output bit for newly-nonzero coef */
  162092. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  162093. emit_bits_p(entropy, (unsigned int) temp, 1);
  162094. /* Emit buffered correction bits that must be associated with this code */
  162095. emit_buffered_bits(entropy, BR_buffer, BR);
  162096. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  162097. BR = 0;
  162098. r = 0; /* reset zero run length */
  162099. }
  162100. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  162101. entropy->EOBRUN++; /* count an EOB */
  162102. entropy->BE += BR; /* concat my correction bits to older ones */
  162103. /* We force out the EOB if we risk either:
  162104. * 1. overflow of the EOB counter;
  162105. * 2. overflow of the correction bit buffer during the next MCU.
  162106. */
  162107. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  162108. emit_eobrun(entropy);
  162109. }
  162110. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162111. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162112. /* Update restart-interval state too */
  162113. if (cinfo->restart_interval) {
  162114. if (entropy->restarts_to_go == 0) {
  162115. entropy->restarts_to_go = cinfo->restart_interval;
  162116. entropy->next_restart_num++;
  162117. entropy->next_restart_num &= 7;
  162118. }
  162119. entropy->restarts_to_go--;
  162120. }
  162121. return TRUE;
  162122. }
  162123. /*
  162124. * Finish up at the end of a Huffman-compressed progressive scan.
  162125. */
  162126. METHODDEF(void)
  162127. finish_pass_phuff (j_compress_ptr cinfo)
  162128. {
  162129. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162130. entropy->next_output_byte = cinfo->dest->next_output_byte;
  162131. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  162132. /* Flush out any buffered data */
  162133. emit_eobrun(entropy);
  162134. flush_bits_p(entropy);
  162135. cinfo->dest->next_output_byte = entropy->next_output_byte;
  162136. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  162137. }
  162138. /*
  162139. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162140. */
  162141. METHODDEF(void)
  162142. finish_pass_gather_phuff (j_compress_ptr cinfo)
  162143. {
  162144. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  162145. boolean is_DC_band;
  162146. int ci, tbl;
  162147. jpeg_component_info * compptr;
  162148. JHUFF_TBL **htblptr;
  162149. boolean did[NUM_HUFF_TBLS];
  162150. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  162151. emit_eobrun(entropy);
  162152. is_DC_band = (cinfo->Ss == 0);
  162153. /* It's important not to apply jpeg_gen_optimal_table more than once
  162154. * per table, because it clobbers the input frequency counts!
  162155. */
  162156. MEMZERO(did, SIZEOF(did));
  162157. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162158. compptr = cinfo->cur_comp_info[ci];
  162159. if (is_DC_band) {
  162160. if (cinfo->Ah != 0) /* DC refinement needs no table */
  162161. continue;
  162162. tbl = compptr->dc_tbl_no;
  162163. } else {
  162164. tbl = compptr->ac_tbl_no;
  162165. }
  162166. if (! did[tbl]) {
  162167. if (is_DC_band)
  162168. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  162169. else
  162170. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  162171. if (*htblptr == NULL)
  162172. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162173. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  162174. did[tbl] = TRUE;
  162175. }
  162176. }
  162177. }
  162178. /*
  162179. * Module initialization routine for progressive Huffman entropy encoding.
  162180. */
  162181. GLOBAL(void)
  162182. jinit_phuff_encoder (j_compress_ptr cinfo)
  162183. {
  162184. phuff_entropy_ptr entropy;
  162185. int i;
  162186. entropy = (phuff_entropy_ptr)
  162187. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162188. SIZEOF(phuff_entropy_encoder));
  162189. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  162190. entropy->pub.start_pass = start_pass_phuff;
  162191. /* Mark tables unallocated */
  162192. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162193. entropy->derived_tbls[i] = NULL;
  162194. entropy->count_ptrs[i] = NULL;
  162195. }
  162196. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  162197. }
  162198. #endif /* C_PROGRESSIVE_SUPPORTED */
  162199. /********* End of inlined file: jcphuff.c *********/
  162200. /********* Start of inlined file: jcprepct.c *********/
  162201. #define JPEG_INTERNALS
  162202. /* At present, jcsample.c can request context rows only for smoothing.
  162203. * In the future, we might also need context rows for CCIR601 sampling
  162204. * or other more-complex downsampling procedures. The code to support
  162205. * context rows should be compiled only if needed.
  162206. */
  162207. #ifdef INPUT_SMOOTHING_SUPPORTED
  162208. #define CONTEXT_ROWS_SUPPORTED
  162209. #endif
  162210. /*
  162211. * For the simple (no-context-row) case, we just need to buffer one
  162212. * row group's worth of pixels for the downsampling step. At the bottom of
  162213. * the image, we pad to a full row group by replicating the last pixel row.
  162214. * The downsampler's last output row is then replicated if needed to pad
  162215. * out to a full iMCU row.
  162216. *
  162217. * When providing context rows, we must buffer three row groups' worth of
  162218. * pixels. Three row groups are physically allocated, but the row pointer
  162219. * arrays are made five row groups high, with the extra pointers above and
  162220. * below "wrapping around" to point to the last and first real row groups.
  162221. * This allows the downsampler to access the proper context rows.
  162222. * At the top and bottom of the image, we create dummy context rows by
  162223. * copying the first or last real pixel row. This copying could be avoided
  162224. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  162225. * trouble on the compression side.
  162226. */
  162227. /* Private buffer controller object */
  162228. typedef struct {
  162229. struct jpeg_c_prep_controller pub; /* public fields */
  162230. /* Downsampling input buffer. This buffer holds color-converted data
  162231. * until we have enough to do a downsample step.
  162232. */
  162233. JSAMPARRAY color_buf[MAX_COMPONENTS];
  162234. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  162235. int next_buf_row; /* index of next row to store in color_buf */
  162236. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  162237. int this_row_group; /* starting row index of group to process */
  162238. int next_buf_stop; /* downsample when we reach this index */
  162239. #endif
  162240. } my_prep_controller;
  162241. typedef my_prep_controller * my_prep_ptr;
  162242. /*
  162243. * Initialize for a processing pass.
  162244. */
  162245. METHODDEF(void)
  162246. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162247. {
  162248. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162249. if (pass_mode != JBUF_PASS_THRU)
  162250. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162251. /* Initialize total-height counter for detecting bottom of image */
  162252. prep->rows_to_go = cinfo->image_height;
  162253. /* Mark the conversion buffer empty */
  162254. prep->next_buf_row = 0;
  162255. #ifdef CONTEXT_ROWS_SUPPORTED
  162256. /* Preset additional state variables for context mode.
  162257. * These aren't used in non-context mode, so we needn't test which mode.
  162258. */
  162259. prep->this_row_group = 0;
  162260. /* Set next_buf_stop to stop after two row groups have been read in. */
  162261. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  162262. #endif
  162263. }
  162264. /*
  162265. * Expand an image vertically from height input_rows to height output_rows,
  162266. * by duplicating the bottom row.
  162267. */
  162268. LOCAL(void)
  162269. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  162270. int input_rows, int output_rows)
  162271. {
  162272. register int row;
  162273. for (row = input_rows; row < output_rows; row++) {
  162274. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  162275. 1, num_cols);
  162276. }
  162277. }
  162278. /*
  162279. * Process some data in the simple no-context case.
  162280. *
  162281. * Preprocessor output data is counted in "row groups". A row group
  162282. * is defined to be v_samp_factor sample rows of each component.
  162283. * Downsampling will produce this much data from each max_v_samp_factor
  162284. * input rows.
  162285. */
  162286. METHODDEF(void)
  162287. pre_process_data (j_compress_ptr cinfo,
  162288. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162289. JDIMENSION in_rows_avail,
  162290. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162291. JDIMENSION out_row_groups_avail)
  162292. {
  162293. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162294. int numrows, ci;
  162295. JDIMENSION inrows;
  162296. jpeg_component_info * compptr;
  162297. while (*in_row_ctr < in_rows_avail &&
  162298. *out_row_group_ctr < out_row_groups_avail) {
  162299. /* Do color conversion to fill the conversion buffer. */
  162300. inrows = in_rows_avail - *in_row_ctr;
  162301. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  162302. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162303. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162304. prep->color_buf,
  162305. (JDIMENSION) prep->next_buf_row,
  162306. numrows);
  162307. *in_row_ctr += numrows;
  162308. prep->next_buf_row += numrows;
  162309. prep->rows_to_go -= numrows;
  162310. /* If at bottom of image, pad to fill the conversion buffer. */
  162311. if (prep->rows_to_go == 0 &&
  162312. prep->next_buf_row < cinfo->max_v_samp_factor) {
  162313. for (ci = 0; ci < cinfo->num_components; ci++) {
  162314. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162315. prep->next_buf_row, cinfo->max_v_samp_factor);
  162316. }
  162317. prep->next_buf_row = cinfo->max_v_samp_factor;
  162318. }
  162319. /* If we've filled the conversion buffer, empty it. */
  162320. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  162321. (*cinfo->downsample->downsample) (cinfo,
  162322. prep->color_buf, (JDIMENSION) 0,
  162323. output_buf, *out_row_group_ctr);
  162324. prep->next_buf_row = 0;
  162325. (*out_row_group_ctr)++;
  162326. }
  162327. /* If at bottom of image, pad the output to a full iMCU height.
  162328. * Note we assume the caller is providing a one-iMCU-height output buffer!
  162329. */
  162330. if (prep->rows_to_go == 0 &&
  162331. *out_row_group_ctr < out_row_groups_avail) {
  162332. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162333. ci++, compptr++) {
  162334. expand_bottom_edge(output_buf[ci],
  162335. compptr->width_in_blocks * DCTSIZE,
  162336. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  162337. (int) (out_row_groups_avail * compptr->v_samp_factor));
  162338. }
  162339. *out_row_group_ctr = out_row_groups_avail;
  162340. break; /* can exit outer loop without test */
  162341. }
  162342. }
  162343. }
  162344. #ifdef CONTEXT_ROWS_SUPPORTED
  162345. /*
  162346. * Process some data in the context case.
  162347. */
  162348. METHODDEF(void)
  162349. pre_process_context (j_compress_ptr cinfo,
  162350. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162351. JDIMENSION in_rows_avail,
  162352. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162353. JDIMENSION out_row_groups_avail)
  162354. {
  162355. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162356. int numrows, ci;
  162357. int buf_height = cinfo->max_v_samp_factor * 3;
  162358. JDIMENSION inrows;
  162359. while (*out_row_group_ctr < out_row_groups_avail) {
  162360. if (*in_row_ctr < in_rows_avail) {
  162361. /* Do color conversion to fill the conversion buffer. */
  162362. inrows = in_rows_avail - *in_row_ctr;
  162363. numrows = prep->next_buf_stop - prep->next_buf_row;
  162364. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162365. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162366. prep->color_buf,
  162367. (JDIMENSION) prep->next_buf_row,
  162368. numrows);
  162369. /* Pad at top of image, if first time through */
  162370. if (prep->rows_to_go == cinfo->image_height) {
  162371. for (ci = 0; ci < cinfo->num_components; ci++) {
  162372. int row;
  162373. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  162374. jcopy_sample_rows(prep->color_buf[ci], 0,
  162375. prep->color_buf[ci], -row,
  162376. 1, cinfo->image_width);
  162377. }
  162378. }
  162379. }
  162380. *in_row_ctr += numrows;
  162381. prep->next_buf_row += numrows;
  162382. prep->rows_to_go -= numrows;
  162383. } else {
  162384. /* Return for more data, unless we are at the bottom of the image. */
  162385. if (prep->rows_to_go != 0)
  162386. break;
  162387. /* When at bottom of image, pad to fill the conversion buffer. */
  162388. if (prep->next_buf_row < prep->next_buf_stop) {
  162389. for (ci = 0; ci < cinfo->num_components; ci++) {
  162390. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162391. prep->next_buf_row, prep->next_buf_stop);
  162392. }
  162393. prep->next_buf_row = prep->next_buf_stop;
  162394. }
  162395. }
  162396. /* If we've gotten enough data, downsample a row group. */
  162397. if (prep->next_buf_row == prep->next_buf_stop) {
  162398. (*cinfo->downsample->downsample) (cinfo,
  162399. prep->color_buf,
  162400. (JDIMENSION) prep->this_row_group,
  162401. output_buf, *out_row_group_ctr);
  162402. (*out_row_group_ctr)++;
  162403. /* Advance pointers with wraparound as necessary. */
  162404. prep->this_row_group += cinfo->max_v_samp_factor;
  162405. if (prep->this_row_group >= buf_height)
  162406. prep->this_row_group = 0;
  162407. if (prep->next_buf_row >= buf_height)
  162408. prep->next_buf_row = 0;
  162409. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  162410. }
  162411. }
  162412. }
  162413. /*
  162414. * Create the wrapped-around downsampling input buffer needed for context mode.
  162415. */
  162416. LOCAL(void)
  162417. create_context_buffer (j_compress_ptr cinfo)
  162418. {
  162419. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162420. int rgroup_height = cinfo->max_v_samp_factor;
  162421. int ci, i;
  162422. jpeg_component_info * compptr;
  162423. JSAMPARRAY true_buffer, fake_buffer;
  162424. /* Grab enough space for fake row pointers for all the components;
  162425. * we need five row groups' worth of pointers for each component.
  162426. */
  162427. fake_buffer = (JSAMPARRAY)
  162428. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162429. (cinfo->num_components * 5 * rgroup_height) *
  162430. SIZEOF(JSAMPROW));
  162431. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162432. ci++, compptr++) {
  162433. /* Allocate the actual buffer space (3 row groups) for this component.
  162434. * We make the buffer wide enough to allow the downsampler to edge-expand
  162435. * horizontally within the buffer, if it so chooses.
  162436. */
  162437. true_buffer = (*cinfo->mem->alloc_sarray)
  162438. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162439. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162440. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162441. (JDIMENSION) (3 * rgroup_height));
  162442. /* Copy true buffer row pointers into the middle of the fake row array */
  162443. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  162444. 3 * rgroup_height * SIZEOF(JSAMPROW));
  162445. /* Fill in the above and below wraparound pointers */
  162446. for (i = 0; i < rgroup_height; i++) {
  162447. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  162448. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  162449. }
  162450. prep->color_buf[ci] = fake_buffer + rgroup_height;
  162451. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  162452. }
  162453. }
  162454. #endif /* CONTEXT_ROWS_SUPPORTED */
  162455. /*
  162456. * Initialize preprocessing controller.
  162457. */
  162458. GLOBAL(void)
  162459. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162460. {
  162461. my_prep_ptr prep;
  162462. int ci;
  162463. jpeg_component_info * compptr;
  162464. if (need_full_buffer) /* safety check */
  162465. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162466. prep = (my_prep_ptr)
  162467. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162468. SIZEOF(my_prep_controller));
  162469. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  162470. prep->pub.start_pass = start_pass_prep;
  162471. /* Allocate the color conversion buffer.
  162472. * We make the buffer wide enough to allow the downsampler to edge-expand
  162473. * horizontally within the buffer, if it so chooses.
  162474. */
  162475. if (cinfo->downsample->need_context_rows) {
  162476. /* Set up to provide context rows */
  162477. #ifdef CONTEXT_ROWS_SUPPORTED
  162478. prep->pub.pre_process_data = pre_process_context;
  162479. create_context_buffer(cinfo);
  162480. #else
  162481. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162482. #endif
  162483. } else {
  162484. /* No context, just make it tall enough for one row group */
  162485. prep->pub.pre_process_data = pre_process_data;
  162486. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162487. ci++, compptr++) {
  162488. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  162489. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162490. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162491. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162492. (JDIMENSION) cinfo->max_v_samp_factor);
  162493. }
  162494. }
  162495. }
  162496. /********* End of inlined file: jcprepct.c *********/
  162497. /********* Start of inlined file: jcsample.c *********/
  162498. #define JPEG_INTERNALS
  162499. /* Pointer to routine to downsample a single component */
  162500. typedef JMETHOD(void, downsample1_ptr,
  162501. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162502. JSAMPARRAY input_data, JSAMPARRAY output_data));
  162503. /* Private subobject */
  162504. typedef struct {
  162505. struct jpeg_downsampler pub; /* public fields */
  162506. /* Downsampling method pointers, one per component */
  162507. downsample1_ptr methods[MAX_COMPONENTS];
  162508. } my_downsampler;
  162509. typedef my_downsampler * my_downsample_ptr;
  162510. /*
  162511. * Initialize for a downsampling pass.
  162512. */
  162513. METHODDEF(void)
  162514. start_pass_downsample (j_compress_ptr cinfo)
  162515. {
  162516. /* no work for now */
  162517. }
  162518. /*
  162519. * Expand a component horizontally from width input_cols to width output_cols,
  162520. * by duplicating the rightmost samples.
  162521. */
  162522. LOCAL(void)
  162523. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  162524. JDIMENSION input_cols, JDIMENSION output_cols)
  162525. {
  162526. register JSAMPROW ptr;
  162527. register JSAMPLE pixval;
  162528. register int count;
  162529. int row;
  162530. int numcols = (int) (output_cols - input_cols);
  162531. if (numcols > 0) {
  162532. for (row = 0; row < num_rows; row++) {
  162533. ptr = image_data[row] + input_cols;
  162534. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  162535. for (count = numcols; count > 0; count--)
  162536. *ptr++ = pixval;
  162537. }
  162538. }
  162539. }
  162540. /*
  162541. * Do downsampling for a whole row group (all components).
  162542. *
  162543. * In this version we simply downsample each component independently.
  162544. */
  162545. METHODDEF(void)
  162546. sep_downsample (j_compress_ptr cinfo,
  162547. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  162548. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  162549. {
  162550. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  162551. int ci;
  162552. jpeg_component_info * compptr;
  162553. JSAMPARRAY in_ptr, out_ptr;
  162554. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162555. ci++, compptr++) {
  162556. in_ptr = input_buf[ci] + in_row_index;
  162557. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  162558. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  162559. }
  162560. }
  162561. /*
  162562. * Downsample pixel values of a single component.
  162563. * One row group is processed per call.
  162564. * This version handles arbitrary integral sampling ratios, without smoothing.
  162565. * Note that this version is not actually used for customary sampling ratios.
  162566. */
  162567. METHODDEF(void)
  162568. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162569. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162570. {
  162571. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  162572. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  162573. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162574. JSAMPROW inptr, outptr;
  162575. INT32 outvalue;
  162576. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  162577. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  162578. numpix = h_expand * v_expand;
  162579. numpix2 = numpix/2;
  162580. /* Expand input data enough to let all the output samples be generated
  162581. * by the standard loop. Special-casing padded output would be more
  162582. * efficient.
  162583. */
  162584. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162585. cinfo->image_width, output_cols * h_expand);
  162586. inrow = 0;
  162587. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162588. outptr = output_data[outrow];
  162589. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  162590. outcol++, outcol_h += h_expand) {
  162591. outvalue = 0;
  162592. for (v = 0; v < v_expand; v++) {
  162593. inptr = input_data[inrow+v] + outcol_h;
  162594. for (h = 0; h < h_expand; h++) {
  162595. outvalue += (INT32) GETJSAMPLE(*inptr++);
  162596. }
  162597. }
  162598. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  162599. }
  162600. inrow += v_expand;
  162601. }
  162602. }
  162603. /*
  162604. * Downsample pixel values of a single component.
  162605. * This version handles the special case of a full-size component,
  162606. * without smoothing.
  162607. */
  162608. METHODDEF(void)
  162609. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162610. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162611. {
  162612. /* Copy the data */
  162613. jcopy_sample_rows(input_data, 0, output_data, 0,
  162614. cinfo->max_v_samp_factor, cinfo->image_width);
  162615. /* Edge-expand */
  162616. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  162617. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  162618. }
  162619. /*
  162620. * Downsample pixel values of a single component.
  162621. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  162622. * without smoothing.
  162623. *
  162624. * A note about the "bias" calculations: when rounding fractional values to
  162625. * integer, we do not want to always round 0.5 up to the next integer.
  162626. * If we did that, we'd introduce a noticeable bias towards larger values.
  162627. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  162628. * alternate pixel locations (a simple ordered dither pattern).
  162629. */
  162630. METHODDEF(void)
  162631. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162632. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162633. {
  162634. int outrow;
  162635. JDIMENSION outcol;
  162636. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162637. register JSAMPROW inptr, outptr;
  162638. register int bias;
  162639. /* Expand input data enough to let all the output samples be generated
  162640. * by the standard loop. Special-casing padded output would be more
  162641. * efficient.
  162642. */
  162643. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162644. cinfo->image_width, output_cols * 2);
  162645. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162646. outptr = output_data[outrow];
  162647. inptr = input_data[outrow];
  162648. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  162649. for (outcol = 0; outcol < output_cols; outcol++) {
  162650. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  162651. + bias) >> 1);
  162652. bias ^= 1; /* 0=>1, 1=>0 */
  162653. inptr += 2;
  162654. }
  162655. }
  162656. }
  162657. /*
  162658. * Downsample pixel values of a single component.
  162659. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162660. * without smoothing.
  162661. */
  162662. METHODDEF(void)
  162663. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162664. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162665. {
  162666. int inrow, outrow;
  162667. JDIMENSION outcol;
  162668. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162669. register JSAMPROW inptr0, inptr1, outptr;
  162670. register int bias;
  162671. /* Expand input data enough to let all the output samples be generated
  162672. * by the standard loop. Special-casing padded output would be more
  162673. * efficient.
  162674. */
  162675. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162676. cinfo->image_width, output_cols * 2);
  162677. inrow = 0;
  162678. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162679. outptr = output_data[outrow];
  162680. inptr0 = input_data[inrow];
  162681. inptr1 = input_data[inrow+1];
  162682. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  162683. for (outcol = 0; outcol < output_cols; outcol++) {
  162684. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162685. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  162686. + bias) >> 2);
  162687. bias ^= 3; /* 1=>2, 2=>1 */
  162688. inptr0 += 2; inptr1 += 2;
  162689. }
  162690. inrow += 2;
  162691. }
  162692. }
  162693. #ifdef INPUT_SMOOTHING_SUPPORTED
  162694. /*
  162695. * Downsample pixel values of a single component.
  162696. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162697. * with smoothing. One row of context is required.
  162698. */
  162699. METHODDEF(void)
  162700. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162701. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162702. {
  162703. int inrow, outrow;
  162704. JDIMENSION colctr;
  162705. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162706. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  162707. INT32 membersum, neighsum, memberscale, neighscale;
  162708. /* Expand input data enough to let all the output samples be generated
  162709. * by the standard loop. Special-casing padded output would be more
  162710. * efficient.
  162711. */
  162712. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162713. cinfo->image_width, output_cols * 2);
  162714. /* We don't bother to form the individual "smoothed" input pixel values;
  162715. * we can directly compute the output which is the average of the four
  162716. * smoothed values. Each of the four member pixels contributes a fraction
  162717. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  162718. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  162719. * output. The four corner-adjacent neighbor pixels contribute a fraction
  162720. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  162721. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  162722. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  162723. * factors are scaled by 2^16 = 65536.
  162724. * Also recall that SF = smoothing_factor / 1024.
  162725. */
  162726. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  162727. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  162728. inrow = 0;
  162729. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162730. outptr = output_data[outrow];
  162731. inptr0 = input_data[inrow];
  162732. inptr1 = input_data[inrow+1];
  162733. above_ptr = input_data[inrow-1];
  162734. below_ptr = input_data[inrow+2];
  162735. /* Special case for first column: pretend column -1 is same as column 0 */
  162736. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162737. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162738. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162739. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162740. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  162741. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  162742. neighsum += neighsum;
  162743. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  162744. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  162745. membersum = membersum * memberscale + neighsum * neighscale;
  162746. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162747. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162748. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162749. /* sum of pixels directly mapped to this output element */
  162750. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162751. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162752. /* sum of edge-neighbor pixels */
  162753. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162754. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162755. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  162756. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  162757. /* The edge-neighbors count twice as much as corner-neighbors */
  162758. neighsum += neighsum;
  162759. /* Add in the corner-neighbors */
  162760. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  162761. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  162762. /* form final output scaled up by 2^16 */
  162763. membersum = membersum * memberscale + neighsum * neighscale;
  162764. /* round, descale and output it */
  162765. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162766. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162767. }
  162768. /* Special case for last column */
  162769. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162770. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162771. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162772. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162773. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  162774. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  162775. neighsum += neighsum;
  162776. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  162777. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  162778. membersum = membersum * memberscale + neighsum * neighscale;
  162779. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162780. inrow += 2;
  162781. }
  162782. }
  162783. /*
  162784. * Downsample pixel values of a single component.
  162785. * This version handles the special case of a full-size component,
  162786. * with smoothing. One row of context is required.
  162787. */
  162788. METHODDEF(void)
  162789. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  162790. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162791. {
  162792. int outrow;
  162793. JDIMENSION colctr;
  162794. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162795. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  162796. INT32 membersum, neighsum, memberscale, neighscale;
  162797. int colsum, lastcolsum, nextcolsum;
  162798. /* Expand input data enough to let all the output samples be generated
  162799. * by the standard loop. Special-casing padded output would be more
  162800. * efficient.
  162801. */
  162802. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162803. cinfo->image_width, output_cols);
  162804. /* Each of the eight neighbor pixels contributes a fraction SF to the
  162805. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  162806. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  162807. * Also recall that SF = smoothing_factor / 1024.
  162808. */
  162809. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  162810. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  162811. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162812. outptr = output_data[outrow];
  162813. inptr = input_data[outrow];
  162814. above_ptr = input_data[outrow-1];
  162815. below_ptr = input_data[outrow+1];
  162816. /* Special case for first column */
  162817. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  162818. GETJSAMPLE(*inptr);
  162819. membersum = GETJSAMPLE(*inptr++);
  162820. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162821. GETJSAMPLE(*inptr);
  162822. neighsum = colsum + (colsum - membersum) + nextcolsum;
  162823. membersum = membersum * memberscale + neighsum * neighscale;
  162824. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162825. lastcolsum = colsum; colsum = nextcolsum;
  162826. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162827. membersum = GETJSAMPLE(*inptr++);
  162828. above_ptr++; below_ptr++;
  162829. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162830. GETJSAMPLE(*inptr);
  162831. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  162832. membersum = membersum * memberscale + neighsum * neighscale;
  162833. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162834. lastcolsum = colsum; colsum = nextcolsum;
  162835. }
  162836. /* Special case for last column */
  162837. membersum = GETJSAMPLE(*inptr);
  162838. neighsum = lastcolsum + (colsum - membersum) + colsum;
  162839. membersum = membersum * memberscale + neighsum * neighscale;
  162840. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162841. }
  162842. }
  162843. #endif /* INPUT_SMOOTHING_SUPPORTED */
  162844. /*
  162845. * Module initialization routine for downsampling.
  162846. * Note that we must select a routine for each component.
  162847. */
  162848. GLOBAL(void)
  162849. jinit_downsampler (j_compress_ptr cinfo)
  162850. {
  162851. my_downsample_ptr downsample;
  162852. int ci;
  162853. jpeg_component_info * compptr;
  162854. boolean smoothok = TRUE;
  162855. downsample = (my_downsample_ptr)
  162856. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162857. SIZEOF(my_downsampler));
  162858. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  162859. downsample->pub.start_pass = start_pass_downsample;
  162860. downsample->pub.downsample = sep_downsample;
  162861. downsample->pub.need_context_rows = FALSE;
  162862. if (cinfo->CCIR601_sampling)
  162863. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  162864. /* Verify we can handle the sampling factors, and set up method pointers */
  162865. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162866. ci++, compptr++) {
  162867. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  162868. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162869. #ifdef INPUT_SMOOTHING_SUPPORTED
  162870. if (cinfo->smoothing_factor) {
  162871. downsample->methods[ci] = fullsize_smooth_downsample;
  162872. downsample->pub.need_context_rows = TRUE;
  162873. } else
  162874. #endif
  162875. downsample->methods[ci] = fullsize_downsample;
  162876. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162877. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162878. smoothok = FALSE;
  162879. downsample->methods[ci] = h2v1_downsample;
  162880. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162881. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  162882. #ifdef INPUT_SMOOTHING_SUPPORTED
  162883. if (cinfo->smoothing_factor) {
  162884. downsample->methods[ci] = h2v2_smooth_downsample;
  162885. downsample->pub.need_context_rows = TRUE;
  162886. } else
  162887. #endif
  162888. downsample->methods[ci] = h2v2_downsample;
  162889. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  162890. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  162891. smoothok = FALSE;
  162892. downsample->methods[ci] = int_downsample;
  162893. } else
  162894. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  162895. }
  162896. #ifdef INPUT_SMOOTHING_SUPPORTED
  162897. if (cinfo->smoothing_factor && !smoothok)
  162898. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  162899. #endif
  162900. }
  162901. /********* End of inlined file: jcsample.c *********/
  162902. /********* Start of inlined file: jctrans.c *********/
  162903. #define JPEG_INTERNALS
  162904. /* Forward declarations */
  162905. LOCAL(void) transencode_master_selection
  162906. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162907. LOCAL(void) transencode_coef_controller
  162908. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162909. /*
  162910. * Compression initialization for writing raw-coefficient data.
  162911. * Before calling this, all parameters and a data destination must be set up.
  162912. * Call jpeg_finish_compress() to actually write the data.
  162913. *
  162914. * The number of passed virtual arrays must match cinfo->num_components.
  162915. * Note that the virtual arrays need not be filled or even realized at
  162916. * the time write_coefficients is called; indeed, if the virtual arrays
  162917. * were requested from this compression object's memory manager, they
  162918. * typically will be realized during this routine and filled afterwards.
  162919. */
  162920. GLOBAL(void)
  162921. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  162922. {
  162923. if (cinfo->global_state != CSTATE_START)
  162924. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162925. /* Mark all tables to be written */
  162926. jpeg_suppress_tables(cinfo, FALSE);
  162927. /* (Re)initialize error mgr and destination modules */
  162928. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162929. (*cinfo->dest->init_destination) (cinfo);
  162930. /* Perform master selection of active modules */
  162931. transencode_master_selection(cinfo, coef_arrays);
  162932. /* Wait for jpeg_finish_compress() call */
  162933. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  162934. cinfo->global_state = CSTATE_WRCOEFS;
  162935. }
  162936. /*
  162937. * Initialize the compression object with default parameters,
  162938. * then copy from the source object all parameters needed for lossless
  162939. * transcoding. Parameters that can be varied without loss (such as
  162940. * scan script and Huffman optimization) are left in their default states.
  162941. */
  162942. GLOBAL(void)
  162943. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  162944. j_compress_ptr dstinfo)
  162945. {
  162946. JQUANT_TBL ** qtblptr;
  162947. jpeg_component_info *incomp, *outcomp;
  162948. JQUANT_TBL *c_quant, *slot_quant;
  162949. int tblno, ci, coefi;
  162950. /* Safety check to ensure start_compress not called yet. */
  162951. if (dstinfo->global_state != CSTATE_START)
  162952. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  162953. /* Copy fundamental image dimensions */
  162954. dstinfo->image_width = srcinfo->image_width;
  162955. dstinfo->image_height = srcinfo->image_height;
  162956. dstinfo->input_components = srcinfo->num_components;
  162957. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  162958. /* Initialize all parameters to default values */
  162959. jpeg_set_defaults(dstinfo);
  162960. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  162961. * Fix it to get the right header markers for the image colorspace.
  162962. */
  162963. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  162964. dstinfo->data_precision = srcinfo->data_precision;
  162965. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  162966. /* Copy the source's quantization tables. */
  162967. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  162968. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  162969. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  162970. if (*qtblptr == NULL)
  162971. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  162972. MEMCOPY((*qtblptr)->quantval,
  162973. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  162974. SIZEOF((*qtblptr)->quantval));
  162975. (*qtblptr)->sent_table = FALSE;
  162976. }
  162977. }
  162978. /* Copy the source's per-component info.
  162979. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  162980. */
  162981. dstinfo->num_components = srcinfo->num_components;
  162982. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  162983. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  162984. MAX_COMPONENTS);
  162985. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  162986. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  162987. outcomp->component_id = incomp->component_id;
  162988. outcomp->h_samp_factor = incomp->h_samp_factor;
  162989. outcomp->v_samp_factor = incomp->v_samp_factor;
  162990. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  162991. /* Make sure saved quantization table for component matches the qtable
  162992. * slot. If not, the input file re-used this qtable slot.
  162993. * IJG encoder currently cannot duplicate this.
  162994. */
  162995. tblno = outcomp->quant_tbl_no;
  162996. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  162997. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  162998. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  162999. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  163000. c_quant = incomp->quant_table;
  163001. if (c_quant != NULL) {
  163002. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  163003. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  163004. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  163005. }
  163006. }
  163007. /* Note: we do not copy the source's Huffman table assignments;
  163008. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  163009. */
  163010. }
  163011. /* Also copy JFIF version and resolution information, if available.
  163012. * Strictly speaking this isn't "critical" info, but it's nearly
  163013. * always appropriate to copy it if available. In particular,
  163014. * if the application chooses to copy JFIF 1.02 extension markers from
  163015. * the source file, we need to copy the version to make sure we don't
  163016. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  163017. * We will *not*, however, copy version info from mislabeled "2.01" files.
  163018. */
  163019. if (srcinfo->saw_JFIF_marker) {
  163020. if (srcinfo->JFIF_major_version == 1) {
  163021. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  163022. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  163023. }
  163024. dstinfo->density_unit = srcinfo->density_unit;
  163025. dstinfo->X_density = srcinfo->X_density;
  163026. dstinfo->Y_density = srcinfo->Y_density;
  163027. }
  163028. }
  163029. /*
  163030. * Master selection of compression modules for transcoding.
  163031. * This substitutes for jcinit.c's initialization of the full compressor.
  163032. */
  163033. LOCAL(void)
  163034. transencode_master_selection (j_compress_ptr cinfo,
  163035. jvirt_barray_ptr * coef_arrays)
  163036. {
  163037. /* Although we don't actually use input_components for transcoding,
  163038. * jcmaster.c's initial_setup will complain if input_components is 0.
  163039. */
  163040. cinfo->input_components = 1;
  163041. /* Initialize master control (includes parameter checking/processing) */
  163042. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  163043. /* Entropy encoding: either Huffman or arithmetic coding. */
  163044. if (cinfo->arith_code) {
  163045. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163046. } else {
  163047. if (cinfo->progressive_mode) {
  163048. #ifdef C_PROGRESSIVE_SUPPORTED
  163049. jinit_phuff_encoder(cinfo);
  163050. #else
  163051. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163052. #endif
  163053. } else
  163054. jinit_huff_encoder(cinfo);
  163055. }
  163056. /* We need a special coefficient buffer controller. */
  163057. transencode_coef_controller(cinfo, coef_arrays);
  163058. jinit_marker_writer(cinfo);
  163059. /* We can now tell the memory manager to allocate virtual arrays. */
  163060. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163061. /* Write the datastream header (SOI, JFIF) immediately.
  163062. * Frame and scan headers are postponed till later.
  163063. * This lets application insert special markers after the SOI.
  163064. */
  163065. (*cinfo->marker->write_file_header) (cinfo);
  163066. }
  163067. /*
  163068. * The rest of this file is a special implementation of the coefficient
  163069. * buffer controller. This is similar to jccoefct.c, but it handles only
  163070. * output from presupplied virtual arrays. Furthermore, we generate any
  163071. * dummy padding blocks on-the-fly rather than expecting them to be present
  163072. * in the arrays.
  163073. */
  163074. /* Private buffer controller object */
  163075. typedef struct {
  163076. struct jpeg_c_coef_controller pub; /* public fields */
  163077. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  163078. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  163079. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  163080. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  163081. /* Virtual block array for each component. */
  163082. jvirt_barray_ptr * whole_image;
  163083. /* Workspace for constructing dummy blocks at right/bottom edges. */
  163084. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  163085. } my_coef_controller2;
  163086. typedef my_coef_controller2 * my_coef_ptr2;
  163087. LOCAL(void)
  163088. start_iMCU_row2 (j_compress_ptr cinfo)
  163089. /* Reset within-iMCU-row counters for a new row */
  163090. {
  163091. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163092. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  163093. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  163094. * But at the bottom of the image, process only what's left.
  163095. */
  163096. if (cinfo->comps_in_scan > 1) {
  163097. coef->MCU_rows_per_iMCU_row = 1;
  163098. } else {
  163099. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  163100. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  163101. else
  163102. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  163103. }
  163104. coef->mcu_ctr = 0;
  163105. coef->MCU_vert_offset = 0;
  163106. }
  163107. /*
  163108. * Initialize for a processing pass.
  163109. */
  163110. METHODDEF(void)
  163111. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163112. {
  163113. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163114. if (pass_mode != JBUF_CRANK_DEST)
  163115. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163116. coef->iMCU_row_num = 0;
  163117. start_iMCU_row2(cinfo);
  163118. }
  163119. /*
  163120. * Process some data.
  163121. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  163122. * per call, ie, v_samp_factor block rows for each component in the scan.
  163123. * The data is obtained from the virtual arrays and fed to the entropy coder.
  163124. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  163125. *
  163126. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  163127. */
  163128. METHODDEF(boolean)
  163129. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  163130. {
  163131. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  163132. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163133. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  163134. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163135. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  163136. JDIMENSION start_col;
  163137. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  163138. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  163139. JBLOCKROW buffer_ptr;
  163140. jpeg_component_info *compptr;
  163141. /* Align the virtual buffers for the components used in this scan. */
  163142. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163143. compptr = cinfo->cur_comp_info[ci];
  163144. buffer[ci] = (*cinfo->mem->access_virt_barray)
  163145. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  163146. coef->iMCU_row_num * compptr->v_samp_factor,
  163147. (JDIMENSION) compptr->v_samp_factor, FALSE);
  163148. }
  163149. /* Loop to process one whole iMCU row */
  163150. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163151. yoffset++) {
  163152. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  163153. MCU_col_num++) {
  163154. /* Construct list of pointers to DCT blocks belonging to this MCU */
  163155. blkn = 0; /* index of current DCT block within MCU */
  163156. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163157. compptr = cinfo->cur_comp_info[ci];
  163158. start_col = MCU_col_num * compptr->MCU_width;
  163159. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  163160. : compptr->last_col_width;
  163161. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163162. if (coef->iMCU_row_num < last_iMCU_row ||
  163163. yindex+yoffset < compptr->last_row_height) {
  163164. /* Fill in pointers to real blocks in this row */
  163165. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  163166. for (xindex = 0; xindex < blockcnt; xindex++)
  163167. MCU_buffer[blkn++] = buffer_ptr++;
  163168. } else {
  163169. /* At bottom of image, need a whole row of dummy blocks */
  163170. xindex = 0;
  163171. }
  163172. /* Fill in any dummy blocks needed in this row.
  163173. * Dummy blocks are filled in the same way as in jccoefct.c:
  163174. * all zeroes in the AC entries, DC entries equal to previous
  163175. * block's DC value. The init routine has already zeroed the
  163176. * AC entries, so we need only set the DC entries correctly.
  163177. */
  163178. for (; xindex < compptr->MCU_width; xindex++) {
  163179. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  163180. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  163181. blkn++;
  163182. }
  163183. }
  163184. }
  163185. /* Try to write the MCU. */
  163186. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  163187. /* Suspension forced; update state counters and exit */
  163188. coef->MCU_vert_offset = yoffset;
  163189. coef->mcu_ctr = MCU_col_num;
  163190. return FALSE;
  163191. }
  163192. }
  163193. /* Completed an MCU row, but perhaps not an iMCU row */
  163194. coef->mcu_ctr = 0;
  163195. }
  163196. /* Completed the iMCU row, advance counters for next one */
  163197. coef->iMCU_row_num++;
  163198. start_iMCU_row2(cinfo);
  163199. return TRUE;
  163200. }
  163201. /*
  163202. * Initialize coefficient buffer controller.
  163203. *
  163204. * Each passed coefficient array must be the right size for that
  163205. * coefficient: width_in_blocks wide and height_in_blocks high,
  163206. * with unitheight at least v_samp_factor.
  163207. */
  163208. LOCAL(void)
  163209. transencode_coef_controller (j_compress_ptr cinfo,
  163210. jvirt_barray_ptr * coef_arrays)
  163211. {
  163212. my_coef_ptr2 coef;
  163213. JBLOCKROW buffer;
  163214. int i;
  163215. coef = (my_coef_ptr2)
  163216. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163217. SIZEOF(my_coef_controller2));
  163218. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  163219. coef->pub.start_pass = start_pass_coef2;
  163220. coef->pub.compress_data = compress_output2;
  163221. /* Save pointer to virtual arrays */
  163222. coef->whole_image = coef_arrays;
  163223. /* Allocate and pre-zero space for dummy DCT blocks. */
  163224. buffer = (JBLOCKROW)
  163225. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163226. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163227. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163228. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  163229. coef->dummy_buffer[i] = buffer + i;
  163230. }
  163231. }
  163232. /********* End of inlined file: jctrans.c *********/
  163233. /********* Start of inlined file: jdapistd.c *********/
  163234. #define JPEG_INTERNALS
  163235. /* Forward declarations */
  163236. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  163237. /*
  163238. * Decompression initialization.
  163239. * jpeg_read_header must be completed before calling this.
  163240. *
  163241. * If a multipass operating mode was selected, this will do all but the
  163242. * last pass, and thus may take a great deal of time.
  163243. *
  163244. * Returns FALSE if suspended. The return value need be inspected only if
  163245. * a suspending data source is used.
  163246. */
  163247. GLOBAL(boolean)
  163248. jpeg_start_decompress (j_decompress_ptr cinfo)
  163249. {
  163250. if (cinfo->global_state == DSTATE_READY) {
  163251. /* First call: initialize master control, select active modules */
  163252. jinit_master_decompress(cinfo);
  163253. if (cinfo->buffered_image) {
  163254. /* No more work here; expecting jpeg_start_output next */
  163255. cinfo->global_state = DSTATE_BUFIMAGE;
  163256. return TRUE;
  163257. }
  163258. cinfo->global_state = DSTATE_PRELOAD;
  163259. }
  163260. if (cinfo->global_state == DSTATE_PRELOAD) {
  163261. /* If file has multiple scans, absorb them all into the coef buffer */
  163262. if (cinfo->inputctl->has_multiple_scans) {
  163263. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163264. for (;;) {
  163265. int retcode;
  163266. /* Call progress monitor hook if present */
  163267. if (cinfo->progress != NULL)
  163268. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163269. /* Absorb some more input */
  163270. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163271. if (retcode == JPEG_SUSPENDED)
  163272. return FALSE;
  163273. if (retcode == JPEG_REACHED_EOI)
  163274. break;
  163275. /* Advance progress counter if appropriate */
  163276. if (cinfo->progress != NULL &&
  163277. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  163278. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  163279. /* jdmaster underestimated number of scans; ratchet up one scan */
  163280. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  163281. }
  163282. }
  163283. }
  163284. #else
  163285. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163286. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163287. }
  163288. cinfo->output_scan_number = cinfo->input_scan_number;
  163289. } else if (cinfo->global_state != DSTATE_PRESCAN)
  163290. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163291. /* Perform any dummy output passes, and set up for the final pass */
  163292. return output_pass_setup(cinfo);
  163293. }
  163294. /*
  163295. * Set up for an output pass, and perform any dummy pass(es) needed.
  163296. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  163297. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  163298. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  163299. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  163300. */
  163301. LOCAL(boolean)
  163302. output_pass_setup (j_decompress_ptr cinfo)
  163303. {
  163304. if (cinfo->global_state != DSTATE_PRESCAN) {
  163305. /* First call: do pass setup */
  163306. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163307. cinfo->output_scanline = 0;
  163308. cinfo->global_state = DSTATE_PRESCAN;
  163309. }
  163310. /* Loop over any required dummy passes */
  163311. while (cinfo->master->is_dummy_pass) {
  163312. #ifdef QUANT_2PASS_SUPPORTED
  163313. /* Crank through the dummy pass */
  163314. while (cinfo->output_scanline < cinfo->output_height) {
  163315. JDIMENSION last_scanline;
  163316. /* Call progress monitor hook if present */
  163317. if (cinfo->progress != NULL) {
  163318. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163319. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163320. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163321. }
  163322. /* Process some data */
  163323. last_scanline = cinfo->output_scanline;
  163324. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  163325. &cinfo->output_scanline, (JDIMENSION) 0);
  163326. if (cinfo->output_scanline == last_scanline)
  163327. return FALSE; /* No progress made, must suspend */
  163328. }
  163329. /* Finish up dummy pass, and set up for another one */
  163330. (*cinfo->master->finish_output_pass) (cinfo);
  163331. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163332. cinfo->output_scanline = 0;
  163333. #else
  163334. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163335. #endif /* QUANT_2PASS_SUPPORTED */
  163336. }
  163337. /* Ready for application to drive output pass through
  163338. * jpeg_read_scanlines or jpeg_read_raw_data.
  163339. */
  163340. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  163341. return TRUE;
  163342. }
  163343. /*
  163344. * Read some scanlines of data from the JPEG decompressor.
  163345. *
  163346. * The return value will be the number of lines actually read.
  163347. * This may be less than the number requested in several cases,
  163348. * including bottom of image, data source suspension, and operating
  163349. * modes that emit multiple scanlines at a time.
  163350. *
  163351. * Note: we warn about excess calls to jpeg_read_scanlines() since
  163352. * this likely signals an application programmer error. However,
  163353. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  163354. */
  163355. GLOBAL(JDIMENSION)
  163356. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  163357. JDIMENSION max_lines)
  163358. {
  163359. JDIMENSION row_ctr;
  163360. if (cinfo->global_state != DSTATE_SCANNING)
  163361. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163362. if (cinfo->output_scanline >= cinfo->output_height) {
  163363. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163364. return 0;
  163365. }
  163366. /* Call progress monitor hook if present */
  163367. if (cinfo->progress != NULL) {
  163368. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163369. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163370. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163371. }
  163372. /* Process some data */
  163373. row_ctr = 0;
  163374. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  163375. cinfo->output_scanline += row_ctr;
  163376. return row_ctr;
  163377. }
  163378. /*
  163379. * Alternate entry point to read raw data.
  163380. * Processes exactly one iMCU row per call, unless suspended.
  163381. */
  163382. GLOBAL(JDIMENSION)
  163383. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  163384. JDIMENSION max_lines)
  163385. {
  163386. JDIMENSION lines_per_iMCU_row;
  163387. if (cinfo->global_state != DSTATE_RAW_OK)
  163388. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163389. if (cinfo->output_scanline >= cinfo->output_height) {
  163390. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163391. return 0;
  163392. }
  163393. /* Call progress monitor hook if present */
  163394. if (cinfo->progress != NULL) {
  163395. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163396. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163397. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163398. }
  163399. /* Verify that at least one iMCU row can be returned. */
  163400. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  163401. if (max_lines < lines_per_iMCU_row)
  163402. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  163403. /* Decompress directly into user's buffer. */
  163404. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  163405. return 0; /* suspension forced, can do nothing more */
  163406. /* OK, we processed one iMCU row. */
  163407. cinfo->output_scanline += lines_per_iMCU_row;
  163408. return lines_per_iMCU_row;
  163409. }
  163410. /* Additional entry points for buffered-image mode. */
  163411. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163412. /*
  163413. * Initialize for an output pass in buffered-image mode.
  163414. */
  163415. GLOBAL(boolean)
  163416. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  163417. {
  163418. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  163419. cinfo->global_state != DSTATE_PRESCAN)
  163420. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163421. /* Limit scan number to valid range */
  163422. if (scan_number <= 0)
  163423. scan_number = 1;
  163424. if (cinfo->inputctl->eoi_reached &&
  163425. scan_number > cinfo->input_scan_number)
  163426. scan_number = cinfo->input_scan_number;
  163427. cinfo->output_scan_number = scan_number;
  163428. /* Perform any dummy output passes, and set up for the real pass */
  163429. return output_pass_setup(cinfo);
  163430. }
  163431. /*
  163432. * Finish up after an output pass in buffered-image mode.
  163433. *
  163434. * Returns FALSE if suspended. The return value need be inspected only if
  163435. * a suspending data source is used.
  163436. */
  163437. GLOBAL(boolean)
  163438. jpeg_finish_output (j_decompress_ptr cinfo)
  163439. {
  163440. if ((cinfo->global_state == DSTATE_SCANNING ||
  163441. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  163442. /* Terminate this pass. */
  163443. /* We do not require the whole pass to have been completed. */
  163444. (*cinfo->master->finish_output_pass) (cinfo);
  163445. cinfo->global_state = DSTATE_BUFPOST;
  163446. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  163447. /* BUFPOST = repeat call after a suspension, anything else is error */
  163448. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163449. }
  163450. /* Read markers looking for SOS or EOI */
  163451. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  163452. ! cinfo->inputctl->eoi_reached) {
  163453. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163454. return FALSE; /* Suspend, come back later */
  163455. }
  163456. cinfo->global_state = DSTATE_BUFIMAGE;
  163457. return TRUE;
  163458. }
  163459. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163460. /********* End of inlined file: jdapistd.c *********/
  163461. /********* Start of inlined file: jdapimin.c *********/
  163462. #define JPEG_INTERNALS
  163463. /*
  163464. * Initialization of a JPEG decompression object.
  163465. * The error manager must already be set up (in case memory manager fails).
  163466. */
  163467. GLOBAL(void)
  163468. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  163469. {
  163470. int i;
  163471. /* Guard against version mismatches between library and caller. */
  163472. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  163473. if (version != JPEG_LIB_VERSION)
  163474. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  163475. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  163476. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  163477. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  163478. /* For debugging purposes, we zero the whole master structure.
  163479. * But the application has already set the err pointer, and may have set
  163480. * client_data, so we have to save and restore those fields.
  163481. * Note: if application hasn't set client_data, tools like Purify may
  163482. * complain here.
  163483. */
  163484. {
  163485. struct jpeg_error_mgr * err = cinfo->err;
  163486. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  163487. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  163488. cinfo->err = err;
  163489. cinfo->client_data = client_data;
  163490. }
  163491. cinfo->is_decompressor = TRUE;
  163492. /* Initialize a memory manager instance for this object */
  163493. jinit_memory_mgr((j_common_ptr) cinfo);
  163494. /* Zero out pointers to permanent structures. */
  163495. cinfo->progress = NULL;
  163496. cinfo->src = NULL;
  163497. for (i = 0; i < NUM_QUANT_TBLS; i++)
  163498. cinfo->quant_tbl_ptrs[i] = NULL;
  163499. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163500. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  163501. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  163502. }
  163503. /* Initialize marker processor so application can override methods
  163504. * for COM, APPn markers before calling jpeg_read_header.
  163505. */
  163506. cinfo->marker_list = NULL;
  163507. jinit_marker_reader(cinfo);
  163508. /* And initialize the overall input controller. */
  163509. jinit_input_controller(cinfo);
  163510. /* OK, I'm ready */
  163511. cinfo->global_state = DSTATE_START;
  163512. }
  163513. /*
  163514. * Destruction of a JPEG decompression object
  163515. */
  163516. GLOBAL(void)
  163517. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  163518. {
  163519. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  163520. }
  163521. /*
  163522. * Abort processing of a JPEG decompression operation,
  163523. * but don't destroy the object itself.
  163524. */
  163525. GLOBAL(void)
  163526. jpeg_abort_decompress (j_decompress_ptr cinfo)
  163527. {
  163528. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  163529. }
  163530. /*
  163531. * Set default decompression parameters.
  163532. */
  163533. LOCAL(void)
  163534. default_decompress_parms (j_decompress_ptr cinfo)
  163535. {
  163536. /* Guess the input colorspace, and set output colorspace accordingly. */
  163537. /* (Wish JPEG committee had provided a real way to specify this...) */
  163538. /* Note application may override our guesses. */
  163539. switch (cinfo->num_components) {
  163540. case 1:
  163541. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  163542. cinfo->out_color_space = JCS_GRAYSCALE;
  163543. break;
  163544. case 3:
  163545. if (cinfo->saw_JFIF_marker) {
  163546. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  163547. } else if (cinfo->saw_Adobe_marker) {
  163548. switch (cinfo->Adobe_transform) {
  163549. case 0:
  163550. cinfo->jpeg_color_space = JCS_RGB;
  163551. break;
  163552. case 1:
  163553. cinfo->jpeg_color_space = JCS_YCbCr;
  163554. break;
  163555. default:
  163556. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163557. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163558. break;
  163559. }
  163560. } else {
  163561. /* Saw no special markers, try to guess from the component IDs */
  163562. int cid0 = cinfo->comp_info[0].component_id;
  163563. int cid1 = cinfo->comp_info[1].component_id;
  163564. int cid2 = cinfo->comp_info[2].component_id;
  163565. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  163566. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  163567. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  163568. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  163569. else {
  163570. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  163571. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163572. }
  163573. }
  163574. /* Always guess RGB is proper output colorspace. */
  163575. cinfo->out_color_space = JCS_RGB;
  163576. break;
  163577. case 4:
  163578. if (cinfo->saw_Adobe_marker) {
  163579. switch (cinfo->Adobe_transform) {
  163580. case 0:
  163581. cinfo->jpeg_color_space = JCS_CMYK;
  163582. break;
  163583. case 2:
  163584. cinfo->jpeg_color_space = JCS_YCCK;
  163585. break;
  163586. default:
  163587. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163588. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  163589. break;
  163590. }
  163591. } else {
  163592. /* No special markers, assume straight CMYK. */
  163593. cinfo->jpeg_color_space = JCS_CMYK;
  163594. }
  163595. cinfo->out_color_space = JCS_CMYK;
  163596. break;
  163597. default:
  163598. cinfo->jpeg_color_space = JCS_UNKNOWN;
  163599. cinfo->out_color_space = JCS_UNKNOWN;
  163600. break;
  163601. }
  163602. /* Set defaults for other decompression parameters. */
  163603. cinfo->scale_num = 1; /* 1:1 scaling */
  163604. cinfo->scale_denom = 1;
  163605. cinfo->output_gamma = 1.0;
  163606. cinfo->buffered_image = FALSE;
  163607. cinfo->raw_data_out = FALSE;
  163608. cinfo->dct_method = JDCT_DEFAULT;
  163609. cinfo->do_fancy_upsampling = TRUE;
  163610. cinfo->do_block_smoothing = TRUE;
  163611. cinfo->quantize_colors = FALSE;
  163612. /* We set these in case application only sets quantize_colors. */
  163613. cinfo->dither_mode = JDITHER_FS;
  163614. #ifdef QUANT_2PASS_SUPPORTED
  163615. cinfo->two_pass_quantize = TRUE;
  163616. #else
  163617. cinfo->two_pass_quantize = FALSE;
  163618. #endif
  163619. cinfo->desired_number_of_colors = 256;
  163620. cinfo->colormap = NULL;
  163621. /* Initialize for no mode change in buffered-image mode. */
  163622. cinfo->enable_1pass_quant = FALSE;
  163623. cinfo->enable_external_quant = FALSE;
  163624. cinfo->enable_2pass_quant = FALSE;
  163625. }
  163626. /*
  163627. * Decompression startup: read start of JPEG datastream to see what's there.
  163628. * Need only initialize JPEG object and supply a data source before calling.
  163629. *
  163630. * This routine will read as far as the first SOS marker (ie, actual start of
  163631. * compressed data), and will save all tables and parameters in the JPEG
  163632. * object. It will also initialize the decompression parameters to default
  163633. * values, and finally return JPEG_HEADER_OK. On return, the application may
  163634. * adjust the decompression parameters and then call jpeg_start_decompress.
  163635. * (Or, if the application only wanted to determine the image parameters,
  163636. * the data need not be decompressed. In that case, call jpeg_abort or
  163637. * jpeg_destroy to release any temporary space.)
  163638. * If an abbreviated (tables only) datastream is presented, the routine will
  163639. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  163640. * re-use the JPEG object to read the abbreviated image datastream(s).
  163641. * It is unnecessary (but OK) to call jpeg_abort in this case.
  163642. * The JPEG_SUSPENDED return code only occurs if the data source module
  163643. * requests suspension of the decompressor. In this case the application
  163644. * should load more source data and then re-call jpeg_read_header to resume
  163645. * processing.
  163646. * If a non-suspending data source is used and require_image is TRUE, then the
  163647. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  163648. *
  163649. * This routine is now just a front end to jpeg_consume_input, with some
  163650. * extra error checking.
  163651. */
  163652. GLOBAL(int)
  163653. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  163654. {
  163655. int retcode;
  163656. if (cinfo->global_state != DSTATE_START &&
  163657. cinfo->global_state != DSTATE_INHEADER)
  163658. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163659. retcode = jpeg_consume_input(cinfo);
  163660. switch (retcode) {
  163661. case JPEG_REACHED_SOS:
  163662. retcode = JPEG_HEADER_OK;
  163663. break;
  163664. case JPEG_REACHED_EOI:
  163665. if (require_image) /* Complain if application wanted an image */
  163666. ERREXIT(cinfo, JERR_NO_IMAGE);
  163667. /* Reset to start state; it would be safer to require the application to
  163668. * call jpeg_abort, but we can't change it now for compatibility reasons.
  163669. * A side effect is to free any temporary memory (there shouldn't be any).
  163670. */
  163671. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  163672. retcode = JPEG_HEADER_TABLES_ONLY;
  163673. break;
  163674. case JPEG_SUSPENDED:
  163675. /* no work */
  163676. break;
  163677. }
  163678. return retcode;
  163679. }
  163680. /*
  163681. * Consume data in advance of what the decompressor requires.
  163682. * This can be called at any time once the decompressor object has
  163683. * been created and a data source has been set up.
  163684. *
  163685. * This routine is essentially a state machine that handles a couple
  163686. * of critical state-transition actions, namely initial setup and
  163687. * transition from header scanning to ready-for-start_decompress.
  163688. * All the actual input is done via the input controller's consume_input
  163689. * method.
  163690. */
  163691. GLOBAL(int)
  163692. jpeg_consume_input (j_decompress_ptr cinfo)
  163693. {
  163694. int retcode = JPEG_SUSPENDED;
  163695. /* NB: every possible DSTATE value should be listed in this switch */
  163696. switch (cinfo->global_state) {
  163697. case DSTATE_START:
  163698. /* Start-of-datastream actions: reset appropriate modules */
  163699. (*cinfo->inputctl->reset_input_controller) (cinfo);
  163700. /* Initialize application's data source module */
  163701. (*cinfo->src->init_source) (cinfo);
  163702. cinfo->global_state = DSTATE_INHEADER;
  163703. /*FALLTHROUGH*/
  163704. case DSTATE_INHEADER:
  163705. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163706. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  163707. /* Set up default parameters based on header data */
  163708. default_decompress_parms(cinfo);
  163709. /* Set global state: ready for start_decompress */
  163710. cinfo->global_state = DSTATE_READY;
  163711. }
  163712. break;
  163713. case DSTATE_READY:
  163714. /* Can't advance past first SOS until start_decompress is called */
  163715. retcode = JPEG_REACHED_SOS;
  163716. break;
  163717. case DSTATE_PRELOAD:
  163718. case DSTATE_PRESCAN:
  163719. case DSTATE_SCANNING:
  163720. case DSTATE_RAW_OK:
  163721. case DSTATE_BUFIMAGE:
  163722. case DSTATE_BUFPOST:
  163723. case DSTATE_STOPPING:
  163724. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163725. break;
  163726. default:
  163727. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163728. }
  163729. return retcode;
  163730. }
  163731. /*
  163732. * Have we finished reading the input file?
  163733. */
  163734. GLOBAL(boolean)
  163735. jpeg_input_complete (j_decompress_ptr cinfo)
  163736. {
  163737. /* Check for valid jpeg object */
  163738. if (cinfo->global_state < DSTATE_START ||
  163739. cinfo->global_state > DSTATE_STOPPING)
  163740. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163741. return cinfo->inputctl->eoi_reached;
  163742. }
  163743. /*
  163744. * Is there more than one scan?
  163745. */
  163746. GLOBAL(boolean)
  163747. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  163748. {
  163749. /* Only valid after jpeg_read_header completes */
  163750. if (cinfo->global_state < DSTATE_READY ||
  163751. cinfo->global_state > DSTATE_STOPPING)
  163752. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163753. return cinfo->inputctl->has_multiple_scans;
  163754. }
  163755. /*
  163756. * Finish JPEG decompression.
  163757. *
  163758. * This will normally just verify the file trailer and release temp storage.
  163759. *
  163760. * Returns FALSE if suspended. The return value need be inspected only if
  163761. * a suspending data source is used.
  163762. */
  163763. GLOBAL(boolean)
  163764. jpeg_finish_decompress (j_decompress_ptr cinfo)
  163765. {
  163766. if ((cinfo->global_state == DSTATE_SCANNING ||
  163767. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  163768. /* Terminate final pass of non-buffered mode */
  163769. if (cinfo->output_scanline < cinfo->output_height)
  163770. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  163771. (*cinfo->master->finish_output_pass) (cinfo);
  163772. cinfo->global_state = DSTATE_STOPPING;
  163773. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  163774. /* Finishing after a buffered-image operation */
  163775. cinfo->global_state = DSTATE_STOPPING;
  163776. } else if (cinfo->global_state != DSTATE_STOPPING) {
  163777. /* STOPPING = repeat call after a suspension, anything else is error */
  163778. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163779. }
  163780. /* Read until EOI */
  163781. while (! cinfo->inputctl->eoi_reached) {
  163782. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163783. return FALSE; /* Suspend, come back later */
  163784. }
  163785. /* Do final cleanup */
  163786. (*cinfo->src->term_source) (cinfo);
  163787. /* We can use jpeg_abort to release memory and reset global_state */
  163788. jpeg_abort((j_common_ptr) cinfo);
  163789. return TRUE;
  163790. }
  163791. /********* End of inlined file: jdapimin.c *********/
  163792. /********* Start of inlined file: jdatasrc.c *********/
  163793. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  163794. /********* Start of inlined file: jerror.h *********/
  163795. /*
  163796. * To define the enum list of message codes, include this file without
  163797. * defining macro JMESSAGE. To create a message string table, include it
  163798. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  163799. */
  163800. #ifndef JMESSAGE
  163801. #ifndef JERROR_H
  163802. /* First time through, define the enum list */
  163803. #define JMAKE_ENUM_LIST
  163804. #else
  163805. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  163806. #define JMESSAGE(code,string)
  163807. #endif /* JERROR_H */
  163808. #endif /* JMESSAGE */
  163809. #ifdef JMAKE_ENUM_LIST
  163810. typedef enum {
  163811. #define JMESSAGE(code,string) code ,
  163812. #endif /* JMAKE_ENUM_LIST */
  163813. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  163814. /* For maintenance convenience, list is alphabetical by message code name */
  163815. JMESSAGE(JERR_ARITH_NOTIMPL,
  163816. "Sorry, there are legal restrictions on arithmetic coding")
  163817. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  163818. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  163819. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  163820. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  163821. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  163822. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  163823. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  163824. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  163825. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  163826. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  163827. JMESSAGE(JERR_BAD_LIB_VERSION,
  163828. "Wrong JPEG library version: library is %d, caller expects %d")
  163829. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  163830. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  163831. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  163832. JMESSAGE(JERR_BAD_PROGRESSION,
  163833. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  163834. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  163835. "Invalid progressive parameters at scan script entry %d")
  163836. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  163837. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  163838. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  163839. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  163840. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  163841. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  163842. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  163843. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  163844. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  163845. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  163846. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  163847. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  163848. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  163849. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  163850. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  163851. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  163852. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  163853. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  163854. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  163855. JMESSAGE(JERR_FILE_READ, "Input file read error")
  163856. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  163857. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  163858. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  163859. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  163860. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  163861. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  163862. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  163863. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  163864. "Cannot transcode due to multiple use of quantization table %d")
  163865. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  163866. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  163867. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  163868. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  163869. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  163870. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  163871. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  163872. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  163873. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  163874. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  163875. JMESSAGE(JERR_QUANT_COMPONENTS,
  163876. "Cannot quantize more than %d color components")
  163877. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  163878. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  163879. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  163880. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  163881. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  163882. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  163883. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  163884. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  163885. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  163886. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  163887. JMESSAGE(JERR_TFILE_WRITE,
  163888. "Write failed on temporary file --- out of disk space?")
  163889. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  163890. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  163891. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  163892. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  163893. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  163894. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  163895. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  163896. JMESSAGE(JMSG_VERSION, JVERSION)
  163897. JMESSAGE(JTRC_16BIT_TABLES,
  163898. "Caution: quantization tables are too coarse for baseline JPEG")
  163899. JMESSAGE(JTRC_ADOBE,
  163900. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  163901. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  163902. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  163903. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  163904. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  163905. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  163906. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  163907. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  163908. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  163909. JMESSAGE(JTRC_EOI, "End Of Image")
  163910. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  163911. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  163912. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  163913. "Warning: thumbnail image size does not match data length %u")
  163914. JMESSAGE(JTRC_JFIF_EXTENSION,
  163915. "JFIF extension marker: type 0x%02x, length %u")
  163916. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  163917. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  163918. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  163919. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  163920. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  163921. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  163922. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  163923. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  163924. JMESSAGE(JTRC_RST, "RST%d")
  163925. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  163926. "Smoothing not supported with nonstandard sampling ratios")
  163927. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  163928. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  163929. JMESSAGE(JTRC_SOI, "Start of Image")
  163930. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  163931. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  163932. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  163933. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  163934. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  163935. JMESSAGE(JTRC_THUMB_JPEG,
  163936. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  163937. JMESSAGE(JTRC_THUMB_PALETTE,
  163938. "JFIF extension marker: palette thumbnail image, length %u")
  163939. JMESSAGE(JTRC_THUMB_RGB,
  163940. "JFIF extension marker: RGB thumbnail image, length %u")
  163941. JMESSAGE(JTRC_UNKNOWN_IDS,
  163942. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  163943. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  163944. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  163945. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  163946. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  163947. "Inconsistent progression sequence for component %d coefficient %d")
  163948. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  163949. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  163950. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  163951. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  163952. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  163953. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  163954. JMESSAGE(JWRN_MUST_RESYNC,
  163955. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  163956. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  163957. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  163958. #ifdef JMAKE_ENUM_LIST
  163959. JMSG_LASTMSGCODE
  163960. } J_MESSAGE_CODE;
  163961. #undef JMAKE_ENUM_LIST
  163962. #endif /* JMAKE_ENUM_LIST */
  163963. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  163964. #undef JMESSAGE
  163965. #ifndef JERROR_H
  163966. #define JERROR_H
  163967. /* Macros to simplify using the error and trace message stuff */
  163968. /* The first parameter is either type of cinfo pointer */
  163969. /* Fatal errors (print message and exit) */
  163970. #define ERREXIT(cinfo,code) \
  163971. ((cinfo)->err->msg_code = (code), \
  163972. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163973. #define ERREXIT1(cinfo,code,p1) \
  163974. ((cinfo)->err->msg_code = (code), \
  163975. (cinfo)->err->msg_parm.i[0] = (p1), \
  163976. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163977. #define ERREXIT2(cinfo,code,p1,p2) \
  163978. ((cinfo)->err->msg_code = (code), \
  163979. (cinfo)->err->msg_parm.i[0] = (p1), \
  163980. (cinfo)->err->msg_parm.i[1] = (p2), \
  163981. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163982. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  163983. ((cinfo)->err->msg_code = (code), \
  163984. (cinfo)->err->msg_parm.i[0] = (p1), \
  163985. (cinfo)->err->msg_parm.i[1] = (p2), \
  163986. (cinfo)->err->msg_parm.i[2] = (p3), \
  163987. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163988. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  163989. ((cinfo)->err->msg_code = (code), \
  163990. (cinfo)->err->msg_parm.i[0] = (p1), \
  163991. (cinfo)->err->msg_parm.i[1] = (p2), \
  163992. (cinfo)->err->msg_parm.i[2] = (p3), \
  163993. (cinfo)->err->msg_parm.i[3] = (p4), \
  163994. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163995. #define ERREXITS(cinfo,code,str) \
  163996. ((cinfo)->err->msg_code = (code), \
  163997. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163998. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163999. #define MAKESTMT(stuff) do { stuff } while (0)
  164000. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  164001. #define WARNMS(cinfo,code) \
  164002. ((cinfo)->err->msg_code = (code), \
  164003. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164004. #define WARNMS1(cinfo,code,p1) \
  164005. ((cinfo)->err->msg_code = (code), \
  164006. (cinfo)->err->msg_parm.i[0] = (p1), \
  164007. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164008. #define WARNMS2(cinfo,code,p1,p2) \
  164009. ((cinfo)->err->msg_code = (code), \
  164010. (cinfo)->err->msg_parm.i[0] = (p1), \
  164011. (cinfo)->err->msg_parm.i[1] = (p2), \
  164012. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  164013. /* Informational/debugging messages */
  164014. #define TRACEMS(cinfo,lvl,code) \
  164015. ((cinfo)->err->msg_code = (code), \
  164016. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164017. #define TRACEMS1(cinfo,lvl,code,p1) \
  164018. ((cinfo)->err->msg_code = (code), \
  164019. (cinfo)->err->msg_parm.i[0] = (p1), \
  164020. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164021. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  164022. ((cinfo)->err->msg_code = (code), \
  164023. (cinfo)->err->msg_parm.i[0] = (p1), \
  164024. (cinfo)->err->msg_parm.i[1] = (p2), \
  164025. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164026. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  164027. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164028. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  164029. (cinfo)->err->msg_code = (code); \
  164030. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164031. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  164032. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164033. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164034. (cinfo)->err->msg_code = (code); \
  164035. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164036. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  164037. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164038. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164039. _mp[4] = (p5); \
  164040. (cinfo)->err->msg_code = (code); \
  164041. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164042. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  164043. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  164044. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  164045. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  164046. (cinfo)->err->msg_code = (code); \
  164047. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  164048. #define TRACEMSS(cinfo,lvl,code,str) \
  164049. ((cinfo)->err->msg_code = (code), \
  164050. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  164051. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  164052. #endif /* JERROR_H */
  164053. /********* End of inlined file: jerror.h *********/
  164054. /* Expanded data source object for stdio input */
  164055. typedef struct {
  164056. struct jpeg_source_mgr pub; /* public fields */
  164057. FILE * infile; /* source stream */
  164058. JOCTET * buffer; /* start of buffer */
  164059. boolean start_of_file; /* have we gotten any data yet? */
  164060. } my_source_mgr;
  164061. typedef my_source_mgr * my_src_ptr;
  164062. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  164063. /*
  164064. * Initialize source --- called by jpeg_read_header
  164065. * before any data is actually read.
  164066. */
  164067. METHODDEF(void)
  164068. init_source (j_decompress_ptr cinfo)
  164069. {
  164070. my_src_ptr src = (my_src_ptr) cinfo->src;
  164071. /* We reset the empty-input-file flag for each image,
  164072. * but we don't clear the input buffer.
  164073. * This is correct behavior for reading a series of images from one source.
  164074. */
  164075. src->start_of_file = TRUE;
  164076. }
  164077. /*
  164078. * Fill the input buffer --- called whenever buffer is emptied.
  164079. *
  164080. * In typical applications, this should read fresh data into the buffer
  164081. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  164082. * reset the pointer & count to the start of the buffer, and return TRUE
  164083. * indicating that the buffer has been reloaded. It is not necessary to
  164084. * fill the buffer entirely, only to obtain at least one more byte.
  164085. *
  164086. * There is no such thing as an EOF return. If the end of the file has been
  164087. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  164088. * the buffer. In most cases, generating a warning message and inserting a
  164089. * fake EOI marker is the best course of action --- this will allow the
  164090. * decompressor to output however much of the image is there. However,
  164091. * the resulting error message is misleading if the real problem is an empty
  164092. * input file, so we handle that case specially.
  164093. *
  164094. * In applications that need to be able to suspend compression due to input
  164095. * not being available yet, a FALSE return indicates that no more data can be
  164096. * obtained right now, but more may be forthcoming later. In this situation,
  164097. * the decompressor will return to its caller (with an indication of the
  164098. * number of scanlines it has read, if any). The application should resume
  164099. * decompression after it has loaded more data into the input buffer. Note
  164100. * that there are substantial restrictions on the use of suspension --- see
  164101. * the documentation.
  164102. *
  164103. * When suspending, the decompressor will back up to a convenient restart point
  164104. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  164105. * indicate where the restart point will be if the current call returns FALSE.
  164106. * Data beyond this point must be rescanned after resumption, so move it to
  164107. * the front of the buffer rather than discarding it.
  164108. */
  164109. METHODDEF(boolean)
  164110. fill_input_buffer (j_decompress_ptr cinfo)
  164111. {
  164112. my_src_ptr src = (my_src_ptr) cinfo->src;
  164113. size_t nbytes;
  164114. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  164115. if (nbytes <= 0) {
  164116. if (src->start_of_file) /* Treat empty input file as fatal error */
  164117. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  164118. WARNMS(cinfo, JWRN_JPEG_EOF);
  164119. /* Insert a fake EOI marker */
  164120. src->buffer[0] = (JOCTET) 0xFF;
  164121. src->buffer[1] = (JOCTET) JPEG_EOI;
  164122. nbytes = 2;
  164123. }
  164124. src->pub.next_input_byte = src->buffer;
  164125. src->pub.bytes_in_buffer = nbytes;
  164126. src->start_of_file = FALSE;
  164127. return TRUE;
  164128. }
  164129. /*
  164130. * Skip data --- used to skip over a potentially large amount of
  164131. * uninteresting data (such as an APPn marker).
  164132. *
  164133. * Writers of suspendable-input applications must note that skip_input_data
  164134. * is not granted the right to give a suspension return. If the skip extends
  164135. * beyond the data currently in the buffer, the buffer can be marked empty so
  164136. * that the next read will cause a fill_input_buffer call that can suspend.
  164137. * Arranging for additional bytes to be discarded before reloading the input
  164138. * buffer is the application writer's problem.
  164139. */
  164140. METHODDEF(void)
  164141. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  164142. {
  164143. my_src_ptr src = (my_src_ptr) cinfo->src;
  164144. /* Just a dumb implementation for now. Could use fseek() except
  164145. * it doesn't work on pipes. Not clear that being smart is worth
  164146. * any trouble anyway --- large skips are infrequent.
  164147. */
  164148. if (num_bytes > 0) {
  164149. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  164150. num_bytes -= (long) src->pub.bytes_in_buffer;
  164151. (void) fill_input_buffer(cinfo);
  164152. /* note we assume that fill_input_buffer will never return FALSE,
  164153. * so suspension need not be handled.
  164154. */
  164155. }
  164156. src->pub.next_input_byte += (size_t) num_bytes;
  164157. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  164158. }
  164159. }
  164160. /*
  164161. * An additional method that can be provided by data source modules is the
  164162. * resync_to_restart method for error recovery in the presence of RST markers.
  164163. * For the moment, this source module just uses the default resync method
  164164. * provided by the JPEG library. That method assumes that no backtracking
  164165. * is possible.
  164166. */
  164167. /*
  164168. * Terminate source --- called by jpeg_finish_decompress
  164169. * after all data has been read. Often a no-op.
  164170. *
  164171. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  164172. * application must deal with any cleanup that should happen even
  164173. * for error exit.
  164174. */
  164175. METHODDEF(void)
  164176. term_source (j_decompress_ptr cinfo)
  164177. {
  164178. /* no work necessary here */
  164179. }
  164180. /*
  164181. * Prepare for input from a stdio stream.
  164182. * The caller must have already opened the stream, and is responsible
  164183. * for closing it after finishing decompression.
  164184. */
  164185. GLOBAL(void)
  164186. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  164187. {
  164188. my_src_ptr src;
  164189. /* The source object and input buffer are made permanent so that a series
  164190. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  164191. * only before the first one. (If we discarded the buffer at the end of
  164192. * one image, we'd likely lose the start of the next one.)
  164193. * This makes it unsafe to use this manager and a different source
  164194. * manager serially with the same JPEG object. Caveat programmer.
  164195. */
  164196. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  164197. cinfo->src = (struct jpeg_source_mgr *)
  164198. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164199. SIZEOF(my_source_mgr));
  164200. src = (my_src_ptr) cinfo->src;
  164201. src->buffer = (JOCTET *)
  164202. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164203. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  164204. }
  164205. src = (my_src_ptr) cinfo->src;
  164206. src->pub.init_source = init_source;
  164207. src->pub.fill_input_buffer = fill_input_buffer;
  164208. src->pub.skip_input_data = skip_input_data;
  164209. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  164210. src->pub.term_source = term_source;
  164211. src->infile = infile;
  164212. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  164213. src->pub.next_input_byte = NULL; /* until buffer loaded */
  164214. }
  164215. /********* End of inlined file: jdatasrc.c *********/
  164216. /********* Start of inlined file: jdcoefct.c *********/
  164217. #define JPEG_INTERNALS
  164218. /* Block smoothing is only applicable for progressive JPEG, so: */
  164219. #ifndef D_PROGRESSIVE_SUPPORTED
  164220. #undef BLOCK_SMOOTHING_SUPPORTED
  164221. #endif
  164222. /* Private buffer controller object */
  164223. typedef struct {
  164224. struct jpeg_d_coef_controller pub; /* public fields */
  164225. /* These variables keep track of the current location of the input side. */
  164226. /* cinfo->input_iMCU_row is also used for this. */
  164227. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  164228. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164229. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164230. /* The output side's location is represented by cinfo->output_iMCU_row. */
  164231. /* In single-pass modes, it's sufficient to buffer just one MCU.
  164232. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  164233. * and let the entropy decoder write into that workspace each time.
  164234. * (On 80x86, the workspace is FAR even though it's not really very big;
  164235. * this is to keep the module interfaces unchanged when a large coefficient
  164236. * buffer is necessary.)
  164237. * In multi-pass modes, this array points to the current MCU's blocks
  164238. * within the virtual arrays; it is used only by the input side.
  164239. */
  164240. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  164241. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164242. /* In multi-pass modes, we need a virtual block array for each component. */
  164243. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  164244. #endif
  164245. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164246. /* When doing block smoothing, we latch coefficient Al values here */
  164247. int * coef_bits_latch;
  164248. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  164249. #endif
  164250. } my_coef_controller3;
  164251. typedef my_coef_controller3 * my_coef_ptr3;
  164252. /* Forward declarations */
  164253. METHODDEF(int) decompress_onepass
  164254. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164255. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164256. METHODDEF(int) decompress_data
  164257. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164258. #endif
  164259. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164260. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  164261. METHODDEF(int) decompress_smooth_data
  164262. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164263. #endif
  164264. LOCAL(void)
  164265. start_iMCU_row3 (j_decompress_ptr cinfo)
  164266. /* Reset within-iMCU-row counters for a new row (input side) */
  164267. {
  164268. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164269. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  164270. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  164271. * But at the bottom of the image, process only what's left.
  164272. */
  164273. if (cinfo->comps_in_scan > 1) {
  164274. coef->MCU_rows_per_iMCU_row = 1;
  164275. } else {
  164276. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  164277. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  164278. else
  164279. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  164280. }
  164281. coef->MCU_ctr = 0;
  164282. coef->MCU_vert_offset = 0;
  164283. }
  164284. /*
  164285. * Initialize for an input processing pass.
  164286. */
  164287. METHODDEF(void)
  164288. start_input_pass (j_decompress_ptr cinfo)
  164289. {
  164290. cinfo->input_iMCU_row = 0;
  164291. start_iMCU_row3(cinfo);
  164292. }
  164293. /*
  164294. * Initialize for an output processing pass.
  164295. */
  164296. METHODDEF(void)
  164297. start_output_pass (j_decompress_ptr cinfo)
  164298. {
  164299. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164300. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164301. /* If multipass, check to see whether to use block smoothing on this pass */
  164302. if (coef->pub.coef_arrays != NULL) {
  164303. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  164304. coef->pub.decompress_data = decompress_smooth_data;
  164305. else
  164306. coef->pub.decompress_data = decompress_data;
  164307. }
  164308. #endif
  164309. cinfo->output_iMCU_row = 0;
  164310. }
  164311. /*
  164312. * Decompress and return some data in the single-pass case.
  164313. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164314. * Input and output must run in lockstep since we have only a one-MCU buffer.
  164315. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164316. *
  164317. * NB: output_buf contains a plane for each component in image,
  164318. * which we index according to the component's SOF position.
  164319. */
  164320. METHODDEF(int)
  164321. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164322. {
  164323. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164324. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164325. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  164326. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164327. int blkn, ci, xindex, yindex, yoffset, useful_width;
  164328. JSAMPARRAY output_ptr;
  164329. JDIMENSION start_col, output_col;
  164330. jpeg_component_info *compptr;
  164331. inverse_DCT_method_ptr inverse_DCT;
  164332. /* Loop to process as much as one whole iMCU row */
  164333. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164334. yoffset++) {
  164335. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  164336. MCU_col_num++) {
  164337. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  164338. jzero_far((void FAR *) coef->MCU_buffer[0],
  164339. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  164340. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164341. /* Suspension forced; update state counters and exit */
  164342. coef->MCU_vert_offset = yoffset;
  164343. coef->MCU_ctr = MCU_col_num;
  164344. return JPEG_SUSPENDED;
  164345. }
  164346. /* Determine where data should go in output_buf and do the IDCT thing.
  164347. * We skip dummy blocks at the right and bottom edges (but blkn gets
  164348. * incremented past them!). Note the inner loop relies on having
  164349. * allocated the MCU_buffer[] blocks sequentially.
  164350. */
  164351. blkn = 0; /* index of current DCT block within MCU */
  164352. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164353. compptr = cinfo->cur_comp_info[ci];
  164354. /* Don't bother to IDCT an uninteresting component. */
  164355. if (! compptr->component_needed) {
  164356. blkn += compptr->MCU_blocks;
  164357. continue;
  164358. }
  164359. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  164360. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  164361. : compptr->last_col_width;
  164362. output_ptr = output_buf[compptr->component_index] +
  164363. yoffset * compptr->DCT_scaled_size;
  164364. start_col = MCU_col_num * compptr->MCU_sample_width;
  164365. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164366. if (cinfo->input_iMCU_row < last_iMCU_row ||
  164367. yoffset+yindex < compptr->last_row_height) {
  164368. output_col = start_col;
  164369. for (xindex = 0; xindex < useful_width; xindex++) {
  164370. (*inverse_DCT) (cinfo, compptr,
  164371. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  164372. output_ptr, output_col);
  164373. output_col += compptr->DCT_scaled_size;
  164374. }
  164375. }
  164376. blkn += compptr->MCU_width;
  164377. output_ptr += compptr->DCT_scaled_size;
  164378. }
  164379. }
  164380. }
  164381. /* Completed an MCU row, but perhaps not an iMCU row */
  164382. coef->MCU_ctr = 0;
  164383. }
  164384. /* Completed the iMCU row, advance counters for next one */
  164385. cinfo->output_iMCU_row++;
  164386. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164387. start_iMCU_row3(cinfo);
  164388. return JPEG_ROW_COMPLETED;
  164389. }
  164390. /* Completed the scan */
  164391. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164392. return JPEG_SCAN_COMPLETED;
  164393. }
  164394. /*
  164395. * Dummy consume-input routine for single-pass operation.
  164396. */
  164397. METHODDEF(int)
  164398. dummy_consume_data (j_decompress_ptr cinfo)
  164399. {
  164400. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  164401. }
  164402. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164403. /*
  164404. * Consume input data and store it in the full-image coefficient buffer.
  164405. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  164406. * ie, v_samp_factor block rows for each component in the scan.
  164407. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164408. */
  164409. METHODDEF(int)
  164410. consume_data (j_decompress_ptr cinfo)
  164411. {
  164412. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164413. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164414. int blkn, ci, xindex, yindex, yoffset;
  164415. JDIMENSION start_col;
  164416. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  164417. JBLOCKROW buffer_ptr;
  164418. jpeg_component_info *compptr;
  164419. /* Align the virtual buffers for the components used in this scan. */
  164420. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164421. compptr = cinfo->cur_comp_info[ci];
  164422. buffer[ci] = (*cinfo->mem->access_virt_barray)
  164423. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  164424. cinfo->input_iMCU_row * compptr->v_samp_factor,
  164425. (JDIMENSION) compptr->v_samp_factor, TRUE);
  164426. /* Note: entropy decoder expects buffer to be zeroed,
  164427. * but this is handled automatically by the memory manager
  164428. * because we requested a pre-zeroed array.
  164429. */
  164430. }
  164431. /* Loop to process one whole iMCU row */
  164432. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164433. yoffset++) {
  164434. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  164435. MCU_col_num++) {
  164436. /* Construct list of pointers to DCT blocks belonging to this MCU */
  164437. blkn = 0; /* index of current DCT block within MCU */
  164438. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164439. compptr = cinfo->cur_comp_info[ci];
  164440. start_col = MCU_col_num * compptr->MCU_width;
  164441. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164442. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  164443. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  164444. coef->MCU_buffer[blkn++] = buffer_ptr++;
  164445. }
  164446. }
  164447. }
  164448. /* Try to fetch the MCU. */
  164449. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164450. /* Suspension forced; update state counters and exit */
  164451. coef->MCU_vert_offset = yoffset;
  164452. coef->MCU_ctr = MCU_col_num;
  164453. return JPEG_SUSPENDED;
  164454. }
  164455. }
  164456. /* Completed an MCU row, but perhaps not an iMCU row */
  164457. coef->MCU_ctr = 0;
  164458. }
  164459. /* Completed the iMCU row, advance counters for next one */
  164460. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164461. start_iMCU_row3(cinfo);
  164462. return JPEG_ROW_COMPLETED;
  164463. }
  164464. /* Completed the scan */
  164465. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164466. return JPEG_SCAN_COMPLETED;
  164467. }
  164468. /*
  164469. * Decompress and return some data in the multi-pass case.
  164470. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164471. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164472. *
  164473. * NB: output_buf contains a plane for each component in image.
  164474. */
  164475. METHODDEF(int)
  164476. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164477. {
  164478. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164479. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164480. JDIMENSION block_num;
  164481. int ci, block_row, block_rows;
  164482. JBLOCKARRAY buffer;
  164483. JBLOCKROW buffer_ptr;
  164484. JSAMPARRAY output_ptr;
  164485. JDIMENSION output_col;
  164486. jpeg_component_info *compptr;
  164487. inverse_DCT_method_ptr inverse_DCT;
  164488. /* Force some input to be done if we are getting ahead of the input. */
  164489. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  164490. (cinfo->input_scan_number == cinfo->output_scan_number &&
  164491. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  164492. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164493. return JPEG_SUSPENDED;
  164494. }
  164495. /* OK, output from the virtual arrays. */
  164496. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164497. ci++, compptr++) {
  164498. /* Don't bother to IDCT an uninteresting component. */
  164499. if (! compptr->component_needed)
  164500. continue;
  164501. /* Align the virtual buffer for this component. */
  164502. buffer = (*cinfo->mem->access_virt_barray)
  164503. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164504. cinfo->output_iMCU_row * compptr->v_samp_factor,
  164505. (JDIMENSION) compptr->v_samp_factor, FALSE);
  164506. /* Count non-dummy DCT block rows in this iMCU row. */
  164507. if (cinfo->output_iMCU_row < last_iMCU_row)
  164508. block_rows = compptr->v_samp_factor;
  164509. else {
  164510. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164511. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164512. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164513. }
  164514. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164515. output_ptr = output_buf[ci];
  164516. /* Loop over all DCT blocks to be processed. */
  164517. for (block_row = 0; block_row < block_rows; block_row++) {
  164518. buffer_ptr = buffer[block_row];
  164519. output_col = 0;
  164520. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  164521. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  164522. output_ptr, output_col);
  164523. buffer_ptr++;
  164524. output_col += compptr->DCT_scaled_size;
  164525. }
  164526. output_ptr += compptr->DCT_scaled_size;
  164527. }
  164528. }
  164529. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164530. return JPEG_ROW_COMPLETED;
  164531. return JPEG_SCAN_COMPLETED;
  164532. }
  164533. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164534. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164535. /*
  164536. * This code applies interblock smoothing as described by section K.8
  164537. * of the JPEG standard: the first 5 AC coefficients are estimated from
  164538. * the DC values of a DCT block and its 8 neighboring blocks.
  164539. * We apply smoothing only for progressive JPEG decoding, and only if
  164540. * the coefficients it can estimate are not yet known to full precision.
  164541. */
  164542. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  164543. #define Q01_POS 1
  164544. #define Q10_POS 8
  164545. #define Q20_POS 16
  164546. #define Q11_POS 9
  164547. #define Q02_POS 2
  164548. /*
  164549. * Determine whether block smoothing is applicable and safe.
  164550. * We also latch the current states of the coef_bits[] entries for the
  164551. * AC coefficients; otherwise, if the input side of the decompressor
  164552. * advances into a new scan, we might think the coefficients are known
  164553. * more accurately than they really are.
  164554. */
  164555. LOCAL(boolean)
  164556. smoothing_ok (j_decompress_ptr cinfo)
  164557. {
  164558. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164559. boolean smoothing_useful = FALSE;
  164560. int ci, coefi;
  164561. jpeg_component_info *compptr;
  164562. JQUANT_TBL * qtable;
  164563. int * coef_bits;
  164564. int * coef_bits_latch;
  164565. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  164566. return FALSE;
  164567. /* Allocate latch area if not already done */
  164568. if (coef->coef_bits_latch == NULL)
  164569. coef->coef_bits_latch = (int *)
  164570. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164571. cinfo->num_components *
  164572. (SAVED_COEFS * SIZEOF(int)));
  164573. coef_bits_latch = coef->coef_bits_latch;
  164574. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164575. ci++, compptr++) {
  164576. /* All components' quantization values must already be latched. */
  164577. if ((qtable = compptr->quant_table) == NULL)
  164578. return FALSE;
  164579. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  164580. if (qtable->quantval[0] == 0 ||
  164581. qtable->quantval[Q01_POS] == 0 ||
  164582. qtable->quantval[Q10_POS] == 0 ||
  164583. qtable->quantval[Q20_POS] == 0 ||
  164584. qtable->quantval[Q11_POS] == 0 ||
  164585. qtable->quantval[Q02_POS] == 0)
  164586. return FALSE;
  164587. /* DC values must be at least partly known for all components. */
  164588. coef_bits = cinfo->coef_bits[ci];
  164589. if (coef_bits[0] < 0)
  164590. return FALSE;
  164591. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  164592. for (coefi = 1; coefi <= 5; coefi++) {
  164593. coef_bits_latch[coefi] = coef_bits[coefi];
  164594. if (coef_bits[coefi] != 0)
  164595. smoothing_useful = TRUE;
  164596. }
  164597. coef_bits_latch += SAVED_COEFS;
  164598. }
  164599. return smoothing_useful;
  164600. }
  164601. /*
  164602. * Variant of decompress_data for use when doing block smoothing.
  164603. */
  164604. METHODDEF(int)
  164605. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164606. {
  164607. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164608. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164609. JDIMENSION block_num, last_block_column;
  164610. int ci, block_row, block_rows, access_rows;
  164611. JBLOCKARRAY buffer;
  164612. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  164613. JSAMPARRAY output_ptr;
  164614. JDIMENSION output_col;
  164615. jpeg_component_info *compptr;
  164616. inverse_DCT_method_ptr inverse_DCT;
  164617. boolean first_row, last_row;
  164618. JBLOCK workspace;
  164619. int *coef_bits;
  164620. JQUANT_TBL *quanttbl;
  164621. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  164622. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  164623. int Al, pred;
  164624. /* Force some input to be done if we are getting ahead of the input. */
  164625. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164626. ! cinfo->inputctl->eoi_reached) {
  164627. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  164628. /* If input is working on current scan, we ordinarily want it to
  164629. * have completed the current row. But if input scan is DC,
  164630. * we want it to keep one row ahead so that next block row's DC
  164631. * values are up to date.
  164632. */
  164633. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  164634. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  164635. break;
  164636. }
  164637. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164638. return JPEG_SUSPENDED;
  164639. }
  164640. /* OK, output from the virtual arrays. */
  164641. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164642. ci++, compptr++) {
  164643. /* Don't bother to IDCT an uninteresting component. */
  164644. if (! compptr->component_needed)
  164645. continue;
  164646. /* Count non-dummy DCT block rows in this iMCU row. */
  164647. if (cinfo->output_iMCU_row < last_iMCU_row) {
  164648. block_rows = compptr->v_samp_factor;
  164649. access_rows = block_rows * 2; /* this and next iMCU row */
  164650. last_row = FALSE;
  164651. } else {
  164652. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164653. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164654. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164655. access_rows = block_rows; /* this iMCU row only */
  164656. last_row = TRUE;
  164657. }
  164658. /* Align the virtual buffer for this component. */
  164659. if (cinfo->output_iMCU_row > 0) {
  164660. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  164661. buffer = (*cinfo->mem->access_virt_barray)
  164662. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164663. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  164664. (JDIMENSION) access_rows, FALSE);
  164665. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  164666. first_row = FALSE;
  164667. } else {
  164668. buffer = (*cinfo->mem->access_virt_barray)
  164669. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164670. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  164671. first_row = TRUE;
  164672. }
  164673. /* Fetch component-dependent info */
  164674. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  164675. quanttbl = compptr->quant_table;
  164676. Q00 = quanttbl->quantval[0];
  164677. Q01 = quanttbl->quantval[Q01_POS];
  164678. Q10 = quanttbl->quantval[Q10_POS];
  164679. Q20 = quanttbl->quantval[Q20_POS];
  164680. Q11 = quanttbl->quantval[Q11_POS];
  164681. Q02 = quanttbl->quantval[Q02_POS];
  164682. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164683. output_ptr = output_buf[ci];
  164684. /* Loop over all DCT blocks to be processed. */
  164685. for (block_row = 0; block_row < block_rows; block_row++) {
  164686. buffer_ptr = buffer[block_row];
  164687. if (first_row && block_row == 0)
  164688. prev_block_row = buffer_ptr;
  164689. else
  164690. prev_block_row = buffer[block_row-1];
  164691. if (last_row && block_row == block_rows-1)
  164692. next_block_row = buffer_ptr;
  164693. else
  164694. next_block_row = buffer[block_row+1];
  164695. /* We fetch the surrounding DC values using a sliding-register approach.
  164696. * Initialize all nine here so as to do the right thing on narrow pics.
  164697. */
  164698. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  164699. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  164700. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  164701. output_col = 0;
  164702. last_block_column = compptr->width_in_blocks - 1;
  164703. for (block_num = 0; block_num <= last_block_column; block_num++) {
  164704. /* Fetch current DCT block into workspace so we can modify it. */
  164705. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  164706. /* Update DC values */
  164707. if (block_num < last_block_column) {
  164708. DC3 = (int) prev_block_row[1][0];
  164709. DC6 = (int) buffer_ptr[1][0];
  164710. DC9 = (int) next_block_row[1][0];
  164711. }
  164712. /* Compute coefficient estimates per K.8.
  164713. * An estimate is applied only if coefficient is still zero,
  164714. * and is not known to be fully accurate.
  164715. */
  164716. /* AC01 */
  164717. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  164718. num = 36 * Q00 * (DC4 - DC6);
  164719. if (num >= 0) {
  164720. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  164721. if (Al > 0 && pred >= (1<<Al))
  164722. pred = (1<<Al)-1;
  164723. } else {
  164724. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  164725. if (Al > 0 && pred >= (1<<Al))
  164726. pred = (1<<Al)-1;
  164727. pred = -pred;
  164728. }
  164729. workspace[1] = (JCOEF) pred;
  164730. }
  164731. /* AC10 */
  164732. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  164733. num = 36 * Q00 * (DC2 - DC8);
  164734. if (num >= 0) {
  164735. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  164736. if (Al > 0 && pred >= (1<<Al))
  164737. pred = (1<<Al)-1;
  164738. } else {
  164739. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  164740. if (Al > 0 && pred >= (1<<Al))
  164741. pred = (1<<Al)-1;
  164742. pred = -pred;
  164743. }
  164744. workspace[8] = (JCOEF) pred;
  164745. }
  164746. /* AC20 */
  164747. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  164748. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  164749. if (num >= 0) {
  164750. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  164751. if (Al > 0 && pred >= (1<<Al))
  164752. pred = (1<<Al)-1;
  164753. } else {
  164754. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  164755. if (Al > 0 && pred >= (1<<Al))
  164756. pred = (1<<Al)-1;
  164757. pred = -pred;
  164758. }
  164759. workspace[16] = (JCOEF) pred;
  164760. }
  164761. /* AC11 */
  164762. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  164763. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  164764. if (num >= 0) {
  164765. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  164766. if (Al > 0 && pred >= (1<<Al))
  164767. pred = (1<<Al)-1;
  164768. } else {
  164769. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  164770. if (Al > 0 && pred >= (1<<Al))
  164771. pred = (1<<Al)-1;
  164772. pred = -pred;
  164773. }
  164774. workspace[9] = (JCOEF) pred;
  164775. }
  164776. /* AC02 */
  164777. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  164778. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  164779. if (num >= 0) {
  164780. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  164781. if (Al > 0 && pred >= (1<<Al))
  164782. pred = (1<<Al)-1;
  164783. } else {
  164784. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  164785. if (Al > 0 && pred >= (1<<Al))
  164786. pred = (1<<Al)-1;
  164787. pred = -pred;
  164788. }
  164789. workspace[2] = (JCOEF) pred;
  164790. }
  164791. /* OK, do the IDCT */
  164792. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  164793. output_ptr, output_col);
  164794. /* Advance for next column */
  164795. DC1 = DC2; DC2 = DC3;
  164796. DC4 = DC5; DC5 = DC6;
  164797. DC7 = DC8; DC8 = DC9;
  164798. buffer_ptr++, prev_block_row++, next_block_row++;
  164799. output_col += compptr->DCT_scaled_size;
  164800. }
  164801. output_ptr += compptr->DCT_scaled_size;
  164802. }
  164803. }
  164804. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164805. return JPEG_ROW_COMPLETED;
  164806. return JPEG_SCAN_COMPLETED;
  164807. }
  164808. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  164809. /*
  164810. * Initialize coefficient buffer controller.
  164811. */
  164812. GLOBAL(void)
  164813. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  164814. {
  164815. my_coef_ptr3 coef;
  164816. coef = (my_coef_ptr3)
  164817. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164818. SIZEOF(my_coef_controller3));
  164819. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  164820. coef->pub.start_input_pass = start_input_pass;
  164821. coef->pub.start_output_pass = start_output_pass;
  164822. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164823. coef->coef_bits_latch = NULL;
  164824. #endif
  164825. /* Create the coefficient buffer. */
  164826. if (need_full_buffer) {
  164827. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164828. /* Allocate a full-image virtual array for each component, */
  164829. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  164830. /* Note we ask for a pre-zeroed array. */
  164831. int ci, access_rows;
  164832. jpeg_component_info *compptr;
  164833. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164834. ci++, compptr++) {
  164835. access_rows = compptr->v_samp_factor;
  164836. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164837. /* If block smoothing could be used, need a bigger window */
  164838. if (cinfo->progressive_mode)
  164839. access_rows *= 3;
  164840. #endif
  164841. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  164842. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  164843. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  164844. (long) compptr->h_samp_factor),
  164845. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164846. (long) compptr->v_samp_factor),
  164847. (JDIMENSION) access_rows);
  164848. }
  164849. coef->pub.consume_data = consume_data;
  164850. coef->pub.decompress_data = decompress_data;
  164851. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  164852. #else
  164853. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164854. #endif
  164855. } else {
  164856. /* We only need a single-MCU buffer. */
  164857. JBLOCKROW buffer;
  164858. int i;
  164859. buffer = (JBLOCKROW)
  164860. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164861. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164862. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  164863. coef->MCU_buffer[i] = buffer + i;
  164864. }
  164865. coef->pub.consume_data = dummy_consume_data;
  164866. coef->pub.decompress_data = decompress_onepass;
  164867. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  164868. }
  164869. }
  164870. /********* End of inlined file: jdcoefct.c *********/
  164871. #undef FIX
  164872. /********* Start of inlined file: jdcolor.c *********/
  164873. #define JPEG_INTERNALS
  164874. /* Private subobject */
  164875. typedef struct {
  164876. struct jpeg_color_deconverter pub; /* public fields */
  164877. /* Private state for YCC->RGB conversion */
  164878. int * Cr_r_tab; /* => table for Cr to R conversion */
  164879. int * Cb_b_tab; /* => table for Cb to B conversion */
  164880. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  164881. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  164882. } my_color_deconverter2;
  164883. typedef my_color_deconverter2 * my_cconvert_ptr2;
  164884. /**************** YCbCr -> RGB conversion: most common case **************/
  164885. /*
  164886. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  164887. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  164888. * The conversion equations to be implemented are therefore
  164889. * R = Y + 1.40200 * Cr
  164890. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  164891. * B = Y + 1.77200 * Cb
  164892. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  164893. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  164894. *
  164895. * To avoid floating-point arithmetic, we represent the fractional constants
  164896. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  164897. * the products by 2^16, with appropriate rounding, to get the correct answer.
  164898. * Notice that Y, being an integral input, does not contribute any fraction
  164899. * so it need not participate in the rounding.
  164900. *
  164901. * For even more speed, we avoid doing any multiplications in the inner loop
  164902. * by precalculating the constants times Cb and Cr for all possible values.
  164903. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  164904. * for 12-bit samples it is still acceptable. It's not very reasonable for
  164905. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  164906. * colorspace anyway.
  164907. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  164908. * values for the G calculation are left scaled up, since we must add them
  164909. * together before rounding.
  164910. */
  164911. #define SCALEBITS 16 /* speediest right-shift on some machines */
  164912. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  164913. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  164914. /*
  164915. * Initialize tables for YCC->RGB colorspace conversion.
  164916. */
  164917. LOCAL(void)
  164918. build_ycc_rgb_table (j_decompress_ptr cinfo)
  164919. {
  164920. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164921. int i;
  164922. INT32 x;
  164923. SHIFT_TEMPS
  164924. cconvert->Cr_r_tab = (int *)
  164925. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164926. (MAXJSAMPLE+1) * SIZEOF(int));
  164927. cconvert->Cb_b_tab = (int *)
  164928. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164929. (MAXJSAMPLE+1) * SIZEOF(int));
  164930. cconvert->Cr_g_tab = (INT32 *)
  164931. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164932. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164933. cconvert->Cb_g_tab = (INT32 *)
  164934. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164935. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164936. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  164937. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  164938. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  164939. /* Cr=>R value is nearest int to 1.40200 * x */
  164940. cconvert->Cr_r_tab[i] = (int)
  164941. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  164942. /* Cb=>B value is nearest int to 1.77200 * x */
  164943. cconvert->Cb_b_tab[i] = (int)
  164944. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  164945. /* Cr=>G value is scaled-up -0.71414 * x */
  164946. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  164947. /* Cb=>G value is scaled-up -0.34414 * x */
  164948. /* We also add in ONE_HALF so that need not do it in inner loop */
  164949. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  164950. }
  164951. }
  164952. /*
  164953. * Convert some rows of samples to the output colorspace.
  164954. *
  164955. * Note that we change from noninterleaved, one-plane-per-component format
  164956. * to interleaved-pixel format. The output buffer is therefore three times
  164957. * as wide as the input buffer.
  164958. * A starting row offset is provided only for the input buffer. The caller
  164959. * can easily adjust the passed output_buf value to accommodate any row
  164960. * offset required on that side.
  164961. */
  164962. METHODDEF(void)
  164963. ycc_rgb_convert (j_decompress_ptr cinfo,
  164964. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164965. JSAMPARRAY output_buf, int num_rows)
  164966. {
  164967. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164968. register int y, cb, cr;
  164969. register JSAMPROW outptr;
  164970. register JSAMPROW inptr0, inptr1, inptr2;
  164971. register JDIMENSION col;
  164972. JDIMENSION num_cols = cinfo->output_width;
  164973. /* copy these pointers into registers if possible */
  164974. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164975. register int * Crrtab = cconvert->Cr_r_tab;
  164976. register int * Cbbtab = cconvert->Cb_b_tab;
  164977. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164978. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164979. SHIFT_TEMPS
  164980. while (--num_rows >= 0) {
  164981. inptr0 = input_buf[0][input_row];
  164982. inptr1 = input_buf[1][input_row];
  164983. inptr2 = input_buf[2][input_row];
  164984. input_row++;
  164985. outptr = *output_buf++;
  164986. for (col = 0; col < num_cols; col++) {
  164987. y = GETJSAMPLE(inptr0[col]);
  164988. cb = GETJSAMPLE(inptr1[col]);
  164989. cr = GETJSAMPLE(inptr2[col]);
  164990. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164991. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  164992. outptr[RGB_GREEN] = range_limit[y +
  164993. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164994. SCALEBITS))];
  164995. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  164996. outptr += RGB_PIXELSIZE;
  164997. }
  164998. }
  164999. }
  165000. /**************** Cases other than YCbCr -> RGB **************/
  165001. /*
  165002. * Color conversion for no colorspace change: just copy the data,
  165003. * converting from separate-planes to interleaved representation.
  165004. */
  165005. METHODDEF(void)
  165006. null_convert2 (j_decompress_ptr cinfo,
  165007. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165008. JSAMPARRAY output_buf, int num_rows)
  165009. {
  165010. register JSAMPROW inptr, outptr;
  165011. register JDIMENSION count;
  165012. register int num_components = cinfo->num_components;
  165013. JDIMENSION num_cols = cinfo->output_width;
  165014. int ci;
  165015. while (--num_rows >= 0) {
  165016. for (ci = 0; ci < num_components; ci++) {
  165017. inptr = input_buf[ci][input_row];
  165018. outptr = output_buf[0] + ci;
  165019. for (count = num_cols; count > 0; count--) {
  165020. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  165021. outptr += num_components;
  165022. }
  165023. }
  165024. input_row++;
  165025. output_buf++;
  165026. }
  165027. }
  165028. /*
  165029. * Color conversion for grayscale: just copy the data.
  165030. * This also works for YCbCr -> grayscale conversion, in which
  165031. * we just copy the Y (luminance) component and ignore chrominance.
  165032. */
  165033. METHODDEF(void)
  165034. grayscale_convert2 (j_decompress_ptr cinfo,
  165035. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165036. JSAMPARRAY output_buf, int num_rows)
  165037. {
  165038. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  165039. num_rows, cinfo->output_width);
  165040. }
  165041. /*
  165042. * Convert grayscale to RGB: just duplicate the graylevel three times.
  165043. * This is provided to support applications that don't want to cope
  165044. * with grayscale as a separate case.
  165045. */
  165046. METHODDEF(void)
  165047. gray_rgb_convert (j_decompress_ptr cinfo,
  165048. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165049. JSAMPARRAY output_buf, int num_rows)
  165050. {
  165051. register JSAMPROW inptr, outptr;
  165052. register JDIMENSION col;
  165053. JDIMENSION num_cols = cinfo->output_width;
  165054. while (--num_rows >= 0) {
  165055. inptr = input_buf[0][input_row++];
  165056. outptr = *output_buf++;
  165057. for (col = 0; col < num_cols; col++) {
  165058. /* We can dispense with GETJSAMPLE() here */
  165059. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  165060. outptr += RGB_PIXELSIZE;
  165061. }
  165062. }
  165063. }
  165064. /*
  165065. * Adobe-style YCCK->CMYK conversion.
  165066. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  165067. * conversion as above, while passing K (black) unchanged.
  165068. * We assume build_ycc_rgb_table has been called.
  165069. */
  165070. METHODDEF(void)
  165071. ycck_cmyk_convert (j_decompress_ptr cinfo,
  165072. JSAMPIMAGE input_buf, JDIMENSION input_row,
  165073. JSAMPARRAY output_buf, int num_rows)
  165074. {
  165075. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  165076. register int y, cb, cr;
  165077. register JSAMPROW outptr;
  165078. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  165079. register JDIMENSION col;
  165080. JDIMENSION num_cols = cinfo->output_width;
  165081. /* copy these pointers into registers if possible */
  165082. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  165083. register int * Crrtab = cconvert->Cr_r_tab;
  165084. register int * Cbbtab = cconvert->Cb_b_tab;
  165085. register INT32 * Crgtab = cconvert->Cr_g_tab;
  165086. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  165087. SHIFT_TEMPS
  165088. while (--num_rows >= 0) {
  165089. inptr0 = input_buf[0][input_row];
  165090. inptr1 = input_buf[1][input_row];
  165091. inptr2 = input_buf[2][input_row];
  165092. inptr3 = input_buf[3][input_row];
  165093. input_row++;
  165094. outptr = *output_buf++;
  165095. for (col = 0; col < num_cols; col++) {
  165096. y = GETJSAMPLE(inptr0[col]);
  165097. cb = GETJSAMPLE(inptr1[col]);
  165098. cr = GETJSAMPLE(inptr2[col]);
  165099. /* Range-limiting is essential due to noise introduced by DCT losses. */
  165100. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  165101. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  165102. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  165103. SCALEBITS)))];
  165104. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  165105. /* K passes through unchanged */
  165106. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  165107. outptr += 4;
  165108. }
  165109. }
  165110. }
  165111. /*
  165112. * Empty method for start_pass.
  165113. */
  165114. METHODDEF(void)
  165115. start_pass_dcolor (j_decompress_ptr cinfo)
  165116. {
  165117. /* no work needed */
  165118. }
  165119. /*
  165120. * Module initialization routine for output colorspace conversion.
  165121. */
  165122. GLOBAL(void)
  165123. jinit_color_deconverter (j_decompress_ptr cinfo)
  165124. {
  165125. my_cconvert_ptr2 cconvert;
  165126. int ci;
  165127. cconvert = (my_cconvert_ptr2)
  165128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165129. SIZEOF(my_color_deconverter2));
  165130. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  165131. cconvert->pub.start_pass = start_pass_dcolor;
  165132. /* Make sure num_components agrees with jpeg_color_space */
  165133. switch (cinfo->jpeg_color_space) {
  165134. case JCS_GRAYSCALE:
  165135. if (cinfo->num_components != 1)
  165136. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165137. break;
  165138. case JCS_RGB:
  165139. case JCS_YCbCr:
  165140. if (cinfo->num_components != 3)
  165141. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165142. break;
  165143. case JCS_CMYK:
  165144. case JCS_YCCK:
  165145. if (cinfo->num_components != 4)
  165146. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165147. break;
  165148. default: /* JCS_UNKNOWN can be anything */
  165149. if (cinfo->num_components < 1)
  165150. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165151. break;
  165152. }
  165153. /* Set out_color_components and conversion method based on requested space.
  165154. * Also clear the component_needed flags for any unused components,
  165155. * so that earlier pipeline stages can avoid useless computation.
  165156. */
  165157. switch (cinfo->out_color_space) {
  165158. case JCS_GRAYSCALE:
  165159. cinfo->out_color_components = 1;
  165160. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  165161. cinfo->jpeg_color_space == JCS_YCbCr) {
  165162. cconvert->pub.color_convert = grayscale_convert2;
  165163. /* For color->grayscale conversion, only the Y (0) component is needed */
  165164. for (ci = 1; ci < cinfo->num_components; ci++)
  165165. cinfo->comp_info[ci].component_needed = FALSE;
  165166. } else
  165167. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165168. break;
  165169. case JCS_RGB:
  165170. cinfo->out_color_components = RGB_PIXELSIZE;
  165171. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  165172. cconvert->pub.color_convert = ycc_rgb_convert;
  165173. build_ycc_rgb_table(cinfo);
  165174. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  165175. cconvert->pub.color_convert = gray_rgb_convert;
  165176. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  165177. cconvert->pub.color_convert = null_convert2;
  165178. } else
  165179. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165180. break;
  165181. case JCS_CMYK:
  165182. cinfo->out_color_components = 4;
  165183. if (cinfo->jpeg_color_space == JCS_YCCK) {
  165184. cconvert->pub.color_convert = ycck_cmyk_convert;
  165185. build_ycc_rgb_table(cinfo);
  165186. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  165187. cconvert->pub.color_convert = null_convert2;
  165188. } else
  165189. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165190. break;
  165191. default:
  165192. /* Permit null conversion to same output space */
  165193. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  165194. cinfo->out_color_components = cinfo->num_components;
  165195. cconvert->pub.color_convert = null_convert2;
  165196. } else /* unsupported non-null conversion */
  165197. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165198. break;
  165199. }
  165200. if (cinfo->quantize_colors)
  165201. cinfo->output_components = 1; /* single colormapped output component */
  165202. else
  165203. cinfo->output_components = cinfo->out_color_components;
  165204. }
  165205. /********* End of inlined file: jdcolor.c *********/
  165206. #undef FIX
  165207. /********* Start of inlined file: jddctmgr.c *********/
  165208. #define JPEG_INTERNALS
  165209. /*
  165210. * The decompressor input side (jdinput.c) saves away the appropriate
  165211. * quantization table for each component at the start of the first scan
  165212. * involving that component. (This is necessary in order to correctly
  165213. * decode files that reuse Q-table slots.)
  165214. * When we are ready to make an output pass, the saved Q-table is converted
  165215. * to a multiplier table that will actually be used by the IDCT routine.
  165216. * The multiplier table contents are IDCT-method-dependent. To support
  165217. * application changes in IDCT method between scans, we can remake the
  165218. * multiplier tables if necessary.
  165219. * In buffered-image mode, the first output pass may occur before any data
  165220. * has been seen for some components, and thus before their Q-tables have
  165221. * been saved away. To handle this case, multiplier tables are preset
  165222. * to zeroes; the result of the IDCT will be a neutral gray level.
  165223. */
  165224. /* Private subobject for this module */
  165225. typedef struct {
  165226. struct jpeg_inverse_dct pub; /* public fields */
  165227. /* This array contains the IDCT method code that each multiplier table
  165228. * is currently set up for, or -1 if it's not yet set up.
  165229. * The actual multiplier tables are pointed to by dct_table in the
  165230. * per-component comp_info structures.
  165231. */
  165232. int cur_method[MAX_COMPONENTS];
  165233. } my_idct_controller;
  165234. typedef my_idct_controller * my_idct_ptr;
  165235. /* Allocated multiplier tables: big enough for any supported variant */
  165236. typedef union {
  165237. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  165238. #ifdef DCT_IFAST_SUPPORTED
  165239. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  165240. #endif
  165241. #ifdef DCT_FLOAT_SUPPORTED
  165242. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  165243. #endif
  165244. } multiplier_table;
  165245. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  165246. * so be sure to compile that code if either ISLOW or SCALING is requested.
  165247. */
  165248. #ifdef DCT_ISLOW_SUPPORTED
  165249. #define PROVIDE_ISLOW_TABLES
  165250. #else
  165251. #ifdef IDCT_SCALING_SUPPORTED
  165252. #define PROVIDE_ISLOW_TABLES
  165253. #endif
  165254. #endif
  165255. /*
  165256. * Prepare for an output pass.
  165257. * Here we select the proper IDCT routine for each component and build
  165258. * a matching multiplier table.
  165259. */
  165260. METHODDEF(void)
  165261. start_pass (j_decompress_ptr cinfo)
  165262. {
  165263. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  165264. int ci, i;
  165265. jpeg_component_info *compptr;
  165266. int method = 0;
  165267. inverse_DCT_method_ptr method_ptr = NULL;
  165268. JQUANT_TBL * qtbl;
  165269. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165270. ci++, compptr++) {
  165271. /* Select the proper IDCT routine for this component's scaling */
  165272. switch (compptr->DCT_scaled_size) {
  165273. #ifdef IDCT_SCALING_SUPPORTED
  165274. case 1:
  165275. method_ptr = jpeg_idct_1x1;
  165276. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165277. break;
  165278. case 2:
  165279. method_ptr = jpeg_idct_2x2;
  165280. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165281. break;
  165282. case 4:
  165283. method_ptr = jpeg_idct_4x4;
  165284. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165285. break;
  165286. #endif
  165287. case DCTSIZE:
  165288. switch (cinfo->dct_method) {
  165289. #ifdef DCT_ISLOW_SUPPORTED
  165290. case JDCT_ISLOW:
  165291. method_ptr = jpeg_idct_islow;
  165292. method = JDCT_ISLOW;
  165293. break;
  165294. #endif
  165295. #ifdef DCT_IFAST_SUPPORTED
  165296. case JDCT_IFAST:
  165297. method_ptr = jpeg_idct_ifast;
  165298. method = JDCT_IFAST;
  165299. break;
  165300. #endif
  165301. #ifdef DCT_FLOAT_SUPPORTED
  165302. case JDCT_FLOAT:
  165303. method_ptr = jpeg_idct_float;
  165304. method = JDCT_FLOAT;
  165305. break;
  165306. #endif
  165307. default:
  165308. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165309. break;
  165310. }
  165311. break;
  165312. default:
  165313. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  165314. break;
  165315. }
  165316. idct->pub.inverse_DCT[ci] = method_ptr;
  165317. /* Create multiplier table from quant table.
  165318. * However, we can skip this if the component is uninteresting
  165319. * or if we already built the table. Also, if no quant table
  165320. * has yet been saved for the component, we leave the
  165321. * multiplier table all-zero; we'll be reading zeroes from the
  165322. * coefficient controller's buffer anyway.
  165323. */
  165324. if (! compptr->component_needed || idct->cur_method[ci] == method)
  165325. continue;
  165326. qtbl = compptr->quant_table;
  165327. if (qtbl == NULL) /* happens if no data yet for component */
  165328. continue;
  165329. idct->cur_method[ci] = method;
  165330. switch (method) {
  165331. #ifdef PROVIDE_ISLOW_TABLES
  165332. case JDCT_ISLOW:
  165333. {
  165334. /* For LL&M IDCT method, multipliers are equal to raw quantization
  165335. * coefficients, but are stored as ints to ensure access efficiency.
  165336. */
  165337. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  165338. for (i = 0; i < DCTSIZE2; i++) {
  165339. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  165340. }
  165341. }
  165342. break;
  165343. #endif
  165344. #ifdef DCT_IFAST_SUPPORTED
  165345. case JDCT_IFAST:
  165346. {
  165347. /* For AA&N IDCT method, multipliers are equal to quantization
  165348. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165349. * scalefactor[0] = 1
  165350. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165351. * For integer operation, the multiplier table is to be scaled by
  165352. * IFAST_SCALE_BITS.
  165353. */
  165354. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  165355. #define CONST_BITS 14
  165356. static const INT16 aanscales[DCTSIZE2] = {
  165357. /* precomputed values scaled up by 14 bits */
  165358. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165359. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  165360. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  165361. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  165362. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165363. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  165364. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  165365. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  165366. };
  165367. SHIFT_TEMPS
  165368. for (i = 0; i < DCTSIZE2; i++) {
  165369. ifmtbl[i] = (IFAST_MULT_TYPE)
  165370. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  165371. (INT32) aanscales[i]),
  165372. CONST_BITS-IFAST_SCALE_BITS);
  165373. }
  165374. }
  165375. break;
  165376. #endif
  165377. #ifdef DCT_FLOAT_SUPPORTED
  165378. case JDCT_FLOAT:
  165379. {
  165380. /* For float AA&N IDCT method, multipliers are equal to quantization
  165381. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165382. * scalefactor[0] = 1
  165383. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165384. */
  165385. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  165386. int row, col;
  165387. static const double aanscalefactor[DCTSIZE] = {
  165388. 1.0, 1.387039845, 1.306562965, 1.175875602,
  165389. 1.0, 0.785694958, 0.541196100, 0.275899379
  165390. };
  165391. i = 0;
  165392. for (row = 0; row < DCTSIZE; row++) {
  165393. for (col = 0; col < DCTSIZE; col++) {
  165394. fmtbl[i] = (FLOAT_MULT_TYPE)
  165395. ((double) qtbl->quantval[i] *
  165396. aanscalefactor[row] * aanscalefactor[col]);
  165397. i++;
  165398. }
  165399. }
  165400. }
  165401. break;
  165402. #endif
  165403. default:
  165404. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165405. break;
  165406. }
  165407. }
  165408. }
  165409. /*
  165410. * Initialize IDCT manager.
  165411. */
  165412. GLOBAL(void)
  165413. jinit_inverse_dct (j_decompress_ptr cinfo)
  165414. {
  165415. my_idct_ptr idct;
  165416. int ci;
  165417. jpeg_component_info *compptr;
  165418. idct = (my_idct_ptr)
  165419. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165420. SIZEOF(my_idct_controller));
  165421. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  165422. idct->pub.start_pass = start_pass;
  165423. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165424. ci++, compptr++) {
  165425. /* Allocate and pre-zero a multiplier table for each component */
  165426. compptr->dct_table =
  165427. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165428. SIZEOF(multiplier_table));
  165429. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  165430. /* Mark multiplier table not yet set up for any method */
  165431. idct->cur_method[ci] = -1;
  165432. }
  165433. }
  165434. /********* End of inlined file: jddctmgr.c *********/
  165435. #undef CONST_BITS
  165436. #undef ASSIGN_STATE
  165437. /********* Start of inlined file: jdhuff.c *********/
  165438. #define JPEG_INTERNALS
  165439. /********* Start of inlined file: jdhuff.h *********/
  165440. /* Short forms of external names for systems with brain-damaged linkers. */
  165441. #ifndef __jdhuff_h__
  165442. #define __jdhuff_h__
  165443. #ifdef NEED_SHORT_EXTERNAL_NAMES
  165444. #define jpeg_make_d_derived_tbl jMkDDerived
  165445. #define jpeg_fill_bit_buffer jFilBitBuf
  165446. #define jpeg_huff_decode jHufDecode
  165447. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  165448. /* Derived data constructed for each Huffman table */
  165449. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  165450. typedef struct {
  165451. /* Basic tables: (element [0] of each array is unused) */
  165452. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  165453. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  165454. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  165455. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  165456. * the smallest code of length k; so given a code of length k, the
  165457. * corresponding symbol is huffval[code + valoffset[k]]
  165458. */
  165459. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  165460. JHUFF_TBL *pub;
  165461. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  165462. * the input data stream. If the next Huffman code is no more
  165463. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  165464. * the corresponding symbol directly from these tables.
  165465. */
  165466. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  165467. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  165468. } d_derived_tbl;
  165469. /* Expand a Huffman table definition into the derived format */
  165470. EXTERN(void) jpeg_make_d_derived_tbl
  165471. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  165472. d_derived_tbl ** pdtbl));
  165473. /*
  165474. * Fetching the next N bits from the input stream is a time-critical operation
  165475. * for the Huffman decoders. We implement it with a combination of inline
  165476. * macros and out-of-line subroutines. Note that N (the number of bits
  165477. * demanded at one time) never exceeds 15 for JPEG use.
  165478. *
  165479. * We read source bytes into get_buffer and dole out bits as needed.
  165480. * If get_buffer already contains enough bits, they are fetched in-line
  165481. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  165482. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  165483. * as full as possible (not just to the number of bits needed; this
  165484. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  165485. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  165486. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  165487. * at least the requested number of bits --- dummy zeroes are inserted if
  165488. * necessary.
  165489. */
  165490. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  165491. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  165492. /* If long is > 32 bits on your machine, and shifting/masking longs is
  165493. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  165494. * appropriately should be a win. Unfortunately we can't define the size
  165495. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  165496. * because not all machines measure sizeof in 8-bit bytes.
  165497. */
  165498. typedef struct { /* Bitreading state saved across MCUs */
  165499. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165500. int bits_left; /* # of unused bits in it */
  165501. } bitread_perm_state;
  165502. typedef struct { /* Bitreading working state within an MCU */
  165503. /* Current data source location */
  165504. /* We need a copy, rather than munging the original, in case of suspension */
  165505. const JOCTET * next_input_byte; /* => next byte to read from source */
  165506. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  165507. /* Bit input buffer --- note these values are kept in register variables,
  165508. * not in this struct, inside the inner loops.
  165509. */
  165510. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165511. int bits_left; /* # of unused bits in it */
  165512. /* Pointer needed by jpeg_fill_bit_buffer. */
  165513. j_decompress_ptr cinfo; /* back link to decompress master record */
  165514. } bitread_working_state;
  165515. /* Macros to declare and load/save bitread local variables. */
  165516. #define BITREAD_STATE_VARS \
  165517. register bit_buf_type get_buffer; \
  165518. register int bits_left; \
  165519. bitread_working_state br_state
  165520. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  165521. br_state.cinfo = cinfop; \
  165522. br_state.next_input_byte = cinfop->src->next_input_byte; \
  165523. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  165524. get_buffer = permstate.get_buffer; \
  165525. bits_left = permstate.bits_left;
  165526. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  165527. cinfop->src->next_input_byte = br_state.next_input_byte; \
  165528. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  165529. permstate.get_buffer = get_buffer; \
  165530. permstate.bits_left = bits_left
  165531. /*
  165532. * These macros provide the in-line portion of bit fetching.
  165533. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  165534. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  165535. * The variables get_buffer and bits_left are assumed to be locals,
  165536. * but the state struct might not be (jpeg_huff_decode needs this).
  165537. * CHECK_BIT_BUFFER(state,n,action);
  165538. * Ensure there are N bits in get_buffer; if suspend, take action.
  165539. * val = GET_BITS(n);
  165540. * Fetch next N bits.
  165541. * val = PEEK_BITS(n);
  165542. * Fetch next N bits without removing them from the buffer.
  165543. * DROP_BITS(n);
  165544. * Discard next N bits.
  165545. * The value N should be a simple variable, not an expression, because it
  165546. * is evaluated multiple times.
  165547. */
  165548. #define CHECK_BIT_BUFFER(state,nbits,action) \
  165549. { if (bits_left < (nbits)) { \
  165550. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  165551. { action; } \
  165552. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  165553. #define GET_BITS(nbits) \
  165554. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  165555. #define PEEK_BITS(nbits) \
  165556. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  165557. #define DROP_BITS(nbits) \
  165558. (bits_left -= (nbits))
  165559. /* Load up the bit buffer to a depth of at least nbits */
  165560. EXTERN(boolean) jpeg_fill_bit_buffer
  165561. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165562. register int bits_left, int nbits));
  165563. /*
  165564. * Code for extracting next Huffman-coded symbol from input bit stream.
  165565. * Again, this is time-critical and we make the main paths be macros.
  165566. *
  165567. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  165568. * without looping. Usually, more than 95% of the Huffman codes will be 8
  165569. * or fewer bits long. The few overlength codes are handled with a loop,
  165570. * which need not be inline code.
  165571. *
  165572. * Notes about the HUFF_DECODE macro:
  165573. * 1. Near the end of the data segment, we may fail to get enough bits
  165574. * for a lookahead. In that case, we do it the hard way.
  165575. * 2. If the lookahead table contains no entry, the next code must be
  165576. * more than HUFF_LOOKAHEAD bits long.
  165577. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  165578. */
  165579. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  165580. { register int nb, look; \
  165581. if (bits_left < HUFF_LOOKAHEAD) { \
  165582. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  165583. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165584. if (bits_left < HUFF_LOOKAHEAD) { \
  165585. nb = 1; goto slowlabel; \
  165586. } \
  165587. } \
  165588. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  165589. if ((nb = htbl->look_nbits[look]) != 0) { \
  165590. DROP_BITS(nb); \
  165591. result = htbl->look_sym[look]; \
  165592. } else { \
  165593. nb = HUFF_LOOKAHEAD+1; \
  165594. slowlabel: \
  165595. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  165596. { failaction; } \
  165597. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165598. } \
  165599. }
  165600. /* Out-of-line case for Huffman code fetching */
  165601. EXTERN(int) jpeg_huff_decode
  165602. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165603. register int bits_left, d_derived_tbl * htbl, int min_bits));
  165604. #endif
  165605. /********* End of inlined file: jdhuff.h *********/
  165606. /* Declarations shared with jdphuff.c */
  165607. /*
  165608. * Expanded entropy decoder object for Huffman decoding.
  165609. *
  165610. * The savable_state subrecord contains fields that change within an MCU,
  165611. * but must not be updated permanently until we complete the MCU.
  165612. */
  165613. typedef struct {
  165614. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165615. } savable_state2;
  165616. /* This macro is to work around compilers with missing or broken
  165617. * structure assignment. You'll need to fix this code if you have
  165618. * such a compiler and you change MAX_COMPS_IN_SCAN.
  165619. */
  165620. #ifndef NO_STRUCT_ASSIGN
  165621. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  165622. #else
  165623. #if MAX_COMPS_IN_SCAN == 4
  165624. #define ASSIGN_STATE(dest,src) \
  165625. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  165626. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  165627. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  165628. (dest).last_dc_val[3] = (src).last_dc_val[3])
  165629. #endif
  165630. #endif
  165631. typedef struct {
  165632. struct jpeg_entropy_decoder pub; /* public fields */
  165633. /* These fields are loaded into local variables at start of each MCU.
  165634. * In case of suspension, we exit WITHOUT updating them.
  165635. */
  165636. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  165637. savable_state2 saved; /* Other state at start of MCU */
  165638. /* These fields are NOT loaded into local working state. */
  165639. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165640. /* Pointers to derived tables (these workspaces have image lifespan) */
  165641. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  165642. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  165643. /* Precalculated info set up by start_pass for use in decode_mcu: */
  165644. /* Pointers to derived tables to be used for each block within an MCU */
  165645. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165646. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165647. /* Whether we care about the DC and AC coefficient values for each block */
  165648. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  165649. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  165650. } huff_entropy_decoder2;
  165651. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  165652. /*
  165653. * Initialize for a Huffman-compressed scan.
  165654. */
  165655. METHODDEF(void)
  165656. start_pass_huff_decoder (j_decompress_ptr cinfo)
  165657. {
  165658. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165659. int ci, blkn, dctbl, actbl;
  165660. jpeg_component_info * compptr;
  165661. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  165662. * This ought to be an error condition, but we make it a warning because
  165663. * there are some baseline files out there with all zeroes in these bytes.
  165664. */
  165665. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  165666. cinfo->Ah != 0 || cinfo->Al != 0)
  165667. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  165668. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165669. compptr = cinfo->cur_comp_info[ci];
  165670. dctbl = compptr->dc_tbl_no;
  165671. actbl = compptr->ac_tbl_no;
  165672. /* Compute derived values for Huffman tables */
  165673. /* We may do this more than once for a table, but it's not expensive */
  165674. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  165675. & entropy->dc_derived_tbls[dctbl]);
  165676. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  165677. & entropy->ac_derived_tbls[actbl]);
  165678. /* Initialize DC predictions to 0 */
  165679. entropy->saved.last_dc_val[ci] = 0;
  165680. }
  165681. /* Precalculate decoding info for each block in an MCU of this scan */
  165682. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165683. ci = cinfo->MCU_membership[blkn];
  165684. compptr = cinfo->cur_comp_info[ci];
  165685. /* Precalculate which table to use for each block */
  165686. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  165687. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  165688. /* Decide whether we really care about the coefficient values */
  165689. if (compptr->component_needed) {
  165690. entropy->dc_needed[blkn] = TRUE;
  165691. /* we don't need the ACs if producing a 1/8th-size image */
  165692. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  165693. } else {
  165694. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  165695. }
  165696. }
  165697. /* Initialize bitread state variables */
  165698. entropy->bitstate.bits_left = 0;
  165699. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  165700. entropy->pub.insufficient_data = FALSE;
  165701. /* Initialize restart counter */
  165702. entropy->restarts_to_go = cinfo->restart_interval;
  165703. }
  165704. /*
  165705. * Compute the derived values for a Huffman table.
  165706. * This routine also performs some validation checks on the table.
  165707. *
  165708. * Note this is also used by jdphuff.c.
  165709. */
  165710. GLOBAL(void)
  165711. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  165712. d_derived_tbl ** pdtbl)
  165713. {
  165714. JHUFF_TBL *htbl;
  165715. d_derived_tbl *dtbl;
  165716. int p, i, l, si, numsymbols;
  165717. int lookbits, ctr;
  165718. char huffsize[257];
  165719. unsigned int huffcode[257];
  165720. unsigned int code;
  165721. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  165722. * paralleling the order of the symbols themselves in htbl->huffval[].
  165723. */
  165724. /* Find the input Huffman table */
  165725. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  165726. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165727. htbl =
  165728. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  165729. if (htbl == NULL)
  165730. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165731. /* Allocate a workspace if we haven't already done so. */
  165732. if (*pdtbl == NULL)
  165733. *pdtbl = (d_derived_tbl *)
  165734. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165735. SIZEOF(d_derived_tbl));
  165736. dtbl = *pdtbl;
  165737. dtbl->pub = htbl; /* fill in back link */
  165738. /* Figure C.1: make table of Huffman code length for each symbol */
  165739. p = 0;
  165740. for (l = 1; l <= 16; l++) {
  165741. i = (int) htbl->bits[l];
  165742. if (i < 0 || p + i > 256) /* protect against table overrun */
  165743. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165744. while (i--)
  165745. huffsize[p++] = (char) l;
  165746. }
  165747. huffsize[p] = 0;
  165748. numsymbols = p;
  165749. /* Figure C.2: generate the codes themselves */
  165750. /* We also validate that the counts represent a legal Huffman code tree. */
  165751. code = 0;
  165752. si = huffsize[0];
  165753. p = 0;
  165754. while (huffsize[p]) {
  165755. while (((int) huffsize[p]) == si) {
  165756. huffcode[p++] = code;
  165757. code++;
  165758. }
  165759. /* code is now 1 more than the last code used for codelength si; but
  165760. * it must still fit in si bits, since no code is allowed to be all ones.
  165761. */
  165762. if (((INT32) code) >= (((INT32) 1) << si))
  165763. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165764. code <<= 1;
  165765. si++;
  165766. }
  165767. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  165768. p = 0;
  165769. for (l = 1; l <= 16; l++) {
  165770. if (htbl->bits[l]) {
  165771. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  165772. * minus the minimum code of length l
  165773. */
  165774. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  165775. p += htbl->bits[l];
  165776. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  165777. } else {
  165778. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  165779. }
  165780. }
  165781. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  165782. /* Compute lookahead tables to speed up decoding.
  165783. * First we set all the table entries to 0, indicating "too long";
  165784. * then we iterate through the Huffman codes that are short enough and
  165785. * fill in all the entries that correspond to bit sequences starting
  165786. * with that code.
  165787. */
  165788. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  165789. p = 0;
  165790. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  165791. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  165792. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  165793. /* Generate left-justified code followed by all possible bit sequences */
  165794. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  165795. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  165796. dtbl->look_nbits[lookbits] = l;
  165797. dtbl->look_sym[lookbits] = htbl->huffval[p];
  165798. lookbits++;
  165799. }
  165800. }
  165801. }
  165802. /* Validate symbols as being reasonable.
  165803. * For AC tables, we make no check, but accept all byte values 0..255.
  165804. * For DC tables, we require the symbols to be in range 0..15.
  165805. * (Tighter bounds could be applied depending on the data depth and mode,
  165806. * but this is sufficient to ensure safe decoding.)
  165807. */
  165808. if (isDC) {
  165809. for (i = 0; i < numsymbols; i++) {
  165810. int sym = htbl->huffval[i];
  165811. if (sym < 0 || sym > 15)
  165812. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165813. }
  165814. }
  165815. }
  165816. /*
  165817. * Out-of-line code for bit fetching (shared with jdphuff.c).
  165818. * See jdhuff.h for info about usage.
  165819. * Note: current values of get_buffer and bits_left are passed as parameters,
  165820. * but are returned in the corresponding fields of the state struct.
  165821. *
  165822. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  165823. * of get_buffer to be used. (On machines with wider words, an even larger
  165824. * buffer could be used.) However, on some machines 32-bit shifts are
  165825. * quite slow and take time proportional to the number of places shifted.
  165826. * (This is true with most PC compilers, for instance.) In this case it may
  165827. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  165828. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  165829. */
  165830. #ifdef SLOW_SHIFT_32
  165831. #define MIN_GET_BITS 15 /* minimum allowable value */
  165832. #else
  165833. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  165834. #endif
  165835. GLOBAL(boolean)
  165836. jpeg_fill_bit_buffer (bitread_working_state * state,
  165837. register bit_buf_type get_buffer, register int bits_left,
  165838. int nbits)
  165839. /* Load up the bit buffer to a depth of at least nbits */
  165840. {
  165841. /* Copy heavily used state fields into locals (hopefully registers) */
  165842. register const JOCTET * next_input_byte = state->next_input_byte;
  165843. register size_t bytes_in_buffer = state->bytes_in_buffer;
  165844. j_decompress_ptr cinfo = state->cinfo;
  165845. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  165846. /* (It is assumed that no request will be for more than that many bits.) */
  165847. /* We fail to do so only if we hit a marker or are forced to suspend. */
  165848. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  165849. while (bits_left < MIN_GET_BITS) {
  165850. register int c;
  165851. /* Attempt to read a byte */
  165852. if (bytes_in_buffer == 0) {
  165853. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165854. return FALSE;
  165855. next_input_byte = cinfo->src->next_input_byte;
  165856. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165857. }
  165858. bytes_in_buffer--;
  165859. c = GETJOCTET(*next_input_byte++);
  165860. /* If it's 0xFF, check and discard stuffed zero byte */
  165861. if (c == 0xFF) {
  165862. /* Loop here to discard any padding FF's on terminating marker,
  165863. * so that we can save a valid unread_marker value. NOTE: we will
  165864. * accept multiple FF's followed by a 0 as meaning a single FF data
  165865. * byte. This data pattern is not valid according to the standard.
  165866. */
  165867. do {
  165868. if (bytes_in_buffer == 0) {
  165869. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165870. return FALSE;
  165871. next_input_byte = cinfo->src->next_input_byte;
  165872. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165873. }
  165874. bytes_in_buffer--;
  165875. c = GETJOCTET(*next_input_byte++);
  165876. } while (c == 0xFF);
  165877. if (c == 0) {
  165878. /* Found FF/00, which represents an FF data byte */
  165879. c = 0xFF;
  165880. } else {
  165881. /* Oops, it's actually a marker indicating end of compressed data.
  165882. * Save the marker code for later use.
  165883. * Fine point: it might appear that we should save the marker into
  165884. * bitread working state, not straight into permanent state. But
  165885. * once we have hit a marker, we cannot need to suspend within the
  165886. * current MCU, because we will read no more bytes from the data
  165887. * source. So it is OK to update permanent state right away.
  165888. */
  165889. cinfo->unread_marker = c;
  165890. /* See if we need to insert some fake zero bits. */
  165891. goto no_more_bytes;
  165892. }
  165893. }
  165894. /* OK, load c into get_buffer */
  165895. get_buffer = (get_buffer << 8) | c;
  165896. bits_left += 8;
  165897. } /* end while */
  165898. } else {
  165899. no_more_bytes:
  165900. /* We get here if we've read the marker that terminates the compressed
  165901. * data segment. There should be enough bits in the buffer register
  165902. * to satisfy the request; if so, no problem.
  165903. */
  165904. if (nbits > bits_left) {
  165905. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  165906. * the data stream, so that we can produce some kind of image.
  165907. * We use a nonvolatile flag to ensure that only one warning message
  165908. * appears per data segment.
  165909. */
  165910. if (! cinfo->entropy->insufficient_data) {
  165911. WARNMS(cinfo, JWRN_HIT_MARKER);
  165912. cinfo->entropy->insufficient_data = TRUE;
  165913. }
  165914. /* Fill the buffer with zero bits */
  165915. get_buffer <<= MIN_GET_BITS - bits_left;
  165916. bits_left = MIN_GET_BITS;
  165917. }
  165918. }
  165919. /* Unload the local registers */
  165920. state->next_input_byte = next_input_byte;
  165921. state->bytes_in_buffer = bytes_in_buffer;
  165922. state->get_buffer = get_buffer;
  165923. state->bits_left = bits_left;
  165924. return TRUE;
  165925. }
  165926. /*
  165927. * Out-of-line code for Huffman code decoding.
  165928. * See jdhuff.h for info about usage.
  165929. */
  165930. GLOBAL(int)
  165931. jpeg_huff_decode (bitread_working_state * state,
  165932. register bit_buf_type get_buffer, register int bits_left,
  165933. d_derived_tbl * htbl, int min_bits)
  165934. {
  165935. register int l = min_bits;
  165936. register INT32 code;
  165937. /* HUFF_DECODE has determined that the code is at least min_bits */
  165938. /* bits long, so fetch that many bits in one swoop. */
  165939. CHECK_BIT_BUFFER(*state, l, return -1);
  165940. code = GET_BITS(l);
  165941. /* Collect the rest of the Huffman code one bit at a time. */
  165942. /* This is per Figure F.16 in the JPEG spec. */
  165943. while (code > htbl->maxcode[l]) {
  165944. code <<= 1;
  165945. CHECK_BIT_BUFFER(*state, 1, return -1);
  165946. code |= GET_BITS(1);
  165947. l++;
  165948. }
  165949. /* Unload the local registers */
  165950. state->get_buffer = get_buffer;
  165951. state->bits_left = bits_left;
  165952. /* With garbage input we may reach the sentinel value l = 17. */
  165953. if (l > 16) {
  165954. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  165955. return 0; /* fake a zero as the safest result */
  165956. }
  165957. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  165958. }
  165959. /*
  165960. * Check for a restart marker & resynchronize decoder.
  165961. * Returns FALSE if must suspend.
  165962. */
  165963. LOCAL(boolean)
  165964. process_restart (j_decompress_ptr cinfo)
  165965. {
  165966. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165967. int ci;
  165968. /* Throw away any unused bits remaining in bit buffer; */
  165969. /* include any full bytes in next_marker's count of discarded bytes */
  165970. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  165971. entropy->bitstate.bits_left = 0;
  165972. /* Advance past the RSTn marker */
  165973. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  165974. return FALSE;
  165975. /* Re-initialize DC predictions to 0 */
  165976. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  165977. entropy->saved.last_dc_val[ci] = 0;
  165978. /* Reset restart counter */
  165979. entropy->restarts_to_go = cinfo->restart_interval;
  165980. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  165981. * against a marker. In that case we will end up treating the next data
  165982. * segment as empty, and we can avoid producing bogus output pixels by
  165983. * leaving the flag set.
  165984. */
  165985. if (cinfo->unread_marker == 0)
  165986. entropy->pub.insufficient_data = FALSE;
  165987. return TRUE;
  165988. }
  165989. /*
  165990. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  165991. * The coefficients are reordered from zigzag order into natural array order,
  165992. * but are not dequantized.
  165993. *
  165994. * The i'th block of the MCU is stored into the block pointed to by
  165995. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  165996. * (Wholesale zeroing is usually a little faster than retail...)
  165997. *
  165998. * Returns FALSE if data source requested suspension. In that case no
  165999. * changes have been made to permanent state. (Exception: some output
  166000. * coefficients may already have been assigned. This is harmless for
  166001. * this module, since we'll just re-assign them on the next call.)
  166002. */
  166003. METHODDEF(boolean)
  166004. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166005. {
  166006. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  166007. int blkn;
  166008. BITREAD_STATE_VARS;
  166009. savable_state2 state;
  166010. /* Process restart marker if needed; may have to suspend */
  166011. if (cinfo->restart_interval) {
  166012. if (entropy->restarts_to_go == 0)
  166013. if (! process_restart(cinfo))
  166014. return FALSE;
  166015. }
  166016. /* If we've run out of data, just leave the MCU set to zeroes.
  166017. * This way, we return uniform gray for the remainder of the segment.
  166018. */
  166019. if (! entropy->pub.insufficient_data) {
  166020. /* Load up working state */
  166021. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166022. ASSIGN_STATE(state, entropy->saved);
  166023. /* Outer loop handles each block in the MCU */
  166024. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166025. JBLOCKROW block = MCU_data[blkn];
  166026. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  166027. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  166028. register int s, k, r;
  166029. /* Decode a single block's worth of coefficients */
  166030. /* Section F.2.2.1: decode the DC coefficient difference */
  166031. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  166032. if (s) {
  166033. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166034. r = GET_BITS(s);
  166035. s = HUFF_EXTEND(r, s);
  166036. }
  166037. if (entropy->dc_needed[blkn]) {
  166038. /* Convert DC difference to actual value, update last_dc_val */
  166039. int ci = cinfo->MCU_membership[blkn];
  166040. s += state.last_dc_val[ci];
  166041. state.last_dc_val[ci] = s;
  166042. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  166043. (*block)[0] = (JCOEF) s;
  166044. }
  166045. if (entropy->ac_needed[blkn]) {
  166046. /* Section F.2.2.2: decode the AC coefficients */
  166047. /* Since zeroes are skipped, output area must be cleared beforehand */
  166048. for (k = 1; k < DCTSIZE2; k++) {
  166049. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  166050. r = s >> 4;
  166051. s &= 15;
  166052. if (s) {
  166053. k += r;
  166054. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166055. r = GET_BITS(s);
  166056. s = HUFF_EXTEND(r, s);
  166057. /* Output coefficient in natural (dezigzagged) order.
  166058. * Note: the extra entries in jpeg_natural_order[] will save us
  166059. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  166060. */
  166061. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  166062. } else {
  166063. if (r != 15)
  166064. break;
  166065. k += 15;
  166066. }
  166067. }
  166068. } else {
  166069. /* Section F.2.2.2: decode the AC coefficients */
  166070. /* In this path we just discard the values */
  166071. for (k = 1; k < DCTSIZE2; k++) {
  166072. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  166073. r = s >> 4;
  166074. s &= 15;
  166075. if (s) {
  166076. k += r;
  166077. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166078. DROP_BITS(s);
  166079. } else {
  166080. if (r != 15)
  166081. break;
  166082. k += 15;
  166083. }
  166084. }
  166085. }
  166086. }
  166087. /* Completed MCU, so update state */
  166088. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166089. ASSIGN_STATE(entropy->saved, state);
  166090. }
  166091. /* Account for restart interval (no-op if not using restarts) */
  166092. entropy->restarts_to_go--;
  166093. return TRUE;
  166094. }
  166095. /*
  166096. * Module initialization routine for Huffman entropy decoding.
  166097. */
  166098. GLOBAL(void)
  166099. jinit_huff_decoder (j_decompress_ptr cinfo)
  166100. {
  166101. huff_entropy_ptr2 entropy;
  166102. int i;
  166103. entropy = (huff_entropy_ptr2)
  166104. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166105. SIZEOF(huff_entropy_decoder2));
  166106. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  166107. entropy->pub.start_pass = start_pass_huff_decoder;
  166108. entropy->pub.decode_mcu = decode_mcu;
  166109. /* Mark tables unallocated */
  166110. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166111. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  166112. }
  166113. }
  166114. /********* End of inlined file: jdhuff.c *********/
  166115. /********* Start of inlined file: jdinput.c *********/
  166116. #define JPEG_INTERNALS
  166117. /* Private state */
  166118. typedef struct {
  166119. struct jpeg_input_controller pub; /* public fields */
  166120. boolean inheaders; /* TRUE until first SOS is reached */
  166121. } my_input_controller;
  166122. typedef my_input_controller * my_inputctl_ptr;
  166123. /* Forward declarations */
  166124. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  166125. /*
  166126. * Routines to calculate various quantities related to the size of the image.
  166127. */
  166128. LOCAL(void)
  166129. initial_setup2 (j_decompress_ptr cinfo)
  166130. /* Called once, when first SOS marker is reached */
  166131. {
  166132. int ci;
  166133. jpeg_component_info *compptr;
  166134. /* Make sure image isn't bigger than I can handle */
  166135. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  166136. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  166137. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  166138. /* For now, precision must match compiled-in value... */
  166139. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  166140. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  166141. /* Check that number of components won't exceed internal array sizes */
  166142. if (cinfo->num_components > MAX_COMPONENTS)
  166143. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  166144. MAX_COMPONENTS);
  166145. /* Compute maximum sampling factors; check factor validity */
  166146. cinfo->max_h_samp_factor = 1;
  166147. cinfo->max_v_samp_factor = 1;
  166148. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166149. ci++, compptr++) {
  166150. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  166151. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  166152. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  166153. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  166154. compptr->h_samp_factor);
  166155. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  166156. compptr->v_samp_factor);
  166157. }
  166158. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  166159. * In the full decompressor, this will be overridden by jdmaster.c;
  166160. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  166161. */
  166162. cinfo->min_DCT_scaled_size = DCTSIZE;
  166163. /* Compute dimensions of components */
  166164. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166165. ci++, compptr++) {
  166166. compptr->DCT_scaled_size = DCTSIZE;
  166167. /* Size in DCT blocks */
  166168. compptr->width_in_blocks = (JDIMENSION)
  166169. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166170. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  166171. compptr->height_in_blocks = (JDIMENSION)
  166172. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166173. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166174. /* downsampled_width and downsampled_height will also be overridden by
  166175. * jdmaster.c if we are doing full decompression. The transcoder library
  166176. * doesn't use these values, but the calling application might.
  166177. */
  166178. /* Size in samples */
  166179. compptr->downsampled_width = (JDIMENSION)
  166180. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166181. (long) cinfo->max_h_samp_factor);
  166182. compptr->downsampled_height = (JDIMENSION)
  166183. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166184. (long) cinfo->max_v_samp_factor);
  166185. /* Mark component needed, until color conversion says otherwise */
  166186. compptr->component_needed = TRUE;
  166187. /* Mark no quantization table yet saved for component */
  166188. compptr->quant_table = NULL;
  166189. }
  166190. /* Compute number of fully interleaved MCU rows. */
  166191. cinfo->total_iMCU_rows = (JDIMENSION)
  166192. jdiv_round_up((long) cinfo->image_height,
  166193. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166194. /* Decide whether file contains multiple scans */
  166195. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  166196. cinfo->inputctl->has_multiple_scans = TRUE;
  166197. else
  166198. cinfo->inputctl->has_multiple_scans = FALSE;
  166199. }
  166200. LOCAL(void)
  166201. per_scan_setup2 (j_decompress_ptr cinfo)
  166202. /* Do computations that are needed before processing a JPEG scan */
  166203. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  166204. {
  166205. int ci, mcublks, tmp;
  166206. jpeg_component_info *compptr;
  166207. if (cinfo->comps_in_scan == 1) {
  166208. /* Noninterleaved (single-component) scan */
  166209. compptr = cinfo->cur_comp_info[0];
  166210. /* Overall image size in MCUs */
  166211. cinfo->MCUs_per_row = compptr->width_in_blocks;
  166212. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  166213. /* For noninterleaved scan, always one block per MCU */
  166214. compptr->MCU_width = 1;
  166215. compptr->MCU_height = 1;
  166216. compptr->MCU_blocks = 1;
  166217. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  166218. compptr->last_col_width = 1;
  166219. /* For noninterleaved scans, it is convenient to define last_row_height
  166220. * as the number of block rows present in the last iMCU row.
  166221. */
  166222. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  166223. if (tmp == 0) tmp = compptr->v_samp_factor;
  166224. compptr->last_row_height = tmp;
  166225. /* Prepare array describing MCU composition */
  166226. cinfo->blocks_in_MCU = 1;
  166227. cinfo->MCU_membership[0] = 0;
  166228. } else {
  166229. /* Interleaved (multi-component) scan */
  166230. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  166231. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  166232. MAX_COMPS_IN_SCAN);
  166233. /* Overall image size in MCUs */
  166234. cinfo->MCUs_per_row = (JDIMENSION)
  166235. jdiv_round_up((long) cinfo->image_width,
  166236. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  166237. cinfo->MCU_rows_in_scan = (JDIMENSION)
  166238. jdiv_round_up((long) cinfo->image_height,
  166239. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166240. cinfo->blocks_in_MCU = 0;
  166241. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166242. compptr = cinfo->cur_comp_info[ci];
  166243. /* Sampling factors give # of blocks of component in each MCU */
  166244. compptr->MCU_width = compptr->h_samp_factor;
  166245. compptr->MCU_height = compptr->v_samp_factor;
  166246. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  166247. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  166248. /* Figure number of non-dummy blocks in last MCU column & row */
  166249. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  166250. if (tmp == 0) tmp = compptr->MCU_width;
  166251. compptr->last_col_width = tmp;
  166252. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  166253. if (tmp == 0) tmp = compptr->MCU_height;
  166254. compptr->last_row_height = tmp;
  166255. /* Prepare array describing MCU composition */
  166256. mcublks = compptr->MCU_blocks;
  166257. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  166258. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  166259. while (mcublks-- > 0) {
  166260. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  166261. }
  166262. }
  166263. }
  166264. }
  166265. /*
  166266. * Save away a copy of the Q-table referenced by each component present
  166267. * in the current scan, unless already saved during a prior scan.
  166268. *
  166269. * In a multiple-scan JPEG file, the encoder could assign different components
  166270. * the same Q-table slot number, but change table definitions between scans
  166271. * so that each component uses a different Q-table. (The IJG encoder is not
  166272. * currently capable of doing this, but other encoders might.) Since we want
  166273. * to be able to dequantize all the components at the end of the file, this
  166274. * means that we have to save away the table actually used for each component.
  166275. * We do this by copying the table at the start of the first scan containing
  166276. * the component.
  166277. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  166278. * slot between scans of a component using that slot. If the encoder does so
  166279. * anyway, this decoder will simply use the Q-table values that were current
  166280. * at the start of the first scan for the component.
  166281. *
  166282. * The decompressor output side looks only at the saved quant tables,
  166283. * not at the current Q-table slots.
  166284. */
  166285. LOCAL(void)
  166286. latch_quant_tables (j_decompress_ptr cinfo)
  166287. {
  166288. int ci, qtblno;
  166289. jpeg_component_info *compptr;
  166290. JQUANT_TBL * qtbl;
  166291. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166292. compptr = cinfo->cur_comp_info[ci];
  166293. /* No work if we already saved Q-table for this component */
  166294. if (compptr->quant_table != NULL)
  166295. continue;
  166296. /* Make sure specified quantization table is present */
  166297. qtblno = compptr->quant_tbl_no;
  166298. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  166299. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  166300. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  166301. /* OK, save away the quantization table */
  166302. qtbl = (JQUANT_TBL *)
  166303. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166304. SIZEOF(JQUANT_TBL));
  166305. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  166306. compptr->quant_table = qtbl;
  166307. }
  166308. }
  166309. /*
  166310. * Initialize the input modules to read a scan of compressed data.
  166311. * The first call to this is done by jdmaster.c after initializing
  166312. * the entire decompressor (during jpeg_start_decompress).
  166313. * Subsequent calls come from consume_markers, below.
  166314. */
  166315. METHODDEF(void)
  166316. start_input_pass2 (j_decompress_ptr cinfo)
  166317. {
  166318. per_scan_setup2(cinfo);
  166319. latch_quant_tables(cinfo);
  166320. (*cinfo->entropy->start_pass) (cinfo);
  166321. (*cinfo->coef->start_input_pass) (cinfo);
  166322. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  166323. }
  166324. /*
  166325. * Finish up after inputting a compressed-data scan.
  166326. * This is called by the coefficient controller after it's read all
  166327. * the expected data of the scan.
  166328. */
  166329. METHODDEF(void)
  166330. finish_input_pass (j_decompress_ptr cinfo)
  166331. {
  166332. cinfo->inputctl->consume_input = consume_markers;
  166333. }
  166334. /*
  166335. * Read JPEG markers before, between, or after compressed-data scans.
  166336. * Change state as necessary when a new scan is reached.
  166337. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  166338. *
  166339. * The consume_input method pointer points either here or to the
  166340. * coefficient controller's consume_data routine, depending on whether
  166341. * we are reading a compressed data segment or inter-segment markers.
  166342. */
  166343. METHODDEF(int)
  166344. consume_markers (j_decompress_ptr cinfo)
  166345. {
  166346. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166347. int val;
  166348. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  166349. return JPEG_REACHED_EOI;
  166350. val = (*cinfo->marker->read_markers) (cinfo);
  166351. switch (val) {
  166352. case JPEG_REACHED_SOS: /* Found SOS */
  166353. if (inputctl->inheaders) { /* 1st SOS */
  166354. initial_setup2(cinfo);
  166355. inputctl->inheaders = FALSE;
  166356. /* Note: start_input_pass must be called by jdmaster.c
  166357. * before any more input can be consumed. jdapimin.c is
  166358. * responsible for enforcing this sequencing.
  166359. */
  166360. } else { /* 2nd or later SOS marker */
  166361. if (! inputctl->pub.has_multiple_scans)
  166362. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  166363. start_input_pass2(cinfo);
  166364. }
  166365. break;
  166366. case JPEG_REACHED_EOI: /* Found EOI */
  166367. inputctl->pub.eoi_reached = TRUE;
  166368. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  166369. if (cinfo->marker->saw_SOF)
  166370. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  166371. } else {
  166372. /* Prevent infinite loop in coef ctlr's decompress_data routine
  166373. * if user set output_scan_number larger than number of scans.
  166374. */
  166375. if (cinfo->output_scan_number > cinfo->input_scan_number)
  166376. cinfo->output_scan_number = cinfo->input_scan_number;
  166377. }
  166378. break;
  166379. case JPEG_SUSPENDED:
  166380. break;
  166381. }
  166382. return val;
  166383. }
  166384. /*
  166385. * Reset state to begin a fresh datastream.
  166386. */
  166387. METHODDEF(void)
  166388. reset_input_controller (j_decompress_ptr cinfo)
  166389. {
  166390. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166391. inputctl->pub.consume_input = consume_markers;
  166392. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166393. inputctl->pub.eoi_reached = FALSE;
  166394. inputctl->inheaders = TRUE;
  166395. /* Reset other modules */
  166396. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166397. (*cinfo->marker->reset_marker_reader) (cinfo);
  166398. /* Reset progression state -- would be cleaner if entropy decoder did this */
  166399. cinfo->coef_bits = NULL;
  166400. }
  166401. /*
  166402. * Initialize the input controller module.
  166403. * This is called only once, when the decompression object is created.
  166404. */
  166405. GLOBAL(void)
  166406. jinit_input_controller (j_decompress_ptr cinfo)
  166407. {
  166408. my_inputctl_ptr inputctl;
  166409. /* Create subobject in permanent pool */
  166410. inputctl = (my_inputctl_ptr)
  166411. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166412. SIZEOF(my_input_controller));
  166413. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  166414. /* Initialize method pointers */
  166415. inputctl->pub.consume_input = consume_markers;
  166416. inputctl->pub.reset_input_controller = reset_input_controller;
  166417. inputctl->pub.start_input_pass = start_input_pass2;
  166418. inputctl->pub.finish_input_pass = finish_input_pass;
  166419. /* Initialize state: can't use reset_input_controller since we don't
  166420. * want to try to reset other modules yet.
  166421. */
  166422. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166423. inputctl->pub.eoi_reached = FALSE;
  166424. inputctl->inheaders = TRUE;
  166425. }
  166426. /********* End of inlined file: jdinput.c *********/
  166427. /********* Start of inlined file: jdmainct.c *********/
  166428. #define JPEG_INTERNALS
  166429. /*
  166430. * In the current system design, the main buffer need never be a full-image
  166431. * buffer; any full-height buffers will be found inside the coefficient or
  166432. * postprocessing controllers. Nonetheless, the main controller is not
  166433. * trivial. Its responsibility is to provide context rows for upsampling/
  166434. * rescaling, and doing this in an efficient fashion is a bit tricky.
  166435. *
  166436. * Postprocessor input data is counted in "row groups". A row group
  166437. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  166438. * sample rows of each component. (We require DCT_scaled_size values to be
  166439. * chosen such that these numbers are integers. In practice DCT_scaled_size
  166440. * values will likely be powers of two, so we actually have the stronger
  166441. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  166442. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  166443. * row group (times any additional scale factor that the upsampler is
  166444. * applying).
  166445. *
  166446. * The coefficient controller will deliver data to us one iMCU row at a time;
  166447. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  166448. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  166449. * to one row of MCUs when the image is fully interleaved.) Note that the
  166450. * number of sample rows varies across components, but the number of row
  166451. * groups does not. Some garbage sample rows may be included in the last iMCU
  166452. * row at the bottom of the image.
  166453. *
  166454. * Depending on the vertical scaling algorithm used, the upsampler may need
  166455. * access to the sample row(s) above and below its current input row group.
  166456. * The upsampler is required to set need_context_rows TRUE at global selection
  166457. * time if so. When need_context_rows is FALSE, this controller can simply
  166458. * obtain one iMCU row at a time from the coefficient controller and dole it
  166459. * out as row groups to the postprocessor.
  166460. *
  166461. * When need_context_rows is TRUE, this controller guarantees that the buffer
  166462. * passed to postprocessing contains at least one row group's worth of samples
  166463. * above and below the row group(s) being processed. Note that the context
  166464. * rows "above" the first passed row group appear at negative row offsets in
  166465. * the passed buffer. At the top and bottom of the image, the required
  166466. * context rows are manufactured by duplicating the first or last real sample
  166467. * row; this avoids having special cases in the upsampling inner loops.
  166468. *
  166469. * The amount of context is fixed at one row group just because that's a
  166470. * convenient number for this controller to work with. The existing
  166471. * upsamplers really only need one sample row of context. An upsampler
  166472. * supporting arbitrary output rescaling might wish for more than one row
  166473. * group of context when shrinking the image; tough, we don't handle that.
  166474. * (This is justified by the assumption that downsizing will be handled mostly
  166475. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  166476. * the upsample step needn't be much less than one.)
  166477. *
  166478. * To provide the desired context, we have to retain the last two row groups
  166479. * of one iMCU row while reading in the next iMCU row. (The last row group
  166480. * can't be processed until we have another row group for its below-context,
  166481. * and so we have to save the next-to-last group too for its above-context.)
  166482. * We could do this most simply by copying data around in our buffer, but
  166483. * that'd be very slow. We can avoid copying any data by creating a rather
  166484. * strange pointer structure. Here's how it works. We allocate a workspace
  166485. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  166486. * of row groups per iMCU row). We create two sets of redundant pointers to
  166487. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  166488. * pointer lists look like this:
  166489. * M+1 M-1
  166490. * master pointer --> 0 master pointer --> 0
  166491. * 1 1
  166492. * ... ...
  166493. * M-3 M-3
  166494. * M-2 M
  166495. * M-1 M+1
  166496. * M M-2
  166497. * M+1 M-1
  166498. * 0 0
  166499. * We read alternate iMCU rows using each master pointer; thus the last two
  166500. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  166501. * The pointer lists are set up so that the required context rows appear to
  166502. * be adjacent to the proper places when we pass the pointer lists to the
  166503. * upsampler.
  166504. *
  166505. * The above pictures describe the normal state of the pointer lists.
  166506. * At top and bottom of the image, we diddle the pointer lists to duplicate
  166507. * the first or last sample row as necessary (this is cheaper than copying
  166508. * sample rows around).
  166509. *
  166510. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  166511. * situation each iMCU row provides only one row group so the buffering logic
  166512. * must be different (eg, we must read two iMCU rows before we can emit the
  166513. * first row group). For now, we simply do not support providing context
  166514. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  166515. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  166516. * want it quick and dirty, so a context-free upsampler is sufficient.
  166517. */
  166518. /* Private buffer controller object */
  166519. typedef struct {
  166520. struct jpeg_d_main_controller pub; /* public fields */
  166521. /* Pointer to allocated workspace (M or M+2 row groups). */
  166522. JSAMPARRAY buffer[MAX_COMPONENTS];
  166523. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  166524. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  166525. /* Remaining fields are only used in the context case. */
  166526. /* These are the master pointers to the funny-order pointer lists. */
  166527. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  166528. int whichptr; /* indicates which pointer set is now in use */
  166529. int context_state; /* process_data state machine status */
  166530. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  166531. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  166532. } my_main_controller4;
  166533. typedef my_main_controller4 * my_main_ptr4;
  166534. /* context_state values: */
  166535. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  166536. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  166537. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  166538. /* Forward declarations */
  166539. METHODDEF(void) process_data_simple_main2
  166540. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166541. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166542. METHODDEF(void) process_data_context_main
  166543. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166544. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166545. #ifdef QUANT_2PASS_SUPPORTED
  166546. METHODDEF(void) process_data_crank_post
  166547. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166548. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166549. #endif
  166550. LOCAL(void)
  166551. alloc_funny_pointers (j_decompress_ptr cinfo)
  166552. /* Allocate space for the funny pointer lists.
  166553. * This is done only once, not once per pass.
  166554. */
  166555. {
  166556. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166557. int ci, rgroup;
  166558. int M = cinfo->min_DCT_scaled_size;
  166559. jpeg_component_info *compptr;
  166560. JSAMPARRAY xbuf;
  166561. /* Get top-level space for component array pointers.
  166562. * We alloc both arrays with one call to save a few cycles.
  166563. */
  166564. main_->xbuffer[0] = (JSAMPIMAGE)
  166565. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166566. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  166567. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  166568. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166569. ci++, compptr++) {
  166570. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166571. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166572. /* Get space for pointer lists --- M+4 row groups in each list.
  166573. * We alloc both pointer lists with one call to save a few cycles.
  166574. */
  166575. xbuf = (JSAMPARRAY)
  166576. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166577. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  166578. xbuf += rgroup; /* want one row group at negative offsets */
  166579. main_->xbuffer[0][ci] = xbuf;
  166580. xbuf += rgroup * (M + 4);
  166581. main_->xbuffer[1][ci] = xbuf;
  166582. }
  166583. }
  166584. LOCAL(void)
  166585. make_funny_pointers (j_decompress_ptr cinfo)
  166586. /* Create the funny pointer lists discussed in the comments above.
  166587. * The actual workspace is already allocated (in main->buffer),
  166588. * and the space for the pointer lists is allocated too.
  166589. * This routine just fills in the curiously ordered lists.
  166590. * This will be repeated at the beginning of each pass.
  166591. */
  166592. {
  166593. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166594. int ci, i, rgroup;
  166595. int M = cinfo->min_DCT_scaled_size;
  166596. jpeg_component_info *compptr;
  166597. JSAMPARRAY buf, xbuf0, xbuf1;
  166598. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166599. ci++, compptr++) {
  166600. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166601. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166602. xbuf0 = main_->xbuffer[0][ci];
  166603. xbuf1 = main_->xbuffer[1][ci];
  166604. /* First copy the workspace pointers as-is */
  166605. buf = main_->buffer[ci];
  166606. for (i = 0; i < rgroup * (M + 2); i++) {
  166607. xbuf0[i] = xbuf1[i] = buf[i];
  166608. }
  166609. /* In the second list, put the last four row groups in swapped order */
  166610. for (i = 0; i < rgroup * 2; i++) {
  166611. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  166612. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  166613. }
  166614. /* The wraparound pointers at top and bottom will be filled later
  166615. * (see set_wraparound_pointers, below). Initially we want the "above"
  166616. * pointers to duplicate the first actual data line. This only needs
  166617. * to happen in xbuffer[0].
  166618. */
  166619. for (i = 0; i < rgroup; i++) {
  166620. xbuf0[i - rgroup] = xbuf0[0];
  166621. }
  166622. }
  166623. }
  166624. LOCAL(void)
  166625. set_wraparound_pointers (j_decompress_ptr cinfo)
  166626. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  166627. * This changes the pointer list state from top-of-image to the normal state.
  166628. */
  166629. {
  166630. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166631. int ci, i, rgroup;
  166632. int M = cinfo->min_DCT_scaled_size;
  166633. jpeg_component_info *compptr;
  166634. JSAMPARRAY xbuf0, xbuf1;
  166635. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166636. ci++, compptr++) {
  166637. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166638. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166639. xbuf0 = main_->xbuffer[0][ci];
  166640. xbuf1 = main_->xbuffer[1][ci];
  166641. for (i = 0; i < rgroup; i++) {
  166642. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  166643. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  166644. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  166645. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  166646. }
  166647. }
  166648. }
  166649. LOCAL(void)
  166650. set_bottom_pointers (j_decompress_ptr cinfo)
  166651. /* Change the pointer lists to duplicate the last sample row at the bottom
  166652. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  166653. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  166654. */
  166655. {
  166656. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166657. int ci, i, rgroup, iMCUheight, rows_left;
  166658. jpeg_component_info *compptr;
  166659. JSAMPARRAY xbuf;
  166660. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166661. ci++, compptr++) {
  166662. /* Count sample rows in one iMCU row and in one row group */
  166663. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  166664. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  166665. /* Count nondummy sample rows remaining for this component */
  166666. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  166667. if (rows_left == 0) rows_left = iMCUheight;
  166668. /* Count nondummy row groups. Should get same answer for each component,
  166669. * so we need only do it once.
  166670. */
  166671. if (ci == 0) {
  166672. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  166673. }
  166674. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  166675. * last partial rowgroup and ensures at least one full rowgroup of context.
  166676. */
  166677. xbuf = main_->xbuffer[main_->whichptr][ci];
  166678. for (i = 0; i < rgroup * 2; i++) {
  166679. xbuf[rows_left + i] = xbuf[rows_left-1];
  166680. }
  166681. }
  166682. }
  166683. /*
  166684. * Initialize for a processing pass.
  166685. */
  166686. METHODDEF(void)
  166687. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  166688. {
  166689. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166690. switch (pass_mode) {
  166691. case JBUF_PASS_THRU:
  166692. if (cinfo->upsample->need_context_rows) {
  166693. main_->pub.process_data = process_data_context_main;
  166694. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  166695. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  166696. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166697. main_->iMCU_row_ctr = 0;
  166698. } else {
  166699. /* Simple case with no context needed */
  166700. main_->pub.process_data = process_data_simple_main2;
  166701. }
  166702. main_->buffer_full = FALSE; /* Mark buffer empty */
  166703. main_->rowgroup_ctr = 0;
  166704. break;
  166705. #ifdef QUANT_2PASS_SUPPORTED
  166706. case JBUF_CRANK_DEST:
  166707. /* For last pass of 2-pass quantization, just crank the postprocessor */
  166708. main_->pub.process_data = process_data_crank_post;
  166709. break;
  166710. #endif
  166711. default:
  166712. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166713. break;
  166714. }
  166715. }
  166716. /*
  166717. * Process some data.
  166718. * This handles the simple case where no context is required.
  166719. */
  166720. METHODDEF(void)
  166721. process_data_simple_main2 (j_decompress_ptr cinfo,
  166722. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166723. JDIMENSION out_rows_avail)
  166724. {
  166725. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166726. JDIMENSION rowgroups_avail;
  166727. /* Read input data if we haven't filled the main buffer yet */
  166728. if (! main_->buffer_full) {
  166729. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  166730. return; /* suspension forced, can do nothing more */
  166731. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166732. }
  166733. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  166734. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  166735. /* Note: at the bottom of the image, we may pass extra garbage row groups
  166736. * to the postprocessor. The postprocessor has to check for bottom
  166737. * of image anyway (at row resolution), so no point in us doing it too.
  166738. */
  166739. /* Feed the postprocessor */
  166740. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  166741. &main_->rowgroup_ctr, rowgroups_avail,
  166742. output_buf, out_row_ctr, out_rows_avail);
  166743. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  166744. if (main_->rowgroup_ctr >= rowgroups_avail) {
  166745. main_->buffer_full = FALSE;
  166746. main_->rowgroup_ctr = 0;
  166747. }
  166748. }
  166749. /*
  166750. * Process some data.
  166751. * This handles the case where context rows must be provided.
  166752. */
  166753. METHODDEF(void)
  166754. process_data_context_main (j_decompress_ptr cinfo,
  166755. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166756. JDIMENSION out_rows_avail)
  166757. {
  166758. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166759. /* Read input data if we haven't filled the main buffer yet */
  166760. if (! main_->buffer_full) {
  166761. if (! (*cinfo->coef->decompress_data) (cinfo,
  166762. main_->xbuffer[main_->whichptr]))
  166763. return; /* suspension forced, can do nothing more */
  166764. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166765. main_->iMCU_row_ctr++; /* count rows received */
  166766. }
  166767. /* Postprocessor typically will not swallow all the input data it is handed
  166768. * in one call (due to filling the output buffer first). Must be prepared
  166769. * to exit and restart. This switch lets us keep track of how far we got.
  166770. * Note that each case falls through to the next on successful completion.
  166771. */
  166772. switch (main_->context_state) {
  166773. case CTX_POSTPONED_ROW:
  166774. /* Call postprocessor using previously set pointers for postponed row */
  166775. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166776. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166777. output_buf, out_row_ctr, out_rows_avail);
  166778. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166779. return; /* Need to suspend */
  166780. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166781. if (*out_row_ctr >= out_rows_avail)
  166782. return; /* Postprocessor exactly filled output buf */
  166783. /*FALLTHROUGH*/
  166784. case CTX_PREPARE_FOR_IMCU:
  166785. /* Prepare to process first M-1 row groups of this iMCU row */
  166786. main_->rowgroup_ctr = 0;
  166787. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  166788. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  166789. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  166790. */
  166791. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  166792. set_bottom_pointers(cinfo);
  166793. main_->context_state = CTX_PROCESS_IMCU;
  166794. /*FALLTHROUGH*/
  166795. case CTX_PROCESS_IMCU:
  166796. /* Call postprocessor using previously set pointers */
  166797. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166798. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166799. output_buf, out_row_ctr, out_rows_avail);
  166800. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166801. return; /* Need to suspend */
  166802. /* After the first iMCU, change wraparound pointers to normal state */
  166803. if (main_->iMCU_row_ctr == 1)
  166804. set_wraparound_pointers(cinfo);
  166805. /* Prepare to load new iMCU row using other xbuffer list */
  166806. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  166807. main_->buffer_full = FALSE;
  166808. /* Still need to process last row group of this iMCU row, */
  166809. /* which is saved at index M+1 of the other xbuffer */
  166810. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  166811. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  166812. main_->context_state = CTX_POSTPONED_ROW;
  166813. }
  166814. }
  166815. /*
  166816. * Process some data.
  166817. * Final pass of two-pass quantization: just call the postprocessor.
  166818. * Source data will be the postprocessor controller's internal buffer.
  166819. */
  166820. #ifdef QUANT_2PASS_SUPPORTED
  166821. METHODDEF(void)
  166822. process_data_crank_post (j_decompress_ptr cinfo,
  166823. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166824. JDIMENSION out_rows_avail)
  166825. {
  166826. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  166827. (JDIMENSION *) NULL, (JDIMENSION) 0,
  166828. output_buf, out_row_ctr, out_rows_avail);
  166829. }
  166830. #endif /* QUANT_2PASS_SUPPORTED */
  166831. /*
  166832. * Initialize main buffer controller.
  166833. */
  166834. GLOBAL(void)
  166835. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  166836. {
  166837. my_main_ptr4 main_;
  166838. int ci, rgroup, ngroups;
  166839. jpeg_component_info *compptr;
  166840. main_ = (my_main_ptr4)
  166841. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166842. SIZEOF(my_main_controller4));
  166843. cinfo->main = (struct jpeg_d_main_controller *) main_;
  166844. main_->pub.start_pass = start_pass_main2;
  166845. if (need_full_buffer) /* shouldn't happen */
  166846. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166847. /* Allocate the workspace.
  166848. * ngroups is the number of row groups we need.
  166849. */
  166850. if (cinfo->upsample->need_context_rows) {
  166851. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  166852. ERREXIT(cinfo, JERR_NOTIMPL);
  166853. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  166854. ngroups = cinfo->min_DCT_scaled_size + 2;
  166855. } else {
  166856. ngroups = cinfo->min_DCT_scaled_size;
  166857. }
  166858. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166859. ci++, compptr++) {
  166860. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166861. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166862. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  166863. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166864. compptr->width_in_blocks * compptr->DCT_scaled_size,
  166865. (JDIMENSION) (rgroup * ngroups));
  166866. }
  166867. }
  166868. /********* End of inlined file: jdmainct.c *********/
  166869. /********* Start of inlined file: jdmarker.c *********/
  166870. #define JPEG_INTERNALS
  166871. /* Private state */
  166872. typedef struct {
  166873. struct jpeg_marker_reader pub; /* public fields */
  166874. /* Application-overridable marker processing methods */
  166875. jpeg_marker_parser_method process_COM;
  166876. jpeg_marker_parser_method process_APPn[16];
  166877. /* Limit on marker data length to save for each marker type */
  166878. unsigned int length_limit_COM;
  166879. unsigned int length_limit_APPn[16];
  166880. /* Status of COM/APPn marker saving */
  166881. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  166882. unsigned int bytes_read; /* data bytes read so far in marker */
  166883. /* Note: cur_marker is not linked into marker_list until it's all read. */
  166884. } my_marker_reader;
  166885. typedef my_marker_reader * my_marker_ptr2;
  166886. /*
  166887. * Macros for fetching data from the data source module.
  166888. *
  166889. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  166890. * the current restart point; we update them only when we have reached a
  166891. * suitable place to restart if a suspension occurs.
  166892. */
  166893. /* Declare and initialize local copies of input pointer/count */
  166894. #define INPUT_VARS(cinfo) \
  166895. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  166896. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  166897. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  166898. /* Unload the local copies --- do this only at a restart boundary */
  166899. #define INPUT_SYNC(cinfo) \
  166900. ( datasrc->next_input_byte = next_input_byte, \
  166901. datasrc->bytes_in_buffer = bytes_in_buffer )
  166902. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  166903. #define INPUT_RELOAD(cinfo) \
  166904. ( next_input_byte = datasrc->next_input_byte, \
  166905. bytes_in_buffer = datasrc->bytes_in_buffer )
  166906. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  166907. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  166908. * but we must reload the local copies after a successful fill.
  166909. */
  166910. #define MAKE_BYTE_AVAIL(cinfo,action) \
  166911. if (bytes_in_buffer == 0) { \
  166912. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  166913. { action; } \
  166914. INPUT_RELOAD(cinfo); \
  166915. }
  166916. /* Read a byte into variable V.
  166917. * If must suspend, take the specified action (typically "return FALSE").
  166918. */
  166919. #define INPUT_BYTE(cinfo,V,action) \
  166920. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166921. bytes_in_buffer--; \
  166922. V = GETJOCTET(*next_input_byte++); )
  166923. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  166924. * V should be declared unsigned int or perhaps INT32.
  166925. */
  166926. #define INPUT_2BYTES(cinfo,V,action) \
  166927. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166928. bytes_in_buffer--; \
  166929. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  166930. MAKE_BYTE_AVAIL(cinfo,action); \
  166931. bytes_in_buffer--; \
  166932. V += GETJOCTET(*next_input_byte++); )
  166933. /*
  166934. * Routines to process JPEG markers.
  166935. *
  166936. * Entry condition: JPEG marker itself has been read and its code saved
  166937. * in cinfo->unread_marker; input restart point is just after the marker.
  166938. *
  166939. * Exit: if return TRUE, have read and processed any parameters, and have
  166940. * updated the restart point to point after the parameters.
  166941. * If return FALSE, was forced to suspend before reaching end of
  166942. * marker parameters; restart point has not been moved. Same routine
  166943. * will be called again after application supplies more input data.
  166944. *
  166945. * This approach to suspension assumes that all of a marker's parameters
  166946. * can fit into a single input bufferload. This should hold for "normal"
  166947. * markers. Some COM/APPn markers might have large parameter segments
  166948. * that might not fit. If we are simply dropping such a marker, we use
  166949. * skip_input_data to get past it, and thereby put the problem on the
  166950. * source manager's shoulders. If we are saving the marker's contents
  166951. * into memory, we use a slightly different convention: when forced to
  166952. * suspend, the marker processor updates the restart point to the end of
  166953. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  166954. * On resumption, cinfo->unread_marker still contains the marker code,
  166955. * but the data source will point to the next chunk of marker data.
  166956. * The marker processor must retain internal state to deal with this.
  166957. *
  166958. * Note that we don't bother to avoid duplicate trace messages if a
  166959. * suspension occurs within marker parameters. Other side effects
  166960. * require more care.
  166961. */
  166962. LOCAL(boolean)
  166963. get_soi (j_decompress_ptr cinfo)
  166964. /* Process an SOI marker */
  166965. {
  166966. int i;
  166967. TRACEMS(cinfo, 1, JTRC_SOI);
  166968. if (cinfo->marker->saw_SOI)
  166969. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  166970. /* Reset all parameters that are defined to be reset by SOI */
  166971. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  166972. cinfo->arith_dc_L[i] = 0;
  166973. cinfo->arith_dc_U[i] = 1;
  166974. cinfo->arith_ac_K[i] = 5;
  166975. }
  166976. cinfo->restart_interval = 0;
  166977. /* Set initial assumptions for colorspace etc */
  166978. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166979. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  166980. cinfo->saw_JFIF_marker = FALSE;
  166981. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  166982. cinfo->JFIF_minor_version = 1;
  166983. cinfo->density_unit = 0;
  166984. cinfo->X_density = 1;
  166985. cinfo->Y_density = 1;
  166986. cinfo->saw_Adobe_marker = FALSE;
  166987. cinfo->Adobe_transform = 0;
  166988. cinfo->marker->saw_SOI = TRUE;
  166989. return TRUE;
  166990. }
  166991. LOCAL(boolean)
  166992. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  166993. /* Process a SOFn marker */
  166994. {
  166995. INT32 length;
  166996. int c, ci;
  166997. jpeg_component_info * compptr;
  166998. INPUT_VARS(cinfo);
  166999. cinfo->progressive_mode = is_prog;
  167000. cinfo->arith_code = is_arith;
  167001. INPUT_2BYTES(cinfo, length, return FALSE);
  167002. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  167003. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  167004. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  167005. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  167006. length -= 8;
  167007. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  167008. (int) cinfo->image_width, (int) cinfo->image_height,
  167009. cinfo->num_components);
  167010. if (cinfo->marker->saw_SOF)
  167011. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  167012. /* We don't support files in which the image height is initially specified */
  167013. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  167014. /* might as well have a general sanity check. */
  167015. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  167016. || cinfo->num_components <= 0)
  167017. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  167018. if (length != (cinfo->num_components * 3))
  167019. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167020. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  167021. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  167022. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167023. cinfo->num_components * SIZEOF(jpeg_component_info));
  167024. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167025. ci++, compptr++) {
  167026. compptr->component_index = ci;
  167027. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  167028. INPUT_BYTE(cinfo, c, return FALSE);
  167029. compptr->h_samp_factor = (c >> 4) & 15;
  167030. compptr->v_samp_factor = (c ) & 15;
  167031. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  167032. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  167033. compptr->component_id, compptr->h_samp_factor,
  167034. compptr->v_samp_factor, compptr->quant_tbl_no);
  167035. }
  167036. cinfo->marker->saw_SOF = TRUE;
  167037. INPUT_SYNC(cinfo);
  167038. return TRUE;
  167039. }
  167040. LOCAL(boolean)
  167041. get_sos (j_decompress_ptr cinfo)
  167042. /* Process a SOS marker */
  167043. {
  167044. INT32 length;
  167045. int i, ci, n, c, cc;
  167046. jpeg_component_info * compptr;
  167047. INPUT_VARS(cinfo);
  167048. if (! cinfo->marker->saw_SOF)
  167049. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  167050. INPUT_2BYTES(cinfo, length, return FALSE);
  167051. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  167052. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  167053. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  167054. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167055. cinfo->comps_in_scan = n;
  167056. /* Collect the component-spec parameters */
  167057. for (i = 0; i < n; i++) {
  167058. INPUT_BYTE(cinfo, cc, return FALSE);
  167059. INPUT_BYTE(cinfo, c, return FALSE);
  167060. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167061. ci++, compptr++) {
  167062. if (cc == compptr->component_id)
  167063. goto id_found;
  167064. }
  167065. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  167066. id_found:
  167067. cinfo->cur_comp_info[i] = compptr;
  167068. compptr->dc_tbl_no = (c >> 4) & 15;
  167069. compptr->ac_tbl_no = (c ) & 15;
  167070. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  167071. compptr->dc_tbl_no, compptr->ac_tbl_no);
  167072. }
  167073. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  167074. INPUT_BYTE(cinfo, c, return FALSE);
  167075. cinfo->Ss = c;
  167076. INPUT_BYTE(cinfo, c, return FALSE);
  167077. cinfo->Se = c;
  167078. INPUT_BYTE(cinfo, c, return FALSE);
  167079. cinfo->Ah = (c >> 4) & 15;
  167080. cinfo->Al = (c ) & 15;
  167081. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  167082. cinfo->Ah, cinfo->Al);
  167083. /* Prepare to scan data & restart markers */
  167084. cinfo->marker->next_restart_num = 0;
  167085. /* Count another SOS marker */
  167086. cinfo->input_scan_number++;
  167087. INPUT_SYNC(cinfo);
  167088. return TRUE;
  167089. }
  167090. #ifdef D_ARITH_CODING_SUPPORTED
  167091. LOCAL(boolean)
  167092. get_dac (j_decompress_ptr cinfo)
  167093. /* Process a DAC marker */
  167094. {
  167095. INT32 length;
  167096. int index, val;
  167097. INPUT_VARS(cinfo);
  167098. INPUT_2BYTES(cinfo, length, return FALSE);
  167099. length -= 2;
  167100. while (length > 0) {
  167101. INPUT_BYTE(cinfo, index, return FALSE);
  167102. INPUT_BYTE(cinfo, val, return FALSE);
  167103. length -= 2;
  167104. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  167105. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  167106. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  167107. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  167108. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  167109. } else { /* define DC table */
  167110. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  167111. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  167112. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  167113. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  167114. }
  167115. }
  167116. if (length != 0)
  167117. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167118. INPUT_SYNC(cinfo);
  167119. return TRUE;
  167120. }
  167121. #else /* ! D_ARITH_CODING_SUPPORTED */
  167122. #define get_dac(cinfo) skip_variable(cinfo)
  167123. #endif /* D_ARITH_CODING_SUPPORTED */
  167124. LOCAL(boolean)
  167125. get_dht (j_decompress_ptr cinfo)
  167126. /* Process a DHT marker */
  167127. {
  167128. INT32 length;
  167129. UINT8 bits[17];
  167130. UINT8 huffval[256];
  167131. int i, index, count;
  167132. JHUFF_TBL **htblptr;
  167133. INPUT_VARS(cinfo);
  167134. INPUT_2BYTES(cinfo, length, return FALSE);
  167135. length -= 2;
  167136. while (length > 16) {
  167137. INPUT_BYTE(cinfo, index, return FALSE);
  167138. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  167139. bits[0] = 0;
  167140. count = 0;
  167141. for (i = 1; i <= 16; i++) {
  167142. INPUT_BYTE(cinfo, bits[i], return FALSE);
  167143. count += bits[i];
  167144. }
  167145. length -= 1 + 16;
  167146. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167147. bits[1], bits[2], bits[3], bits[4],
  167148. bits[5], bits[6], bits[7], bits[8]);
  167149. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  167150. bits[9], bits[10], bits[11], bits[12],
  167151. bits[13], bits[14], bits[15], bits[16]);
  167152. /* Here we just do minimal validation of the counts to avoid walking
  167153. * off the end of our table space. jdhuff.c will check more carefully.
  167154. */
  167155. if (count > 256 || ((INT32) count) > length)
  167156. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  167157. for (i = 0; i < count; i++)
  167158. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  167159. length -= count;
  167160. if (index & 0x10) { /* AC table definition */
  167161. index -= 0x10;
  167162. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  167163. } else { /* DC table definition */
  167164. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  167165. }
  167166. if (index < 0 || index >= NUM_HUFF_TBLS)
  167167. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  167168. if (*htblptr == NULL)
  167169. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  167170. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  167171. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  167172. }
  167173. if (length != 0)
  167174. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167175. INPUT_SYNC(cinfo);
  167176. return TRUE;
  167177. }
  167178. LOCAL(boolean)
  167179. get_dqt (j_decompress_ptr cinfo)
  167180. /* Process a DQT marker */
  167181. {
  167182. INT32 length;
  167183. int n, i, prec;
  167184. unsigned int tmp;
  167185. JQUANT_TBL *quant_ptr;
  167186. INPUT_VARS(cinfo);
  167187. INPUT_2BYTES(cinfo, length, return FALSE);
  167188. length -= 2;
  167189. while (length > 0) {
  167190. INPUT_BYTE(cinfo, n, return FALSE);
  167191. prec = n >> 4;
  167192. n &= 0x0F;
  167193. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  167194. if (n >= NUM_QUANT_TBLS)
  167195. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  167196. if (cinfo->quant_tbl_ptrs[n] == NULL)
  167197. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  167198. quant_ptr = cinfo->quant_tbl_ptrs[n];
  167199. for (i = 0; i < DCTSIZE2; i++) {
  167200. if (prec)
  167201. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167202. else
  167203. INPUT_BYTE(cinfo, tmp, return FALSE);
  167204. /* We convert the zigzag-order table to natural array order. */
  167205. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  167206. }
  167207. if (cinfo->err->trace_level >= 2) {
  167208. for (i = 0; i < DCTSIZE2; i += 8) {
  167209. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  167210. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  167211. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  167212. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  167213. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  167214. }
  167215. }
  167216. length -= DCTSIZE2+1;
  167217. if (prec) length -= DCTSIZE2;
  167218. }
  167219. if (length != 0)
  167220. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167221. INPUT_SYNC(cinfo);
  167222. return TRUE;
  167223. }
  167224. LOCAL(boolean)
  167225. get_dri (j_decompress_ptr cinfo)
  167226. /* Process a DRI marker */
  167227. {
  167228. INT32 length;
  167229. unsigned int tmp;
  167230. INPUT_VARS(cinfo);
  167231. INPUT_2BYTES(cinfo, length, return FALSE);
  167232. if (length != 4)
  167233. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167234. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167235. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  167236. cinfo->restart_interval = tmp;
  167237. INPUT_SYNC(cinfo);
  167238. return TRUE;
  167239. }
  167240. /*
  167241. * Routines for processing APPn and COM markers.
  167242. * These are either saved in memory or discarded, per application request.
  167243. * APP0 and APP14 are specially checked to see if they are
  167244. * JFIF and Adobe markers, respectively.
  167245. */
  167246. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  167247. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  167248. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  167249. LOCAL(void)
  167250. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167251. unsigned int datalen, INT32 remaining)
  167252. /* Examine first few bytes from an APP0.
  167253. * Take appropriate action if it is a JFIF marker.
  167254. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167255. */
  167256. {
  167257. INT32 totallen = (INT32) datalen + remaining;
  167258. if (datalen >= APP0_DATA_LEN &&
  167259. GETJOCTET(data[0]) == 0x4A &&
  167260. GETJOCTET(data[1]) == 0x46 &&
  167261. GETJOCTET(data[2]) == 0x49 &&
  167262. GETJOCTET(data[3]) == 0x46 &&
  167263. GETJOCTET(data[4]) == 0) {
  167264. /* Found JFIF APP0 marker: save info */
  167265. cinfo->saw_JFIF_marker = TRUE;
  167266. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  167267. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  167268. cinfo->density_unit = GETJOCTET(data[7]);
  167269. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  167270. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  167271. /* Check version.
  167272. * Major version must be 1, anything else signals an incompatible change.
  167273. * (We used to treat this as an error, but now it's a nonfatal warning,
  167274. * because some bozo at Hijaak couldn't read the spec.)
  167275. * Minor version should be 0..2, but process anyway if newer.
  167276. */
  167277. if (cinfo->JFIF_major_version != 1)
  167278. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  167279. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  167280. /* Generate trace messages */
  167281. TRACEMS5(cinfo, 1, JTRC_JFIF,
  167282. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  167283. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  167284. /* Validate thumbnail dimensions and issue appropriate messages */
  167285. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  167286. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  167287. GETJOCTET(data[12]), GETJOCTET(data[13]));
  167288. totallen -= APP0_DATA_LEN;
  167289. if (totallen !=
  167290. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  167291. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  167292. } else if (datalen >= 6 &&
  167293. GETJOCTET(data[0]) == 0x4A &&
  167294. GETJOCTET(data[1]) == 0x46 &&
  167295. GETJOCTET(data[2]) == 0x58 &&
  167296. GETJOCTET(data[3]) == 0x58 &&
  167297. GETJOCTET(data[4]) == 0) {
  167298. /* Found JFIF "JFXX" extension APP0 marker */
  167299. /* The library doesn't actually do anything with these,
  167300. * but we try to produce a helpful trace message.
  167301. */
  167302. switch (GETJOCTET(data[5])) {
  167303. case 0x10:
  167304. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  167305. break;
  167306. case 0x11:
  167307. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  167308. break;
  167309. case 0x13:
  167310. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  167311. break;
  167312. default:
  167313. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  167314. GETJOCTET(data[5]), (int) totallen);
  167315. break;
  167316. }
  167317. } else {
  167318. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  167319. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  167320. }
  167321. }
  167322. LOCAL(void)
  167323. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167324. unsigned int datalen, INT32 remaining)
  167325. /* Examine first few bytes from an APP14.
  167326. * Take appropriate action if it is an Adobe marker.
  167327. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167328. */
  167329. {
  167330. unsigned int version, flags0, flags1, transform;
  167331. if (datalen >= APP14_DATA_LEN &&
  167332. GETJOCTET(data[0]) == 0x41 &&
  167333. GETJOCTET(data[1]) == 0x64 &&
  167334. GETJOCTET(data[2]) == 0x6F &&
  167335. GETJOCTET(data[3]) == 0x62 &&
  167336. GETJOCTET(data[4]) == 0x65) {
  167337. /* Found Adobe APP14 marker */
  167338. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  167339. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  167340. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  167341. transform = GETJOCTET(data[11]);
  167342. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  167343. cinfo->saw_Adobe_marker = TRUE;
  167344. cinfo->Adobe_transform = (UINT8) transform;
  167345. } else {
  167346. /* Start of APP14 does not match "Adobe", or too short */
  167347. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  167348. }
  167349. }
  167350. METHODDEF(boolean)
  167351. get_interesting_appn (j_decompress_ptr cinfo)
  167352. /* Process an APP0 or APP14 marker without saving it */
  167353. {
  167354. INT32 length;
  167355. JOCTET b[APPN_DATA_LEN];
  167356. unsigned int i, numtoread;
  167357. INPUT_VARS(cinfo);
  167358. INPUT_2BYTES(cinfo, length, return FALSE);
  167359. length -= 2;
  167360. /* get the interesting part of the marker data */
  167361. if (length >= APPN_DATA_LEN)
  167362. numtoread = APPN_DATA_LEN;
  167363. else if (length > 0)
  167364. numtoread = (unsigned int) length;
  167365. else
  167366. numtoread = 0;
  167367. for (i = 0; i < numtoread; i++)
  167368. INPUT_BYTE(cinfo, b[i], return FALSE);
  167369. length -= numtoread;
  167370. /* process it */
  167371. switch (cinfo->unread_marker) {
  167372. case M_APP0:
  167373. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  167374. break;
  167375. case M_APP14:
  167376. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  167377. break;
  167378. default:
  167379. /* can't get here unless jpeg_save_markers chooses wrong processor */
  167380. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167381. break;
  167382. }
  167383. /* skip any remaining data -- could be lots */
  167384. INPUT_SYNC(cinfo);
  167385. if (length > 0)
  167386. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167387. return TRUE;
  167388. }
  167389. #ifdef SAVE_MARKERS_SUPPORTED
  167390. METHODDEF(boolean)
  167391. save_marker (j_decompress_ptr cinfo)
  167392. /* Save an APPn or COM marker into the marker list */
  167393. {
  167394. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167395. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  167396. unsigned int bytes_read, data_length;
  167397. JOCTET FAR * data;
  167398. INT32 length = 0;
  167399. INPUT_VARS(cinfo);
  167400. if (cur_marker == NULL) {
  167401. /* begin reading a marker */
  167402. INPUT_2BYTES(cinfo, length, return FALSE);
  167403. length -= 2;
  167404. if (length >= 0) { /* watch out for bogus length word */
  167405. /* figure out how much we want to save */
  167406. unsigned int limit;
  167407. if (cinfo->unread_marker == (int) M_COM)
  167408. limit = marker->length_limit_COM;
  167409. else
  167410. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  167411. if ((unsigned int) length < limit)
  167412. limit = (unsigned int) length;
  167413. /* allocate and initialize the marker item */
  167414. cur_marker = (jpeg_saved_marker_ptr)
  167415. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167416. SIZEOF(struct jpeg_marker_struct) + limit);
  167417. cur_marker->next = NULL;
  167418. cur_marker->marker = (UINT8) cinfo->unread_marker;
  167419. cur_marker->original_length = (unsigned int) length;
  167420. cur_marker->data_length = limit;
  167421. /* data area is just beyond the jpeg_marker_struct */
  167422. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  167423. marker->cur_marker = cur_marker;
  167424. marker->bytes_read = 0;
  167425. bytes_read = 0;
  167426. data_length = limit;
  167427. } else {
  167428. /* deal with bogus length word */
  167429. bytes_read = data_length = 0;
  167430. data = NULL;
  167431. }
  167432. } else {
  167433. /* resume reading a marker */
  167434. bytes_read = marker->bytes_read;
  167435. data_length = cur_marker->data_length;
  167436. data = cur_marker->data + bytes_read;
  167437. }
  167438. while (bytes_read < data_length) {
  167439. INPUT_SYNC(cinfo); /* move the restart point to here */
  167440. marker->bytes_read = bytes_read;
  167441. /* If there's not at least one byte in buffer, suspend */
  167442. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  167443. /* Copy bytes with reasonable rapidity */
  167444. while (bytes_read < data_length && bytes_in_buffer > 0) {
  167445. *data++ = *next_input_byte++;
  167446. bytes_in_buffer--;
  167447. bytes_read++;
  167448. }
  167449. }
  167450. /* Done reading what we want to read */
  167451. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  167452. /* Add new marker to end of list */
  167453. if (cinfo->marker_list == NULL) {
  167454. cinfo->marker_list = cur_marker;
  167455. } else {
  167456. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  167457. while (prev->next != NULL)
  167458. prev = prev->next;
  167459. prev->next = cur_marker;
  167460. }
  167461. /* Reset pointer & calc remaining data length */
  167462. data = cur_marker->data;
  167463. length = cur_marker->original_length - data_length;
  167464. }
  167465. /* Reset to initial state for next marker */
  167466. marker->cur_marker = NULL;
  167467. /* Process the marker if interesting; else just make a generic trace msg */
  167468. switch (cinfo->unread_marker) {
  167469. case M_APP0:
  167470. examine_app0(cinfo, data, data_length, length);
  167471. break;
  167472. case M_APP14:
  167473. examine_app14(cinfo, data, data_length, length);
  167474. break;
  167475. default:
  167476. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  167477. (int) (data_length + length));
  167478. break;
  167479. }
  167480. /* skip any remaining data -- could be lots */
  167481. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167482. if (length > 0)
  167483. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167484. return TRUE;
  167485. }
  167486. #endif /* SAVE_MARKERS_SUPPORTED */
  167487. METHODDEF(boolean)
  167488. skip_variable (j_decompress_ptr cinfo)
  167489. /* Skip over an unknown or uninteresting variable-length marker */
  167490. {
  167491. INT32 length;
  167492. INPUT_VARS(cinfo);
  167493. INPUT_2BYTES(cinfo, length, return FALSE);
  167494. length -= 2;
  167495. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  167496. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167497. if (length > 0)
  167498. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167499. return TRUE;
  167500. }
  167501. /*
  167502. * Find the next JPEG marker, save it in cinfo->unread_marker.
  167503. * Returns FALSE if had to suspend before reaching a marker;
  167504. * in that case cinfo->unread_marker is unchanged.
  167505. *
  167506. * Note that the result might not be a valid marker code,
  167507. * but it will never be 0 or FF.
  167508. */
  167509. LOCAL(boolean)
  167510. next_marker (j_decompress_ptr cinfo)
  167511. {
  167512. int c;
  167513. INPUT_VARS(cinfo);
  167514. for (;;) {
  167515. INPUT_BYTE(cinfo, c, return FALSE);
  167516. /* Skip any non-FF bytes.
  167517. * This may look a bit inefficient, but it will not occur in a valid file.
  167518. * We sync after each discarded byte so that a suspending data source
  167519. * can discard the byte from its buffer.
  167520. */
  167521. while (c != 0xFF) {
  167522. cinfo->marker->discarded_bytes++;
  167523. INPUT_SYNC(cinfo);
  167524. INPUT_BYTE(cinfo, c, return FALSE);
  167525. }
  167526. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  167527. * pad bytes, so don't count them in discarded_bytes. We assume there
  167528. * will not be so many consecutive FF bytes as to overflow a suspending
  167529. * data source's input buffer.
  167530. */
  167531. do {
  167532. INPUT_BYTE(cinfo, c, return FALSE);
  167533. } while (c == 0xFF);
  167534. if (c != 0)
  167535. break; /* found a valid marker, exit loop */
  167536. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  167537. * Discard it and loop back to try again.
  167538. */
  167539. cinfo->marker->discarded_bytes += 2;
  167540. INPUT_SYNC(cinfo);
  167541. }
  167542. if (cinfo->marker->discarded_bytes != 0) {
  167543. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  167544. cinfo->marker->discarded_bytes = 0;
  167545. }
  167546. cinfo->unread_marker = c;
  167547. INPUT_SYNC(cinfo);
  167548. return TRUE;
  167549. }
  167550. LOCAL(boolean)
  167551. first_marker (j_decompress_ptr cinfo)
  167552. /* Like next_marker, but used to obtain the initial SOI marker. */
  167553. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  167554. * we might well scan an entire input file before realizing it ain't JPEG.
  167555. * If an application wants to process non-JFIF files, it must seek to the
  167556. * SOI before calling the JPEG library.
  167557. */
  167558. {
  167559. int c, c2;
  167560. INPUT_VARS(cinfo);
  167561. INPUT_BYTE(cinfo, c, return FALSE);
  167562. INPUT_BYTE(cinfo, c2, return FALSE);
  167563. if (c != 0xFF || c2 != (int) M_SOI)
  167564. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  167565. cinfo->unread_marker = c2;
  167566. INPUT_SYNC(cinfo);
  167567. return TRUE;
  167568. }
  167569. /*
  167570. * Read markers until SOS or EOI.
  167571. *
  167572. * Returns same codes as are defined for jpeg_consume_input:
  167573. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167574. */
  167575. METHODDEF(int)
  167576. read_markers (j_decompress_ptr cinfo)
  167577. {
  167578. /* Outer loop repeats once for each marker. */
  167579. for (;;) {
  167580. /* Collect the marker proper, unless we already did. */
  167581. /* NB: first_marker() enforces the requirement that SOI appear first. */
  167582. if (cinfo->unread_marker == 0) {
  167583. if (! cinfo->marker->saw_SOI) {
  167584. if (! first_marker(cinfo))
  167585. return JPEG_SUSPENDED;
  167586. } else {
  167587. if (! next_marker(cinfo))
  167588. return JPEG_SUSPENDED;
  167589. }
  167590. }
  167591. /* At this point cinfo->unread_marker contains the marker code and the
  167592. * input point is just past the marker proper, but before any parameters.
  167593. * A suspension will cause us to return with this state still true.
  167594. */
  167595. switch (cinfo->unread_marker) {
  167596. case M_SOI:
  167597. if (! get_soi(cinfo))
  167598. return JPEG_SUSPENDED;
  167599. break;
  167600. case M_SOF0: /* Baseline */
  167601. case M_SOF1: /* Extended sequential, Huffman */
  167602. if (! get_sof(cinfo, FALSE, FALSE))
  167603. return JPEG_SUSPENDED;
  167604. break;
  167605. case M_SOF2: /* Progressive, Huffman */
  167606. if (! get_sof(cinfo, TRUE, FALSE))
  167607. return JPEG_SUSPENDED;
  167608. break;
  167609. case M_SOF9: /* Extended sequential, arithmetic */
  167610. if (! get_sof(cinfo, FALSE, TRUE))
  167611. return JPEG_SUSPENDED;
  167612. break;
  167613. case M_SOF10: /* Progressive, arithmetic */
  167614. if (! get_sof(cinfo, TRUE, TRUE))
  167615. return JPEG_SUSPENDED;
  167616. break;
  167617. /* Currently unsupported SOFn types */
  167618. case M_SOF3: /* Lossless, Huffman */
  167619. case M_SOF5: /* Differential sequential, Huffman */
  167620. case M_SOF6: /* Differential progressive, Huffman */
  167621. case M_SOF7: /* Differential lossless, Huffman */
  167622. case M_JPG: /* Reserved for JPEG extensions */
  167623. case M_SOF11: /* Lossless, arithmetic */
  167624. case M_SOF13: /* Differential sequential, arithmetic */
  167625. case M_SOF14: /* Differential progressive, arithmetic */
  167626. case M_SOF15: /* Differential lossless, arithmetic */
  167627. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  167628. break;
  167629. case M_SOS:
  167630. if (! get_sos(cinfo))
  167631. return JPEG_SUSPENDED;
  167632. cinfo->unread_marker = 0; /* processed the marker */
  167633. return JPEG_REACHED_SOS;
  167634. case M_EOI:
  167635. TRACEMS(cinfo, 1, JTRC_EOI);
  167636. cinfo->unread_marker = 0; /* processed the marker */
  167637. return JPEG_REACHED_EOI;
  167638. case M_DAC:
  167639. if (! get_dac(cinfo))
  167640. return JPEG_SUSPENDED;
  167641. break;
  167642. case M_DHT:
  167643. if (! get_dht(cinfo))
  167644. return JPEG_SUSPENDED;
  167645. break;
  167646. case M_DQT:
  167647. if (! get_dqt(cinfo))
  167648. return JPEG_SUSPENDED;
  167649. break;
  167650. case M_DRI:
  167651. if (! get_dri(cinfo))
  167652. return JPEG_SUSPENDED;
  167653. break;
  167654. case M_APP0:
  167655. case M_APP1:
  167656. case M_APP2:
  167657. case M_APP3:
  167658. case M_APP4:
  167659. case M_APP5:
  167660. case M_APP6:
  167661. case M_APP7:
  167662. case M_APP8:
  167663. case M_APP9:
  167664. case M_APP10:
  167665. case M_APP11:
  167666. case M_APP12:
  167667. case M_APP13:
  167668. case M_APP14:
  167669. case M_APP15:
  167670. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  167671. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  167672. return JPEG_SUSPENDED;
  167673. break;
  167674. case M_COM:
  167675. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  167676. return JPEG_SUSPENDED;
  167677. break;
  167678. case M_RST0: /* these are all parameterless */
  167679. case M_RST1:
  167680. case M_RST2:
  167681. case M_RST3:
  167682. case M_RST4:
  167683. case M_RST5:
  167684. case M_RST6:
  167685. case M_RST7:
  167686. case M_TEM:
  167687. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  167688. break;
  167689. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  167690. if (! skip_variable(cinfo))
  167691. return JPEG_SUSPENDED;
  167692. break;
  167693. default: /* must be DHP, EXP, JPGn, or RESn */
  167694. /* For now, we treat the reserved markers as fatal errors since they are
  167695. * likely to be used to signal incompatible JPEG Part 3 extensions.
  167696. * Once the JPEG 3 version-number marker is well defined, this code
  167697. * ought to change!
  167698. */
  167699. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167700. break;
  167701. }
  167702. /* Successfully processed marker, so reset state variable */
  167703. cinfo->unread_marker = 0;
  167704. } /* end loop */
  167705. }
  167706. /*
  167707. * Read a restart marker, which is expected to appear next in the datastream;
  167708. * if the marker is not there, take appropriate recovery action.
  167709. * Returns FALSE if suspension is required.
  167710. *
  167711. * This is called by the entropy decoder after it has read an appropriate
  167712. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  167713. * has already read a marker from the data source. Under normal conditions
  167714. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  167715. * it holds a marker which the decoder will be unable to read past.
  167716. */
  167717. METHODDEF(boolean)
  167718. read_restart_marker (j_decompress_ptr cinfo)
  167719. {
  167720. /* Obtain a marker unless we already did. */
  167721. /* Note that next_marker will complain if it skips any data. */
  167722. if (cinfo->unread_marker == 0) {
  167723. if (! next_marker(cinfo))
  167724. return FALSE;
  167725. }
  167726. if (cinfo->unread_marker ==
  167727. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  167728. /* Normal case --- swallow the marker and let entropy decoder continue */
  167729. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  167730. cinfo->unread_marker = 0;
  167731. } else {
  167732. /* Uh-oh, the restart markers have been messed up. */
  167733. /* Let the data source manager determine how to resync. */
  167734. if (! (*cinfo->src->resync_to_restart) (cinfo,
  167735. cinfo->marker->next_restart_num))
  167736. return FALSE;
  167737. }
  167738. /* Update next-restart state */
  167739. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  167740. return TRUE;
  167741. }
  167742. /*
  167743. * This is the default resync_to_restart method for data source managers
  167744. * to use if they don't have any better approach. Some data source managers
  167745. * may be able to back up, or may have additional knowledge about the data
  167746. * which permits a more intelligent recovery strategy; such managers would
  167747. * presumably supply their own resync method.
  167748. *
  167749. * read_restart_marker calls resync_to_restart if it finds a marker other than
  167750. * the restart marker it was expecting. (This code is *not* used unless
  167751. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  167752. * the marker code actually found (might be anything, except 0 or FF).
  167753. * The desired restart marker number (0..7) is passed as a parameter.
  167754. * This routine is supposed to apply whatever error recovery strategy seems
  167755. * appropriate in order to position the input stream to the next data segment.
  167756. * Note that cinfo->unread_marker is treated as a marker appearing before
  167757. * the current data-source input point; usually it should be reset to zero
  167758. * before returning.
  167759. * Returns FALSE if suspension is required.
  167760. *
  167761. * This implementation is substantially constrained by wanting to treat the
  167762. * input as a data stream; this means we can't back up. Therefore, we have
  167763. * only the following actions to work with:
  167764. * 1. Simply discard the marker and let the entropy decoder resume at next
  167765. * byte of file.
  167766. * 2. Read forward until we find another marker, discarding intervening
  167767. * data. (In theory we could look ahead within the current bufferload,
  167768. * without having to discard data if we don't find the desired marker.
  167769. * This idea is not implemented here, in part because it makes behavior
  167770. * dependent on buffer size and chance buffer-boundary positions.)
  167771. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  167772. * This will cause the entropy decoder to process an empty data segment,
  167773. * inserting dummy zeroes, and then we will reprocess the marker.
  167774. *
  167775. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  167776. * appropriate if the found marker is a future restart marker (indicating
  167777. * that we have missed the desired restart marker, probably because it got
  167778. * corrupted).
  167779. * We apply #2 or #3 if the found marker is a restart marker no more than
  167780. * two counts behind or ahead of the expected one. We also apply #2 if the
  167781. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  167782. * If the found marker is a restart marker more than 2 counts away, we do #1
  167783. * (too much risk that the marker is erroneous; with luck we will be able to
  167784. * resync at some future point).
  167785. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  167786. * overrunning the end of a scan. An implementation limited to single-scan
  167787. * files might find it better to apply #2 for markers other than EOI, since
  167788. * any other marker would have to be bogus data in that case.
  167789. */
  167790. GLOBAL(boolean)
  167791. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  167792. {
  167793. int marker = cinfo->unread_marker;
  167794. int action = 1;
  167795. /* Always put up a warning. */
  167796. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  167797. /* Outer loop handles repeated decision after scanning forward. */
  167798. for (;;) {
  167799. if (marker < (int) M_SOF0)
  167800. action = 2; /* invalid marker */
  167801. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  167802. action = 3; /* valid non-restart marker */
  167803. else {
  167804. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  167805. marker == ((int) M_RST0 + ((desired+2) & 7)))
  167806. action = 3; /* one of the next two expected restarts */
  167807. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  167808. marker == ((int) M_RST0 + ((desired-2) & 7)))
  167809. action = 2; /* a prior restart, so advance */
  167810. else
  167811. action = 1; /* desired restart or too far away */
  167812. }
  167813. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  167814. switch (action) {
  167815. case 1:
  167816. /* Discard marker and let entropy decoder resume processing. */
  167817. cinfo->unread_marker = 0;
  167818. return TRUE;
  167819. case 2:
  167820. /* Scan to the next marker, and repeat the decision loop. */
  167821. if (! next_marker(cinfo))
  167822. return FALSE;
  167823. marker = cinfo->unread_marker;
  167824. break;
  167825. case 3:
  167826. /* Return without advancing past this marker. */
  167827. /* Entropy decoder will be forced to process an empty segment. */
  167828. return TRUE;
  167829. }
  167830. } /* end loop */
  167831. }
  167832. /*
  167833. * Reset marker processing state to begin a fresh datastream.
  167834. */
  167835. METHODDEF(void)
  167836. reset_marker_reader (j_decompress_ptr cinfo)
  167837. {
  167838. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167839. cinfo->comp_info = NULL; /* until allocated by get_sof */
  167840. cinfo->input_scan_number = 0; /* no SOS seen yet */
  167841. cinfo->unread_marker = 0; /* no pending marker */
  167842. marker->pub.saw_SOI = FALSE; /* set internal state too */
  167843. marker->pub.saw_SOF = FALSE;
  167844. marker->pub.discarded_bytes = 0;
  167845. marker->cur_marker = NULL;
  167846. }
  167847. /*
  167848. * Initialize the marker reader module.
  167849. * This is called only once, when the decompression object is created.
  167850. */
  167851. GLOBAL(void)
  167852. jinit_marker_reader (j_decompress_ptr cinfo)
  167853. {
  167854. my_marker_ptr2 marker;
  167855. int i;
  167856. /* Create subobject in permanent pool */
  167857. marker = (my_marker_ptr2)
  167858. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167859. SIZEOF(my_marker_reader));
  167860. cinfo->marker = (struct jpeg_marker_reader *) marker;
  167861. /* Initialize public method pointers */
  167862. marker->pub.reset_marker_reader = reset_marker_reader;
  167863. marker->pub.read_markers = read_markers;
  167864. marker->pub.read_restart_marker = read_restart_marker;
  167865. /* Initialize COM/APPn processing.
  167866. * By default, we examine and then discard APP0 and APP14,
  167867. * but simply discard COM and all other APPn.
  167868. */
  167869. marker->process_COM = skip_variable;
  167870. marker->length_limit_COM = 0;
  167871. for (i = 0; i < 16; i++) {
  167872. marker->process_APPn[i] = skip_variable;
  167873. marker->length_limit_APPn[i] = 0;
  167874. }
  167875. marker->process_APPn[0] = get_interesting_appn;
  167876. marker->process_APPn[14] = get_interesting_appn;
  167877. /* Reset marker processing state */
  167878. reset_marker_reader(cinfo);
  167879. }
  167880. /*
  167881. * Control saving of COM and APPn markers into marker_list.
  167882. */
  167883. #ifdef SAVE_MARKERS_SUPPORTED
  167884. GLOBAL(void)
  167885. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  167886. unsigned int length_limit)
  167887. {
  167888. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167889. long maxlength;
  167890. jpeg_marker_parser_method processor;
  167891. /* Length limit mustn't be larger than what we can allocate
  167892. * (should only be a concern in a 16-bit environment).
  167893. */
  167894. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  167895. if (((long) length_limit) > maxlength)
  167896. length_limit = (unsigned int) maxlength;
  167897. /* Choose processor routine to use.
  167898. * APP0/APP14 have special requirements.
  167899. */
  167900. if (length_limit) {
  167901. processor = save_marker;
  167902. /* If saving APP0/APP14, save at least enough for our internal use. */
  167903. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  167904. length_limit = APP0_DATA_LEN;
  167905. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  167906. length_limit = APP14_DATA_LEN;
  167907. } else {
  167908. processor = skip_variable;
  167909. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  167910. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  167911. processor = get_interesting_appn;
  167912. }
  167913. if (marker_code == (int) M_COM) {
  167914. marker->process_COM = processor;
  167915. marker->length_limit_COM = length_limit;
  167916. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  167917. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  167918. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  167919. } else
  167920. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167921. }
  167922. #endif /* SAVE_MARKERS_SUPPORTED */
  167923. /*
  167924. * Install a special processing method for COM or APPn markers.
  167925. */
  167926. GLOBAL(void)
  167927. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  167928. jpeg_marker_parser_method routine)
  167929. {
  167930. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167931. if (marker_code == (int) M_COM)
  167932. marker->process_COM = routine;
  167933. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  167934. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  167935. else
  167936. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167937. }
  167938. /********* End of inlined file: jdmarker.c *********/
  167939. /********* Start of inlined file: jdmaster.c *********/
  167940. #define JPEG_INTERNALS
  167941. /* Private state */
  167942. typedef struct {
  167943. struct jpeg_decomp_master pub; /* public fields */
  167944. int pass_number; /* # of passes completed */
  167945. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  167946. /* Saved references to initialized quantizer modules,
  167947. * in case we need to switch modes.
  167948. */
  167949. struct jpeg_color_quantizer * quantizer_1pass;
  167950. struct jpeg_color_quantizer * quantizer_2pass;
  167951. } my_decomp_master;
  167952. typedef my_decomp_master * my_master_ptr6;
  167953. /*
  167954. * Determine whether merged upsample/color conversion should be used.
  167955. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  167956. */
  167957. LOCAL(boolean)
  167958. use_merged_upsample (j_decompress_ptr cinfo)
  167959. {
  167960. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167961. /* Merging is the equivalent of plain box-filter upsampling */
  167962. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  167963. return FALSE;
  167964. /* jdmerge.c only supports YCC=>RGB color conversion */
  167965. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  167966. cinfo->out_color_space != JCS_RGB ||
  167967. cinfo->out_color_components != RGB_PIXELSIZE)
  167968. return FALSE;
  167969. /* and it only handles 2h1v or 2h2v sampling ratios */
  167970. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  167971. cinfo->comp_info[1].h_samp_factor != 1 ||
  167972. cinfo->comp_info[2].h_samp_factor != 1 ||
  167973. cinfo->comp_info[0].v_samp_factor > 2 ||
  167974. cinfo->comp_info[1].v_samp_factor != 1 ||
  167975. cinfo->comp_info[2].v_samp_factor != 1)
  167976. return FALSE;
  167977. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  167978. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167979. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167980. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  167981. return FALSE;
  167982. /* ??? also need to test for upsample-time rescaling, when & if supported */
  167983. return TRUE; /* by golly, it'll work... */
  167984. #else
  167985. return FALSE;
  167986. #endif
  167987. }
  167988. /*
  167989. * Compute output image dimensions and related values.
  167990. * NOTE: this is exported for possible use by application.
  167991. * Hence it mustn't do anything that can't be done twice.
  167992. * Also note that it may be called before the master module is initialized!
  167993. */
  167994. GLOBAL(void)
  167995. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  167996. /* Do computations that are needed before master selection phase */
  167997. {
  167998. #ifdef IDCT_SCALING_SUPPORTED
  167999. int ci;
  168000. jpeg_component_info *compptr;
  168001. #endif
  168002. /* Prevent application from calling me at wrong times */
  168003. if (cinfo->global_state != DSTATE_READY)
  168004. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168005. #ifdef IDCT_SCALING_SUPPORTED
  168006. /* Compute actual output image dimensions and DCT scaling choices. */
  168007. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  168008. /* Provide 1/8 scaling */
  168009. cinfo->output_width = (JDIMENSION)
  168010. jdiv_round_up((long) cinfo->image_width, 8L);
  168011. cinfo->output_height = (JDIMENSION)
  168012. jdiv_round_up((long) cinfo->image_height, 8L);
  168013. cinfo->min_DCT_scaled_size = 1;
  168014. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  168015. /* Provide 1/4 scaling */
  168016. cinfo->output_width = (JDIMENSION)
  168017. jdiv_round_up((long) cinfo->image_width, 4L);
  168018. cinfo->output_height = (JDIMENSION)
  168019. jdiv_round_up((long) cinfo->image_height, 4L);
  168020. cinfo->min_DCT_scaled_size = 2;
  168021. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  168022. /* Provide 1/2 scaling */
  168023. cinfo->output_width = (JDIMENSION)
  168024. jdiv_round_up((long) cinfo->image_width, 2L);
  168025. cinfo->output_height = (JDIMENSION)
  168026. jdiv_round_up((long) cinfo->image_height, 2L);
  168027. cinfo->min_DCT_scaled_size = 4;
  168028. } else {
  168029. /* Provide 1/1 scaling */
  168030. cinfo->output_width = cinfo->image_width;
  168031. cinfo->output_height = cinfo->image_height;
  168032. cinfo->min_DCT_scaled_size = DCTSIZE;
  168033. }
  168034. /* In selecting the actual DCT scaling for each component, we try to
  168035. * scale up the chroma components via IDCT scaling rather than upsampling.
  168036. * This saves time if the upsampler gets to use 1:1 scaling.
  168037. * Note this code assumes that the supported DCT scalings are powers of 2.
  168038. */
  168039. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168040. ci++, compptr++) {
  168041. int ssize = cinfo->min_DCT_scaled_size;
  168042. while (ssize < DCTSIZE &&
  168043. (compptr->h_samp_factor * ssize * 2 <=
  168044. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  168045. (compptr->v_samp_factor * ssize * 2 <=
  168046. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  168047. ssize = ssize * 2;
  168048. }
  168049. compptr->DCT_scaled_size = ssize;
  168050. }
  168051. /* Recompute downsampled dimensions of components;
  168052. * application needs to know these if using raw downsampled data.
  168053. */
  168054. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168055. ci++, compptr++) {
  168056. /* Size in samples, after IDCT scaling */
  168057. compptr->downsampled_width = (JDIMENSION)
  168058. jdiv_round_up((long) cinfo->image_width *
  168059. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  168060. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  168061. compptr->downsampled_height = (JDIMENSION)
  168062. jdiv_round_up((long) cinfo->image_height *
  168063. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  168064. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  168065. }
  168066. #else /* !IDCT_SCALING_SUPPORTED */
  168067. /* Hardwire it to "no scaling" */
  168068. cinfo->output_width = cinfo->image_width;
  168069. cinfo->output_height = cinfo->image_height;
  168070. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  168071. * and has computed unscaled downsampled_width and downsampled_height.
  168072. */
  168073. #endif /* IDCT_SCALING_SUPPORTED */
  168074. /* Report number of components in selected colorspace. */
  168075. /* Probably this should be in the color conversion module... */
  168076. switch (cinfo->out_color_space) {
  168077. case JCS_GRAYSCALE:
  168078. cinfo->out_color_components = 1;
  168079. break;
  168080. case JCS_RGB:
  168081. #if RGB_PIXELSIZE != 3
  168082. cinfo->out_color_components = RGB_PIXELSIZE;
  168083. break;
  168084. #endif /* else share code with YCbCr */
  168085. case JCS_YCbCr:
  168086. cinfo->out_color_components = 3;
  168087. break;
  168088. case JCS_CMYK:
  168089. case JCS_YCCK:
  168090. cinfo->out_color_components = 4;
  168091. break;
  168092. default: /* else must be same colorspace as in file */
  168093. cinfo->out_color_components = cinfo->num_components;
  168094. break;
  168095. }
  168096. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  168097. cinfo->out_color_components);
  168098. /* See if upsampler will want to emit more than one row at a time */
  168099. if (use_merged_upsample(cinfo))
  168100. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  168101. else
  168102. cinfo->rec_outbuf_height = 1;
  168103. }
  168104. /*
  168105. * Several decompression processes need to range-limit values to the range
  168106. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  168107. * due to noise introduced by quantization, roundoff error, etc. These
  168108. * processes are inner loops and need to be as fast as possible. On most
  168109. * machines, particularly CPUs with pipelines or instruction prefetch,
  168110. * a (subscript-check-less) C table lookup
  168111. * x = sample_range_limit[x];
  168112. * is faster than explicit tests
  168113. * if (x < 0) x = 0;
  168114. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  168115. * These processes all use a common table prepared by the routine below.
  168116. *
  168117. * For most steps we can mathematically guarantee that the initial value
  168118. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  168119. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  168120. * limiting step (just after the IDCT), a wildly out-of-range value is
  168121. * possible if the input data is corrupt. To avoid any chance of indexing
  168122. * off the end of memory and getting a bad-pointer trap, we perform the
  168123. * post-IDCT limiting thus:
  168124. * x = range_limit[x & MASK];
  168125. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  168126. * samples. Under normal circumstances this is more than enough range and
  168127. * a correct output will be generated; with bogus input data the mask will
  168128. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  168129. * For the post-IDCT step, we want to convert the data from signed to unsigned
  168130. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  168131. * So the post-IDCT limiting table ends up looking like this:
  168132. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  168133. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168134. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  168135. * 0,1,...,CENTERJSAMPLE-1
  168136. * Negative inputs select values from the upper half of the table after
  168137. * masking.
  168138. *
  168139. * We can save some space by overlapping the start of the post-IDCT table
  168140. * with the simpler range limiting table. The post-IDCT table begins at
  168141. * sample_range_limit + CENTERJSAMPLE.
  168142. *
  168143. * Note that the table is allocated in near data space on PCs; it's small
  168144. * enough and used often enough to justify this.
  168145. */
  168146. LOCAL(void)
  168147. prepare_range_limit_table (j_decompress_ptr cinfo)
  168148. /* Allocate and fill in the sample_range_limit table */
  168149. {
  168150. JSAMPLE * table;
  168151. int i;
  168152. table = (JSAMPLE *)
  168153. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168154. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168155. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  168156. cinfo->sample_range_limit = table;
  168157. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  168158. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  168159. /* Main part of "simple" table: limit[x] = x */
  168160. for (i = 0; i <= MAXJSAMPLE; i++)
  168161. table[i] = (JSAMPLE) i;
  168162. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  168163. /* End of simple table, rest of first half of post-IDCT table */
  168164. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  168165. table[i] = MAXJSAMPLE;
  168166. /* Second half of post-IDCT table */
  168167. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  168168. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  168169. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  168170. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  168171. }
  168172. /*
  168173. * Master selection of decompression modules.
  168174. * This is done once at jpeg_start_decompress time. We determine
  168175. * which modules will be used and give them appropriate initialization calls.
  168176. * We also initialize the decompressor input side to begin consuming data.
  168177. *
  168178. * Since jpeg_read_header has finished, we know what is in the SOF
  168179. * and (first) SOS markers. We also have all the application parameter
  168180. * settings.
  168181. */
  168182. LOCAL(void)
  168183. master_selection (j_decompress_ptr cinfo)
  168184. {
  168185. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168186. boolean use_c_buffer;
  168187. long samplesperrow;
  168188. JDIMENSION jd_samplesperrow;
  168189. /* Initialize dimensions and other stuff */
  168190. jpeg_calc_output_dimensions(cinfo);
  168191. prepare_range_limit_table(cinfo);
  168192. /* Width of an output scanline must be representable as JDIMENSION. */
  168193. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  168194. jd_samplesperrow = (JDIMENSION) samplesperrow;
  168195. if ((long) jd_samplesperrow != samplesperrow)
  168196. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  168197. /* Initialize my private state */
  168198. master->pass_number = 0;
  168199. master->using_merged_upsample = use_merged_upsample(cinfo);
  168200. /* Color quantizer selection */
  168201. master->quantizer_1pass = NULL;
  168202. master->quantizer_2pass = NULL;
  168203. /* No mode changes if not using buffered-image mode. */
  168204. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  168205. cinfo->enable_1pass_quant = FALSE;
  168206. cinfo->enable_external_quant = FALSE;
  168207. cinfo->enable_2pass_quant = FALSE;
  168208. }
  168209. if (cinfo->quantize_colors) {
  168210. if (cinfo->raw_data_out)
  168211. ERREXIT(cinfo, JERR_NOTIMPL);
  168212. /* 2-pass quantizer only works in 3-component color space. */
  168213. if (cinfo->out_color_components != 3) {
  168214. cinfo->enable_1pass_quant = TRUE;
  168215. cinfo->enable_external_quant = FALSE;
  168216. cinfo->enable_2pass_quant = FALSE;
  168217. cinfo->colormap = NULL;
  168218. } else if (cinfo->colormap != NULL) {
  168219. cinfo->enable_external_quant = TRUE;
  168220. } else if (cinfo->two_pass_quantize) {
  168221. cinfo->enable_2pass_quant = TRUE;
  168222. } else {
  168223. cinfo->enable_1pass_quant = TRUE;
  168224. }
  168225. if (cinfo->enable_1pass_quant) {
  168226. #ifdef QUANT_1PASS_SUPPORTED
  168227. jinit_1pass_quantizer(cinfo);
  168228. master->quantizer_1pass = cinfo->cquantize;
  168229. #else
  168230. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168231. #endif
  168232. }
  168233. /* We use the 2-pass code to map to external colormaps. */
  168234. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  168235. #ifdef QUANT_2PASS_SUPPORTED
  168236. jinit_2pass_quantizer(cinfo);
  168237. master->quantizer_2pass = cinfo->cquantize;
  168238. #else
  168239. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168240. #endif
  168241. }
  168242. /* If both quantizers are initialized, the 2-pass one is left active;
  168243. * this is necessary for starting with quantization to an external map.
  168244. */
  168245. }
  168246. /* Post-processing: in particular, color conversion first */
  168247. if (! cinfo->raw_data_out) {
  168248. if (master->using_merged_upsample) {
  168249. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168250. jinit_merged_upsampler(cinfo); /* does color conversion too */
  168251. #else
  168252. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168253. #endif
  168254. } else {
  168255. jinit_color_deconverter(cinfo);
  168256. jinit_upsampler(cinfo);
  168257. }
  168258. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  168259. }
  168260. /* Inverse DCT */
  168261. jinit_inverse_dct(cinfo);
  168262. /* Entropy decoding: either Huffman or arithmetic coding. */
  168263. if (cinfo->arith_code) {
  168264. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168265. } else {
  168266. if (cinfo->progressive_mode) {
  168267. #ifdef D_PROGRESSIVE_SUPPORTED
  168268. jinit_phuff_decoder(cinfo);
  168269. #else
  168270. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168271. #endif
  168272. } else
  168273. jinit_huff_decoder(cinfo);
  168274. }
  168275. /* Initialize principal buffer controllers. */
  168276. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  168277. jinit_d_coef_controller(cinfo, use_c_buffer);
  168278. if (! cinfo->raw_data_out)
  168279. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  168280. /* We can now tell the memory manager to allocate virtual arrays. */
  168281. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168282. /* Initialize input side of decompressor to consume first scan. */
  168283. (*cinfo->inputctl->start_input_pass) (cinfo);
  168284. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168285. /* If jpeg_start_decompress will read the whole file, initialize
  168286. * progress monitoring appropriately. The input step is counted
  168287. * as one pass.
  168288. */
  168289. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  168290. cinfo->inputctl->has_multiple_scans) {
  168291. int nscans;
  168292. /* Estimate number of scans to set pass_limit. */
  168293. if (cinfo->progressive_mode) {
  168294. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  168295. nscans = 2 + 3 * cinfo->num_components;
  168296. } else {
  168297. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  168298. nscans = cinfo->num_components;
  168299. }
  168300. cinfo->progress->pass_counter = 0L;
  168301. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  168302. cinfo->progress->completed_passes = 0;
  168303. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  168304. /* Count the input pass as done */
  168305. master->pass_number++;
  168306. }
  168307. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168308. }
  168309. /*
  168310. * Per-pass setup.
  168311. * This is called at the beginning of each output pass. We determine which
  168312. * modules will be active during this pass and give them appropriate
  168313. * start_pass calls. We also set is_dummy_pass to indicate whether this
  168314. * is a "real" output pass or a dummy pass for color quantization.
  168315. * (In the latter case, jdapistd.c will crank the pass to completion.)
  168316. */
  168317. METHODDEF(void)
  168318. prepare_for_output_pass (j_decompress_ptr cinfo)
  168319. {
  168320. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168321. if (master->pub.is_dummy_pass) {
  168322. #ifdef QUANT_2PASS_SUPPORTED
  168323. /* Final pass of 2-pass quantization */
  168324. master->pub.is_dummy_pass = FALSE;
  168325. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  168326. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  168327. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  168328. #else
  168329. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168330. #endif /* QUANT_2PASS_SUPPORTED */
  168331. } else {
  168332. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  168333. /* Select new quantization method */
  168334. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  168335. cinfo->cquantize = master->quantizer_2pass;
  168336. master->pub.is_dummy_pass = TRUE;
  168337. } else if (cinfo->enable_1pass_quant) {
  168338. cinfo->cquantize = master->quantizer_1pass;
  168339. } else {
  168340. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168341. }
  168342. }
  168343. (*cinfo->idct->start_pass) (cinfo);
  168344. (*cinfo->coef->start_output_pass) (cinfo);
  168345. if (! cinfo->raw_data_out) {
  168346. if (! master->using_merged_upsample)
  168347. (*cinfo->cconvert->start_pass) (cinfo);
  168348. (*cinfo->upsample->start_pass) (cinfo);
  168349. if (cinfo->quantize_colors)
  168350. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  168351. (*cinfo->post->start_pass) (cinfo,
  168352. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  168353. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  168354. }
  168355. }
  168356. /* Set up progress monitor's pass info if present */
  168357. if (cinfo->progress != NULL) {
  168358. cinfo->progress->completed_passes = master->pass_number;
  168359. cinfo->progress->total_passes = master->pass_number +
  168360. (master->pub.is_dummy_pass ? 2 : 1);
  168361. /* In buffered-image mode, we assume one more output pass if EOI not
  168362. * yet reached, but no more passes if EOI has been reached.
  168363. */
  168364. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  168365. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  168366. }
  168367. }
  168368. }
  168369. /*
  168370. * Finish up at end of an output pass.
  168371. */
  168372. METHODDEF(void)
  168373. finish_output_pass (j_decompress_ptr cinfo)
  168374. {
  168375. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168376. if (cinfo->quantize_colors)
  168377. (*cinfo->cquantize->finish_pass) (cinfo);
  168378. master->pass_number++;
  168379. }
  168380. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168381. /*
  168382. * Switch to a new external colormap between output passes.
  168383. */
  168384. GLOBAL(void)
  168385. jpeg_new_colormap (j_decompress_ptr cinfo)
  168386. {
  168387. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168388. /* Prevent application from calling me at wrong times */
  168389. if (cinfo->global_state != DSTATE_BUFIMAGE)
  168390. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168391. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  168392. cinfo->colormap != NULL) {
  168393. /* Select 2-pass quantizer for external colormap use */
  168394. cinfo->cquantize = master->quantizer_2pass;
  168395. /* Notify quantizer of colormap change */
  168396. (*cinfo->cquantize->new_color_map) (cinfo);
  168397. master->pub.is_dummy_pass = FALSE; /* just in case */
  168398. } else
  168399. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168400. }
  168401. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168402. /*
  168403. * Initialize master decompression control and select active modules.
  168404. * This is performed at the start of jpeg_start_decompress.
  168405. */
  168406. GLOBAL(void)
  168407. jinit_master_decompress (j_decompress_ptr cinfo)
  168408. {
  168409. my_master_ptr6 master;
  168410. master = (my_master_ptr6)
  168411. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168412. SIZEOF(my_decomp_master));
  168413. cinfo->master = (struct jpeg_decomp_master *) master;
  168414. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  168415. master->pub.finish_output_pass = finish_output_pass;
  168416. master->pub.is_dummy_pass = FALSE;
  168417. master_selection(cinfo);
  168418. }
  168419. /********* End of inlined file: jdmaster.c *********/
  168420. #undef FIX
  168421. /********* Start of inlined file: jdmerge.c *********/
  168422. #define JPEG_INTERNALS
  168423. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168424. /* Private subobject */
  168425. typedef struct {
  168426. struct jpeg_upsampler pub; /* public fields */
  168427. /* Pointer to routine to do actual upsampling/conversion of one row group */
  168428. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  168429. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168430. JSAMPARRAY output_buf));
  168431. /* Private state for YCC->RGB conversion */
  168432. int * Cr_r_tab; /* => table for Cr to R conversion */
  168433. int * Cb_b_tab; /* => table for Cb to B conversion */
  168434. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168435. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168436. /* For 2:1 vertical sampling, we produce two output rows at a time.
  168437. * We need a "spare" row buffer to hold the second output row if the
  168438. * application provides just a one-row buffer; we also use the spare
  168439. * to discard the dummy last row if the image height is odd.
  168440. */
  168441. JSAMPROW spare_row;
  168442. boolean spare_full; /* T if spare buffer is occupied */
  168443. JDIMENSION out_row_width; /* samples per output row */
  168444. JDIMENSION rows_to_go; /* counts rows remaining in image */
  168445. } my_upsampler;
  168446. typedef my_upsampler * my_upsample_ptr;
  168447. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168448. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168449. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168450. /*
  168451. * Initialize tables for YCC->RGB colorspace conversion.
  168452. * This is taken directly from jdcolor.c; see that file for more info.
  168453. */
  168454. LOCAL(void)
  168455. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  168456. {
  168457. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168458. int i;
  168459. INT32 x;
  168460. SHIFT_TEMPS
  168461. upsample->Cr_r_tab = (int *)
  168462. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168463. (MAXJSAMPLE+1) * SIZEOF(int));
  168464. upsample->Cb_b_tab = (int *)
  168465. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168466. (MAXJSAMPLE+1) * SIZEOF(int));
  168467. upsample->Cr_g_tab = (INT32 *)
  168468. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168469. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168470. upsample->Cb_g_tab = (INT32 *)
  168471. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168472. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168473. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168474. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168475. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168476. /* Cr=>R value is nearest int to 1.40200 * x */
  168477. upsample->Cr_r_tab[i] = (int)
  168478. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168479. /* Cb=>B value is nearest int to 1.77200 * x */
  168480. upsample->Cb_b_tab[i] = (int)
  168481. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168482. /* Cr=>G value is scaled-up -0.71414 * x */
  168483. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168484. /* Cb=>G value is scaled-up -0.34414 * x */
  168485. /* We also add in ONE_HALF so that need not do it in inner loop */
  168486. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168487. }
  168488. }
  168489. /*
  168490. * Initialize for an upsampling pass.
  168491. */
  168492. METHODDEF(void)
  168493. start_pass_merged_upsample (j_decompress_ptr cinfo)
  168494. {
  168495. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168496. /* Mark the spare buffer empty */
  168497. upsample->spare_full = FALSE;
  168498. /* Initialize total-height counter for detecting bottom of image */
  168499. upsample->rows_to_go = cinfo->output_height;
  168500. }
  168501. /*
  168502. * Control routine to do upsampling (and color conversion).
  168503. *
  168504. * The control routine just handles the row buffering considerations.
  168505. */
  168506. METHODDEF(void)
  168507. merged_2v_upsample (j_decompress_ptr cinfo,
  168508. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168509. JDIMENSION in_row_groups_avail,
  168510. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168511. JDIMENSION out_rows_avail)
  168512. /* 2:1 vertical sampling case: may need a spare row. */
  168513. {
  168514. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168515. JSAMPROW work_ptrs[2];
  168516. JDIMENSION num_rows; /* number of rows returned to caller */
  168517. if (upsample->spare_full) {
  168518. /* If we have a spare row saved from a previous cycle, just return it. */
  168519. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  168520. 1, upsample->out_row_width);
  168521. num_rows = 1;
  168522. upsample->spare_full = FALSE;
  168523. } else {
  168524. /* Figure number of rows to return to caller. */
  168525. num_rows = 2;
  168526. /* Not more than the distance to the end of the image. */
  168527. if (num_rows > upsample->rows_to_go)
  168528. num_rows = upsample->rows_to_go;
  168529. /* And not more than what the client can accept: */
  168530. out_rows_avail -= *out_row_ctr;
  168531. if (num_rows > out_rows_avail)
  168532. num_rows = out_rows_avail;
  168533. /* Create output pointer array for upsampler. */
  168534. work_ptrs[0] = output_buf[*out_row_ctr];
  168535. if (num_rows > 1) {
  168536. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  168537. } else {
  168538. work_ptrs[1] = upsample->spare_row;
  168539. upsample->spare_full = TRUE;
  168540. }
  168541. /* Now do the upsampling. */
  168542. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  168543. }
  168544. /* Adjust counts */
  168545. *out_row_ctr += num_rows;
  168546. upsample->rows_to_go -= num_rows;
  168547. /* When the buffer is emptied, declare this input row group consumed */
  168548. if (! upsample->spare_full)
  168549. (*in_row_group_ctr)++;
  168550. }
  168551. METHODDEF(void)
  168552. merged_1v_upsample (j_decompress_ptr cinfo,
  168553. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168554. JDIMENSION in_row_groups_avail,
  168555. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168556. JDIMENSION out_rows_avail)
  168557. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  168558. {
  168559. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168560. /* Just do the upsampling. */
  168561. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  168562. output_buf + *out_row_ctr);
  168563. /* Adjust counts */
  168564. (*out_row_ctr)++;
  168565. (*in_row_group_ctr)++;
  168566. }
  168567. /*
  168568. * These are the routines invoked by the control routines to do
  168569. * the actual upsampling/conversion. One row group is processed per call.
  168570. *
  168571. * Note: since we may be writing directly into application-supplied buffers,
  168572. * we have to be honest about the output width; we can't assume the buffer
  168573. * has been rounded up to an even width.
  168574. */
  168575. /*
  168576. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  168577. */
  168578. METHODDEF(void)
  168579. h2v1_merged_upsample (j_decompress_ptr cinfo,
  168580. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168581. JSAMPARRAY output_buf)
  168582. {
  168583. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168584. register int y, cred, cgreen, cblue;
  168585. int cb, cr;
  168586. register JSAMPROW outptr;
  168587. JSAMPROW inptr0, inptr1, inptr2;
  168588. JDIMENSION col;
  168589. /* copy these pointers into registers if possible */
  168590. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168591. int * Crrtab = upsample->Cr_r_tab;
  168592. int * Cbbtab = upsample->Cb_b_tab;
  168593. INT32 * Crgtab = upsample->Cr_g_tab;
  168594. INT32 * Cbgtab = upsample->Cb_g_tab;
  168595. SHIFT_TEMPS
  168596. inptr0 = input_buf[0][in_row_group_ctr];
  168597. inptr1 = input_buf[1][in_row_group_ctr];
  168598. inptr2 = input_buf[2][in_row_group_ctr];
  168599. outptr = output_buf[0];
  168600. /* Loop for each pair of output pixels */
  168601. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168602. /* Do the chroma part of the calculation */
  168603. cb = GETJSAMPLE(*inptr1++);
  168604. cr = GETJSAMPLE(*inptr2++);
  168605. cred = Crrtab[cr];
  168606. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168607. cblue = Cbbtab[cb];
  168608. /* Fetch 2 Y values and emit 2 pixels */
  168609. y = GETJSAMPLE(*inptr0++);
  168610. outptr[RGB_RED] = range_limit[y + cred];
  168611. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168612. outptr[RGB_BLUE] = range_limit[y + cblue];
  168613. outptr += RGB_PIXELSIZE;
  168614. y = GETJSAMPLE(*inptr0++);
  168615. outptr[RGB_RED] = range_limit[y + cred];
  168616. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168617. outptr[RGB_BLUE] = range_limit[y + cblue];
  168618. outptr += RGB_PIXELSIZE;
  168619. }
  168620. /* If image width is odd, do the last output column separately */
  168621. if (cinfo->output_width & 1) {
  168622. cb = GETJSAMPLE(*inptr1);
  168623. cr = GETJSAMPLE(*inptr2);
  168624. cred = Crrtab[cr];
  168625. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168626. cblue = Cbbtab[cb];
  168627. y = GETJSAMPLE(*inptr0);
  168628. outptr[RGB_RED] = range_limit[y + cred];
  168629. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168630. outptr[RGB_BLUE] = range_limit[y + cblue];
  168631. }
  168632. }
  168633. /*
  168634. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  168635. */
  168636. METHODDEF(void)
  168637. h2v2_merged_upsample (j_decompress_ptr cinfo,
  168638. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168639. JSAMPARRAY output_buf)
  168640. {
  168641. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168642. register int y, cred, cgreen, cblue;
  168643. int cb, cr;
  168644. register JSAMPROW outptr0, outptr1;
  168645. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  168646. JDIMENSION col;
  168647. /* copy these pointers into registers if possible */
  168648. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168649. int * Crrtab = upsample->Cr_r_tab;
  168650. int * Cbbtab = upsample->Cb_b_tab;
  168651. INT32 * Crgtab = upsample->Cr_g_tab;
  168652. INT32 * Cbgtab = upsample->Cb_g_tab;
  168653. SHIFT_TEMPS
  168654. inptr00 = input_buf[0][in_row_group_ctr*2];
  168655. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  168656. inptr1 = input_buf[1][in_row_group_ctr];
  168657. inptr2 = input_buf[2][in_row_group_ctr];
  168658. outptr0 = output_buf[0];
  168659. outptr1 = output_buf[1];
  168660. /* Loop for each group of output pixels */
  168661. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168662. /* Do the chroma part of the calculation */
  168663. cb = GETJSAMPLE(*inptr1++);
  168664. cr = GETJSAMPLE(*inptr2++);
  168665. cred = Crrtab[cr];
  168666. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168667. cblue = Cbbtab[cb];
  168668. /* Fetch 4 Y values and emit 4 pixels */
  168669. y = GETJSAMPLE(*inptr00++);
  168670. outptr0[RGB_RED] = range_limit[y + cred];
  168671. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168672. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168673. outptr0 += RGB_PIXELSIZE;
  168674. y = GETJSAMPLE(*inptr00++);
  168675. outptr0[RGB_RED] = range_limit[y + cred];
  168676. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168677. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168678. outptr0 += RGB_PIXELSIZE;
  168679. y = GETJSAMPLE(*inptr01++);
  168680. outptr1[RGB_RED] = range_limit[y + cred];
  168681. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168682. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168683. outptr1 += RGB_PIXELSIZE;
  168684. y = GETJSAMPLE(*inptr01++);
  168685. outptr1[RGB_RED] = range_limit[y + cred];
  168686. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168687. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168688. outptr1 += RGB_PIXELSIZE;
  168689. }
  168690. /* If image width is odd, do the last output column separately */
  168691. if (cinfo->output_width & 1) {
  168692. cb = GETJSAMPLE(*inptr1);
  168693. cr = GETJSAMPLE(*inptr2);
  168694. cred = Crrtab[cr];
  168695. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168696. cblue = Cbbtab[cb];
  168697. y = GETJSAMPLE(*inptr00);
  168698. outptr0[RGB_RED] = range_limit[y + cred];
  168699. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168700. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168701. y = GETJSAMPLE(*inptr01);
  168702. outptr1[RGB_RED] = range_limit[y + cred];
  168703. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168704. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168705. }
  168706. }
  168707. /*
  168708. * Module initialization routine for merged upsampling/color conversion.
  168709. *
  168710. * NB: this is called under the conditions determined by use_merged_upsample()
  168711. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  168712. * of this module; no safety checks are made here.
  168713. */
  168714. GLOBAL(void)
  168715. jinit_merged_upsampler (j_decompress_ptr cinfo)
  168716. {
  168717. my_upsample_ptr upsample;
  168718. upsample = (my_upsample_ptr)
  168719. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168720. SIZEOF(my_upsampler));
  168721. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168722. upsample->pub.start_pass = start_pass_merged_upsample;
  168723. upsample->pub.need_context_rows = FALSE;
  168724. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  168725. if (cinfo->max_v_samp_factor == 2) {
  168726. upsample->pub.upsample = merged_2v_upsample;
  168727. upsample->upmethod = h2v2_merged_upsample;
  168728. /* Allocate a spare row buffer */
  168729. upsample->spare_row = (JSAMPROW)
  168730. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168731. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  168732. } else {
  168733. upsample->pub.upsample = merged_1v_upsample;
  168734. upsample->upmethod = h2v1_merged_upsample;
  168735. /* No spare row needed */
  168736. upsample->spare_row = NULL;
  168737. }
  168738. build_ycc_rgb_table2(cinfo);
  168739. }
  168740. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  168741. /********* End of inlined file: jdmerge.c *********/
  168742. #undef ASSIGN_STATE
  168743. /********* Start of inlined file: jdphuff.c *********/
  168744. #define JPEG_INTERNALS
  168745. #ifdef D_PROGRESSIVE_SUPPORTED
  168746. /*
  168747. * Expanded entropy decoder object for progressive Huffman decoding.
  168748. *
  168749. * The savable_state subrecord contains fields that change within an MCU,
  168750. * but must not be updated permanently until we complete the MCU.
  168751. */
  168752. typedef struct {
  168753. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  168754. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168755. } savable_state3;
  168756. /* This macro is to work around compilers with missing or broken
  168757. * structure assignment. You'll need to fix this code if you have
  168758. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168759. */
  168760. #ifndef NO_STRUCT_ASSIGN
  168761. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168762. #else
  168763. #if MAX_COMPS_IN_SCAN == 4
  168764. #define ASSIGN_STATE(dest,src) \
  168765. ((dest).EOBRUN = (src).EOBRUN, \
  168766. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  168767. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  168768. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  168769. (dest).last_dc_val[3] = (src).last_dc_val[3])
  168770. #endif
  168771. #endif
  168772. typedef struct {
  168773. struct jpeg_entropy_decoder pub; /* public fields */
  168774. /* These fields are loaded into local variables at start of each MCU.
  168775. * In case of suspension, we exit WITHOUT updating them.
  168776. */
  168777. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  168778. savable_state3 saved; /* Other state at start of MCU */
  168779. /* These fields are NOT loaded into local working state. */
  168780. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  168781. /* Pointers to derived tables (these workspaces have image lifespan) */
  168782. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  168783. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  168784. } phuff_entropy_decoder;
  168785. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  168786. /* Forward declarations */
  168787. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  168788. JBLOCKROW *MCU_data));
  168789. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  168790. JBLOCKROW *MCU_data));
  168791. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  168792. JBLOCKROW *MCU_data));
  168793. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  168794. JBLOCKROW *MCU_data));
  168795. /*
  168796. * Initialize for a Huffman-compressed scan.
  168797. */
  168798. METHODDEF(void)
  168799. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  168800. {
  168801. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168802. boolean is_DC_band, bad;
  168803. int ci, coefi, tbl;
  168804. int *coef_bit_ptr;
  168805. jpeg_component_info * compptr;
  168806. is_DC_band = (cinfo->Ss == 0);
  168807. /* Validate scan parameters */
  168808. bad = FALSE;
  168809. if (is_DC_band) {
  168810. if (cinfo->Se != 0)
  168811. bad = TRUE;
  168812. } else {
  168813. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  168814. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  168815. bad = TRUE;
  168816. /* AC scans may have only one component */
  168817. if (cinfo->comps_in_scan != 1)
  168818. bad = TRUE;
  168819. }
  168820. if (cinfo->Ah != 0) {
  168821. /* Successive approximation refinement scan: must have Al = Ah-1. */
  168822. if (cinfo->Al != cinfo->Ah-1)
  168823. bad = TRUE;
  168824. }
  168825. if (cinfo->Al > 13) /* need not check for < 0 */
  168826. bad = TRUE;
  168827. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  168828. * but the spec doesn't say so, and we try to be liberal about what we
  168829. * accept. Note: large Al values could result in out-of-range DC
  168830. * coefficients during early scans, leading to bizarre displays due to
  168831. * overflows in the IDCT math. But we won't crash.
  168832. */
  168833. if (bad)
  168834. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  168835. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  168836. /* Update progression status, and verify that scan order is legal.
  168837. * Note that inter-scan inconsistencies are treated as warnings
  168838. * not fatal errors ... not clear if this is right way to behave.
  168839. */
  168840. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168841. int cindex = cinfo->cur_comp_info[ci]->component_index;
  168842. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  168843. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  168844. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  168845. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  168846. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  168847. if (cinfo->Ah != expected)
  168848. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  168849. coef_bit_ptr[coefi] = cinfo->Al;
  168850. }
  168851. }
  168852. /* Select MCU decoding routine */
  168853. if (cinfo->Ah == 0) {
  168854. if (is_DC_band)
  168855. entropy->pub.decode_mcu = decode_mcu_DC_first;
  168856. else
  168857. entropy->pub.decode_mcu = decode_mcu_AC_first;
  168858. } else {
  168859. if (is_DC_band)
  168860. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  168861. else
  168862. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  168863. }
  168864. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168865. compptr = cinfo->cur_comp_info[ci];
  168866. /* Make sure requested tables are present, and compute derived tables.
  168867. * We may build same derived table more than once, but it's not expensive.
  168868. */
  168869. if (is_DC_band) {
  168870. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  168871. tbl = compptr->dc_tbl_no;
  168872. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  168873. & entropy->derived_tbls[tbl]);
  168874. }
  168875. } else {
  168876. tbl = compptr->ac_tbl_no;
  168877. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  168878. & entropy->derived_tbls[tbl]);
  168879. /* remember the single active table */
  168880. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  168881. }
  168882. /* Initialize DC predictions to 0 */
  168883. entropy->saved.last_dc_val[ci] = 0;
  168884. }
  168885. /* Initialize bitread state variables */
  168886. entropy->bitstate.bits_left = 0;
  168887. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168888. entropy->pub.insufficient_data = FALSE;
  168889. /* Initialize private state variables */
  168890. entropy->saved.EOBRUN = 0;
  168891. /* Initialize restart counter */
  168892. entropy->restarts_to_go = cinfo->restart_interval;
  168893. }
  168894. /*
  168895. * Check for a restart marker & resynchronize decoder.
  168896. * Returns FALSE if must suspend.
  168897. */
  168898. LOCAL(boolean)
  168899. process_restartp (j_decompress_ptr cinfo)
  168900. {
  168901. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168902. int ci;
  168903. /* Throw away any unused bits remaining in bit buffer; */
  168904. /* include any full bytes in next_marker's count of discarded bytes */
  168905. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  168906. entropy->bitstate.bits_left = 0;
  168907. /* Advance past the RSTn marker */
  168908. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  168909. return FALSE;
  168910. /* Re-initialize DC predictions to 0 */
  168911. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  168912. entropy->saved.last_dc_val[ci] = 0;
  168913. /* Re-init EOB run count, too */
  168914. entropy->saved.EOBRUN = 0;
  168915. /* Reset restart counter */
  168916. entropy->restarts_to_go = cinfo->restart_interval;
  168917. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  168918. * against a marker. In that case we will end up treating the next data
  168919. * segment as empty, and we can avoid producing bogus output pixels by
  168920. * leaving the flag set.
  168921. */
  168922. if (cinfo->unread_marker == 0)
  168923. entropy->pub.insufficient_data = FALSE;
  168924. return TRUE;
  168925. }
  168926. /*
  168927. * Huffman MCU decoding.
  168928. * Each of these routines decodes and returns one MCU's worth of
  168929. * Huffman-compressed coefficients.
  168930. * The coefficients are reordered from zigzag order into natural array order,
  168931. * but are not dequantized.
  168932. *
  168933. * The i'th block of the MCU is stored into the block pointed to by
  168934. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  168935. *
  168936. * We return FALSE if data source requested suspension. In that case no
  168937. * changes have been made to permanent state. (Exception: some output
  168938. * coefficients may already have been assigned. This is harmless for
  168939. * spectral selection, since we'll just re-assign them on the next call.
  168940. * Successive approximation AC refinement has to be more careful, however.)
  168941. */
  168942. /*
  168943. * MCU decoding for DC initial scan (either spectral selection,
  168944. * or first pass of successive approximation).
  168945. */
  168946. METHODDEF(boolean)
  168947. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168948. {
  168949. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168950. int Al = cinfo->Al;
  168951. register int s, r;
  168952. int blkn, ci;
  168953. JBLOCKROW block;
  168954. BITREAD_STATE_VARS;
  168955. savable_state3 state;
  168956. d_derived_tbl * tbl;
  168957. jpeg_component_info * compptr;
  168958. /* Process restart marker if needed; may have to suspend */
  168959. if (cinfo->restart_interval) {
  168960. if (entropy->restarts_to_go == 0)
  168961. if (! process_restartp(cinfo))
  168962. return FALSE;
  168963. }
  168964. /* If we've run out of data, just leave the MCU set to zeroes.
  168965. * This way, we return uniform gray for the remainder of the segment.
  168966. */
  168967. if (! entropy->pub.insufficient_data) {
  168968. /* Load up working state */
  168969. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168970. ASSIGN_STATE(state, entropy->saved);
  168971. /* Outer loop handles each block in the MCU */
  168972. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168973. block = MCU_data[blkn];
  168974. ci = cinfo->MCU_membership[blkn];
  168975. compptr = cinfo->cur_comp_info[ci];
  168976. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  168977. /* Decode a single block's worth of coefficients */
  168978. /* Section F.2.2.1: decode the DC coefficient difference */
  168979. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  168980. if (s) {
  168981. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168982. r = GET_BITS(s);
  168983. s = HUFF_EXTEND(r, s);
  168984. }
  168985. /* Convert DC difference to actual value, update last_dc_val */
  168986. s += state.last_dc_val[ci];
  168987. state.last_dc_val[ci] = s;
  168988. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  168989. (*block)[0] = (JCOEF) (s << Al);
  168990. }
  168991. /* Completed MCU, so update state */
  168992. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168993. ASSIGN_STATE(entropy->saved, state);
  168994. }
  168995. /* Account for restart interval (no-op if not using restarts) */
  168996. entropy->restarts_to_go--;
  168997. return TRUE;
  168998. }
  168999. /*
  169000. * MCU decoding for AC initial scan (either spectral selection,
  169001. * or first pass of successive approximation).
  169002. */
  169003. METHODDEF(boolean)
  169004. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169005. {
  169006. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169007. int Se = cinfo->Se;
  169008. int Al = cinfo->Al;
  169009. register int s, k, r;
  169010. unsigned int EOBRUN;
  169011. JBLOCKROW block;
  169012. BITREAD_STATE_VARS;
  169013. d_derived_tbl * tbl;
  169014. /* Process restart marker if needed; may have to suspend */
  169015. if (cinfo->restart_interval) {
  169016. if (entropy->restarts_to_go == 0)
  169017. if (! process_restartp(cinfo))
  169018. return FALSE;
  169019. }
  169020. /* If we've run out of data, just leave the MCU set to zeroes.
  169021. * This way, we return uniform gray for the remainder of the segment.
  169022. */
  169023. if (! entropy->pub.insufficient_data) {
  169024. /* Load up working state.
  169025. * We can avoid loading/saving bitread state if in an EOB run.
  169026. */
  169027. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  169028. /* There is always only one block per MCU */
  169029. if (EOBRUN > 0) /* if it's a band of zeroes... */
  169030. EOBRUN--; /* ...process it now (we do nothing) */
  169031. else {
  169032. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169033. block = MCU_data[0];
  169034. tbl = entropy->ac_derived_tbl;
  169035. for (k = cinfo->Ss; k <= Se; k++) {
  169036. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  169037. r = s >> 4;
  169038. s &= 15;
  169039. if (s) {
  169040. k += r;
  169041. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169042. r = GET_BITS(s);
  169043. s = HUFF_EXTEND(r, s);
  169044. /* Scale and output coefficient in natural (dezigzagged) order */
  169045. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  169046. } else {
  169047. if (r == 15) { /* ZRL */
  169048. k += 15; /* skip 15 zeroes in band */
  169049. } else { /* EOBr, run length is 2^r + appended bits */
  169050. EOBRUN = 1 << r;
  169051. if (r) { /* EOBr, r > 0 */
  169052. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  169053. r = GET_BITS(r);
  169054. EOBRUN += r;
  169055. }
  169056. EOBRUN--; /* this band is processed at this moment */
  169057. break; /* force end-of-band */
  169058. }
  169059. }
  169060. }
  169061. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169062. }
  169063. /* Completed MCU, so update state */
  169064. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169065. }
  169066. /* Account for restart interval (no-op if not using restarts) */
  169067. entropy->restarts_to_go--;
  169068. return TRUE;
  169069. }
  169070. /*
  169071. * MCU decoding for DC successive approximation refinement scan.
  169072. * Note: we assume such scans can be multi-component, although the spec
  169073. * is not very clear on the point.
  169074. */
  169075. METHODDEF(boolean)
  169076. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169077. {
  169078. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169079. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169080. int blkn;
  169081. JBLOCKROW block;
  169082. BITREAD_STATE_VARS;
  169083. /* Process restart marker if needed; may have to suspend */
  169084. if (cinfo->restart_interval) {
  169085. if (entropy->restarts_to_go == 0)
  169086. if (! process_restartp(cinfo))
  169087. return FALSE;
  169088. }
  169089. /* Not worth the cycles to check insufficient_data here,
  169090. * since we will not change the data anyway if we read zeroes.
  169091. */
  169092. /* Load up working state */
  169093. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169094. /* Outer loop handles each block in the MCU */
  169095. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169096. block = MCU_data[blkn];
  169097. /* Encoded data is simply the next bit of the two's-complement DC value */
  169098. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  169099. if (GET_BITS(1))
  169100. (*block)[0] |= p1;
  169101. /* Note: since we use |=, repeating the assignment later is safe */
  169102. }
  169103. /* Completed MCU, so update state */
  169104. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169105. /* Account for restart interval (no-op if not using restarts) */
  169106. entropy->restarts_to_go--;
  169107. return TRUE;
  169108. }
  169109. /*
  169110. * MCU decoding for AC successive approximation refinement scan.
  169111. */
  169112. METHODDEF(boolean)
  169113. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169114. {
  169115. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  169116. int Se = cinfo->Se;
  169117. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  169118. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  169119. register int s, k, r;
  169120. unsigned int EOBRUN;
  169121. JBLOCKROW block;
  169122. JCOEFPTR thiscoef;
  169123. BITREAD_STATE_VARS;
  169124. d_derived_tbl * tbl;
  169125. int num_newnz;
  169126. int newnz_pos[DCTSIZE2];
  169127. /* Process restart marker if needed; may have to suspend */
  169128. if (cinfo->restart_interval) {
  169129. if (entropy->restarts_to_go == 0)
  169130. if (! process_restartp(cinfo))
  169131. return FALSE;
  169132. }
  169133. /* If we've run out of data, don't modify the MCU.
  169134. */
  169135. if (! entropy->pub.insufficient_data) {
  169136. /* Load up working state */
  169137. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169138. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  169139. /* There is always only one block per MCU */
  169140. block = MCU_data[0];
  169141. tbl = entropy->ac_derived_tbl;
  169142. /* If we are forced to suspend, we must undo the assignments to any newly
  169143. * nonzero coefficients in the block, because otherwise we'd get confused
  169144. * next time about which coefficients were already nonzero.
  169145. * But we need not undo addition of bits to already-nonzero coefficients;
  169146. * instead, we can test the current bit to see if we already did it.
  169147. */
  169148. num_newnz = 0;
  169149. /* initialize coefficient loop counter to start of band */
  169150. k = cinfo->Ss;
  169151. if (EOBRUN == 0) {
  169152. for (; k <= Se; k++) {
  169153. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  169154. r = s >> 4;
  169155. s &= 15;
  169156. if (s) {
  169157. if (s != 1) /* size of new coef should always be 1 */
  169158. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  169159. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169160. if (GET_BITS(1))
  169161. s = p1; /* newly nonzero coef is positive */
  169162. else
  169163. s = m1; /* newly nonzero coef is negative */
  169164. } else {
  169165. if (r != 15) {
  169166. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  169167. if (r) {
  169168. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  169169. r = GET_BITS(r);
  169170. EOBRUN += r;
  169171. }
  169172. break; /* rest of block is handled by EOB logic */
  169173. }
  169174. /* note s = 0 for processing ZRL */
  169175. }
  169176. /* Advance over already-nonzero coefs and r still-zero coefs,
  169177. * appending correction bits to the nonzeroes. A correction bit is 1
  169178. * if the absolute value of the coefficient must be increased.
  169179. */
  169180. do {
  169181. thiscoef = *block + jpeg_natural_order[k];
  169182. if (*thiscoef != 0) {
  169183. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169184. if (GET_BITS(1)) {
  169185. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  169186. if (*thiscoef >= 0)
  169187. *thiscoef += p1;
  169188. else
  169189. *thiscoef += m1;
  169190. }
  169191. }
  169192. } else {
  169193. if (--r < 0)
  169194. break; /* reached target zero coefficient */
  169195. }
  169196. k++;
  169197. } while (k <= Se);
  169198. if (s) {
  169199. int pos = jpeg_natural_order[k];
  169200. /* Output newly nonzero coefficient */
  169201. (*block)[pos] = (JCOEF) s;
  169202. /* Remember its position in case we have to suspend */
  169203. newnz_pos[num_newnz++] = pos;
  169204. }
  169205. }
  169206. }
  169207. if (EOBRUN > 0) {
  169208. /* Scan any remaining coefficient positions after the end-of-band
  169209. * (the last newly nonzero coefficient, if any). Append a correction
  169210. * bit to each already-nonzero coefficient. A correction bit is 1
  169211. * if the absolute value of the coefficient must be increased.
  169212. */
  169213. for (; k <= Se; k++) {
  169214. thiscoef = *block + jpeg_natural_order[k];
  169215. if (*thiscoef != 0) {
  169216. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169217. if (GET_BITS(1)) {
  169218. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  169219. if (*thiscoef >= 0)
  169220. *thiscoef += p1;
  169221. else
  169222. *thiscoef += m1;
  169223. }
  169224. }
  169225. }
  169226. }
  169227. /* Count one block completed in EOB run */
  169228. EOBRUN--;
  169229. }
  169230. /* Completed MCU, so update state */
  169231. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169232. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169233. }
  169234. /* Account for restart interval (no-op if not using restarts) */
  169235. entropy->restarts_to_go--;
  169236. return TRUE;
  169237. undoit:
  169238. /* Re-zero any output coefficients that we made newly nonzero */
  169239. while (num_newnz > 0)
  169240. (*block)[newnz_pos[--num_newnz]] = 0;
  169241. return FALSE;
  169242. }
  169243. /*
  169244. * Module initialization routine for progressive Huffman entropy decoding.
  169245. */
  169246. GLOBAL(void)
  169247. jinit_phuff_decoder (j_decompress_ptr cinfo)
  169248. {
  169249. phuff_entropy_ptr2 entropy;
  169250. int *coef_bit_ptr;
  169251. int ci, i;
  169252. entropy = (phuff_entropy_ptr2)
  169253. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169254. SIZEOF(phuff_entropy_decoder));
  169255. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169256. entropy->pub.start_pass = start_pass_phuff_decoder;
  169257. /* Mark derived tables unallocated */
  169258. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169259. entropy->derived_tbls[i] = NULL;
  169260. }
  169261. /* Create progression status table */
  169262. cinfo->coef_bits = (int (*)[DCTSIZE2])
  169263. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169264. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  169265. coef_bit_ptr = & cinfo->coef_bits[0][0];
  169266. for (ci = 0; ci < cinfo->num_components; ci++)
  169267. for (i = 0; i < DCTSIZE2; i++)
  169268. *coef_bit_ptr++ = -1;
  169269. }
  169270. #endif /* D_PROGRESSIVE_SUPPORTED */
  169271. /********* End of inlined file: jdphuff.c *********/
  169272. /********* Start of inlined file: jdpostct.c *********/
  169273. #define JPEG_INTERNALS
  169274. /* Private buffer controller object */
  169275. typedef struct {
  169276. struct jpeg_d_post_controller pub; /* public fields */
  169277. /* Color quantization source buffer: this holds output data from
  169278. * the upsample/color conversion step to be passed to the quantizer.
  169279. * For two-pass color quantization, we need a full-image buffer;
  169280. * for one-pass operation, a strip buffer is sufficient.
  169281. */
  169282. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  169283. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  169284. JDIMENSION strip_height; /* buffer size in rows */
  169285. /* for two-pass mode only: */
  169286. JDIMENSION starting_row; /* row # of first row in current strip */
  169287. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  169288. } my_post_controller;
  169289. typedef my_post_controller * my_post_ptr;
  169290. /* Forward declarations */
  169291. METHODDEF(void) post_process_1pass
  169292. JPP((j_decompress_ptr cinfo,
  169293. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169294. JDIMENSION in_row_groups_avail,
  169295. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169296. JDIMENSION out_rows_avail));
  169297. #ifdef QUANT_2PASS_SUPPORTED
  169298. METHODDEF(void) post_process_prepass
  169299. JPP((j_decompress_ptr cinfo,
  169300. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169301. JDIMENSION in_row_groups_avail,
  169302. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169303. JDIMENSION out_rows_avail));
  169304. METHODDEF(void) post_process_2pass
  169305. JPP((j_decompress_ptr cinfo,
  169306. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169307. JDIMENSION in_row_groups_avail,
  169308. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169309. JDIMENSION out_rows_avail));
  169310. #endif
  169311. /*
  169312. * Initialize for a processing pass.
  169313. */
  169314. METHODDEF(void)
  169315. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  169316. {
  169317. my_post_ptr post = (my_post_ptr) cinfo->post;
  169318. switch (pass_mode) {
  169319. case JBUF_PASS_THRU:
  169320. if (cinfo->quantize_colors) {
  169321. /* Single-pass processing with color quantization. */
  169322. post->pub.post_process_data = post_process_1pass;
  169323. /* We could be doing buffered-image output before starting a 2-pass
  169324. * color quantization; in that case, jinit_d_post_controller did not
  169325. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  169326. */
  169327. if (post->buffer == NULL) {
  169328. post->buffer = (*cinfo->mem->access_virt_sarray)
  169329. ((j_common_ptr) cinfo, post->whole_image,
  169330. (JDIMENSION) 0, post->strip_height, TRUE);
  169331. }
  169332. } else {
  169333. /* For single-pass processing without color quantization,
  169334. * I have no work to do; just call the upsampler directly.
  169335. */
  169336. post->pub.post_process_data = cinfo->upsample->upsample;
  169337. }
  169338. break;
  169339. #ifdef QUANT_2PASS_SUPPORTED
  169340. case JBUF_SAVE_AND_PASS:
  169341. /* First pass of 2-pass quantization */
  169342. if (post->whole_image == NULL)
  169343. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169344. post->pub.post_process_data = post_process_prepass;
  169345. break;
  169346. case JBUF_CRANK_DEST:
  169347. /* Second pass of 2-pass quantization */
  169348. if (post->whole_image == NULL)
  169349. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169350. post->pub.post_process_data = post_process_2pass;
  169351. break;
  169352. #endif /* QUANT_2PASS_SUPPORTED */
  169353. default:
  169354. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169355. break;
  169356. }
  169357. post->starting_row = post->next_row = 0;
  169358. }
  169359. /*
  169360. * Process some data in the one-pass (strip buffer) case.
  169361. * This is used for color precision reduction as well as one-pass quantization.
  169362. */
  169363. METHODDEF(void)
  169364. post_process_1pass (j_decompress_ptr cinfo,
  169365. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169366. JDIMENSION in_row_groups_avail,
  169367. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169368. JDIMENSION out_rows_avail)
  169369. {
  169370. my_post_ptr post = (my_post_ptr) cinfo->post;
  169371. JDIMENSION num_rows, max_rows;
  169372. /* Fill the buffer, but not more than what we can dump out in one go. */
  169373. /* Note we rely on the upsampler to detect bottom of image. */
  169374. max_rows = out_rows_avail - *out_row_ctr;
  169375. if (max_rows > post->strip_height)
  169376. max_rows = post->strip_height;
  169377. num_rows = 0;
  169378. (*cinfo->upsample->upsample) (cinfo,
  169379. input_buf, in_row_group_ctr, in_row_groups_avail,
  169380. post->buffer, &num_rows, max_rows);
  169381. /* Quantize and emit data. */
  169382. (*cinfo->cquantize->color_quantize) (cinfo,
  169383. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  169384. *out_row_ctr += num_rows;
  169385. }
  169386. #ifdef QUANT_2PASS_SUPPORTED
  169387. /*
  169388. * Process some data in the first pass of 2-pass quantization.
  169389. */
  169390. METHODDEF(void)
  169391. post_process_prepass (j_decompress_ptr cinfo,
  169392. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169393. JDIMENSION in_row_groups_avail,
  169394. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169395. JDIMENSION out_rows_avail)
  169396. {
  169397. my_post_ptr post = (my_post_ptr) cinfo->post;
  169398. JDIMENSION old_next_row, num_rows;
  169399. /* Reposition virtual buffer if at start of strip. */
  169400. if (post->next_row == 0) {
  169401. post->buffer = (*cinfo->mem->access_virt_sarray)
  169402. ((j_common_ptr) cinfo, post->whole_image,
  169403. post->starting_row, post->strip_height, TRUE);
  169404. }
  169405. /* Upsample some data (up to a strip height's worth). */
  169406. old_next_row = post->next_row;
  169407. (*cinfo->upsample->upsample) (cinfo,
  169408. input_buf, in_row_group_ctr, in_row_groups_avail,
  169409. post->buffer, &post->next_row, post->strip_height);
  169410. /* Allow quantizer to scan new data. No data is emitted, */
  169411. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  169412. if (post->next_row > old_next_row) {
  169413. num_rows = post->next_row - old_next_row;
  169414. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  169415. (JSAMPARRAY) NULL, (int) num_rows);
  169416. *out_row_ctr += num_rows;
  169417. }
  169418. /* Advance if we filled the strip. */
  169419. if (post->next_row >= post->strip_height) {
  169420. post->starting_row += post->strip_height;
  169421. post->next_row = 0;
  169422. }
  169423. }
  169424. /*
  169425. * Process some data in the second pass of 2-pass quantization.
  169426. */
  169427. METHODDEF(void)
  169428. post_process_2pass (j_decompress_ptr cinfo,
  169429. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169430. JDIMENSION in_row_groups_avail,
  169431. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169432. JDIMENSION out_rows_avail)
  169433. {
  169434. my_post_ptr post = (my_post_ptr) cinfo->post;
  169435. JDIMENSION num_rows, max_rows;
  169436. /* Reposition virtual buffer if at start of strip. */
  169437. if (post->next_row == 0) {
  169438. post->buffer = (*cinfo->mem->access_virt_sarray)
  169439. ((j_common_ptr) cinfo, post->whole_image,
  169440. post->starting_row, post->strip_height, FALSE);
  169441. }
  169442. /* Determine number of rows to emit. */
  169443. num_rows = post->strip_height - post->next_row; /* available in strip */
  169444. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  169445. if (num_rows > max_rows)
  169446. num_rows = max_rows;
  169447. /* We have to check bottom of image here, can't depend on upsampler. */
  169448. max_rows = cinfo->output_height - post->starting_row;
  169449. if (num_rows > max_rows)
  169450. num_rows = max_rows;
  169451. /* Quantize and emit data. */
  169452. (*cinfo->cquantize->color_quantize) (cinfo,
  169453. post->buffer + post->next_row, output_buf + *out_row_ctr,
  169454. (int) num_rows);
  169455. *out_row_ctr += num_rows;
  169456. /* Advance if we filled the strip. */
  169457. post->next_row += num_rows;
  169458. if (post->next_row >= post->strip_height) {
  169459. post->starting_row += post->strip_height;
  169460. post->next_row = 0;
  169461. }
  169462. }
  169463. #endif /* QUANT_2PASS_SUPPORTED */
  169464. /*
  169465. * Initialize postprocessing controller.
  169466. */
  169467. GLOBAL(void)
  169468. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169469. {
  169470. my_post_ptr post;
  169471. post = (my_post_ptr)
  169472. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169473. SIZEOF(my_post_controller));
  169474. cinfo->post = (struct jpeg_d_post_controller *) post;
  169475. post->pub.start_pass = start_pass_dpost;
  169476. post->whole_image = NULL; /* flag for no virtual arrays */
  169477. post->buffer = NULL; /* flag for no strip buffer */
  169478. /* Create the quantization buffer, if needed */
  169479. if (cinfo->quantize_colors) {
  169480. /* The buffer strip height is max_v_samp_factor, which is typically
  169481. * an efficient number of rows for upsampling to return.
  169482. * (In the presence of output rescaling, we might want to be smarter?)
  169483. */
  169484. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  169485. if (need_full_buffer) {
  169486. /* Two-pass color quantization: need full-image storage. */
  169487. /* We round up the number of rows to a multiple of the strip height. */
  169488. #ifdef QUANT_2PASS_SUPPORTED
  169489. post->whole_image = (*cinfo->mem->request_virt_sarray)
  169490. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  169491. cinfo->output_width * cinfo->out_color_components,
  169492. (JDIMENSION) jround_up((long) cinfo->output_height,
  169493. (long) post->strip_height),
  169494. post->strip_height);
  169495. #else
  169496. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169497. #endif /* QUANT_2PASS_SUPPORTED */
  169498. } else {
  169499. /* One-pass color quantization: just make a strip buffer. */
  169500. post->buffer = (*cinfo->mem->alloc_sarray)
  169501. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169502. cinfo->output_width * cinfo->out_color_components,
  169503. post->strip_height);
  169504. }
  169505. }
  169506. }
  169507. /********* End of inlined file: jdpostct.c *********/
  169508. #undef FIX
  169509. /********* Start of inlined file: jdsample.c *********/
  169510. #define JPEG_INTERNALS
  169511. /* Pointer to routine to upsample a single component */
  169512. typedef JMETHOD(void, upsample1_ptr,
  169513. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169514. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  169515. /* Private subobject */
  169516. typedef struct {
  169517. struct jpeg_upsampler pub; /* public fields */
  169518. /* Color conversion buffer. When using separate upsampling and color
  169519. * conversion steps, this buffer holds one upsampled row group until it
  169520. * has been color converted and output.
  169521. * Note: we do not allocate any storage for component(s) which are full-size,
  169522. * ie do not need rescaling. The corresponding entry of color_buf[] is
  169523. * simply set to point to the input data array, thereby avoiding copying.
  169524. */
  169525. JSAMPARRAY color_buf[MAX_COMPONENTS];
  169526. /* Per-component upsampling method pointers */
  169527. upsample1_ptr methods[MAX_COMPONENTS];
  169528. int next_row_out; /* counts rows emitted from color_buf */
  169529. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169530. /* Height of an input row group for each component. */
  169531. int rowgroup_height[MAX_COMPONENTS];
  169532. /* These arrays save pixel expansion factors so that int_expand need not
  169533. * recompute them each time. They are unused for other upsampling methods.
  169534. */
  169535. UINT8 h_expand[MAX_COMPONENTS];
  169536. UINT8 v_expand[MAX_COMPONENTS];
  169537. } my_upsampler2;
  169538. typedef my_upsampler2 * my_upsample_ptr2;
  169539. /*
  169540. * Initialize for an upsampling pass.
  169541. */
  169542. METHODDEF(void)
  169543. start_pass_upsample (j_decompress_ptr cinfo)
  169544. {
  169545. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169546. /* Mark the conversion buffer empty */
  169547. upsample->next_row_out = cinfo->max_v_samp_factor;
  169548. /* Initialize total-height counter for detecting bottom of image */
  169549. upsample->rows_to_go = cinfo->output_height;
  169550. }
  169551. /*
  169552. * Control routine to do upsampling (and color conversion).
  169553. *
  169554. * In this version we upsample each component independently.
  169555. * We upsample one row group into the conversion buffer, then apply
  169556. * color conversion a row at a time.
  169557. */
  169558. METHODDEF(void)
  169559. sep_upsample (j_decompress_ptr cinfo,
  169560. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169561. JDIMENSION in_row_groups_avail,
  169562. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169563. JDIMENSION out_rows_avail)
  169564. {
  169565. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169566. int ci;
  169567. jpeg_component_info * compptr;
  169568. JDIMENSION num_rows;
  169569. /* Fill the conversion buffer, if it's empty */
  169570. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  169571. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169572. ci++, compptr++) {
  169573. /* Invoke per-component upsample method. Notice we pass a POINTER
  169574. * to color_buf[ci], so that fullsize_upsample can change it.
  169575. */
  169576. (*upsample->methods[ci]) (cinfo, compptr,
  169577. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  169578. upsample->color_buf + ci);
  169579. }
  169580. upsample->next_row_out = 0;
  169581. }
  169582. /* Color-convert and emit rows */
  169583. /* How many we have in the buffer: */
  169584. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  169585. /* Not more than the distance to the end of the image. Need this test
  169586. * in case the image height is not a multiple of max_v_samp_factor:
  169587. */
  169588. if (num_rows > upsample->rows_to_go)
  169589. num_rows = upsample->rows_to_go;
  169590. /* And not more than what the client can accept: */
  169591. out_rows_avail -= *out_row_ctr;
  169592. if (num_rows > out_rows_avail)
  169593. num_rows = out_rows_avail;
  169594. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  169595. (JDIMENSION) upsample->next_row_out,
  169596. output_buf + *out_row_ctr,
  169597. (int) num_rows);
  169598. /* Adjust counts */
  169599. *out_row_ctr += num_rows;
  169600. upsample->rows_to_go -= num_rows;
  169601. upsample->next_row_out += num_rows;
  169602. /* When the buffer is emptied, declare this input row group consumed */
  169603. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  169604. (*in_row_group_ctr)++;
  169605. }
  169606. /*
  169607. * These are the routines invoked by sep_upsample to upsample pixel values
  169608. * of a single component. One row group is processed per call.
  169609. */
  169610. /*
  169611. * For full-size components, we just make color_buf[ci] point at the
  169612. * input buffer, and thus avoid copying any data. Note that this is
  169613. * safe only because sep_upsample doesn't declare the input row group
  169614. * "consumed" until we are done color converting and emitting it.
  169615. */
  169616. METHODDEF(void)
  169617. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169618. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169619. {
  169620. *output_data_ptr = input_data;
  169621. }
  169622. /*
  169623. * This is a no-op version used for "uninteresting" components.
  169624. * These components will not be referenced by color conversion.
  169625. */
  169626. METHODDEF(void)
  169627. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169628. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169629. {
  169630. *output_data_ptr = NULL; /* safety check */
  169631. }
  169632. /*
  169633. * This version handles any integral sampling ratios.
  169634. * This is not used for typical JPEG files, so it need not be fast.
  169635. * Nor, for that matter, is it particularly accurate: the algorithm is
  169636. * simple replication of the input pixel onto the corresponding output
  169637. * pixels. The hi-falutin sampling literature refers to this as a
  169638. * "box filter". A box filter tends to introduce visible artifacts,
  169639. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  169640. * you would be well advised to improve this code.
  169641. */
  169642. METHODDEF(void)
  169643. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169644. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169645. {
  169646. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169647. JSAMPARRAY output_data = *output_data_ptr;
  169648. register JSAMPROW inptr, outptr;
  169649. register JSAMPLE invalue;
  169650. register int h;
  169651. JSAMPROW outend;
  169652. int h_expand, v_expand;
  169653. int inrow, outrow;
  169654. h_expand = upsample->h_expand[compptr->component_index];
  169655. v_expand = upsample->v_expand[compptr->component_index];
  169656. inrow = outrow = 0;
  169657. while (outrow < cinfo->max_v_samp_factor) {
  169658. /* Generate one output row with proper horizontal expansion */
  169659. inptr = input_data[inrow];
  169660. outptr = output_data[outrow];
  169661. outend = outptr + cinfo->output_width;
  169662. while (outptr < outend) {
  169663. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169664. for (h = h_expand; h > 0; h--) {
  169665. *outptr++ = invalue;
  169666. }
  169667. }
  169668. /* Generate any additional output rows by duplicating the first one */
  169669. if (v_expand > 1) {
  169670. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169671. v_expand-1, cinfo->output_width);
  169672. }
  169673. inrow++;
  169674. outrow += v_expand;
  169675. }
  169676. }
  169677. /*
  169678. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  169679. * It's still a box filter.
  169680. */
  169681. METHODDEF(void)
  169682. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169683. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169684. {
  169685. JSAMPARRAY output_data = *output_data_ptr;
  169686. register JSAMPROW inptr, outptr;
  169687. register JSAMPLE invalue;
  169688. JSAMPROW outend;
  169689. int inrow;
  169690. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169691. inptr = input_data[inrow];
  169692. outptr = output_data[inrow];
  169693. outend = outptr + cinfo->output_width;
  169694. while (outptr < outend) {
  169695. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169696. *outptr++ = invalue;
  169697. *outptr++ = invalue;
  169698. }
  169699. }
  169700. }
  169701. /*
  169702. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  169703. * It's still a box filter.
  169704. */
  169705. METHODDEF(void)
  169706. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169707. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169708. {
  169709. JSAMPARRAY output_data = *output_data_ptr;
  169710. register JSAMPROW inptr, outptr;
  169711. register JSAMPLE invalue;
  169712. JSAMPROW outend;
  169713. int inrow, outrow;
  169714. inrow = outrow = 0;
  169715. while (outrow < cinfo->max_v_samp_factor) {
  169716. inptr = input_data[inrow];
  169717. outptr = output_data[outrow];
  169718. outend = outptr + cinfo->output_width;
  169719. while (outptr < outend) {
  169720. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169721. *outptr++ = invalue;
  169722. *outptr++ = invalue;
  169723. }
  169724. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169725. 1, cinfo->output_width);
  169726. inrow++;
  169727. outrow += 2;
  169728. }
  169729. }
  169730. /*
  169731. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  169732. *
  169733. * The upsampling algorithm is linear interpolation between pixel centers,
  169734. * also known as a "triangle filter". This is a good compromise between
  169735. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  169736. * of the way between input pixel centers.
  169737. *
  169738. * A note about the "bias" calculations: when rounding fractional values to
  169739. * integer, we do not want to always round 0.5 up to the next integer.
  169740. * If we did that, we'd introduce a noticeable bias towards larger values.
  169741. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  169742. * alternate pixel locations (a simple ordered dither pattern).
  169743. */
  169744. METHODDEF(void)
  169745. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169746. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169747. {
  169748. JSAMPARRAY output_data = *output_data_ptr;
  169749. register JSAMPROW inptr, outptr;
  169750. register int invalue;
  169751. register JDIMENSION colctr;
  169752. int inrow;
  169753. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169754. inptr = input_data[inrow];
  169755. outptr = output_data[inrow];
  169756. /* Special case for first column */
  169757. invalue = GETJSAMPLE(*inptr++);
  169758. *outptr++ = (JSAMPLE) invalue;
  169759. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  169760. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169761. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  169762. invalue = GETJSAMPLE(*inptr++) * 3;
  169763. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  169764. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  169765. }
  169766. /* Special case for last column */
  169767. invalue = GETJSAMPLE(*inptr);
  169768. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  169769. *outptr++ = (JSAMPLE) invalue;
  169770. }
  169771. }
  169772. /*
  169773. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  169774. * Again a triangle filter; see comments for h2v1 case, above.
  169775. *
  169776. * It is OK for us to reference the adjacent input rows because we demanded
  169777. * context from the main buffer controller (see initialization code).
  169778. */
  169779. METHODDEF(void)
  169780. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169781. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169782. {
  169783. JSAMPARRAY output_data = *output_data_ptr;
  169784. register JSAMPROW inptr0, inptr1, outptr;
  169785. #if BITS_IN_JSAMPLE == 8
  169786. register int thiscolsum, lastcolsum, nextcolsum;
  169787. #else
  169788. register INT32 thiscolsum, lastcolsum, nextcolsum;
  169789. #endif
  169790. register JDIMENSION colctr;
  169791. int inrow, outrow, v;
  169792. inrow = outrow = 0;
  169793. while (outrow < cinfo->max_v_samp_factor) {
  169794. for (v = 0; v < 2; v++) {
  169795. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  169796. inptr0 = input_data[inrow];
  169797. if (v == 0) /* next nearest is row above */
  169798. inptr1 = input_data[inrow-1];
  169799. else /* next nearest is row below */
  169800. inptr1 = input_data[inrow+1];
  169801. outptr = output_data[outrow++];
  169802. /* Special case for first column */
  169803. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169804. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169805. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  169806. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169807. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169808. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169809. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  169810. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  169811. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169812. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169813. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169814. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169815. }
  169816. /* Special case for last column */
  169817. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169818. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  169819. }
  169820. inrow++;
  169821. }
  169822. }
  169823. /*
  169824. * Module initialization routine for upsampling.
  169825. */
  169826. GLOBAL(void)
  169827. jinit_upsampler (j_decompress_ptr cinfo)
  169828. {
  169829. my_upsample_ptr2 upsample;
  169830. int ci;
  169831. jpeg_component_info * compptr;
  169832. boolean need_buffer, do_fancy;
  169833. int h_in_group, v_in_group, h_out_group, v_out_group;
  169834. upsample = (my_upsample_ptr2)
  169835. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169836. SIZEOF(my_upsampler2));
  169837. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169838. upsample->pub.start_pass = start_pass_upsample;
  169839. upsample->pub.upsample = sep_upsample;
  169840. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  169841. if (cinfo->CCIR601_sampling) /* this isn't supported */
  169842. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  169843. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  169844. * so don't ask for it.
  169845. */
  169846. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  169847. /* Verify we can handle the sampling factors, select per-component methods,
  169848. * and create storage as needed.
  169849. */
  169850. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169851. ci++, compptr++) {
  169852. /* Compute size of an "input group" after IDCT scaling. This many samples
  169853. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  169854. */
  169855. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  169856. cinfo->min_DCT_scaled_size;
  169857. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169858. cinfo->min_DCT_scaled_size;
  169859. h_out_group = cinfo->max_h_samp_factor;
  169860. v_out_group = cinfo->max_v_samp_factor;
  169861. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  169862. need_buffer = TRUE;
  169863. if (! compptr->component_needed) {
  169864. /* Don't bother to upsample an uninteresting component. */
  169865. upsample->methods[ci] = noop_upsample;
  169866. need_buffer = FALSE;
  169867. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  169868. /* Fullsize components can be processed without any work. */
  169869. upsample->methods[ci] = fullsize_upsample;
  169870. need_buffer = FALSE;
  169871. } else if (h_in_group * 2 == h_out_group &&
  169872. v_in_group == v_out_group) {
  169873. /* Special cases for 2h1v upsampling */
  169874. if (do_fancy && compptr->downsampled_width > 2)
  169875. upsample->methods[ci] = h2v1_fancy_upsample;
  169876. else
  169877. upsample->methods[ci] = h2v1_upsample;
  169878. } else if (h_in_group * 2 == h_out_group &&
  169879. v_in_group * 2 == v_out_group) {
  169880. /* Special cases for 2h2v upsampling */
  169881. if (do_fancy && compptr->downsampled_width > 2) {
  169882. upsample->methods[ci] = h2v2_fancy_upsample;
  169883. upsample->pub.need_context_rows = TRUE;
  169884. } else
  169885. upsample->methods[ci] = h2v2_upsample;
  169886. } else if ((h_out_group % h_in_group) == 0 &&
  169887. (v_out_group % v_in_group) == 0) {
  169888. /* Generic integral-factors upsampling method */
  169889. upsample->methods[ci] = int_upsample;
  169890. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  169891. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  169892. } else
  169893. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  169894. if (need_buffer) {
  169895. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  169896. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169897. (JDIMENSION) jround_up((long) cinfo->output_width,
  169898. (long) cinfo->max_h_samp_factor),
  169899. (JDIMENSION) cinfo->max_v_samp_factor);
  169900. }
  169901. }
  169902. }
  169903. /********* End of inlined file: jdsample.c *********/
  169904. /********* Start of inlined file: jdtrans.c *********/
  169905. #define JPEG_INTERNALS
  169906. /* Forward declarations */
  169907. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  169908. /*
  169909. * Read the coefficient arrays from a JPEG file.
  169910. * jpeg_read_header must be completed before calling this.
  169911. *
  169912. * The entire image is read into a set of virtual coefficient-block arrays,
  169913. * one per component. The return value is a pointer to the array of
  169914. * virtual-array descriptors. These can be manipulated directly via the
  169915. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  169916. * To release the memory occupied by the virtual arrays, call
  169917. * jpeg_finish_decompress() when done with the data.
  169918. *
  169919. * An alternative usage is to simply obtain access to the coefficient arrays
  169920. * during a buffered-image-mode decompression operation. This is allowed
  169921. * after any jpeg_finish_output() call. The arrays can be accessed until
  169922. * jpeg_finish_decompress() is called. (Note that any call to the library
  169923. * may reposition the arrays, so don't rely on access_virt_barray() results
  169924. * to stay valid across library calls.)
  169925. *
  169926. * Returns NULL if suspended. This case need be checked only if
  169927. * a suspending data source is used.
  169928. */
  169929. GLOBAL(jvirt_barray_ptr *)
  169930. jpeg_read_coefficients (j_decompress_ptr cinfo)
  169931. {
  169932. if (cinfo->global_state == DSTATE_READY) {
  169933. /* First call: initialize active modules */
  169934. transdecode_master_selection(cinfo);
  169935. cinfo->global_state = DSTATE_RDCOEFS;
  169936. }
  169937. if (cinfo->global_state == DSTATE_RDCOEFS) {
  169938. /* Absorb whole file into the coef buffer */
  169939. for (;;) {
  169940. int retcode;
  169941. /* Call progress monitor hook if present */
  169942. if (cinfo->progress != NULL)
  169943. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  169944. /* Absorb some more input */
  169945. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  169946. if (retcode == JPEG_SUSPENDED)
  169947. return NULL;
  169948. if (retcode == JPEG_REACHED_EOI)
  169949. break;
  169950. /* Advance progress counter if appropriate */
  169951. if (cinfo->progress != NULL &&
  169952. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  169953. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  169954. /* startup underestimated number of scans; ratchet up one scan */
  169955. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  169956. }
  169957. }
  169958. }
  169959. /* Set state so that jpeg_finish_decompress does the right thing */
  169960. cinfo->global_state = DSTATE_STOPPING;
  169961. }
  169962. /* At this point we should be in state DSTATE_STOPPING if being used
  169963. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  169964. * to the coefficients during a full buffered-image-mode decompression.
  169965. */
  169966. if ((cinfo->global_state == DSTATE_STOPPING ||
  169967. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  169968. return cinfo->coef->coef_arrays;
  169969. }
  169970. /* Oops, improper usage */
  169971. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169972. return NULL; /* keep compiler happy */
  169973. }
  169974. /*
  169975. * Master selection of decompression modules for transcoding.
  169976. * This substitutes for jdmaster.c's initialization of the full decompressor.
  169977. */
  169978. LOCAL(void)
  169979. transdecode_master_selection (j_decompress_ptr cinfo)
  169980. {
  169981. /* This is effectively a buffered-image operation. */
  169982. cinfo->buffered_image = TRUE;
  169983. /* Entropy decoding: either Huffman or arithmetic coding. */
  169984. if (cinfo->arith_code) {
  169985. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169986. } else {
  169987. if (cinfo->progressive_mode) {
  169988. #ifdef D_PROGRESSIVE_SUPPORTED
  169989. jinit_phuff_decoder(cinfo);
  169990. #else
  169991. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169992. #endif
  169993. } else
  169994. jinit_huff_decoder(cinfo);
  169995. }
  169996. /* Always get a full-image coefficient buffer. */
  169997. jinit_d_coef_controller(cinfo, TRUE);
  169998. /* We can now tell the memory manager to allocate virtual arrays. */
  169999. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  170000. /* Initialize input side of decompressor to consume first scan. */
  170001. (*cinfo->inputctl->start_input_pass) (cinfo);
  170002. /* Initialize progress monitoring. */
  170003. if (cinfo->progress != NULL) {
  170004. int nscans;
  170005. /* Estimate number of scans to set pass_limit. */
  170006. if (cinfo->progressive_mode) {
  170007. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  170008. nscans = 2 + 3 * cinfo->num_components;
  170009. } else if (cinfo->inputctl->has_multiple_scans) {
  170010. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  170011. nscans = cinfo->num_components;
  170012. } else {
  170013. nscans = 1;
  170014. }
  170015. cinfo->progress->pass_counter = 0L;
  170016. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  170017. cinfo->progress->completed_passes = 0;
  170018. cinfo->progress->total_passes = 1;
  170019. }
  170020. }
  170021. /********* End of inlined file: jdtrans.c *********/
  170022. /********* Start of inlined file: jfdctflt.c *********/
  170023. #define JPEG_INTERNALS
  170024. #ifdef DCT_FLOAT_SUPPORTED
  170025. /*
  170026. * This module is specialized to the case DCTSIZE = 8.
  170027. */
  170028. #if DCTSIZE != 8
  170029. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170030. #endif
  170031. /*
  170032. * Perform the forward DCT on one block of samples.
  170033. */
  170034. GLOBAL(void)
  170035. jpeg_fdct_float (FAST_FLOAT * data)
  170036. {
  170037. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170038. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  170039. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  170040. FAST_FLOAT *dataptr;
  170041. int ctr;
  170042. /* Pass 1: process rows. */
  170043. dataptr = data;
  170044. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170045. tmp0 = dataptr[0] + dataptr[7];
  170046. tmp7 = dataptr[0] - dataptr[7];
  170047. tmp1 = dataptr[1] + dataptr[6];
  170048. tmp6 = dataptr[1] - dataptr[6];
  170049. tmp2 = dataptr[2] + dataptr[5];
  170050. tmp5 = dataptr[2] - dataptr[5];
  170051. tmp3 = dataptr[3] + dataptr[4];
  170052. tmp4 = dataptr[3] - dataptr[4];
  170053. /* Even part */
  170054. tmp10 = tmp0 + tmp3; /* phase 2 */
  170055. tmp13 = tmp0 - tmp3;
  170056. tmp11 = tmp1 + tmp2;
  170057. tmp12 = tmp1 - tmp2;
  170058. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170059. dataptr[4] = tmp10 - tmp11;
  170060. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170061. dataptr[2] = tmp13 + z1; /* phase 5 */
  170062. dataptr[6] = tmp13 - z1;
  170063. /* Odd part */
  170064. tmp10 = tmp4 + tmp5; /* phase 2 */
  170065. tmp11 = tmp5 + tmp6;
  170066. tmp12 = tmp6 + tmp7;
  170067. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170068. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170069. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170070. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170071. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170072. z11 = tmp7 + z3; /* phase 5 */
  170073. z13 = tmp7 - z3;
  170074. dataptr[5] = z13 + z2; /* phase 6 */
  170075. dataptr[3] = z13 - z2;
  170076. dataptr[1] = z11 + z4;
  170077. dataptr[7] = z11 - z4;
  170078. dataptr += DCTSIZE; /* advance pointer to next row */
  170079. }
  170080. /* Pass 2: process columns. */
  170081. dataptr = data;
  170082. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170083. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170084. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170085. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170086. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170087. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170088. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170089. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170090. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170091. /* Even part */
  170092. tmp10 = tmp0 + tmp3; /* phase 2 */
  170093. tmp13 = tmp0 - tmp3;
  170094. tmp11 = tmp1 + tmp2;
  170095. tmp12 = tmp1 - tmp2;
  170096. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170097. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170098. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  170099. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170100. dataptr[DCTSIZE*6] = tmp13 - z1;
  170101. /* Odd part */
  170102. tmp10 = tmp4 + tmp5; /* phase 2 */
  170103. tmp11 = tmp5 + tmp6;
  170104. tmp12 = tmp6 + tmp7;
  170105. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170106. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  170107. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  170108. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  170109. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  170110. z11 = tmp7 + z3; /* phase 5 */
  170111. z13 = tmp7 - z3;
  170112. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170113. dataptr[DCTSIZE*3] = z13 - z2;
  170114. dataptr[DCTSIZE*1] = z11 + z4;
  170115. dataptr[DCTSIZE*7] = z11 - z4;
  170116. dataptr++; /* advance pointer to next column */
  170117. }
  170118. }
  170119. #endif /* DCT_FLOAT_SUPPORTED */
  170120. /********* End of inlined file: jfdctflt.c *********/
  170121. /********* Start of inlined file: jfdctint.c *********/
  170122. #define JPEG_INTERNALS
  170123. #ifdef DCT_ISLOW_SUPPORTED
  170124. /*
  170125. * This module is specialized to the case DCTSIZE = 8.
  170126. */
  170127. #if DCTSIZE != 8
  170128. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170129. #endif
  170130. /*
  170131. * The poop on this scaling stuff is as follows:
  170132. *
  170133. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  170134. * larger than the true DCT outputs. The final outputs are therefore
  170135. * a factor of N larger than desired; since N=8 this can be cured by
  170136. * a simple right shift at the end of the algorithm. The advantage of
  170137. * this arrangement is that we save two multiplications per 1-D DCT,
  170138. * because the y0 and y4 outputs need not be divided by sqrt(N).
  170139. * In the IJG code, this factor of 8 is removed by the quantization step
  170140. * (in jcdctmgr.c), NOT in this module.
  170141. *
  170142. * We have to do addition and subtraction of the integer inputs, which
  170143. * is no problem, and multiplication by fractional constants, which is
  170144. * a problem to do in integer arithmetic. We multiply all the constants
  170145. * by CONST_SCALE and convert them to integer constants (thus retaining
  170146. * CONST_BITS bits of precision in the constants). After doing a
  170147. * multiplication we have to divide the product by CONST_SCALE, with proper
  170148. * rounding, to produce the correct output. This division can be done
  170149. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170150. * as long as possible so that partial sums can be added together with
  170151. * full fractional precision.
  170152. *
  170153. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170154. * they are represented to better-than-integral precision. These outputs
  170155. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170156. * with the recommended scaling. (For 12-bit sample data, the intermediate
  170157. * array is INT32 anyway.)
  170158. *
  170159. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170160. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170161. * shows that the values given below are the most effective.
  170162. */
  170163. #if BITS_IN_JSAMPLE == 8
  170164. #define CONST_BITS 13
  170165. #define PASS1_BITS 2
  170166. #else
  170167. #define CONST_BITS 13
  170168. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170169. #endif
  170170. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170171. * causing a lot of useless floating-point operations at run time.
  170172. * To get around this we use the following pre-calculated constants.
  170173. * If you change CONST_BITS you may want to add appropriate values.
  170174. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170175. */
  170176. #if CONST_BITS == 13
  170177. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170178. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170179. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170180. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170181. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170182. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170183. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170184. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170185. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170186. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170187. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170188. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170189. #else
  170190. #define FIX_0_298631336 FIX(0.298631336)
  170191. #define FIX_0_390180644 FIX(0.390180644)
  170192. #define FIX_0_541196100 FIX(0.541196100)
  170193. #define FIX_0_765366865 FIX(0.765366865)
  170194. #define FIX_0_899976223 FIX(0.899976223)
  170195. #define FIX_1_175875602 FIX(1.175875602)
  170196. #define FIX_1_501321110 FIX(1.501321110)
  170197. #define FIX_1_847759065 FIX(1.847759065)
  170198. #define FIX_1_961570560 FIX(1.961570560)
  170199. #define FIX_2_053119869 FIX(2.053119869)
  170200. #define FIX_2_562915447 FIX(2.562915447)
  170201. #define FIX_3_072711026 FIX(3.072711026)
  170202. #endif
  170203. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170204. * For 8-bit samples with the recommended scaling, all the variable
  170205. * and constant values involved are no more than 16 bits wide, so a
  170206. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170207. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170208. */
  170209. #if BITS_IN_JSAMPLE == 8
  170210. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170211. #else
  170212. #define MULTIPLY(var,const) ((var) * (const))
  170213. #endif
  170214. /*
  170215. * Perform the forward DCT on one block of samples.
  170216. */
  170217. GLOBAL(void)
  170218. jpeg_fdct_islow (DCTELEM * data)
  170219. {
  170220. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170221. INT32 tmp10, tmp11, tmp12, tmp13;
  170222. INT32 z1, z2, z3, z4, z5;
  170223. DCTELEM *dataptr;
  170224. int ctr;
  170225. SHIFT_TEMPS
  170226. /* Pass 1: process rows. */
  170227. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  170228. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170229. dataptr = data;
  170230. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170231. tmp0 = dataptr[0] + dataptr[7];
  170232. tmp7 = dataptr[0] - dataptr[7];
  170233. tmp1 = dataptr[1] + dataptr[6];
  170234. tmp6 = dataptr[1] - dataptr[6];
  170235. tmp2 = dataptr[2] + dataptr[5];
  170236. tmp5 = dataptr[2] - dataptr[5];
  170237. tmp3 = dataptr[3] + dataptr[4];
  170238. tmp4 = dataptr[3] - dataptr[4];
  170239. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170240. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170241. */
  170242. tmp10 = tmp0 + tmp3;
  170243. tmp13 = tmp0 - tmp3;
  170244. tmp11 = tmp1 + tmp2;
  170245. tmp12 = tmp1 - tmp2;
  170246. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  170247. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  170248. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170249. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170250. CONST_BITS-PASS1_BITS);
  170251. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170252. CONST_BITS-PASS1_BITS);
  170253. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170254. * cK represents cos(K*pi/16).
  170255. * i0..i3 in the paper are tmp4..tmp7 here.
  170256. */
  170257. z1 = tmp4 + tmp7;
  170258. z2 = tmp5 + tmp6;
  170259. z3 = tmp4 + tmp6;
  170260. z4 = tmp5 + tmp7;
  170261. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170262. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170263. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170264. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170265. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170266. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170267. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170268. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170269. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170270. z3 += z5;
  170271. z4 += z5;
  170272. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  170273. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  170274. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  170275. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  170276. dataptr += DCTSIZE; /* advance pointer to next row */
  170277. }
  170278. /* Pass 2: process columns.
  170279. * We remove the PASS1_BITS scaling, but leave the results scaled up
  170280. * by an overall factor of 8.
  170281. */
  170282. dataptr = data;
  170283. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170284. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170285. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170286. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170287. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170288. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170289. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170290. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170291. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170292. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170293. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170294. */
  170295. tmp10 = tmp0 + tmp3;
  170296. tmp13 = tmp0 - tmp3;
  170297. tmp11 = tmp1 + tmp2;
  170298. tmp12 = tmp1 - tmp2;
  170299. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  170300. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  170301. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170302. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170303. CONST_BITS+PASS1_BITS);
  170304. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170305. CONST_BITS+PASS1_BITS);
  170306. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170307. * cK represents cos(K*pi/16).
  170308. * i0..i3 in the paper are tmp4..tmp7 here.
  170309. */
  170310. z1 = tmp4 + tmp7;
  170311. z2 = tmp5 + tmp6;
  170312. z3 = tmp4 + tmp6;
  170313. z4 = tmp5 + tmp7;
  170314. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170315. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170316. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170317. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170318. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170319. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170320. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170321. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170322. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170323. z3 += z5;
  170324. z4 += z5;
  170325. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  170326. CONST_BITS+PASS1_BITS);
  170327. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  170328. CONST_BITS+PASS1_BITS);
  170329. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  170330. CONST_BITS+PASS1_BITS);
  170331. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  170332. CONST_BITS+PASS1_BITS);
  170333. dataptr++; /* advance pointer to next column */
  170334. }
  170335. }
  170336. #endif /* DCT_ISLOW_SUPPORTED */
  170337. /********* End of inlined file: jfdctint.c *********/
  170338. #undef CONST_BITS
  170339. #undef MULTIPLY
  170340. #undef FIX_0_541196100
  170341. /********* Start of inlined file: jfdctfst.c *********/
  170342. #define JPEG_INTERNALS
  170343. #ifdef DCT_IFAST_SUPPORTED
  170344. /*
  170345. * This module is specialized to the case DCTSIZE = 8.
  170346. */
  170347. #if DCTSIZE != 8
  170348. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170349. #endif
  170350. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170351. * see jfdctint.c for more details. However, we choose to descale
  170352. * (right shift) multiplication products as soon as they are formed,
  170353. * rather than carrying additional fractional bits into subsequent additions.
  170354. * This compromises accuracy slightly, but it lets us save a few shifts.
  170355. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170356. * everywhere except in the multiplications proper; this saves a good deal
  170357. * of work on 16-bit-int machines.
  170358. *
  170359. * Again to save a few shifts, the intermediate results between pass 1 and
  170360. * pass 2 are not upscaled, but are represented only to integral precision.
  170361. *
  170362. * A final compromise is to represent the multiplicative constants to only
  170363. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170364. * machines, and may also reduce the cost of multiplication (since there
  170365. * are fewer one-bits in the constants).
  170366. */
  170367. #define CONST_BITS 8
  170368. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170369. * causing a lot of useless floating-point operations at run time.
  170370. * To get around this we use the following pre-calculated constants.
  170371. * If you change CONST_BITS you may want to add appropriate values.
  170372. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170373. */
  170374. #if CONST_BITS == 8
  170375. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  170376. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  170377. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  170378. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  170379. #else
  170380. #define FIX_0_382683433 FIX(0.382683433)
  170381. #define FIX_0_541196100 FIX(0.541196100)
  170382. #define FIX_0_707106781 FIX(0.707106781)
  170383. #define FIX_1_306562965 FIX(1.306562965)
  170384. #endif
  170385. /* We can gain a little more speed, with a further compromise in accuracy,
  170386. * by omitting the addition in a descaling shift. This yields an incorrectly
  170387. * rounded result half the time...
  170388. */
  170389. #ifndef USE_ACCURATE_ROUNDING
  170390. #undef DESCALE
  170391. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170392. #endif
  170393. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170394. * descale to yield a DCTELEM result.
  170395. */
  170396. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170397. /*
  170398. * Perform the forward DCT on one block of samples.
  170399. */
  170400. GLOBAL(void)
  170401. jpeg_fdct_ifast (DCTELEM * data)
  170402. {
  170403. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170404. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170405. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  170406. DCTELEM *dataptr;
  170407. int ctr;
  170408. SHIFT_TEMPS
  170409. /* Pass 1: process rows. */
  170410. dataptr = data;
  170411. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170412. tmp0 = dataptr[0] + dataptr[7];
  170413. tmp7 = dataptr[0] - dataptr[7];
  170414. tmp1 = dataptr[1] + dataptr[6];
  170415. tmp6 = dataptr[1] - dataptr[6];
  170416. tmp2 = dataptr[2] + dataptr[5];
  170417. tmp5 = dataptr[2] - dataptr[5];
  170418. tmp3 = dataptr[3] + dataptr[4];
  170419. tmp4 = dataptr[3] - dataptr[4];
  170420. /* Even part */
  170421. tmp10 = tmp0 + tmp3; /* phase 2 */
  170422. tmp13 = tmp0 - tmp3;
  170423. tmp11 = tmp1 + tmp2;
  170424. tmp12 = tmp1 - tmp2;
  170425. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170426. dataptr[4] = tmp10 - tmp11;
  170427. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170428. dataptr[2] = tmp13 + z1; /* phase 5 */
  170429. dataptr[6] = tmp13 - z1;
  170430. /* Odd part */
  170431. tmp10 = tmp4 + tmp5; /* phase 2 */
  170432. tmp11 = tmp5 + tmp6;
  170433. tmp12 = tmp6 + tmp7;
  170434. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170435. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170436. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170437. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170438. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170439. z11 = tmp7 + z3; /* phase 5 */
  170440. z13 = tmp7 - z3;
  170441. dataptr[5] = z13 + z2; /* phase 6 */
  170442. dataptr[3] = z13 - z2;
  170443. dataptr[1] = z11 + z4;
  170444. dataptr[7] = z11 - z4;
  170445. dataptr += DCTSIZE; /* advance pointer to next row */
  170446. }
  170447. /* Pass 2: process columns. */
  170448. dataptr = data;
  170449. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170450. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170451. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170452. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170453. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170454. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170455. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170456. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170457. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170458. /* Even part */
  170459. tmp10 = tmp0 + tmp3; /* phase 2 */
  170460. tmp13 = tmp0 - tmp3;
  170461. tmp11 = tmp1 + tmp2;
  170462. tmp12 = tmp1 - tmp2;
  170463. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170464. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170465. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170466. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170467. dataptr[DCTSIZE*6] = tmp13 - z1;
  170468. /* Odd part */
  170469. tmp10 = tmp4 + tmp5; /* phase 2 */
  170470. tmp11 = tmp5 + tmp6;
  170471. tmp12 = tmp6 + tmp7;
  170472. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170473. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170474. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170475. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170476. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170477. z11 = tmp7 + z3; /* phase 5 */
  170478. z13 = tmp7 - z3;
  170479. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170480. dataptr[DCTSIZE*3] = z13 - z2;
  170481. dataptr[DCTSIZE*1] = z11 + z4;
  170482. dataptr[DCTSIZE*7] = z11 - z4;
  170483. dataptr++; /* advance pointer to next column */
  170484. }
  170485. }
  170486. #endif /* DCT_IFAST_SUPPORTED */
  170487. /********* End of inlined file: jfdctfst.c *********/
  170488. #undef FIX_0_541196100
  170489. /********* Start of inlined file: jidctflt.c *********/
  170490. #define JPEG_INTERNALS
  170491. #ifdef DCT_FLOAT_SUPPORTED
  170492. /*
  170493. * This module is specialized to the case DCTSIZE = 8.
  170494. */
  170495. #if DCTSIZE != 8
  170496. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170497. #endif
  170498. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170499. * entry; produce a float result.
  170500. */
  170501. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  170502. /*
  170503. * Perform dequantization and inverse DCT on one block of coefficients.
  170504. */
  170505. GLOBAL(void)
  170506. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170507. JCOEFPTR coef_block,
  170508. JSAMPARRAY output_buf, JDIMENSION output_col)
  170509. {
  170510. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170511. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  170512. FAST_FLOAT z5, z10, z11, z12, z13;
  170513. JCOEFPTR inptr;
  170514. FLOAT_MULT_TYPE * quantptr;
  170515. FAST_FLOAT * wsptr;
  170516. JSAMPROW outptr;
  170517. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170518. int ctr;
  170519. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  170520. SHIFT_TEMPS
  170521. /* Pass 1: process columns from input, store into work array. */
  170522. inptr = coef_block;
  170523. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  170524. wsptr = workspace;
  170525. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170526. /* Due to quantization, we will usually find that many of the input
  170527. * coefficients are zero, especially the AC terms. We can exploit this
  170528. * by short-circuiting the IDCT calculation for any column in which all
  170529. * the AC terms are zero. In that case each output is equal to the
  170530. * DC coefficient (with scale factor as needed).
  170531. * With typical images and quantization tables, half or more of the
  170532. * column DCT calculations can be simplified this way.
  170533. */
  170534. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170535. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170536. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170537. inptr[DCTSIZE*7] == 0) {
  170538. /* AC terms all zero */
  170539. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170540. wsptr[DCTSIZE*0] = dcval;
  170541. wsptr[DCTSIZE*1] = dcval;
  170542. wsptr[DCTSIZE*2] = dcval;
  170543. wsptr[DCTSIZE*3] = dcval;
  170544. wsptr[DCTSIZE*4] = dcval;
  170545. wsptr[DCTSIZE*5] = dcval;
  170546. wsptr[DCTSIZE*6] = dcval;
  170547. wsptr[DCTSIZE*7] = dcval;
  170548. inptr++; /* advance pointers to next column */
  170549. quantptr++;
  170550. wsptr++;
  170551. continue;
  170552. }
  170553. /* Even part */
  170554. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170555. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170556. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170557. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170558. tmp10 = tmp0 + tmp2; /* phase 3 */
  170559. tmp11 = tmp0 - tmp2;
  170560. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170561. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  170562. tmp0 = tmp10 + tmp13; /* phase 2 */
  170563. tmp3 = tmp10 - tmp13;
  170564. tmp1 = tmp11 + tmp12;
  170565. tmp2 = tmp11 - tmp12;
  170566. /* Odd part */
  170567. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170568. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170569. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170570. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170571. z13 = tmp6 + tmp5; /* phase 6 */
  170572. z10 = tmp6 - tmp5;
  170573. z11 = tmp4 + tmp7;
  170574. z12 = tmp4 - tmp7;
  170575. tmp7 = z11 + z13; /* phase 5 */
  170576. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  170577. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170578. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170579. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170580. tmp6 = tmp12 - tmp7; /* phase 2 */
  170581. tmp5 = tmp11 - tmp6;
  170582. tmp4 = tmp10 + tmp5;
  170583. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  170584. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  170585. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  170586. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  170587. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  170588. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  170589. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  170590. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  170591. inptr++; /* advance pointers to next column */
  170592. quantptr++;
  170593. wsptr++;
  170594. }
  170595. /* Pass 2: process rows from work array, store into output array. */
  170596. /* Note that we must descale the results by a factor of 8 == 2**3. */
  170597. wsptr = workspace;
  170598. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170599. outptr = output_buf[ctr] + output_col;
  170600. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170601. * However, the column calculation has created many nonzero AC terms, so
  170602. * the simplification applies less often (typically 5% to 10% of the time).
  170603. * And testing floats for zero is relatively expensive, so we don't bother.
  170604. */
  170605. /* Even part */
  170606. tmp10 = wsptr[0] + wsptr[4];
  170607. tmp11 = wsptr[0] - wsptr[4];
  170608. tmp13 = wsptr[2] + wsptr[6];
  170609. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  170610. tmp0 = tmp10 + tmp13;
  170611. tmp3 = tmp10 - tmp13;
  170612. tmp1 = tmp11 + tmp12;
  170613. tmp2 = tmp11 - tmp12;
  170614. /* Odd part */
  170615. z13 = wsptr[5] + wsptr[3];
  170616. z10 = wsptr[5] - wsptr[3];
  170617. z11 = wsptr[1] + wsptr[7];
  170618. z12 = wsptr[1] - wsptr[7];
  170619. tmp7 = z11 + z13;
  170620. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  170621. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170622. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170623. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170624. tmp6 = tmp12 - tmp7;
  170625. tmp5 = tmp11 - tmp6;
  170626. tmp4 = tmp10 + tmp5;
  170627. /* Final output stage: scale down by a factor of 8 and range-limit */
  170628. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  170629. & RANGE_MASK];
  170630. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  170631. & RANGE_MASK];
  170632. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  170633. & RANGE_MASK];
  170634. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  170635. & RANGE_MASK];
  170636. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  170637. & RANGE_MASK];
  170638. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  170639. & RANGE_MASK];
  170640. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  170641. & RANGE_MASK];
  170642. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  170643. & RANGE_MASK];
  170644. wsptr += DCTSIZE; /* advance pointer to next row */
  170645. }
  170646. }
  170647. #endif /* DCT_FLOAT_SUPPORTED */
  170648. /********* End of inlined file: jidctflt.c *********/
  170649. #undef CONST_BITS
  170650. #undef FIX_1_847759065
  170651. #undef MULTIPLY
  170652. #undef DEQUANTIZE
  170653. #undef DESCALE
  170654. /********* Start of inlined file: jidctfst.c *********/
  170655. #define JPEG_INTERNALS
  170656. #ifdef DCT_IFAST_SUPPORTED
  170657. /*
  170658. * This module is specialized to the case DCTSIZE = 8.
  170659. */
  170660. #if DCTSIZE != 8
  170661. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170662. #endif
  170663. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170664. * see jidctint.c for more details. However, we choose to descale
  170665. * (right shift) multiplication products as soon as they are formed,
  170666. * rather than carrying additional fractional bits into subsequent additions.
  170667. * This compromises accuracy slightly, but it lets us save a few shifts.
  170668. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170669. * everywhere except in the multiplications proper; this saves a good deal
  170670. * of work on 16-bit-int machines.
  170671. *
  170672. * The dequantized coefficients are not integers because the AA&N scaling
  170673. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  170674. * so that the first and second IDCT rounds have the same input scaling.
  170675. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  170676. * avoid a descaling shift; this compromises accuracy rather drastically
  170677. * for small quantization table entries, but it saves a lot of shifts.
  170678. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  170679. * so we use a much larger scaling factor to preserve accuracy.
  170680. *
  170681. * A final compromise is to represent the multiplicative constants to only
  170682. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170683. * machines, and may also reduce the cost of multiplication (since there
  170684. * are fewer one-bits in the constants).
  170685. */
  170686. #if BITS_IN_JSAMPLE == 8
  170687. #define CONST_BITS 8
  170688. #define PASS1_BITS 2
  170689. #else
  170690. #define CONST_BITS 8
  170691. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170692. #endif
  170693. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170694. * causing a lot of useless floating-point operations at run time.
  170695. * To get around this we use the following pre-calculated constants.
  170696. * If you change CONST_BITS you may want to add appropriate values.
  170697. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170698. */
  170699. #if CONST_BITS == 8
  170700. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  170701. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  170702. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  170703. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  170704. #else
  170705. #define FIX_1_082392200 FIX(1.082392200)
  170706. #define FIX_1_414213562 FIX(1.414213562)
  170707. #define FIX_1_847759065 FIX(1.847759065)
  170708. #define FIX_2_613125930 FIX(2.613125930)
  170709. #endif
  170710. /* We can gain a little more speed, with a further compromise in accuracy,
  170711. * by omitting the addition in a descaling shift. This yields an incorrectly
  170712. * rounded result half the time...
  170713. */
  170714. #ifndef USE_ACCURATE_ROUNDING
  170715. #undef DESCALE
  170716. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170717. #endif
  170718. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170719. * descale to yield a DCTELEM result.
  170720. */
  170721. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170722. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170723. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  170724. * multiplication will do. For 12-bit data, the multiplier table is
  170725. * declared INT32, so a 32-bit multiply will be used.
  170726. */
  170727. #if BITS_IN_JSAMPLE == 8
  170728. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  170729. #else
  170730. #define DEQUANTIZE(coef,quantval) \
  170731. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  170732. #endif
  170733. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  170734. * We assume that int right shift is unsigned if INT32 right shift is.
  170735. */
  170736. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  170737. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  170738. #if BITS_IN_JSAMPLE == 8
  170739. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  170740. #else
  170741. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  170742. #endif
  170743. #define IRIGHT_SHIFT(x,shft) \
  170744. ((ishift_temp = (x)) < 0 ? \
  170745. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  170746. (ishift_temp >> (shft)))
  170747. #else
  170748. #define ISHIFT_TEMPS
  170749. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  170750. #endif
  170751. #ifdef USE_ACCURATE_ROUNDING
  170752. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  170753. #else
  170754. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  170755. #endif
  170756. /*
  170757. * Perform dequantization and inverse DCT on one block of coefficients.
  170758. */
  170759. GLOBAL(void)
  170760. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170761. JCOEFPTR coef_block,
  170762. JSAMPARRAY output_buf, JDIMENSION output_col)
  170763. {
  170764. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170765. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170766. DCTELEM z5, z10, z11, z12, z13;
  170767. JCOEFPTR inptr;
  170768. IFAST_MULT_TYPE * quantptr;
  170769. int * wsptr;
  170770. JSAMPROW outptr;
  170771. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170772. int ctr;
  170773. int workspace[DCTSIZE2]; /* buffers data between passes */
  170774. SHIFT_TEMPS /* for DESCALE */
  170775. ISHIFT_TEMPS /* for IDESCALE */
  170776. /* Pass 1: process columns from input, store into work array. */
  170777. inptr = coef_block;
  170778. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  170779. wsptr = workspace;
  170780. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170781. /* Due to quantization, we will usually find that many of the input
  170782. * coefficients are zero, especially the AC terms. We can exploit this
  170783. * by short-circuiting the IDCT calculation for any column in which all
  170784. * the AC terms are zero. In that case each output is equal to the
  170785. * DC coefficient (with scale factor as needed).
  170786. * With typical images and quantization tables, half or more of the
  170787. * column DCT calculations can be simplified this way.
  170788. */
  170789. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170790. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170791. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170792. inptr[DCTSIZE*7] == 0) {
  170793. /* AC terms all zero */
  170794. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170795. wsptr[DCTSIZE*0] = dcval;
  170796. wsptr[DCTSIZE*1] = dcval;
  170797. wsptr[DCTSIZE*2] = dcval;
  170798. wsptr[DCTSIZE*3] = dcval;
  170799. wsptr[DCTSIZE*4] = dcval;
  170800. wsptr[DCTSIZE*5] = dcval;
  170801. wsptr[DCTSIZE*6] = dcval;
  170802. wsptr[DCTSIZE*7] = dcval;
  170803. inptr++; /* advance pointers to next column */
  170804. quantptr++;
  170805. wsptr++;
  170806. continue;
  170807. }
  170808. /* Even part */
  170809. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170810. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170811. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170812. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170813. tmp10 = tmp0 + tmp2; /* phase 3 */
  170814. tmp11 = tmp0 - tmp2;
  170815. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170816. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  170817. tmp0 = tmp10 + tmp13; /* phase 2 */
  170818. tmp3 = tmp10 - tmp13;
  170819. tmp1 = tmp11 + tmp12;
  170820. tmp2 = tmp11 - tmp12;
  170821. /* Odd part */
  170822. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170823. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170824. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170825. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170826. z13 = tmp6 + tmp5; /* phase 6 */
  170827. z10 = tmp6 - tmp5;
  170828. z11 = tmp4 + tmp7;
  170829. z12 = tmp4 - tmp7;
  170830. tmp7 = z11 + z13; /* phase 5 */
  170831. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170832. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170833. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170834. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170835. tmp6 = tmp12 - tmp7; /* phase 2 */
  170836. tmp5 = tmp11 - tmp6;
  170837. tmp4 = tmp10 + tmp5;
  170838. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  170839. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  170840. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  170841. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  170842. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  170843. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  170844. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  170845. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  170846. inptr++; /* advance pointers to next column */
  170847. quantptr++;
  170848. wsptr++;
  170849. }
  170850. /* Pass 2: process rows from work array, store into output array. */
  170851. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170852. /* and also undo the PASS1_BITS scaling. */
  170853. wsptr = workspace;
  170854. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170855. outptr = output_buf[ctr] + output_col;
  170856. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170857. * However, the column calculation has created many nonzero AC terms, so
  170858. * the simplification applies less often (typically 5% to 10% of the time).
  170859. * On machines with very fast multiplication, it's possible that the
  170860. * test takes more time than it's worth. In that case this section
  170861. * may be commented out.
  170862. */
  170863. #ifndef NO_ZERO_ROW_TEST
  170864. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170865. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170866. /* AC terms all zero */
  170867. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  170868. & RANGE_MASK];
  170869. outptr[0] = dcval;
  170870. outptr[1] = dcval;
  170871. outptr[2] = dcval;
  170872. outptr[3] = dcval;
  170873. outptr[4] = dcval;
  170874. outptr[5] = dcval;
  170875. outptr[6] = dcval;
  170876. outptr[7] = dcval;
  170877. wsptr += DCTSIZE; /* advance pointer to next row */
  170878. continue;
  170879. }
  170880. #endif
  170881. /* Even part */
  170882. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  170883. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  170884. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  170885. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  170886. - tmp13;
  170887. tmp0 = tmp10 + tmp13;
  170888. tmp3 = tmp10 - tmp13;
  170889. tmp1 = tmp11 + tmp12;
  170890. tmp2 = tmp11 - tmp12;
  170891. /* Odd part */
  170892. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  170893. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  170894. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  170895. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  170896. tmp7 = z11 + z13; /* phase 5 */
  170897. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170898. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170899. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170900. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170901. tmp6 = tmp12 - tmp7; /* phase 2 */
  170902. tmp5 = tmp11 - tmp6;
  170903. tmp4 = tmp10 + tmp5;
  170904. /* Final output stage: scale down by a factor of 8 and range-limit */
  170905. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  170906. & RANGE_MASK];
  170907. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  170908. & RANGE_MASK];
  170909. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  170910. & RANGE_MASK];
  170911. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  170912. & RANGE_MASK];
  170913. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  170914. & RANGE_MASK];
  170915. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  170916. & RANGE_MASK];
  170917. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  170918. & RANGE_MASK];
  170919. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  170920. & RANGE_MASK];
  170921. wsptr += DCTSIZE; /* advance pointer to next row */
  170922. }
  170923. }
  170924. #endif /* DCT_IFAST_SUPPORTED */
  170925. /********* End of inlined file: jidctfst.c *********/
  170926. #undef CONST_BITS
  170927. #undef FIX_1_847759065
  170928. #undef MULTIPLY
  170929. #undef DEQUANTIZE
  170930. /********* Start of inlined file: jidctint.c *********/
  170931. #define JPEG_INTERNALS
  170932. #ifdef DCT_ISLOW_SUPPORTED
  170933. /*
  170934. * This module is specialized to the case DCTSIZE = 8.
  170935. */
  170936. #if DCTSIZE != 8
  170937. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170938. #endif
  170939. /*
  170940. * The poop on this scaling stuff is as follows:
  170941. *
  170942. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  170943. * larger than the true IDCT outputs. The final outputs are therefore
  170944. * a factor of N larger than desired; since N=8 this can be cured by
  170945. * a simple right shift at the end of the algorithm. The advantage of
  170946. * this arrangement is that we save two multiplications per 1-D IDCT,
  170947. * because the y0 and y4 inputs need not be divided by sqrt(N).
  170948. *
  170949. * We have to do addition and subtraction of the integer inputs, which
  170950. * is no problem, and multiplication by fractional constants, which is
  170951. * a problem to do in integer arithmetic. We multiply all the constants
  170952. * by CONST_SCALE and convert them to integer constants (thus retaining
  170953. * CONST_BITS bits of precision in the constants). After doing a
  170954. * multiplication we have to divide the product by CONST_SCALE, with proper
  170955. * rounding, to produce the correct output. This division can be done
  170956. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170957. * as long as possible so that partial sums can be added together with
  170958. * full fractional precision.
  170959. *
  170960. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170961. * they are represented to better-than-integral precision. These outputs
  170962. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170963. * with the recommended scaling. (To scale up 12-bit sample data further, an
  170964. * intermediate INT32 array would be needed.)
  170965. *
  170966. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170967. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170968. * shows that the values given below are the most effective.
  170969. */
  170970. #if BITS_IN_JSAMPLE == 8
  170971. #define CONST_BITS 13
  170972. #define PASS1_BITS 2
  170973. #else
  170974. #define CONST_BITS 13
  170975. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170976. #endif
  170977. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170978. * causing a lot of useless floating-point operations at run time.
  170979. * To get around this we use the following pre-calculated constants.
  170980. * If you change CONST_BITS you may want to add appropriate values.
  170981. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170982. */
  170983. #if CONST_BITS == 13
  170984. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170985. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170986. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170987. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170988. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170989. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170990. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170991. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170992. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170993. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170994. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170995. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170996. #else
  170997. #define FIX_0_298631336 FIX(0.298631336)
  170998. #define FIX_0_390180644 FIX(0.390180644)
  170999. #define FIX_0_541196100 FIX(0.541196100)
  171000. #define FIX_0_765366865 FIX(0.765366865)
  171001. #define FIX_0_899976223 FIX(0.899976223)
  171002. #define FIX_1_175875602 FIX(1.175875602)
  171003. #define FIX_1_501321110 FIX(1.501321110)
  171004. #define FIX_1_847759065 FIX(1.847759065)
  171005. #define FIX_1_961570560 FIX(1.961570560)
  171006. #define FIX_2_053119869 FIX(2.053119869)
  171007. #define FIX_2_562915447 FIX(2.562915447)
  171008. #define FIX_3_072711026 FIX(3.072711026)
  171009. #endif
  171010. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171011. * For 8-bit samples with the recommended scaling, all the variable
  171012. * and constant values involved are no more than 16 bits wide, so a
  171013. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171014. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171015. */
  171016. #if BITS_IN_JSAMPLE == 8
  171017. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171018. #else
  171019. #define MULTIPLY(var,const) ((var) * (const))
  171020. #endif
  171021. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171022. * entry; produce an int result. In this module, both inputs and result
  171023. * are 16 bits or less, so either int or short multiply will work.
  171024. */
  171025. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  171026. /*
  171027. * Perform dequantization and inverse DCT on one block of coefficients.
  171028. */
  171029. GLOBAL(void)
  171030. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171031. JCOEFPTR coef_block,
  171032. JSAMPARRAY output_buf, JDIMENSION output_col)
  171033. {
  171034. INT32 tmp0, tmp1, tmp2, tmp3;
  171035. INT32 tmp10, tmp11, tmp12, tmp13;
  171036. INT32 z1, z2, z3, z4, z5;
  171037. JCOEFPTR inptr;
  171038. ISLOW_MULT_TYPE * quantptr;
  171039. int * wsptr;
  171040. JSAMPROW outptr;
  171041. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171042. int ctr;
  171043. int workspace[DCTSIZE2]; /* buffers data between passes */
  171044. SHIFT_TEMPS
  171045. /* Pass 1: process columns from input, store into work array. */
  171046. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  171047. /* furthermore, we scale the results by 2**PASS1_BITS. */
  171048. inptr = coef_block;
  171049. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171050. wsptr = workspace;
  171051. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  171052. /* Due to quantization, we will usually find that many of the input
  171053. * coefficients are zero, especially the AC terms. We can exploit this
  171054. * by short-circuiting the IDCT calculation for any column in which all
  171055. * the AC terms are zero. In that case each output is equal to the
  171056. * DC coefficient (with scale factor as needed).
  171057. * With typical images and quantization tables, half or more of the
  171058. * column DCT calculations can be simplified this way.
  171059. */
  171060. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171061. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  171062. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  171063. inptr[DCTSIZE*7] == 0) {
  171064. /* AC terms all zero */
  171065. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171066. wsptr[DCTSIZE*0] = dcval;
  171067. wsptr[DCTSIZE*1] = dcval;
  171068. wsptr[DCTSIZE*2] = dcval;
  171069. wsptr[DCTSIZE*3] = dcval;
  171070. wsptr[DCTSIZE*4] = dcval;
  171071. wsptr[DCTSIZE*5] = dcval;
  171072. wsptr[DCTSIZE*6] = dcval;
  171073. wsptr[DCTSIZE*7] = dcval;
  171074. inptr++; /* advance pointers to next column */
  171075. quantptr++;
  171076. wsptr++;
  171077. continue;
  171078. }
  171079. /* Even part: reverse the even part of the forward DCT. */
  171080. /* The rotator is sqrt(2)*c(-6). */
  171081. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171082. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171083. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171084. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171085. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171086. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171087. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  171088. tmp0 = (z2 + z3) << CONST_BITS;
  171089. tmp1 = (z2 - z3) << CONST_BITS;
  171090. tmp10 = tmp0 + tmp3;
  171091. tmp13 = tmp0 - tmp3;
  171092. tmp11 = tmp1 + tmp2;
  171093. tmp12 = tmp1 - tmp2;
  171094. /* Odd part per figure 8; the matrix is unitary and hence its
  171095. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171096. */
  171097. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171098. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171099. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171100. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171101. z1 = tmp0 + tmp3;
  171102. z2 = tmp1 + tmp2;
  171103. z3 = tmp0 + tmp2;
  171104. z4 = tmp1 + tmp3;
  171105. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171106. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171107. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171108. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171109. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171110. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171111. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171112. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171113. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171114. z3 += z5;
  171115. z4 += z5;
  171116. tmp0 += z1 + z3;
  171117. tmp1 += z2 + z4;
  171118. tmp2 += z2 + z3;
  171119. tmp3 += z1 + z4;
  171120. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171121. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  171122. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  171123. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  171124. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  171125. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  171126. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  171127. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  171128. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  171129. inptr++; /* advance pointers to next column */
  171130. quantptr++;
  171131. wsptr++;
  171132. }
  171133. /* Pass 2: process rows from work array, store into output array. */
  171134. /* Note that we must descale the results by a factor of 8 == 2**3, */
  171135. /* and also undo the PASS1_BITS scaling. */
  171136. wsptr = workspace;
  171137. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  171138. outptr = output_buf[ctr] + output_col;
  171139. /* Rows of zeroes can be exploited in the same way as we did with columns.
  171140. * However, the column calculation has created many nonzero AC terms, so
  171141. * the simplification applies less often (typically 5% to 10% of the time).
  171142. * On machines with very fast multiplication, it's possible that the
  171143. * test takes more time than it's worth. In that case this section
  171144. * may be commented out.
  171145. */
  171146. #ifndef NO_ZERO_ROW_TEST
  171147. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  171148. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171149. /* AC terms all zero */
  171150. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171151. & RANGE_MASK];
  171152. outptr[0] = dcval;
  171153. outptr[1] = dcval;
  171154. outptr[2] = dcval;
  171155. outptr[3] = dcval;
  171156. outptr[4] = dcval;
  171157. outptr[5] = dcval;
  171158. outptr[6] = dcval;
  171159. outptr[7] = dcval;
  171160. wsptr += DCTSIZE; /* advance pointer to next row */
  171161. continue;
  171162. }
  171163. #endif
  171164. /* Even part: reverse the even part of the forward DCT. */
  171165. /* The rotator is sqrt(2)*c(-6). */
  171166. z2 = (INT32) wsptr[2];
  171167. z3 = (INT32) wsptr[6];
  171168. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  171169. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  171170. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  171171. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  171172. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  171173. tmp10 = tmp0 + tmp3;
  171174. tmp13 = tmp0 - tmp3;
  171175. tmp11 = tmp1 + tmp2;
  171176. tmp12 = tmp1 - tmp2;
  171177. /* Odd part per figure 8; the matrix is unitary and hence its
  171178. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171179. */
  171180. tmp0 = (INT32) wsptr[7];
  171181. tmp1 = (INT32) wsptr[5];
  171182. tmp2 = (INT32) wsptr[3];
  171183. tmp3 = (INT32) wsptr[1];
  171184. z1 = tmp0 + tmp3;
  171185. z2 = tmp1 + tmp2;
  171186. z3 = tmp0 + tmp2;
  171187. z4 = tmp1 + tmp3;
  171188. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171189. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171190. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171191. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171192. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171193. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171194. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171195. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171196. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171197. z3 += z5;
  171198. z4 += z5;
  171199. tmp0 += z1 + z3;
  171200. tmp1 += z2 + z4;
  171201. tmp2 += z2 + z3;
  171202. tmp3 += z1 + z4;
  171203. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171204. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  171205. CONST_BITS+PASS1_BITS+3)
  171206. & RANGE_MASK];
  171207. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  171208. CONST_BITS+PASS1_BITS+3)
  171209. & RANGE_MASK];
  171210. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  171211. CONST_BITS+PASS1_BITS+3)
  171212. & RANGE_MASK];
  171213. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  171214. CONST_BITS+PASS1_BITS+3)
  171215. & RANGE_MASK];
  171216. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  171217. CONST_BITS+PASS1_BITS+3)
  171218. & RANGE_MASK];
  171219. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  171220. CONST_BITS+PASS1_BITS+3)
  171221. & RANGE_MASK];
  171222. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  171223. CONST_BITS+PASS1_BITS+3)
  171224. & RANGE_MASK];
  171225. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  171226. CONST_BITS+PASS1_BITS+3)
  171227. & RANGE_MASK];
  171228. wsptr += DCTSIZE; /* advance pointer to next row */
  171229. }
  171230. }
  171231. #endif /* DCT_ISLOW_SUPPORTED */
  171232. /********* End of inlined file: jidctint.c *********/
  171233. /********* Start of inlined file: jidctred.c *********/
  171234. #define JPEG_INTERNALS
  171235. #ifdef IDCT_SCALING_SUPPORTED
  171236. /*
  171237. * This module is specialized to the case DCTSIZE = 8.
  171238. */
  171239. #if DCTSIZE != 8
  171240. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171241. #endif
  171242. /* Scaling is the same as in jidctint.c. */
  171243. #if BITS_IN_JSAMPLE == 8
  171244. #define CONST_BITS 13
  171245. #define PASS1_BITS 2
  171246. #else
  171247. #define CONST_BITS 13
  171248. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171249. #endif
  171250. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171251. * causing a lot of useless floating-point operations at run time.
  171252. * To get around this we use the following pre-calculated constants.
  171253. * If you change CONST_BITS you may want to add appropriate values.
  171254. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171255. */
  171256. #if CONST_BITS == 13
  171257. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  171258. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  171259. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  171260. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  171261. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171262. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  171263. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171264. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  171265. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  171266. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  171267. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171268. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  171269. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171270. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  171271. #else
  171272. #define FIX_0_211164243 FIX(0.211164243)
  171273. #define FIX_0_509795579 FIX(0.509795579)
  171274. #define FIX_0_601344887 FIX(0.601344887)
  171275. #define FIX_0_720959822 FIX(0.720959822)
  171276. #define FIX_0_765366865 FIX(0.765366865)
  171277. #define FIX_0_850430095 FIX(0.850430095)
  171278. #define FIX_0_899976223 FIX(0.899976223)
  171279. #define FIX_1_061594337 FIX(1.061594337)
  171280. #define FIX_1_272758580 FIX(1.272758580)
  171281. #define FIX_1_451774981 FIX(1.451774981)
  171282. #define FIX_1_847759065 FIX(1.847759065)
  171283. #define FIX_2_172734803 FIX(2.172734803)
  171284. #define FIX_2_562915447 FIX(2.562915447)
  171285. #define FIX_3_624509785 FIX(3.624509785)
  171286. #endif
  171287. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171288. * For 8-bit samples with the recommended scaling, all the variable
  171289. * and constant values involved are no more than 16 bits wide, so a
  171290. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171291. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171292. */
  171293. #if BITS_IN_JSAMPLE == 8
  171294. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171295. #else
  171296. #define MULTIPLY(var,const) ((var) * (const))
  171297. #endif
  171298. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171299. * entry; produce an int result. In this module, both inputs and result
  171300. * are 16 bits or less, so either int or short multiply will work.
  171301. */
  171302. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  171303. /*
  171304. * Perform dequantization and inverse DCT on one block of coefficients,
  171305. * producing a reduced-size 4x4 output block.
  171306. */
  171307. GLOBAL(void)
  171308. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171309. JCOEFPTR coef_block,
  171310. JSAMPARRAY output_buf, JDIMENSION output_col)
  171311. {
  171312. INT32 tmp0, tmp2, tmp10, tmp12;
  171313. INT32 z1, z2, z3, z4;
  171314. JCOEFPTR inptr;
  171315. ISLOW_MULT_TYPE * quantptr;
  171316. int * wsptr;
  171317. JSAMPROW outptr;
  171318. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171319. int ctr;
  171320. int workspace[DCTSIZE*4]; /* buffers data between passes */
  171321. SHIFT_TEMPS
  171322. /* Pass 1: process columns from input, store into work array. */
  171323. inptr = coef_block;
  171324. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171325. wsptr = workspace;
  171326. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171327. /* Don't bother to process column 4, because second pass won't use it */
  171328. if (ctr == DCTSIZE-4)
  171329. continue;
  171330. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171331. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  171332. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  171333. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  171334. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171335. wsptr[DCTSIZE*0] = dcval;
  171336. wsptr[DCTSIZE*1] = dcval;
  171337. wsptr[DCTSIZE*2] = dcval;
  171338. wsptr[DCTSIZE*3] = dcval;
  171339. continue;
  171340. }
  171341. /* Even part */
  171342. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171343. tmp0 <<= (CONST_BITS+1);
  171344. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171345. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171346. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  171347. tmp10 = tmp0 + tmp2;
  171348. tmp12 = tmp0 - tmp2;
  171349. /* Odd part */
  171350. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171351. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171352. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171353. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171354. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171355. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171356. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171357. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171358. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171359. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171360. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171361. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171362. /* Final output stage */
  171363. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  171364. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  171365. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  171366. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  171367. }
  171368. /* Pass 2: process 4 rows from work array, store into output array. */
  171369. wsptr = workspace;
  171370. for (ctr = 0; ctr < 4; ctr++) {
  171371. outptr = output_buf[ctr] + output_col;
  171372. /* It's not clear whether a zero row test is worthwhile here ... */
  171373. #ifndef NO_ZERO_ROW_TEST
  171374. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  171375. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171376. /* AC terms all zero */
  171377. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171378. & RANGE_MASK];
  171379. outptr[0] = dcval;
  171380. outptr[1] = dcval;
  171381. outptr[2] = dcval;
  171382. outptr[3] = dcval;
  171383. wsptr += DCTSIZE; /* advance pointer to next row */
  171384. continue;
  171385. }
  171386. #endif
  171387. /* Even part */
  171388. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  171389. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  171390. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  171391. tmp10 = tmp0 + tmp2;
  171392. tmp12 = tmp0 - tmp2;
  171393. /* Odd part */
  171394. z1 = (INT32) wsptr[7];
  171395. z2 = (INT32) wsptr[5];
  171396. z3 = (INT32) wsptr[3];
  171397. z4 = (INT32) wsptr[1];
  171398. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171399. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171400. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171401. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171402. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171403. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171404. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171405. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171406. /* Final output stage */
  171407. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  171408. CONST_BITS+PASS1_BITS+3+1)
  171409. & RANGE_MASK];
  171410. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  171411. CONST_BITS+PASS1_BITS+3+1)
  171412. & RANGE_MASK];
  171413. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  171414. CONST_BITS+PASS1_BITS+3+1)
  171415. & RANGE_MASK];
  171416. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  171417. CONST_BITS+PASS1_BITS+3+1)
  171418. & RANGE_MASK];
  171419. wsptr += DCTSIZE; /* advance pointer to next row */
  171420. }
  171421. }
  171422. /*
  171423. * Perform dequantization and inverse DCT on one block of coefficients,
  171424. * producing a reduced-size 2x2 output block.
  171425. */
  171426. GLOBAL(void)
  171427. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171428. JCOEFPTR coef_block,
  171429. JSAMPARRAY output_buf, JDIMENSION output_col)
  171430. {
  171431. INT32 tmp0, tmp10, z1;
  171432. JCOEFPTR inptr;
  171433. ISLOW_MULT_TYPE * quantptr;
  171434. int * wsptr;
  171435. JSAMPROW outptr;
  171436. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171437. int ctr;
  171438. int workspace[DCTSIZE*2]; /* buffers data between passes */
  171439. SHIFT_TEMPS
  171440. /* Pass 1: process columns from input, store into work array. */
  171441. inptr = coef_block;
  171442. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171443. wsptr = workspace;
  171444. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171445. /* Don't bother to process columns 2,4,6 */
  171446. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  171447. continue;
  171448. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  171449. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  171450. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  171451. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171452. wsptr[DCTSIZE*0] = dcval;
  171453. wsptr[DCTSIZE*1] = dcval;
  171454. continue;
  171455. }
  171456. /* Even part */
  171457. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171458. tmp10 = z1 << (CONST_BITS+2);
  171459. /* Odd part */
  171460. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171461. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  171462. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171463. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  171464. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171465. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  171466. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171467. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171468. /* Final output stage */
  171469. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  171470. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  171471. }
  171472. /* Pass 2: process 2 rows from work array, store into output array. */
  171473. wsptr = workspace;
  171474. for (ctr = 0; ctr < 2; ctr++) {
  171475. outptr = output_buf[ctr] + output_col;
  171476. /* It's not clear whether a zero row test is worthwhile here ... */
  171477. #ifndef NO_ZERO_ROW_TEST
  171478. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  171479. /* AC terms all zero */
  171480. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171481. & RANGE_MASK];
  171482. outptr[0] = dcval;
  171483. outptr[1] = dcval;
  171484. wsptr += DCTSIZE; /* advance pointer to next row */
  171485. continue;
  171486. }
  171487. #endif
  171488. /* Even part */
  171489. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  171490. /* Odd part */
  171491. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  171492. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  171493. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  171494. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171495. /* Final output stage */
  171496. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  171497. CONST_BITS+PASS1_BITS+3+2)
  171498. & RANGE_MASK];
  171499. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  171500. CONST_BITS+PASS1_BITS+3+2)
  171501. & RANGE_MASK];
  171502. wsptr += DCTSIZE; /* advance pointer to next row */
  171503. }
  171504. }
  171505. /*
  171506. * Perform dequantization and inverse DCT on one block of coefficients,
  171507. * producing a reduced-size 1x1 output block.
  171508. */
  171509. GLOBAL(void)
  171510. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171511. JCOEFPTR coef_block,
  171512. JSAMPARRAY output_buf, JDIMENSION output_col)
  171513. {
  171514. int dcval;
  171515. ISLOW_MULT_TYPE * quantptr;
  171516. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171517. SHIFT_TEMPS
  171518. /* We hardly need an inverse DCT routine for this: just take the
  171519. * average pixel value, which is one-eighth of the DC coefficient.
  171520. */
  171521. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171522. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  171523. dcval = (int) DESCALE((INT32) dcval, 3);
  171524. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  171525. }
  171526. #endif /* IDCT_SCALING_SUPPORTED */
  171527. /********* End of inlined file: jidctred.c *********/
  171528. /********* Start of inlined file: jmemmgr.c *********/
  171529. #define JPEG_INTERNALS
  171530. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  171531. /********* Start of inlined file: jmemsys.h *********/
  171532. #ifndef __jmemsys_h__
  171533. #define __jmemsys_h__
  171534. /* Short forms of external names for systems with brain-damaged linkers. */
  171535. #ifdef NEED_SHORT_EXTERNAL_NAMES
  171536. #define jpeg_get_small jGetSmall
  171537. #define jpeg_free_small jFreeSmall
  171538. #define jpeg_get_large jGetLarge
  171539. #define jpeg_free_large jFreeLarge
  171540. #define jpeg_mem_available jMemAvail
  171541. #define jpeg_open_backing_store jOpenBackStore
  171542. #define jpeg_mem_init jMemInit
  171543. #define jpeg_mem_term jMemTerm
  171544. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  171545. /*
  171546. * These two functions are used to allocate and release small chunks of
  171547. * memory. (Typically the total amount requested through jpeg_get_small is
  171548. * no more than 20K or so; this will be requested in chunks of a few K each.)
  171549. * Behavior should be the same as for the standard library functions malloc
  171550. * and free; in particular, jpeg_get_small must return NULL on failure.
  171551. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  171552. * size of the object being freed, just in case it's needed.
  171553. * On an 80x86 machine using small-data memory model, these manage near heap.
  171554. */
  171555. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  171556. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  171557. size_t sizeofobject));
  171558. /*
  171559. * These two functions are used to allocate and release large chunks of
  171560. * memory (up to the total free space designated by jpeg_mem_available).
  171561. * The interface is the same as above, except that on an 80x86 machine,
  171562. * far pointers are used. On most other machines these are identical to
  171563. * the jpeg_get/free_small routines; but we keep them separate anyway,
  171564. * in case a different allocation strategy is desirable for large chunks.
  171565. */
  171566. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  171567. size_t sizeofobject));
  171568. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  171569. size_t sizeofobject));
  171570. /*
  171571. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  171572. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  171573. * matter, but that case should never come into play). This macro is needed
  171574. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  171575. * On those machines, we expect that jconfig.h will provide a proper value.
  171576. * On machines with 32-bit flat address spaces, any large constant may be used.
  171577. *
  171578. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  171579. * size_t and will be a multiple of sizeof(align_type).
  171580. */
  171581. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  171582. #define MAX_ALLOC_CHUNK 1000000000L
  171583. #endif
  171584. /*
  171585. * This routine computes the total space still available for allocation by
  171586. * jpeg_get_large. If more space than this is needed, backing store will be
  171587. * used. NOTE: any memory already allocated must not be counted.
  171588. *
  171589. * There is a minimum space requirement, corresponding to the minimum
  171590. * feasible buffer sizes; jmemmgr.c will request that much space even if
  171591. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  171592. * all working storage in memory, is also passed in case it is useful.
  171593. * Finally, the total space already allocated is passed. If no better
  171594. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  171595. * is often a suitable calculation.
  171596. *
  171597. * It is OK for jpeg_mem_available to underestimate the space available
  171598. * (that'll just lead to more backing-store access than is really necessary).
  171599. * However, an overestimate will lead to failure. Hence it's wise to subtract
  171600. * a slop factor from the true available space. 5% should be enough.
  171601. *
  171602. * On machines with lots of virtual memory, any large constant may be returned.
  171603. * Conversely, zero may be returned to always use the minimum amount of memory.
  171604. */
  171605. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  171606. long min_bytes_needed,
  171607. long max_bytes_needed,
  171608. long already_allocated));
  171609. /*
  171610. * This structure holds whatever state is needed to access a single
  171611. * backing-store object. The read/write/close method pointers are called
  171612. * by jmemmgr.c to manipulate the backing-store object; all other fields
  171613. * are private to the system-dependent backing store routines.
  171614. */
  171615. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  171616. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  171617. typedef unsigned short XMSH; /* type of extended-memory handles */
  171618. typedef unsigned short EMSH; /* type of expanded-memory handles */
  171619. typedef union {
  171620. short file_handle; /* DOS file handle if it's a temp file */
  171621. XMSH xms_handle; /* handle if it's a chunk of XMS */
  171622. EMSH ems_handle; /* handle if it's a chunk of EMS */
  171623. } handle_union;
  171624. #endif /* USE_MSDOS_MEMMGR */
  171625. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  171626. #include <Files.h>
  171627. #endif /* USE_MAC_MEMMGR */
  171628. //typedef struct backing_store_struct * backing_store_ptr;
  171629. typedef struct backing_store_struct {
  171630. /* Methods for reading/writing/closing this backing-store object */
  171631. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  171632. struct backing_store_struct *info,
  171633. void FAR * buffer_address,
  171634. long file_offset, long byte_count));
  171635. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  171636. struct backing_store_struct *info,
  171637. void FAR * buffer_address,
  171638. long file_offset, long byte_count));
  171639. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  171640. struct backing_store_struct *info));
  171641. /* Private fields for system-dependent backing-store management */
  171642. #ifdef USE_MSDOS_MEMMGR
  171643. /* For the MS-DOS manager (jmemdos.c), we need: */
  171644. handle_union handle; /* reference to backing-store storage object */
  171645. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171646. #else
  171647. #ifdef USE_MAC_MEMMGR
  171648. /* For the Mac manager (jmemmac.c), we need: */
  171649. short temp_file; /* file reference number to temp file */
  171650. FSSpec tempSpec; /* the FSSpec for the temp file */
  171651. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171652. #else
  171653. /* For a typical implementation with temp files, we need: */
  171654. FILE * temp_file; /* stdio reference to temp file */
  171655. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  171656. #endif
  171657. #endif
  171658. } backing_store_info;
  171659. /*
  171660. * Initial opening of a backing-store object. This must fill in the
  171661. * read/write/close pointers in the object. The read/write routines
  171662. * may take an error exit if the specified maximum file size is exceeded.
  171663. * (If jpeg_mem_available always returns a large value, this routine can
  171664. * just take an error exit.)
  171665. */
  171666. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  171667. struct backing_store_struct *info,
  171668. long total_bytes_needed));
  171669. /*
  171670. * These routines take care of any system-dependent initialization and
  171671. * cleanup required. jpeg_mem_init will be called before anything is
  171672. * allocated (and, therefore, nothing in cinfo is of use except the error
  171673. * manager pointer). It should return a suitable default value for
  171674. * max_memory_to_use; this may subsequently be overridden by the surrounding
  171675. * application. (Note that max_memory_to_use is only important if
  171676. * jpeg_mem_available chooses to consult it ... no one else will.)
  171677. * jpeg_mem_term may assume that all requested memory has been freed and that
  171678. * all opened backing-store objects have been closed.
  171679. */
  171680. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  171681. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  171682. #endif
  171683. /********* End of inlined file: jmemsys.h *********/
  171684. /* import the system-dependent declarations */
  171685. #ifndef NO_GETENV
  171686. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  171687. extern char * getenv JPP((const char * name));
  171688. #endif
  171689. #endif
  171690. /*
  171691. * Some important notes:
  171692. * The allocation routines provided here must never return NULL.
  171693. * They should exit to error_exit if unsuccessful.
  171694. *
  171695. * It's not a good idea to try to merge the sarray and barray routines,
  171696. * even though they are textually almost the same, because samples are
  171697. * usually stored as bytes while coefficients are shorts or ints. Thus,
  171698. * in machines where byte pointers have a different representation from
  171699. * word pointers, the resulting machine code could not be the same.
  171700. */
  171701. /*
  171702. * Many machines require storage alignment: longs must start on 4-byte
  171703. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  171704. * always returns pointers that are multiples of the worst-case alignment
  171705. * requirement, and we had better do so too.
  171706. * There isn't any really portable way to determine the worst-case alignment
  171707. * requirement. This module assumes that the alignment requirement is
  171708. * multiples of sizeof(ALIGN_TYPE).
  171709. * By default, we define ALIGN_TYPE as double. This is necessary on some
  171710. * workstations (where doubles really do need 8-byte alignment) and will work
  171711. * fine on nearly everything. If your machine has lesser alignment needs,
  171712. * you can save a few bytes by making ALIGN_TYPE smaller.
  171713. * The only place I know of where this will NOT work is certain Macintosh
  171714. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  171715. * Doing 10-byte alignment is counterproductive because longwords won't be
  171716. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  171717. * such a compiler.
  171718. */
  171719. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  171720. #define ALIGN_TYPE double
  171721. #endif
  171722. /*
  171723. * We allocate objects from "pools", where each pool is gotten with a single
  171724. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  171725. * overhead within a pool, except for alignment padding. Each pool has a
  171726. * header with a link to the next pool of the same class.
  171727. * Small and large pool headers are identical except that the latter's
  171728. * link pointer must be FAR on 80x86 machines.
  171729. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  171730. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  171731. * of the alignment requirement of ALIGN_TYPE.
  171732. */
  171733. typedef union small_pool_struct * small_pool_ptr;
  171734. typedef union small_pool_struct {
  171735. struct {
  171736. small_pool_ptr next; /* next in list of pools */
  171737. size_t bytes_used; /* how many bytes already used within pool */
  171738. size_t bytes_left; /* bytes still available in this pool */
  171739. } hdr;
  171740. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171741. } small_pool_hdr;
  171742. typedef union large_pool_struct FAR * large_pool_ptr;
  171743. typedef union large_pool_struct {
  171744. struct {
  171745. large_pool_ptr next; /* next in list of pools */
  171746. size_t bytes_used; /* how many bytes already used within pool */
  171747. size_t bytes_left; /* bytes still available in this pool */
  171748. } hdr;
  171749. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171750. } large_pool_hdr;
  171751. /*
  171752. * Here is the full definition of a memory manager object.
  171753. */
  171754. typedef struct {
  171755. struct jpeg_memory_mgr pub; /* public fields */
  171756. /* Each pool identifier (lifetime class) names a linked list of pools. */
  171757. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  171758. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  171759. /* Since we only have one lifetime class of virtual arrays, only one
  171760. * linked list is necessary (for each datatype). Note that the virtual
  171761. * array control blocks being linked together are actually stored somewhere
  171762. * in the small-pool list.
  171763. */
  171764. jvirt_sarray_ptr virt_sarray_list;
  171765. jvirt_barray_ptr virt_barray_list;
  171766. /* This counts total space obtained from jpeg_get_small/large */
  171767. long total_space_allocated;
  171768. /* alloc_sarray and alloc_barray set this value for use by virtual
  171769. * array routines.
  171770. */
  171771. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  171772. } my_memory_mgr;
  171773. typedef my_memory_mgr * my_mem_ptr;
  171774. /*
  171775. * The control blocks for virtual arrays.
  171776. * Note that these blocks are allocated in the "small" pool area.
  171777. * System-dependent info for the associated backing store (if any) is hidden
  171778. * inside the backing_store_info struct.
  171779. */
  171780. struct jvirt_sarray_control {
  171781. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  171782. JDIMENSION rows_in_array; /* total virtual array height */
  171783. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  171784. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  171785. JDIMENSION rows_in_mem; /* height of memory buffer */
  171786. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171787. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171788. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171789. boolean pre_zero; /* pre-zero mode requested? */
  171790. boolean dirty; /* do current buffer contents need written? */
  171791. boolean b_s_open; /* is backing-store data valid? */
  171792. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  171793. backing_store_info b_s_info; /* System-dependent control info */
  171794. };
  171795. struct jvirt_barray_control {
  171796. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  171797. JDIMENSION rows_in_array; /* total virtual array height */
  171798. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  171799. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  171800. JDIMENSION rows_in_mem; /* height of memory buffer */
  171801. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171802. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171803. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171804. boolean pre_zero; /* pre-zero mode requested? */
  171805. boolean dirty; /* do current buffer contents need written? */
  171806. boolean b_s_open; /* is backing-store data valid? */
  171807. jvirt_barray_ptr next; /* link to next virtual barray control block */
  171808. backing_store_info b_s_info; /* System-dependent control info */
  171809. };
  171810. #ifdef MEM_STATS /* optional extra stuff for statistics */
  171811. LOCAL(void)
  171812. print_mem_stats (j_common_ptr cinfo, int pool_id)
  171813. {
  171814. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171815. small_pool_ptr shdr_ptr;
  171816. large_pool_ptr lhdr_ptr;
  171817. /* Since this is only a debugging stub, we can cheat a little by using
  171818. * fprintf directly rather than going through the trace message code.
  171819. * This is helpful because message parm array can't handle longs.
  171820. */
  171821. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  171822. pool_id, mem->total_space_allocated);
  171823. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  171824. lhdr_ptr = lhdr_ptr->hdr.next) {
  171825. fprintf(stderr, " Large chunk used %ld\n",
  171826. (long) lhdr_ptr->hdr.bytes_used);
  171827. }
  171828. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  171829. shdr_ptr = shdr_ptr->hdr.next) {
  171830. fprintf(stderr, " Small chunk used %ld free %ld\n",
  171831. (long) shdr_ptr->hdr.bytes_used,
  171832. (long) shdr_ptr->hdr.bytes_left);
  171833. }
  171834. }
  171835. #endif /* MEM_STATS */
  171836. LOCAL(void)
  171837. out_of_memory (j_common_ptr cinfo, int which)
  171838. /* Report an out-of-memory error and stop execution */
  171839. /* If we compiled MEM_STATS support, report alloc requests before dying */
  171840. {
  171841. #ifdef MEM_STATS
  171842. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  171843. #endif
  171844. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  171845. }
  171846. /*
  171847. * Allocation of "small" objects.
  171848. *
  171849. * For these, we use pooled storage. When a new pool must be created,
  171850. * we try to get enough space for the current request plus a "slop" factor,
  171851. * where the slop will be the amount of leftover space in the new pool.
  171852. * The speed vs. space tradeoff is largely determined by the slop values.
  171853. * A different slop value is provided for each pool class (lifetime),
  171854. * and we also distinguish the first pool of a class from later ones.
  171855. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  171856. * machines, but may be too small if longs are 64 bits or more.
  171857. */
  171858. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  171859. {
  171860. 1600, /* first PERMANENT pool */
  171861. 16000 /* first IMAGE pool */
  171862. };
  171863. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  171864. {
  171865. 0, /* additional PERMANENT pools */
  171866. 5000 /* additional IMAGE pools */
  171867. };
  171868. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  171869. METHODDEF(void *)
  171870. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171871. /* Allocate a "small" object */
  171872. {
  171873. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171874. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  171875. char * data_ptr;
  171876. size_t odd_bytes, min_request, slop;
  171877. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171878. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  171879. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  171880. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171881. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171882. if (odd_bytes > 0)
  171883. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171884. /* See if space is available in any existing pool */
  171885. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171886. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171887. prev_hdr_ptr = NULL;
  171888. hdr_ptr = mem->small_list[pool_id];
  171889. while (hdr_ptr != NULL) {
  171890. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  171891. break; /* found pool with enough space */
  171892. prev_hdr_ptr = hdr_ptr;
  171893. hdr_ptr = hdr_ptr->hdr.next;
  171894. }
  171895. /* Time to make a new pool? */
  171896. if (hdr_ptr == NULL) {
  171897. /* min_request is what we need now, slop is what will be leftover */
  171898. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  171899. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171900. slop = first_pool_slop[pool_id];
  171901. else
  171902. slop = extra_pool_slop[pool_id];
  171903. /* Don't ask for more than MAX_ALLOC_CHUNK */
  171904. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  171905. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  171906. /* Try to get space, if fail reduce slop and try again */
  171907. for (;;) {
  171908. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  171909. if (hdr_ptr != NULL)
  171910. break;
  171911. slop /= 2;
  171912. if (slop < MIN_SLOP) /* give up when it gets real small */
  171913. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  171914. }
  171915. mem->total_space_allocated += min_request + slop;
  171916. /* Success, initialize the new pool header and add to end of list */
  171917. hdr_ptr->hdr.next = NULL;
  171918. hdr_ptr->hdr.bytes_used = 0;
  171919. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  171920. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171921. mem->small_list[pool_id] = hdr_ptr;
  171922. else
  171923. prev_hdr_ptr->hdr.next = hdr_ptr;
  171924. }
  171925. /* OK, allocate the object from the current pool */
  171926. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  171927. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  171928. hdr_ptr->hdr.bytes_used += sizeofobject;
  171929. hdr_ptr->hdr.bytes_left -= sizeofobject;
  171930. return (void *) data_ptr;
  171931. }
  171932. /*
  171933. * Allocation of "large" objects.
  171934. *
  171935. * The external semantics of these are the same as "small" objects,
  171936. * except that FAR pointers are used on 80x86. However the pool
  171937. * management heuristics are quite different. We assume that each
  171938. * request is large enough that it may as well be passed directly to
  171939. * jpeg_get_large; the pool management just links everything together
  171940. * so that we can free it all on demand.
  171941. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  171942. * structures. The routines that create these structures (see below)
  171943. * deliberately bunch rows together to ensure a large request size.
  171944. */
  171945. METHODDEF(void FAR *)
  171946. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171947. /* Allocate a "large" object */
  171948. {
  171949. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171950. large_pool_ptr hdr_ptr;
  171951. size_t odd_bytes;
  171952. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171953. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  171954. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  171955. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171956. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171957. if (odd_bytes > 0)
  171958. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171959. /* Always make a new pool */
  171960. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171961. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171962. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  171963. SIZEOF(large_pool_hdr));
  171964. if (hdr_ptr == NULL)
  171965. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  171966. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  171967. /* Success, initialize the new pool header and add to list */
  171968. hdr_ptr->hdr.next = mem->large_list[pool_id];
  171969. /* We maintain space counts in each pool header for statistical purposes,
  171970. * even though they are not needed for allocation.
  171971. */
  171972. hdr_ptr->hdr.bytes_used = sizeofobject;
  171973. hdr_ptr->hdr.bytes_left = 0;
  171974. mem->large_list[pool_id] = hdr_ptr;
  171975. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  171976. }
  171977. /*
  171978. * Creation of 2-D sample arrays.
  171979. * The pointers are in near heap, the samples themselves in FAR heap.
  171980. *
  171981. * To minimize allocation overhead and to allow I/O of large contiguous
  171982. * blocks, we allocate the sample rows in groups of as many rows as possible
  171983. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  171984. * NB: the virtual array control routines, later in this file, know about
  171985. * this chunking of rows. The rowsperchunk value is left in the mem manager
  171986. * object so that it can be saved away if this sarray is the workspace for
  171987. * a virtual array.
  171988. */
  171989. METHODDEF(JSAMPARRAY)
  171990. alloc_sarray (j_common_ptr cinfo, int pool_id,
  171991. JDIMENSION samplesperrow, JDIMENSION numrows)
  171992. /* Allocate a 2-D sample array */
  171993. {
  171994. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171995. JSAMPARRAY result;
  171996. JSAMPROW workspace;
  171997. JDIMENSION rowsperchunk, currow, i;
  171998. long ltemp;
  171999. /* Calculate max # of rows allowed in one allocation chunk */
  172000. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  172001. ((long) samplesperrow * SIZEOF(JSAMPLE));
  172002. if (ltemp <= 0)
  172003. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172004. if (ltemp < (long) numrows)
  172005. rowsperchunk = (JDIMENSION) ltemp;
  172006. else
  172007. rowsperchunk = numrows;
  172008. mem->last_rowsperchunk = rowsperchunk;
  172009. /* Get space for row pointers (small object) */
  172010. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  172011. (size_t) (numrows * SIZEOF(JSAMPROW)));
  172012. /* Get the rows themselves (large objects) */
  172013. currow = 0;
  172014. while (currow < numrows) {
  172015. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  172016. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  172017. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  172018. * SIZEOF(JSAMPLE)));
  172019. for (i = rowsperchunk; i > 0; i--) {
  172020. result[currow++] = workspace;
  172021. workspace += samplesperrow;
  172022. }
  172023. }
  172024. return result;
  172025. }
  172026. /*
  172027. * Creation of 2-D coefficient-block arrays.
  172028. * This is essentially the same as the code for sample arrays, above.
  172029. */
  172030. METHODDEF(JBLOCKARRAY)
  172031. alloc_barray (j_common_ptr cinfo, int pool_id,
  172032. JDIMENSION blocksperrow, JDIMENSION numrows)
  172033. /* Allocate a 2-D coefficient-block array */
  172034. {
  172035. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172036. JBLOCKARRAY result;
  172037. JBLOCKROW workspace;
  172038. JDIMENSION rowsperchunk, currow, i;
  172039. long ltemp;
  172040. /* Calculate max # of rows allowed in one allocation chunk */
  172041. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  172042. ((long) blocksperrow * SIZEOF(JBLOCK));
  172043. if (ltemp <= 0)
  172044. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172045. if (ltemp < (long) numrows)
  172046. rowsperchunk = (JDIMENSION) ltemp;
  172047. else
  172048. rowsperchunk = numrows;
  172049. mem->last_rowsperchunk = rowsperchunk;
  172050. /* Get space for row pointers (small object) */
  172051. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  172052. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  172053. /* Get the rows themselves (large objects) */
  172054. currow = 0;
  172055. while (currow < numrows) {
  172056. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  172057. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  172058. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  172059. * SIZEOF(JBLOCK)));
  172060. for (i = rowsperchunk; i > 0; i--) {
  172061. result[currow++] = workspace;
  172062. workspace += blocksperrow;
  172063. }
  172064. }
  172065. return result;
  172066. }
  172067. /*
  172068. * About virtual array management:
  172069. *
  172070. * The above "normal" array routines are only used to allocate strip buffers
  172071. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  172072. * are handled as "virtual" arrays. The array is still accessed a strip at a
  172073. * time, but the memory manager must save the whole array for repeated
  172074. * accesses. The intended implementation is that there is a strip buffer in
  172075. * memory (as high as is possible given the desired memory limit), plus a
  172076. * backing file that holds the rest of the array.
  172077. *
  172078. * The request_virt_array routines are told the total size of the image and
  172079. * the maximum number of rows that will be accessed at once. The in-memory
  172080. * buffer must be at least as large as the maxaccess value.
  172081. *
  172082. * The request routines create control blocks but not the in-memory buffers.
  172083. * That is postponed until realize_virt_arrays is called. At that time the
  172084. * total amount of space needed is known (approximately, anyway), so free
  172085. * memory can be divided up fairly.
  172086. *
  172087. * The access_virt_array routines are responsible for making a specific strip
  172088. * area accessible (after reading or writing the backing file, if necessary).
  172089. * Note that the access routines are told whether the caller intends to modify
  172090. * the accessed strip; during a read-only pass this saves having to rewrite
  172091. * data to disk. The access routines are also responsible for pre-zeroing
  172092. * any newly accessed rows, if pre-zeroing was requested.
  172093. *
  172094. * In current usage, the access requests are usually for nonoverlapping
  172095. * strips; that is, successive access start_row numbers differ by exactly
  172096. * num_rows = maxaccess. This means we can get good performance with simple
  172097. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  172098. * of the access height; then there will never be accesses across bufferload
  172099. * boundaries. The code will still work with overlapping access requests,
  172100. * but it doesn't handle bufferload overlaps very efficiently.
  172101. */
  172102. METHODDEF(jvirt_sarray_ptr)
  172103. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172104. JDIMENSION samplesperrow, JDIMENSION numrows,
  172105. JDIMENSION maxaccess)
  172106. /* Request a virtual 2-D sample array */
  172107. {
  172108. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172109. jvirt_sarray_ptr result;
  172110. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172111. if (pool_id != JPOOL_IMAGE)
  172112. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172113. /* get control block */
  172114. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  172115. SIZEOF(struct jvirt_sarray_control));
  172116. result->mem_buffer = NULL; /* marks array not yet realized */
  172117. result->rows_in_array = numrows;
  172118. result->samplesperrow = samplesperrow;
  172119. result->maxaccess = maxaccess;
  172120. result->pre_zero = pre_zero;
  172121. result->b_s_open = FALSE; /* no associated backing-store object */
  172122. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  172123. mem->virt_sarray_list = result;
  172124. return result;
  172125. }
  172126. METHODDEF(jvirt_barray_ptr)
  172127. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  172128. JDIMENSION blocksperrow, JDIMENSION numrows,
  172129. JDIMENSION maxaccess)
  172130. /* Request a virtual 2-D coefficient-block array */
  172131. {
  172132. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172133. jvirt_barray_ptr result;
  172134. /* Only IMAGE-lifetime virtual arrays are currently supported */
  172135. if (pool_id != JPOOL_IMAGE)
  172136. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172137. /* get control block */
  172138. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  172139. SIZEOF(struct jvirt_barray_control));
  172140. result->mem_buffer = NULL; /* marks array not yet realized */
  172141. result->rows_in_array = numrows;
  172142. result->blocksperrow = blocksperrow;
  172143. result->maxaccess = maxaccess;
  172144. result->pre_zero = pre_zero;
  172145. result->b_s_open = FALSE; /* no associated backing-store object */
  172146. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  172147. mem->virt_barray_list = result;
  172148. return result;
  172149. }
  172150. METHODDEF(void)
  172151. realize_virt_arrays (j_common_ptr cinfo)
  172152. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  172153. {
  172154. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172155. long space_per_minheight, maximum_space, avail_mem;
  172156. long minheights, max_minheights;
  172157. jvirt_sarray_ptr sptr;
  172158. jvirt_barray_ptr bptr;
  172159. /* Compute the minimum space needed (maxaccess rows in each buffer)
  172160. * and the maximum space needed (full image height in each buffer).
  172161. * These may be of use to the system-dependent jpeg_mem_available routine.
  172162. */
  172163. space_per_minheight = 0;
  172164. maximum_space = 0;
  172165. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172166. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172167. space_per_minheight += (long) sptr->maxaccess *
  172168. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172169. maximum_space += (long) sptr->rows_in_array *
  172170. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  172171. }
  172172. }
  172173. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172174. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172175. space_per_minheight += (long) bptr->maxaccess *
  172176. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172177. maximum_space += (long) bptr->rows_in_array *
  172178. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172179. }
  172180. }
  172181. if (space_per_minheight <= 0)
  172182. return; /* no unrealized arrays, no work */
  172183. /* Determine amount of memory to actually use; this is system-dependent. */
  172184. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  172185. mem->total_space_allocated);
  172186. /* If the maximum space needed is available, make all the buffers full
  172187. * height; otherwise parcel it out with the same number of minheights
  172188. * in each buffer.
  172189. */
  172190. if (avail_mem >= maximum_space)
  172191. max_minheights = 1000000000L;
  172192. else {
  172193. max_minheights = avail_mem / space_per_minheight;
  172194. /* If there doesn't seem to be enough space, try to get the minimum
  172195. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  172196. */
  172197. if (max_minheights <= 0)
  172198. max_minheights = 1;
  172199. }
  172200. /* Allocate the in-memory buffers and initialize backing store as needed. */
  172201. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172202. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172203. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  172204. if (minheights <= max_minheights) {
  172205. /* This buffer fits in memory */
  172206. sptr->rows_in_mem = sptr->rows_in_array;
  172207. } else {
  172208. /* It doesn't fit in memory, create backing store. */
  172209. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  172210. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  172211. (long) sptr->rows_in_array *
  172212. (long) sptr->samplesperrow *
  172213. (long) SIZEOF(JSAMPLE));
  172214. sptr->b_s_open = TRUE;
  172215. }
  172216. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  172217. sptr->samplesperrow, sptr->rows_in_mem);
  172218. sptr->rowsperchunk = mem->last_rowsperchunk;
  172219. sptr->cur_start_row = 0;
  172220. sptr->first_undef_row = 0;
  172221. sptr->dirty = FALSE;
  172222. }
  172223. }
  172224. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172225. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172226. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  172227. if (minheights <= max_minheights) {
  172228. /* This buffer fits in memory */
  172229. bptr->rows_in_mem = bptr->rows_in_array;
  172230. } else {
  172231. /* It doesn't fit in memory, create backing store. */
  172232. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  172233. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  172234. (long) bptr->rows_in_array *
  172235. (long) bptr->blocksperrow *
  172236. (long) SIZEOF(JBLOCK));
  172237. bptr->b_s_open = TRUE;
  172238. }
  172239. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  172240. bptr->blocksperrow, bptr->rows_in_mem);
  172241. bptr->rowsperchunk = mem->last_rowsperchunk;
  172242. bptr->cur_start_row = 0;
  172243. bptr->first_undef_row = 0;
  172244. bptr->dirty = FALSE;
  172245. }
  172246. }
  172247. }
  172248. LOCAL(void)
  172249. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  172250. /* Do backing store read or write of a virtual sample array */
  172251. {
  172252. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172253. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172254. file_offset = ptr->cur_start_row * bytesperrow;
  172255. /* Loop to read or write each allocation chunk in mem_buffer */
  172256. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172257. /* One chunk, but check for short chunk at end of buffer */
  172258. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172259. /* Transfer no more than is currently defined */
  172260. thisrow = (long) ptr->cur_start_row + i;
  172261. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172262. /* Transfer no more than fits in file */
  172263. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172264. if (rows <= 0) /* this chunk might be past end of file! */
  172265. break;
  172266. byte_count = rows * bytesperrow;
  172267. if (writing)
  172268. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172269. (void FAR *) ptr->mem_buffer[i],
  172270. file_offset, byte_count);
  172271. else
  172272. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172273. (void FAR *) ptr->mem_buffer[i],
  172274. file_offset, byte_count);
  172275. file_offset += byte_count;
  172276. }
  172277. }
  172278. LOCAL(void)
  172279. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  172280. /* Do backing store read or write of a virtual coefficient-block array */
  172281. {
  172282. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172283. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  172284. file_offset = ptr->cur_start_row * bytesperrow;
  172285. /* Loop to read or write each allocation chunk in mem_buffer */
  172286. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172287. /* One chunk, but check for short chunk at end of buffer */
  172288. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172289. /* Transfer no more than is currently defined */
  172290. thisrow = (long) ptr->cur_start_row + i;
  172291. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172292. /* Transfer no more than fits in file */
  172293. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172294. if (rows <= 0) /* this chunk might be past end of file! */
  172295. break;
  172296. byte_count = rows * bytesperrow;
  172297. if (writing)
  172298. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172299. (void FAR *) ptr->mem_buffer[i],
  172300. file_offset, byte_count);
  172301. else
  172302. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172303. (void FAR *) ptr->mem_buffer[i],
  172304. file_offset, byte_count);
  172305. file_offset += byte_count;
  172306. }
  172307. }
  172308. METHODDEF(JSAMPARRAY)
  172309. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  172310. JDIMENSION start_row, JDIMENSION num_rows,
  172311. boolean writable)
  172312. /* Access the part of a virtual sample array starting at start_row */
  172313. /* and extending for num_rows rows. writable is true if */
  172314. /* caller intends to modify the accessed area. */
  172315. {
  172316. JDIMENSION end_row = start_row + num_rows;
  172317. JDIMENSION undef_row;
  172318. /* debugging check */
  172319. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172320. ptr->mem_buffer == NULL)
  172321. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172322. /* Make the desired part of the virtual array accessible */
  172323. if (start_row < ptr->cur_start_row ||
  172324. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172325. if (! ptr->b_s_open)
  172326. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172327. /* Flush old buffer contents if necessary */
  172328. if (ptr->dirty) {
  172329. do_sarray_io(cinfo, ptr, TRUE);
  172330. ptr->dirty = FALSE;
  172331. }
  172332. /* Decide what part of virtual array to access.
  172333. * Algorithm: if target address > current window, assume forward scan,
  172334. * load starting at target address. If target address < current window,
  172335. * assume backward scan, load so that target area is top of window.
  172336. * Note that when switching from forward write to forward read, will have
  172337. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172338. */
  172339. if (start_row > ptr->cur_start_row) {
  172340. ptr->cur_start_row = start_row;
  172341. } else {
  172342. /* use long arithmetic here to avoid overflow & unsigned problems */
  172343. long ltemp;
  172344. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172345. if (ltemp < 0)
  172346. ltemp = 0; /* don't fall off front end of file */
  172347. ptr->cur_start_row = (JDIMENSION) ltemp;
  172348. }
  172349. /* Read in the selected part of the array.
  172350. * During the initial write pass, we will do no actual read
  172351. * because the selected part is all undefined.
  172352. */
  172353. do_sarray_io(cinfo, ptr, FALSE);
  172354. }
  172355. /* Ensure the accessed part of the array is defined; prezero if needed.
  172356. * To improve locality of access, we only prezero the part of the array
  172357. * that the caller is about to access, not the entire in-memory array.
  172358. */
  172359. if (ptr->first_undef_row < end_row) {
  172360. if (ptr->first_undef_row < start_row) {
  172361. if (writable) /* writer skipped over a section of array */
  172362. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172363. undef_row = start_row; /* but reader is allowed to read ahead */
  172364. } else {
  172365. undef_row = ptr->first_undef_row;
  172366. }
  172367. if (writable)
  172368. ptr->first_undef_row = end_row;
  172369. if (ptr->pre_zero) {
  172370. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172371. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172372. end_row -= ptr->cur_start_row;
  172373. while (undef_row < end_row) {
  172374. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172375. undef_row++;
  172376. }
  172377. } else {
  172378. if (! writable) /* reader looking at undefined data */
  172379. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172380. }
  172381. }
  172382. /* Flag the buffer dirty if caller will write in it */
  172383. if (writable)
  172384. ptr->dirty = TRUE;
  172385. /* Return address of proper part of the buffer */
  172386. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172387. }
  172388. METHODDEF(JBLOCKARRAY)
  172389. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  172390. JDIMENSION start_row, JDIMENSION num_rows,
  172391. boolean writable)
  172392. /* Access the part of a virtual block array starting at start_row */
  172393. /* and extending for num_rows rows. writable is true if */
  172394. /* caller intends to modify the accessed area. */
  172395. {
  172396. JDIMENSION end_row = start_row + num_rows;
  172397. JDIMENSION undef_row;
  172398. /* debugging check */
  172399. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172400. ptr->mem_buffer == NULL)
  172401. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172402. /* Make the desired part of the virtual array accessible */
  172403. if (start_row < ptr->cur_start_row ||
  172404. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172405. if (! ptr->b_s_open)
  172406. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172407. /* Flush old buffer contents if necessary */
  172408. if (ptr->dirty) {
  172409. do_barray_io(cinfo, ptr, TRUE);
  172410. ptr->dirty = FALSE;
  172411. }
  172412. /* Decide what part of virtual array to access.
  172413. * Algorithm: if target address > current window, assume forward scan,
  172414. * load starting at target address. If target address < current window,
  172415. * assume backward scan, load so that target area is top of window.
  172416. * Note that when switching from forward write to forward read, will have
  172417. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172418. */
  172419. if (start_row > ptr->cur_start_row) {
  172420. ptr->cur_start_row = start_row;
  172421. } else {
  172422. /* use long arithmetic here to avoid overflow & unsigned problems */
  172423. long ltemp;
  172424. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172425. if (ltemp < 0)
  172426. ltemp = 0; /* don't fall off front end of file */
  172427. ptr->cur_start_row = (JDIMENSION) ltemp;
  172428. }
  172429. /* Read in the selected part of the array.
  172430. * During the initial write pass, we will do no actual read
  172431. * because the selected part is all undefined.
  172432. */
  172433. do_barray_io(cinfo, ptr, FALSE);
  172434. }
  172435. /* Ensure the accessed part of the array is defined; prezero if needed.
  172436. * To improve locality of access, we only prezero the part of the array
  172437. * that the caller is about to access, not the entire in-memory array.
  172438. */
  172439. if (ptr->first_undef_row < end_row) {
  172440. if (ptr->first_undef_row < start_row) {
  172441. if (writable) /* writer skipped over a section of array */
  172442. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172443. undef_row = start_row; /* but reader is allowed to read ahead */
  172444. } else {
  172445. undef_row = ptr->first_undef_row;
  172446. }
  172447. if (writable)
  172448. ptr->first_undef_row = end_row;
  172449. if (ptr->pre_zero) {
  172450. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  172451. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172452. end_row -= ptr->cur_start_row;
  172453. while (undef_row < end_row) {
  172454. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172455. undef_row++;
  172456. }
  172457. } else {
  172458. if (! writable) /* reader looking at undefined data */
  172459. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172460. }
  172461. }
  172462. /* Flag the buffer dirty if caller will write in it */
  172463. if (writable)
  172464. ptr->dirty = TRUE;
  172465. /* Return address of proper part of the buffer */
  172466. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172467. }
  172468. /*
  172469. * Release all objects belonging to a specified pool.
  172470. */
  172471. METHODDEF(void)
  172472. free_pool (j_common_ptr cinfo, int pool_id)
  172473. {
  172474. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172475. small_pool_ptr shdr_ptr;
  172476. large_pool_ptr lhdr_ptr;
  172477. size_t space_freed;
  172478. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172479. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172480. #ifdef MEM_STATS
  172481. if (cinfo->err->trace_level > 1)
  172482. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  172483. #endif
  172484. /* If freeing IMAGE pool, close any virtual arrays first */
  172485. if (pool_id == JPOOL_IMAGE) {
  172486. jvirt_sarray_ptr sptr;
  172487. jvirt_barray_ptr bptr;
  172488. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172489. if (sptr->b_s_open) { /* there may be no backing store */
  172490. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  172491. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  172492. }
  172493. }
  172494. mem->virt_sarray_list = NULL;
  172495. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172496. if (bptr->b_s_open) { /* there may be no backing store */
  172497. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  172498. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  172499. }
  172500. }
  172501. mem->virt_barray_list = NULL;
  172502. }
  172503. /* Release large objects */
  172504. lhdr_ptr = mem->large_list[pool_id];
  172505. mem->large_list[pool_id] = NULL;
  172506. while (lhdr_ptr != NULL) {
  172507. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  172508. space_freed = lhdr_ptr->hdr.bytes_used +
  172509. lhdr_ptr->hdr.bytes_left +
  172510. SIZEOF(large_pool_hdr);
  172511. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  172512. mem->total_space_allocated -= space_freed;
  172513. lhdr_ptr = next_lhdr_ptr;
  172514. }
  172515. /* Release small objects */
  172516. shdr_ptr = mem->small_list[pool_id];
  172517. mem->small_list[pool_id] = NULL;
  172518. while (shdr_ptr != NULL) {
  172519. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  172520. space_freed = shdr_ptr->hdr.bytes_used +
  172521. shdr_ptr->hdr.bytes_left +
  172522. SIZEOF(small_pool_hdr);
  172523. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  172524. mem->total_space_allocated -= space_freed;
  172525. shdr_ptr = next_shdr_ptr;
  172526. }
  172527. }
  172528. /*
  172529. * Close up shop entirely.
  172530. * Note that this cannot be called unless cinfo->mem is non-NULL.
  172531. */
  172532. METHODDEF(void)
  172533. self_destruct (j_common_ptr cinfo)
  172534. {
  172535. int pool;
  172536. /* Close all backing store, release all memory.
  172537. * Releasing pools in reverse order might help avoid fragmentation
  172538. * with some (brain-damaged) malloc libraries.
  172539. */
  172540. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172541. free_pool(cinfo, pool);
  172542. }
  172543. /* Release the memory manager control block too. */
  172544. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  172545. cinfo->mem = NULL; /* ensures I will be called only once */
  172546. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172547. }
  172548. /*
  172549. * Memory manager initialization.
  172550. * When this is called, only the error manager pointer is valid in cinfo!
  172551. */
  172552. GLOBAL(void)
  172553. jinit_memory_mgr (j_common_ptr cinfo)
  172554. {
  172555. my_mem_ptr mem;
  172556. long max_to_use;
  172557. int pool;
  172558. size_t test_mac;
  172559. cinfo->mem = NULL; /* for safety if init fails */
  172560. /* Check for configuration errors.
  172561. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  172562. * doesn't reflect any real hardware alignment requirement.
  172563. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  172564. * in common if and only if X is a power of 2, ie has only one one-bit.
  172565. * Some compilers may give an "unreachable code" warning here; ignore it.
  172566. */
  172567. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  172568. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  172569. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  172570. * a multiple of SIZEOF(ALIGN_TYPE).
  172571. * Again, an "unreachable code" warning may be ignored here.
  172572. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  172573. */
  172574. test_mac = (size_t) MAX_ALLOC_CHUNK;
  172575. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  172576. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  172577. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  172578. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  172579. /* Attempt to allocate memory manager's control block */
  172580. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  172581. if (mem == NULL) {
  172582. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172583. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  172584. }
  172585. /* OK, fill in the method pointers */
  172586. mem->pub.alloc_small = alloc_small;
  172587. mem->pub.alloc_large = alloc_large;
  172588. mem->pub.alloc_sarray = alloc_sarray;
  172589. mem->pub.alloc_barray = alloc_barray;
  172590. mem->pub.request_virt_sarray = request_virt_sarray;
  172591. mem->pub.request_virt_barray = request_virt_barray;
  172592. mem->pub.realize_virt_arrays = realize_virt_arrays;
  172593. mem->pub.access_virt_sarray = access_virt_sarray;
  172594. mem->pub.access_virt_barray = access_virt_barray;
  172595. mem->pub.free_pool = free_pool;
  172596. mem->pub.self_destruct = self_destruct;
  172597. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  172598. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  172599. /* Initialize working state */
  172600. mem->pub.max_memory_to_use = max_to_use;
  172601. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172602. mem->small_list[pool] = NULL;
  172603. mem->large_list[pool] = NULL;
  172604. }
  172605. mem->virt_sarray_list = NULL;
  172606. mem->virt_barray_list = NULL;
  172607. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  172608. /* Declare ourselves open for business */
  172609. cinfo->mem = & mem->pub;
  172610. /* Check for an environment variable JPEGMEM; if found, override the
  172611. * default max_memory setting from jpeg_mem_init. Note that the
  172612. * surrounding application may again override this value.
  172613. * If your system doesn't support getenv(), define NO_GETENV to disable
  172614. * this feature.
  172615. */
  172616. #ifndef NO_GETENV
  172617. { char * memenv;
  172618. if ((memenv = getenv("JPEGMEM")) != NULL) {
  172619. char ch = 'x';
  172620. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  172621. if (ch == 'm' || ch == 'M')
  172622. max_to_use *= 1000L;
  172623. mem->pub.max_memory_to_use = max_to_use * 1000L;
  172624. }
  172625. }
  172626. }
  172627. #endif
  172628. }
  172629. /********* End of inlined file: jmemmgr.c *********/
  172630. /********* Start of inlined file: jmemnobs.c *********/
  172631. #define JPEG_INTERNALS
  172632. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  172633. extern void * malloc JPP((size_t size));
  172634. extern void free JPP((void *ptr));
  172635. #endif
  172636. /*
  172637. * Memory allocation and freeing are controlled by the regular library
  172638. * routines malloc() and free().
  172639. */
  172640. GLOBAL(void *)
  172641. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  172642. {
  172643. return (void *) malloc(sizeofobject);
  172644. }
  172645. GLOBAL(void)
  172646. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  172647. {
  172648. free(object);
  172649. }
  172650. /*
  172651. * "Large" objects are treated the same as "small" ones.
  172652. * NB: although we include FAR keywords in the routine declarations,
  172653. * this file won't actually work in 80x86 small/medium model; at least,
  172654. * you probably won't be able to process useful-size images in only 64KB.
  172655. */
  172656. GLOBAL(void FAR *)
  172657. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  172658. {
  172659. return (void FAR *) malloc(sizeofobject);
  172660. }
  172661. GLOBAL(void)
  172662. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  172663. {
  172664. free(object);
  172665. }
  172666. /*
  172667. * This routine computes the total memory space available for allocation.
  172668. * Here we always say, "we got all you want bud!"
  172669. */
  172670. GLOBAL(long)
  172671. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  172672. long max_bytes_needed, long already_allocated)
  172673. {
  172674. return max_bytes_needed;
  172675. }
  172676. /*
  172677. * Backing store (temporary file) management.
  172678. * Since jpeg_mem_available always promised the moon,
  172679. * this should never be called and we can just error out.
  172680. */
  172681. GLOBAL(void)
  172682. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  172683. long total_bytes_needed)
  172684. {
  172685. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  172686. }
  172687. /*
  172688. * These routines take care of any system-dependent initialization and
  172689. * cleanup required. Here, there isn't any.
  172690. */
  172691. GLOBAL(long)
  172692. jpeg_mem_init (j_common_ptr cinfo)
  172693. {
  172694. return 0; /* just set max_memory_to_use to 0 */
  172695. }
  172696. GLOBAL(void)
  172697. jpeg_mem_term (j_common_ptr cinfo)
  172698. {
  172699. /* no work */
  172700. }
  172701. /********* End of inlined file: jmemnobs.c *********/
  172702. /********* Start of inlined file: jquant1.c *********/
  172703. #define JPEG_INTERNALS
  172704. #ifdef QUANT_1PASS_SUPPORTED
  172705. /*
  172706. * The main purpose of 1-pass quantization is to provide a fast, if not very
  172707. * high quality, colormapped output capability. A 2-pass quantizer usually
  172708. * gives better visual quality; however, for quantized grayscale output this
  172709. * quantizer is perfectly adequate. Dithering is highly recommended with this
  172710. * quantizer, though you can turn it off if you really want to.
  172711. *
  172712. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  172713. * image. We use a map consisting of all combinations of Ncolors[i] color
  172714. * values for the i'th component. The Ncolors[] values are chosen so that
  172715. * their product, the total number of colors, is no more than that requested.
  172716. * (In most cases, the product will be somewhat less.)
  172717. *
  172718. * Since the colormap is orthogonal, the representative value for each color
  172719. * component can be determined without considering the other components;
  172720. * then these indexes can be combined into a colormap index by a standard
  172721. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  172722. * can be precalculated and stored in the lookup table colorindex[].
  172723. * colorindex[i][j] maps pixel value j in component i to the nearest
  172724. * representative value (grid plane) for that component; this index is
  172725. * multiplied by the array stride for component i, so that the
  172726. * index of the colormap entry closest to a given pixel value is just
  172727. * sum( colorindex[component-number][pixel-component-value] )
  172728. * Aside from being fast, this scheme allows for variable spacing between
  172729. * representative values with no additional lookup cost.
  172730. *
  172731. * If gamma correction has been applied in color conversion, it might be wise
  172732. * to adjust the color grid spacing so that the representative colors are
  172733. * equidistant in linear space. At this writing, gamma correction is not
  172734. * implemented by jdcolor, so nothing is done here.
  172735. */
  172736. /* Declarations for ordered dithering.
  172737. *
  172738. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  172739. * dithering is described in many references, for instance Dale Schumacher's
  172740. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  172741. * In place of Schumacher's comparisons against a "threshold" value, we add a
  172742. * "dither" value to the input pixel and then round the result to the nearest
  172743. * output value. The dither value is equivalent to (0.5 - threshold) times
  172744. * the distance between output values. For ordered dithering, we assume that
  172745. * the output colors are equally spaced; if not, results will probably be
  172746. * worse, since the dither may be too much or too little at a given point.
  172747. *
  172748. * The normal calculation would be to form pixel value + dither, range-limit
  172749. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  172750. * We can skip the separate range-limiting step by extending the colorindex
  172751. * table in both directions.
  172752. */
  172753. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  172754. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  172755. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  172756. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  172757. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  172758. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  172759. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  172760. /* Bayer's order-4 dither array. Generated by the code given in
  172761. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  172762. * The values in this array must range from 0 to ODITHER_CELLS-1.
  172763. */
  172764. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  172765. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  172766. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  172767. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  172768. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  172769. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  172770. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  172771. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  172772. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  172773. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  172774. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  172775. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  172776. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  172777. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  172778. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  172779. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  172780. };
  172781. /* Declarations for Floyd-Steinberg dithering.
  172782. *
  172783. * Errors are accumulated into the array fserrors[], at a resolution of
  172784. * 1/16th of a pixel count. The error at a given pixel is propagated
  172785. * to its not-yet-processed neighbors using the standard F-S fractions,
  172786. * ... (here) 7/16
  172787. * 3/16 5/16 1/16
  172788. * We work left-to-right on even rows, right-to-left on odd rows.
  172789. *
  172790. * We can get away with a single array (holding one row's worth of errors)
  172791. * by using it to store the current row's errors at pixel columns not yet
  172792. * processed, but the next row's errors at columns already processed. We
  172793. * need only a few extra variables to hold the errors immediately around the
  172794. * current column. (If we are lucky, those variables are in registers, but
  172795. * even if not, they're probably cheaper to access than array elements are.)
  172796. *
  172797. * The fserrors[] array is indexed [component#][position].
  172798. * We provide (#columns + 2) entries per component; the extra entry at each
  172799. * end saves us from special-casing the first and last pixels.
  172800. *
  172801. * Note: on a wide image, we might not have enough room in a PC's near data
  172802. * segment to hold the error array; so it is allocated with alloc_large.
  172803. */
  172804. #if BITS_IN_JSAMPLE == 8
  172805. typedef INT16 FSERROR; /* 16 bits should be enough */
  172806. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  172807. #else
  172808. typedef INT32 FSERROR; /* may need more than 16 bits */
  172809. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  172810. #endif
  172811. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  172812. /* Private subobject */
  172813. #define MAX_Q_COMPS 4 /* max components I can handle */
  172814. typedef struct {
  172815. struct jpeg_color_quantizer pub; /* public fields */
  172816. /* Initially allocated colormap is saved here */
  172817. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  172818. int sv_actual; /* number of entries in use */
  172819. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  172820. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  172821. * premultiplied as described above. Since colormap indexes must fit into
  172822. * JSAMPLEs, the entries of this array will too.
  172823. */
  172824. boolean is_padded; /* is the colorindex padded for odither? */
  172825. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  172826. /* Variables for ordered dithering */
  172827. int row_index; /* cur row's vertical index in dither matrix */
  172828. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  172829. /* Variables for Floyd-Steinberg dithering */
  172830. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  172831. boolean on_odd_row; /* flag to remember which row we are on */
  172832. } my_cquantizer;
  172833. typedef my_cquantizer * my_cquantize_ptr;
  172834. /*
  172835. * Policy-making subroutines for create_colormap and create_colorindex.
  172836. * These routines determine the colormap to be used. The rest of the module
  172837. * only assumes that the colormap is orthogonal.
  172838. *
  172839. * * select_ncolors decides how to divvy up the available colors
  172840. * among the components.
  172841. * * output_value defines the set of representative values for a component.
  172842. * * largest_input_value defines the mapping from input values to
  172843. * representative values for a component.
  172844. * Note that the latter two routines may impose different policies for
  172845. * different components, though this is not currently done.
  172846. */
  172847. LOCAL(int)
  172848. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  172849. /* Determine allocation of desired colors to components, */
  172850. /* and fill in Ncolors[] array to indicate choice. */
  172851. /* Return value is total number of colors (product of Ncolors[] values). */
  172852. {
  172853. int nc = cinfo->out_color_components; /* number of color components */
  172854. int max_colors = cinfo->desired_number_of_colors;
  172855. int total_colors, iroot, i, j;
  172856. boolean changed;
  172857. long temp;
  172858. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  172859. /* We can allocate at least the nc'th root of max_colors per component. */
  172860. /* Compute floor(nc'th root of max_colors). */
  172861. iroot = 1;
  172862. do {
  172863. iroot++;
  172864. temp = iroot; /* set temp = iroot ** nc */
  172865. for (i = 1; i < nc; i++)
  172866. temp *= iroot;
  172867. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  172868. iroot--; /* now iroot = floor(root) */
  172869. /* Must have at least 2 color values per component */
  172870. if (iroot < 2)
  172871. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  172872. /* Initialize to iroot color values for each component */
  172873. total_colors = 1;
  172874. for (i = 0; i < nc; i++) {
  172875. Ncolors[i] = iroot;
  172876. total_colors *= iroot;
  172877. }
  172878. /* We may be able to increment the count for one or more components without
  172879. * exceeding max_colors, though we know not all can be incremented.
  172880. * Sometimes, the first component can be incremented more than once!
  172881. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  172882. * In RGB colorspace, try to increment G first, then R, then B.
  172883. */
  172884. do {
  172885. changed = FALSE;
  172886. for (i = 0; i < nc; i++) {
  172887. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  172888. /* calculate new total_colors if Ncolors[j] is incremented */
  172889. temp = total_colors / Ncolors[j];
  172890. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  172891. if (temp > (long) max_colors)
  172892. break; /* won't fit, done with this pass */
  172893. Ncolors[j]++; /* OK, apply the increment */
  172894. total_colors = (int) temp;
  172895. changed = TRUE;
  172896. }
  172897. } while (changed);
  172898. return total_colors;
  172899. }
  172900. LOCAL(int)
  172901. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172902. /* Return j'th output value, where j will range from 0 to maxj */
  172903. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  172904. {
  172905. /* We always provide values 0 and MAXJSAMPLE for each component;
  172906. * any additional values are equally spaced between these limits.
  172907. * (Forcing the upper and lower values to the limits ensures that
  172908. * dithering can't produce a color outside the selected gamut.)
  172909. */
  172910. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  172911. }
  172912. LOCAL(int)
  172913. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172914. /* Return largest input value that should map to j'th output value */
  172915. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  172916. {
  172917. /* Breakpoints are halfway between values returned by output_value */
  172918. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  172919. }
  172920. /*
  172921. * Create the colormap.
  172922. */
  172923. LOCAL(void)
  172924. create_colormap (j_decompress_ptr cinfo)
  172925. {
  172926. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172927. JSAMPARRAY colormap; /* Created colormap */
  172928. int total_colors; /* Number of distinct output colors */
  172929. int i,j,k, nci, blksize, blkdist, ptr, val;
  172930. /* Select number of colors for each component */
  172931. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  172932. /* Report selected color counts */
  172933. if (cinfo->out_color_components == 3)
  172934. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  172935. total_colors, cquantize->Ncolors[0],
  172936. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  172937. else
  172938. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  172939. /* Allocate and fill in the colormap. */
  172940. /* The colors are ordered in the map in standard row-major order, */
  172941. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  172942. colormap = (*cinfo->mem->alloc_sarray)
  172943. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172944. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  172945. /* blksize is number of adjacent repeated entries for a component */
  172946. /* blkdist is distance between groups of identical entries for a component */
  172947. blkdist = total_colors;
  172948. for (i = 0; i < cinfo->out_color_components; i++) {
  172949. /* fill in colormap entries for i'th color component */
  172950. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172951. blksize = blkdist / nci;
  172952. for (j = 0; j < nci; j++) {
  172953. /* Compute j'th output value (out of nci) for component */
  172954. val = output_value(cinfo, i, j, nci-1);
  172955. /* Fill in all colormap entries that have this value of this component */
  172956. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  172957. /* fill in blksize entries beginning at ptr */
  172958. for (k = 0; k < blksize; k++)
  172959. colormap[i][ptr+k] = (JSAMPLE) val;
  172960. }
  172961. }
  172962. blkdist = blksize; /* blksize of this color is blkdist of next */
  172963. }
  172964. /* Save the colormap in private storage,
  172965. * where it will survive color quantization mode changes.
  172966. */
  172967. cquantize->sv_colormap = colormap;
  172968. cquantize->sv_actual = total_colors;
  172969. }
  172970. /*
  172971. * Create the color index table.
  172972. */
  172973. LOCAL(void)
  172974. create_colorindex (j_decompress_ptr cinfo)
  172975. {
  172976. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172977. JSAMPROW indexptr;
  172978. int i,j,k, nci, blksize, val, pad;
  172979. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  172980. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  172981. * This is not necessary in the other dithering modes. However, we
  172982. * flag whether it was done in case user changes dithering mode.
  172983. */
  172984. if (cinfo->dither_mode == JDITHER_ORDERED) {
  172985. pad = MAXJSAMPLE*2;
  172986. cquantize->is_padded = TRUE;
  172987. } else {
  172988. pad = 0;
  172989. cquantize->is_padded = FALSE;
  172990. }
  172991. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  172992. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172993. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  172994. (JDIMENSION) cinfo->out_color_components);
  172995. /* blksize is number of adjacent repeated entries for a component */
  172996. blksize = cquantize->sv_actual;
  172997. for (i = 0; i < cinfo->out_color_components; i++) {
  172998. /* fill in colorindex entries for i'th color component */
  172999. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173000. blksize = blksize / nci;
  173001. /* adjust colorindex pointers to provide padding at negative indexes. */
  173002. if (pad)
  173003. cquantize->colorindex[i] += MAXJSAMPLE;
  173004. /* in loop, val = index of current output value, */
  173005. /* and k = largest j that maps to current val */
  173006. indexptr = cquantize->colorindex[i];
  173007. val = 0;
  173008. k = largest_input_value(cinfo, i, 0, nci-1);
  173009. for (j = 0; j <= MAXJSAMPLE; j++) {
  173010. while (j > k) /* advance val if past boundary */
  173011. k = largest_input_value(cinfo, i, ++val, nci-1);
  173012. /* premultiply so that no multiplication needed in main processing */
  173013. indexptr[j] = (JSAMPLE) (val * blksize);
  173014. }
  173015. /* Pad at both ends if necessary */
  173016. if (pad)
  173017. for (j = 1; j <= MAXJSAMPLE; j++) {
  173018. indexptr[-j] = indexptr[0];
  173019. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  173020. }
  173021. }
  173022. }
  173023. /*
  173024. * Create an ordered-dither array for a component having ncolors
  173025. * distinct output values.
  173026. */
  173027. LOCAL(ODITHER_MATRIX_PTR)
  173028. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  173029. {
  173030. ODITHER_MATRIX_PTR odither;
  173031. int j,k;
  173032. INT32 num,den;
  173033. odither = (ODITHER_MATRIX_PTR)
  173034. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173035. SIZEOF(ODITHER_MATRIX));
  173036. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  173037. * Hence the dither value for the matrix cell with fill order f
  173038. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  173039. * On 16-bit-int machine, be careful to avoid overflow.
  173040. */
  173041. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  173042. for (j = 0; j < ODITHER_SIZE; j++) {
  173043. for (k = 0; k < ODITHER_SIZE; k++) {
  173044. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  173045. * MAXJSAMPLE;
  173046. /* Ensure round towards zero despite C's lack of consistency
  173047. * about rounding negative values in integer division...
  173048. */
  173049. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  173050. }
  173051. }
  173052. return odither;
  173053. }
  173054. /*
  173055. * Create the ordered-dither tables.
  173056. * Components having the same number of representative colors may
  173057. * share a dither table.
  173058. */
  173059. LOCAL(void)
  173060. create_odither_tables (j_decompress_ptr cinfo)
  173061. {
  173062. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173063. ODITHER_MATRIX_PTR odither;
  173064. int i, j, nci;
  173065. for (i = 0; i < cinfo->out_color_components; i++) {
  173066. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  173067. odither = NULL; /* search for matching prior component */
  173068. for (j = 0; j < i; j++) {
  173069. if (nci == cquantize->Ncolors[j]) {
  173070. odither = cquantize->odither[j];
  173071. break;
  173072. }
  173073. }
  173074. if (odither == NULL) /* need a new table? */
  173075. odither = make_odither_array(cinfo, nci);
  173076. cquantize->odither[i] = odither;
  173077. }
  173078. }
  173079. /*
  173080. * Map some rows of pixels to the output colormapped representation.
  173081. */
  173082. METHODDEF(void)
  173083. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173084. JSAMPARRAY output_buf, int num_rows)
  173085. /* General case, no dithering */
  173086. {
  173087. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173088. JSAMPARRAY colorindex = cquantize->colorindex;
  173089. register int pixcode, ci;
  173090. register JSAMPROW ptrin, ptrout;
  173091. int row;
  173092. JDIMENSION col;
  173093. JDIMENSION width = cinfo->output_width;
  173094. register int nc = cinfo->out_color_components;
  173095. for (row = 0; row < num_rows; row++) {
  173096. ptrin = input_buf[row];
  173097. ptrout = output_buf[row];
  173098. for (col = width; col > 0; col--) {
  173099. pixcode = 0;
  173100. for (ci = 0; ci < nc; ci++) {
  173101. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  173102. }
  173103. *ptrout++ = (JSAMPLE) pixcode;
  173104. }
  173105. }
  173106. }
  173107. METHODDEF(void)
  173108. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173109. JSAMPARRAY output_buf, int num_rows)
  173110. /* Fast path for out_color_components==3, no dithering */
  173111. {
  173112. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173113. register int pixcode;
  173114. register JSAMPROW ptrin, ptrout;
  173115. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173116. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173117. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173118. int row;
  173119. JDIMENSION col;
  173120. JDIMENSION width = cinfo->output_width;
  173121. for (row = 0; row < num_rows; row++) {
  173122. ptrin = input_buf[row];
  173123. ptrout = output_buf[row];
  173124. for (col = width; col > 0; col--) {
  173125. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  173126. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  173127. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  173128. *ptrout++ = (JSAMPLE) pixcode;
  173129. }
  173130. }
  173131. }
  173132. METHODDEF(void)
  173133. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173134. JSAMPARRAY output_buf, int num_rows)
  173135. /* General case, with ordered dithering */
  173136. {
  173137. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173138. register JSAMPROW input_ptr;
  173139. register JSAMPROW output_ptr;
  173140. JSAMPROW colorindex_ci;
  173141. int * dither; /* points to active row of dither matrix */
  173142. int row_index, col_index; /* current indexes into dither matrix */
  173143. int nc = cinfo->out_color_components;
  173144. int ci;
  173145. int row;
  173146. JDIMENSION col;
  173147. JDIMENSION width = cinfo->output_width;
  173148. for (row = 0; row < num_rows; row++) {
  173149. /* Initialize output values to 0 so can process components separately */
  173150. jzero_far((void FAR *) output_buf[row],
  173151. (size_t) (width * SIZEOF(JSAMPLE)));
  173152. row_index = cquantize->row_index;
  173153. for (ci = 0; ci < nc; ci++) {
  173154. input_ptr = input_buf[row] + ci;
  173155. output_ptr = output_buf[row];
  173156. colorindex_ci = cquantize->colorindex[ci];
  173157. dither = cquantize->odither[ci][row_index];
  173158. col_index = 0;
  173159. for (col = width; col > 0; col--) {
  173160. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  173161. * select output value, accumulate into output code for this pixel.
  173162. * Range-limiting need not be done explicitly, as we have extended
  173163. * the colorindex table to produce the right answers for out-of-range
  173164. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  173165. * required amount of padding.
  173166. */
  173167. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  173168. input_ptr += nc;
  173169. output_ptr++;
  173170. col_index = (col_index + 1) & ODITHER_MASK;
  173171. }
  173172. }
  173173. /* Advance row index for next row */
  173174. row_index = (row_index + 1) & ODITHER_MASK;
  173175. cquantize->row_index = row_index;
  173176. }
  173177. }
  173178. METHODDEF(void)
  173179. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173180. JSAMPARRAY output_buf, int num_rows)
  173181. /* Fast path for out_color_components==3, with ordered dithering */
  173182. {
  173183. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173184. register int pixcode;
  173185. register JSAMPROW input_ptr;
  173186. register JSAMPROW output_ptr;
  173187. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173188. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173189. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173190. int * dither0; /* points to active row of dither matrix */
  173191. int * dither1;
  173192. int * dither2;
  173193. int row_index, col_index; /* current indexes into dither matrix */
  173194. int row;
  173195. JDIMENSION col;
  173196. JDIMENSION width = cinfo->output_width;
  173197. for (row = 0; row < num_rows; row++) {
  173198. row_index = cquantize->row_index;
  173199. input_ptr = input_buf[row];
  173200. output_ptr = output_buf[row];
  173201. dither0 = cquantize->odither[0][row_index];
  173202. dither1 = cquantize->odither[1][row_index];
  173203. dither2 = cquantize->odither[2][row_index];
  173204. col_index = 0;
  173205. for (col = width; col > 0; col--) {
  173206. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  173207. dither0[col_index]]);
  173208. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  173209. dither1[col_index]]);
  173210. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  173211. dither2[col_index]]);
  173212. *output_ptr++ = (JSAMPLE) pixcode;
  173213. col_index = (col_index + 1) & ODITHER_MASK;
  173214. }
  173215. row_index = (row_index + 1) & ODITHER_MASK;
  173216. cquantize->row_index = row_index;
  173217. }
  173218. }
  173219. METHODDEF(void)
  173220. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173221. JSAMPARRAY output_buf, int num_rows)
  173222. /* General case, with Floyd-Steinberg dithering */
  173223. {
  173224. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173225. register LOCFSERROR cur; /* current error or pixel value */
  173226. LOCFSERROR belowerr; /* error for pixel below cur */
  173227. LOCFSERROR bpreverr; /* error for below/prev col */
  173228. LOCFSERROR bnexterr; /* error for below/next col */
  173229. LOCFSERROR delta;
  173230. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173231. register JSAMPROW input_ptr;
  173232. register JSAMPROW output_ptr;
  173233. JSAMPROW colorindex_ci;
  173234. JSAMPROW colormap_ci;
  173235. int pixcode;
  173236. int nc = cinfo->out_color_components;
  173237. int dir; /* 1 for left-to-right, -1 for right-to-left */
  173238. int dirnc; /* dir * nc */
  173239. int ci;
  173240. int row;
  173241. JDIMENSION col;
  173242. JDIMENSION width = cinfo->output_width;
  173243. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173244. SHIFT_TEMPS
  173245. for (row = 0; row < num_rows; row++) {
  173246. /* Initialize output values to 0 so can process components separately */
  173247. jzero_far((void FAR *) output_buf[row],
  173248. (size_t) (width * SIZEOF(JSAMPLE)));
  173249. for (ci = 0; ci < nc; ci++) {
  173250. input_ptr = input_buf[row] + ci;
  173251. output_ptr = output_buf[row];
  173252. if (cquantize->on_odd_row) {
  173253. /* work right to left in this row */
  173254. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  173255. output_ptr += width-1;
  173256. dir = -1;
  173257. dirnc = -nc;
  173258. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  173259. } else {
  173260. /* work left to right in this row */
  173261. dir = 1;
  173262. dirnc = nc;
  173263. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  173264. }
  173265. colorindex_ci = cquantize->colorindex[ci];
  173266. colormap_ci = cquantize->sv_colormap[ci];
  173267. /* Preset error values: no error propagated to first pixel from left */
  173268. cur = 0;
  173269. /* and no error propagated to row below yet */
  173270. belowerr = bpreverr = 0;
  173271. for (col = width; col > 0; col--) {
  173272. /* cur holds the error propagated from the previous pixel on the
  173273. * current line. Add the error propagated from the previous line
  173274. * to form the complete error correction term for this pixel, and
  173275. * round the error term (which is expressed * 16) to an integer.
  173276. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  173277. * for either sign of the error value.
  173278. * Note: errorptr points to *previous* column's array entry.
  173279. */
  173280. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  173281. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  173282. * The maximum error is +- MAXJSAMPLE; this sets the required size
  173283. * of the range_limit array.
  173284. */
  173285. cur += GETJSAMPLE(*input_ptr);
  173286. cur = GETJSAMPLE(range_limit[cur]);
  173287. /* Select output value, accumulate into output code for this pixel */
  173288. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  173289. *output_ptr += (JSAMPLE) pixcode;
  173290. /* Compute actual representation error at this pixel */
  173291. /* Note: we can do this even though we don't have the final */
  173292. /* pixel code, because the colormap is orthogonal. */
  173293. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  173294. /* Compute error fractions to be propagated to adjacent pixels.
  173295. * Add these into the running sums, and simultaneously shift the
  173296. * next-line error sums left by 1 column.
  173297. */
  173298. bnexterr = cur;
  173299. delta = cur * 2;
  173300. cur += delta; /* form error * 3 */
  173301. errorptr[0] = (FSERROR) (bpreverr + cur);
  173302. cur += delta; /* form error * 5 */
  173303. bpreverr = belowerr + cur;
  173304. belowerr = bnexterr;
  173305. cur += delta; /* form error * 7 */
  173306. /* At this point cur contains the 7/16 error value to be propagated
  173307. * to the next pixel on the current line, and all the errors for the
  173308. * next line have been shifted over. We are therefore ready to move on.
  173309. */
  173310. input_ptr += dirnc; /* advance input ptr to next column */
  173311. output_ptr += dir; /* advance output ptr to next column */
  173312. errorptr += dir; /* advance errorptr to current column */
  173313. }
  173314. /* Post-loop cleanup: we must unload the final error value into the
  173315. * final fserrors[] entry. Note we need not unload belowerr because
  173316. * it is for the dummy column before or after the actual array.
  173317. */
  173318. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  173319. }
  173320. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  173321. }
  173322. }
  173323. /*
  173324. * Allocate workspace for Floyd-Steinberg errors.
  173325. */
  173326. LOCAL(void)
  173327. alloc_fs_workspace (j_decompress_ptr cinfo)
  173328. {
  173329. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173330. size_t arraysize;
  173331. int i;
  173332. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173333. for (i = 0; i < cinfo->out_color_components; i++) {
  173334. cquantize->fserrors[i] = (FSERRPTR)
  173335. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  173336. }
  173337. }
  173338. /*
  173339. * Initialize for one-pass color quantization.
  173340. */
  173341. METHODDEF(void)
  173342. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  173343. {
  173344. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173345. size_t arraysize;
  173346. int i;
  173347. /* Install my colormap. */
  173348. cinfo->colormap = cquantize->sv_colormap;
  173349. cinfo->actual_number_of_colors = cquantize->sv_actual;
  173350. /* Initialize for desired dithering mode. */
  173351. switch (cinfo->dither_mode) {
  173352. case JDITHER_NONE:
  173353. if (cinfo->out_color_components == 3)
  173354. cquantize->pub.color_quantize = color_quantize3;
  173355. else
  173356. cquantize->pub.color_quantize = color_quantize;
  173357. break;
  173358. case JDITHER_ORDERED:
  173359. if (cinfo->out_color_components == 3)
  173360. cquantize->pub.color_quantize = quantize3_ord_dither;
  173361. else
  173362. cquantize->pub.color_quantize = quantize_ord_dither;
  173363. cquantize->row_index = 0; /* initialize state for ordered dither */
  173364. /* If user changed to ordered dither from another mode,
  173365. * we must recreate the color index table with padding.
  173366. * This will cost extra space, but probably isn't very likely.
  173367. */
  173368. if (! cquantize->is_padded)
  173369. create_colorindex(cinfo);
  173370. /* Create ordered-dither tables if we didn't already. */
  173371. if (cquantize->odither[0] == NULL)
  173372. create_odither_tables(cinfo);
  173373. break;
  173374. case JDITHER_FS:
  173375. cquantize->pub.color_quantize = quantize_fs_dither;
  173376. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  173377. /* Allocate Floyd-Steinberg workspace if didn't already. */
  173378. if (cquantize->fserrors[0] == NULL)
  173379. alloc_fs_workspace(cinfo);
  173380. /* Initialize the propagated errors to zero. */
  173381. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173382. for (i = 0; i < cinfo->out_color_components; i++)
  173383. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  173384. break;
  173385. default:
  173386. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173387. break;
  173388. }
  173389. }
  173390. /*
  173391. * Finish up at the end of the pass.
  173392. */
  173393. METHODDEF(void)
  173394. finish_pass_1_quant (j_decompress_ptr cinfo)
  173395. {
  173396. /* no work in 1-pass case */
  173397. }
  173398. /*
  173399. * Switch to a new external colormap between output passes.
  173400. * Shouldn't get to this module!
  173401. */
  173402. METHODDEF(void)
  173403. new_color_map_1_quant (j_decompress_ptr cinfo)
  173404. {
  173405. ERREXIT(cinfo, JERR_MODE_CHANGE);
  173406. }
  173407. /*
  173408. * Module initialization routine for 1-pass color quantization.
  173409. */
  173410. GLOBAL(void)
  173411. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  173412. {
  173413. my_cquantize_ptr cquantize;
  173414. cquantize = (my_cquantize_ptr)
  173415. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173416. SIZEOF(my_cquantizer));
  173417. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  173418. cquantize->pub.start_pass = start_pass_1_quant;
  173419. cquantize->pub.finish_pass = finish_pass_1_quant;
  173420. cquantize->pub.new_color_map = new_color_map_1_quant;
  173421. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  173422. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  173423. /* Make sure my internal arrays won't overflow */
  173424. if (cinfo->out_color_components > MAX_Q_COMPS)
  173425. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  173426. /* Make sure colormap indexes can be represented by JSAMPLEs */
  173427. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  173428. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  173429. /* Create the colormap and color index table. */
  173430. create_colormap(cinfo);
  173431. create_colorindex(cinfo);
  173432. /* Allocate Floyd-Steinberg workspace now if requested.
  173433. * We do this now since it is FAR storage and may affect the memory
  173434. * manager's space calculations. If the user changes to FS dither
  173435. * mode in a later pass, we will allocate the space then, and will
  173436. * possibly overrun the max_memory_to_use setting.
  173437. */
  173438. if (cinfo->dither_mode == JDITHER_FS)
  173439. alloc_fs_workspace(cinfo);
  173440. }
  173441. #endif /* QUANT_1PASS_SUPPORTED */
  173442. /********* End of inlined file: jquant1.c *********/
  173443. /********* Start of inlined file: jquant2.c *********/
  173444. #define JPEG_INTERNALS
  173445. #ifdef QUANT_2PASS_SUPPORTED
  173446. /*
  173447. * This module implements the well-known Heckbert paradigm for color
  173448. * quantization. Most of the ideas used here can be traced back to
  173449. * Heckbert's seminal paper
  173450. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  173451. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  173452. *
  173453. * In the first pass over the image, we accumulate a histogram showing the
  173454. * usage count of each possible color. To keep the histogram to a reasonable
  173455. * size, we reduce the precision of the input; typical practice is to retain
  173456. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  173457. * in the same histogram cell.
  173458. *
  173459. * Next, the color-selection step begins with a box representing the whole
  173460. * color space, and repeatedly splits the "largest" remaining box until we
  173461. * have as many boxes as desired colors. Then the mean color in each
  173462. * remaining box becomes one of the possible output colors.
  173463. *
  173464. * The second pass over the image maps each input pixel to the closest output
  173465. * color (optionally after applying a Floyd-Steinberg dithering correction).
  173466. * This mapping is logically trivial, but making it go fast enough requires
  173467. * considerable care.
  173468. *
  173469. * Heckbert-style quantizers vary a good deal in their policies for choosing
  173470. * the "largest" box and deciding where to cut it. The particular policies
  173471. * used here have proved out well in experimental comparisons, but better ones
  173472. * may yet be found.
  173473. *
  173474. * In earlier versions of the IJG code, this module quantized in YCbCr color
  173475. * space, processing the raw upsampled data without a color conversion step.
  173476. * This allowed the color conversion math to be done only once per colormap
  173477. * entry, not once per pixel. However, that optimization precluded other
  173478. * useful optimizations (such as merging color conversion with upsampling)
  173479. * and it also interfered with desired capabilities such as quantizing to an
  173480. * externally-supplied colormap. We have therefore abandoned that approach.
  173481. * The present code works in the post-conversion color space, typically RGB.
  173482. *
  173483. * To improve the visual quality of the results, we actually work in scaled
  173484. * RGB space, giving G distances more weight than R, and R in turn more than
  173485. * B. To do everything in integer math, we must use integer scale factors.
  173486. * The 2/3/1 scale factors used here correspond loosely to the relative
  173487. * weights of the colors in the NTSC grayscale equation.
  173488. * If you want to use this code to quantize a non-RGB color space, you'll
  173489. * probably need to change these scale factors.
  173490. */
  173491. #define R_SCALE 2 /* scale R distances by this much */
  173492. #define G_SCALE 3 /* scale G distances by this much */
  173493. #define B_SCALE 1 /* and B by this much */
  173494. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  173495. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  173496. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  173497. * you'll get compile errors until you extend this logic. In that case
  173498. * you'll probably want to tweak the histogram sizes too.
  173499. */
  173500. #if RGB_RED == 0
  173501. #define C0_SCALE R_SCALE
  173502. #endif
  173503. #if RGB_BLUE == 0
  173504. #define C0_SCALE B_SCALE
  173505. #endif
  173506. #if RGB_GREEN == 1
  173507. #define C1_SCALE G_SCALE
  173508. #endif
  173509. #if RGB_RED == 2
  173510. #define C2_SCALE R_SCALE
  173511. #endif
  173512. #if RGB_BLUE == 2
  173513. #define C2_SCALE B_SCALE
  173514. #endif
  173515. /*
  173516. * First we have the histogram data structure and routines for creating it.
  173517. *
  173518. * The number of bits of precision can be adjusted by changing these symbols.
  173519. * We recommend keeping 6 bits for G and 5 each for R and B.
  173520. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  173521. * better results; if you are short of memory, 5 bits all around will save
  173522. * some space but degrade the results.
  173523. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  173524. * (preferably unsigned long) for each cell. In practice this is overkill;
  173525. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  173526. * and clamping those that do overflow to the maximum value will give close-
  173527. * enough results. This reduces the recommended histogram size from 256Kb
  173528. * to 128Kb, which is a useful savings on PC-class machines.
  173529. * (In the second pass the histogram space is re-used for pixel mapping data;
  173530. * in that capacity, each cell must be able to store zero to the number of
  173531. * desired colors. 16 bits/cell is plenty for that too.)
  173532. * Since the JPEG code is intended to run in small memory model on 80x86
  173533. * machines, we can't just allocate the histogram in one chunk. Instead
  173534. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  173535. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  173536. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  173537. * on 80x86 machines, the pointer row is in near memory but the actual
  173538. * arrays are in far memory (same arrangement as we use for image arrays).
  173539. */
  173540. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  173541. /* These will do the right thing for either R,G,B or B,G,R color order,
  173542. * but you may not like the results for other color orders.
  173543. */
  173544. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  173545. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  173546. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  173547. /* Number of elements along histogram axes. */
  173548. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  173549. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  173550. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  173551. /* These are the amounts to shift an input value to get a histogram index. */
  173552. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  173553. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  173554. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  173555. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  173556. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  173557. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  173558. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  173559. typedef hist2d * hist3d; /* type for top-level pointer */
  173560. /* Declarations for Floyd-Steinberg dithering.
  173561. *
  173562. * Errors are accumulated into the array fserrors[], at a resolution of
  173563. * 1/16th of a pixel count. The error at a given pixel is propagated
  173564. * to its not-yet-processed neighbors using the standard F-S fractions,
  173565. * ... (here) 7/16
  173566. * 3/16 5/16 1/16
  173567. * We work left-to-right on even rows, right-to-left on odd rows.
  173568. *
  173569. * We can get away with a single array (holding one row's worth of errors)
  173570. * by using it to store the current row's errors at pixel columns not yet
  173571. * processed, but the next row's errors at columns already processed. We
  173572. * need only a few extra variables to hold the errors immediately around the
  173573. * current column. (If we are lucky, those variables are in registers, but
  173574. * even if not, they're probably cheaper to access than array elements are.)
  173575. *
  173576. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  173577. * each end saves us from special-casing the first and last pixels.
  173578. * Each entry is three values long, one value for each color component.
  173579. *
  173580. * Note: on a wide image, we might not have enough room in a PC's near data
  173581. * segment to hold the error array; so it is allocated with alloc_large.
  173582. */
  173583. #if BITS_IN_JSAMPLE == 8
  173584. typedef INT16 FSERROR; /* 16 bits should be enough */
  173585. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  173586. #else
  173587. typedef INT32 FSERROR; /* may need more than 16 bits */
  173588. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  173589. #endif
  173590. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  173591. /* Private subobject */
  173592. typedef struct {
  173593. struct jpeg_color_quantizer pub; /* public fields */
  173594. /* Space for the eventually created colormap is stashed here */
  173595. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  173596. int desired; /* desired # of colors = size of colormap */
  173597. /* Variables for accumulating image statistics */
  173598. hist3d histogram; /* pointer to the histogram */
  173599. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  173600. /* Variables for Floyd-Steinberg dithering */
  173601. FSERRPTR fserrors; /* accumulated errors */
  173602. boolean on_odd_row; /* flag to remember which row we are on */
  173603. int * error_limiter; /* table for clamping the applied error */
  173604. } my_cquantizer2;
  173605. typedef my_cquantizer2 * my_cquantize_ptr2;
  173606. /*
  173607. * Prescan some rows of pixels.
  173608. * In this module the prescan simply updates the histogram, which has been
  173609. * initialized to zeroes by start_pass.
  173610. * An output_buf parameter is required by the method signature, but no data
  173611. * is actually output (in fact the buffer controller is probably passing a
  173612. * NULL pointer).
  173613. */
  173614. METHODDEF(void)
  173615. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173616. JSAMPARRAY output_buf, int num_rows)
  173617. {
  173618. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173619. register JSAMPROW ptr;
  173620. register histptr histp;
  173621. register hist3d histogram = cquantize->histogram;
  173622. int row;
  173623. JDIMENSION col;
  173624. JDIMENSION width = cinfo->output_width;
  173625. for (row = 0; row < num_rows; row++) {
  173626. ptr = input_buf[row];
  173627. for (col = width; col > 0; col--) {
  173628. /* get pixel value and index into the histogram */
  173629. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  173630. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  173631. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  173632. /* increment, check for overflow and undo increment if so. */
  173633. if (++(*histp) <= 0)
  173634. (*histp)--;
  173635. ptr += 3;
  173636. }
  173637. }
  173638. }
  173639. /*
  173640. * Next we have the really interesting routines: selection of a colormap
  173641. * given the completed histogram.
  173642. * These routines work with a list of "boxes", each representing a rectangular
  173643. * subset of the input color space (to histogram precision).
  173644. */
  173645. typedef struct {
  173646. /* The bounds of the box (inclusive); expressed as histogram indexes */
  173647. int c0min, c0max;
  173648. int c1min, c1max;
  173649. int c2min, c2max;
  173650. /* The volume (actually 2-norm) of the box */
  173651. INT32 volume;
  173652. /* The number of nonzero histogram cells within this box */
  173653. long colorcount;
  173654. } box;
  173655. typedef box * boxptr;
  173656. LOCAL(boxptr)
  173657. find_biggest_color_pop (boxptr boxlist, int numboxes)
  173658. /* Find the splittable box with the largest color population */
  173659. /* Returns NULL if no splittable boxes remain */
  173660. {
  173661. register boxptr boxp;
  173662. register int i;
  173663. register long maxc = 0;
  173664. boxptr which = NULL;
  173665. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173666. if (boxp->colorcount > maxc && boxp->volume > 0) {
  173667. which = boxp;
  173668. maxc = boxp->colorcount;
  173669. }
  173670. }
  173671. return which;
  173672. }
  173673. LOCAL(boxptr)
  173674. find_biggest_volume (boxptr boxlist, int numboxes)
  173675. /* Find the splittable box with the largest (scaled) volume */
  173676. /* Returns NULL if no splittable boxes remain */
  173677. {
  173678. register boxptr boxp;
  173679. register int i;
  173680. register INT32 maxv = 0;
  173681. boxptr which = NULL;
  173682. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173683. if (boxp->volume > maxv) {
  173684. which = boxp;
  173685. maxv = boxp->volume;
  173686. }
  173687. }
  173688. return which;
  173689. }
  173690. LOCAL(void)
  173691. update_box (j_decompress_ptr cinfo, boxptr boxp)
  173692. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  173693. /* and recompute its volume and population */
  173694. {
  173695. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173696. hist3d histogram = cquantize->histogram;
  173697. histptr histp;
  173698. int c0,c1,c2;
  173699. int c0min,c0max,c1min,c1max,c2min,c2max;
  173700. INT32 dist0,dist1,dist2;
  173701. long ccount;
  173702. c0min = boxp->c0min; c0max = boxp->c0max;
  173703. c1min = boxp->c1min; c1max = boxp->c1max;
  173704. c2min = boxp->c2min; c2max = boxp->c2max;
  173705. if (c0max > c0min)
  173706. for (c0 = c0min; c0 <= c0max; c0++)
  173707. for (c1 = c1min; c1 <= c1max; c1++) {
  173708. histp = & histogram[c0][c1][c2min];
  173709. for (c2 = c2min; c2 <= c2max; c2++)
  173710. if (*histp++ != 0) {
  173711. boxp->c0min = c0min = c0;
  173712. goto have_c0min;
  173713. }
  173714. }
  173715. have_c0min:
  173716. if (c0max > c0min)
  173717. for (c0 = c0max; c0 >= c0min; c0--)
  173718. for (c1 = c1min; c1 <= c1max; c1++) {
  173719. histp = & histogram[c0][c1][c2min];
  173720. for (c2 = c2min; c2 <= c2max; c2++)
  173721. if (*histp++ != 0) {
  173722. boxp->c0max = c0max = c0;
  173723. goto have_c0max;
  173724. }
  173725. }
  173726. have_c0max:
  173727. if (c1max > c1min)
  173728. for (c1 = c1min; c1 <= c1max; c1++)
  173729. for (c0 = c0min; c0 <= c0max; c0++) {
  173730. histp = & histogram[c0][c1][c2min];
  173731. for (c2 = c2min; c2 <= c2max; c2++)
  173732. if (*histp++ != 0) {
  173733. boxp->c1min = c1min = c1;
  173734. goto have_c1min;
  173735. }
  173736. }
  173737. have_c1min:
  173738. if (c1max > c1min)
  173739. for (c1 = c1max; c1 >= c1min; c1--)
  173740. for (c0 = c0min; c0 <= c0max; c0++) {
  173741. histp = & histogram[c0][c1][c2min];
  173742. for (c2 = c2min; c2 <= c2max; c2++)
  173743. if (*histp++ != 0) {
  173744. boxp->c1max = c1max = c1;
  173745. goto have_c1max;
  173746. }
  173747. }
  173748. have_c1max:
  173749. if (c2max > c2min)
  173750. for (c2 = c2min; c2 <= c2max; c2++)
  173751. for (c0 = c0min; c0 <= c0max; c0++) {
  173752. histp = & histogram[c0][c1min][c2];
  173753. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173754. if (*histp != 0) {
  173755. boxp->c2min = c2min = c2;
  173756. goto have_c2min;
  173757. }
  173758. }
  173759. have_c2min:
  173760. if (c2max > c2min)
  173761. for (c2 = c2max; c2 >= c2min; c2--)
  173762. for (c0 = c0min; c0 <= c0max; c0++) {
  173763. histp = & histogram[c0][c1min][c2];
  173764. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173765. if (*histp != 0) {
  173766. boxp->c2max = c2max = c2;
  173767. goto have_c2max;
  173768. }
  173769. }
  173770. have_c2max:
  173771. /* Update box volume.
  173772. * We use 2-norm rather than real volume here; this biases the method
  173773. * against making long narrow boxes, and it has the side benefit that
  173774. * a box is splittable iff norm > 0.
  173775. * Since the differences are expressed in histogram-cell units,
  173776. * we have to shift back to JSAMPLE units to get consistent distances;
  173777. * after which, we scale according to the selected distance scale factors.
  173778. */
  173779. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  173780. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  173781. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  173782. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  173783. /* Now scan remaining volume of box and compute population */
  173784. ccount = 0;
  173785. for (c0 = c0min; c0 <= c0max; c0++)
  173786. for (c1 = c1min; c1 <= c1max; c1++) {
  173787. histp = & histogram[c0][c1][c2min];
  173788. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  173789. if (*histp != 0) {
  173790. ccount++;
  173791. }
  173792. }
  173793. boxp->colorcount = ccount;
  173794. }
  173795. LOCAL(int)
  173796. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  173797. int desired_colors)
  173798. /* Repeatedly select and split the largest box until we have enough boxes */
  173799. {
  173800. int n,lb;
  173801. int c0,c1,c2,cmax;
  173802. register boxptr b1,b2;
  173803. while (numboxes < desired_colors) {
  173804. /* Select box to split.
  173805. * Current algorithm: by population for first half, then by volume.
  173806. */
  173807. if (numboxes*2 <= desired_colors) {
  173808. b1 = find_biggest_color_pop(boxlist, numboxes);
  173809. } else {
  173810. b1 = find_biggest_volume(boxlist, numboxes);
  173811. }
  173812. if (b1 == NULL) /* no splittable boxes left! */
  173813. break;
  173814. b2 = &boxlist[numboxes]; /* where new box will go */
  173815. /* Copy the color bounds to the new box. */
  173816. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  173817. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  173818. /* Choose which axis to split the box on.
  173819. * Current algorithm: longest scaled axis.
  173820. * See notes in update_box about scaling distances.
  173821. */
  173822. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  173823. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  173824. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  173825. /* We want to break any ties in favor of green, then red, blue last.
  173826. * This code does the right thing for R,G,B or B,G,R color orders only.
  173827. */
  173828. #if RGB_RED == 0
  173829. cmax = c1; n = 1;
  173830. if (c0 > cmax) { cmax = c0; n = 0; }
  173831. if (c2 > cmax) { n = 2; }
  173832. #else
  173833. cmax = c1; n = 1;
  173834. if (c2 > cmax) { cmax = c2; n = 2; }
  173835. if (c0 > cmax) { n = 0; }
  173836. #endif
  173837. /* Choose split point along selected axis, and update box bounds.
  173838. * Current algorithm: split at halfway point.
  173839. * (Since the box has been shrunk to minimum volume,
  173840. * any split will produce two nonempty subboxes.)
  173841. * Note that lb value is max for lower box, so must be < old max.
  173842. */
  173843. switch (n) {
  173844. case 0:
  173845. lb = (b1->c0max + b1->c0min) / 2;
  173846. b1->c0max = lb;
  173847. b2->c0min = lb+1;
  173848. break;
  173849. case 1:
  173850. lb = (b1->c1max + b1->c1min) / 2;
  173851. b1->c1max = lb;
  173852. b2->c1min = lb+1;
  173853. break;
  173854. case 2:
  173855. lb = (b1->c2max + b1->c2min) / 2;
  173856. b1->c2max = lb;
  173857. b2->c2min = lb+1;
  173858. break;
  173859. }
  173860. /* Update stats for boxes */
  173861. update_box(cinfo, b1);
  173862. update_box(cinfo, b2);
  173863. numboxes++;
  173864. }
  173865. return numboxes;
  173866. }
  173867. LOCAL(void)
  173868. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  173869. /* Compute representative color for a box, put it in colormap[icolor] */
  173870. {
  173871. /* Current algorithm: mean weighted by pixels (not colors) */
  173872. /* Note it is important to get the rounding correct! */
  173873. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173874. hist3d histogram = cquantize->histogram;
  173875. histptr histp;
  173876. int c0,c1,c2;
  173877. int c0min,c0max,c1min,c1max,c2min,c2max;
  173878. long count;
  173879. long total = 0;
  173880. long c0total = 0;
  173881. long c1total = 0;
  173882. long c2total = 0;
  173883. c0min = boxp->c0min; c0max = boxp->c0max;
  173884. c1min = boxp->c1min; c1max = boxp->c1max;
  173885. c2min = boxp->c2min; c2max = boxp->c2max;
  173886. for (c0 = c0min; c0 <= c0max; c0++)
  173887. for (c1 = c1min; c1 <= c1max; c1++) {
  173888. histp = & histogram[c0][c1][c2min];
  173889. for (c2 = c2min; c2 <= c2max; c2++) {
  173890. if ((count = *histp++) != 0) {
  173891. total += count;
  173892. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  173893. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  173894. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  173895. }
  173896. }
  173897. }
  173898. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  173899. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  173900. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  173901. }
  173902. LOCAL(void)
  173903. select_colors (j_decompress_ptr cinfo, int desired_colors)
  173904. /* Master routine for color selection */
  173905. {
  173906. boxptr boxlist;
  173907. int numboxes;
  173908. int i;
  173909. /* Allocate workspace for box list */
  173910. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  173911. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  173912. /* Initialize one box containing whole space */
  173913. numboxes = 1;
  173914. boxlist[0].c0min = 0;
  173915. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  173916. boxlist[0].c1min = 0;
  173917. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  173918. boxlist[0].c2min = 0;
  173919. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  173920. /* Shrink it to actually-used volume and set its statistics */
  173921. update_box(cinfo, & boxlist[0]);
  173922. /* Perform median-cut to produce final box list */
  173923. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  173924. /* Compute the representative color for each box, fill colormap */
  173925. for (i = 0; i < numboxes; i++)
  173926. compute_color(cinfo, & boxlist[i], i);
  173927. cinfo->actual_number_of_colors = numboxes;
  173928. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  173929. }
  173930. /*
  173931. * These routines are concerned with the time-critical task of mapping input
  173932. * colors to the nearest color in the selected colormap.
  173933. *
  173934. * We re-use the histogram space as an "inverse color map", essentially a
  173935. * cache for the results of nearest-color searches. All colors within a
  173936. * histogram cell will be mapped to the same colormap entry, namely the one
  173937. * closest to the cell's center. This may not be quite the closest entry to
  173938. * the actual input color, but it's almost as good. A zero in the cache
  173939. * indicates we haven't found the nearest color for that cell yet; the array
  173940. * is cleared to zeroes before starting the mapping pass. When we find the
  173941. * nearest color for a cell, its colormap index plus one is recorded in the
  173942. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  173943. * when they need to use an unfilled entry in the cache.
  173944. *
  173945. * Our method of efficiently finding nearest colors is based on the "locally
  173946. * sorted search" idea described by Heckbert and on the incremental distance
  173947. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  173948. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  173949. * the distances from a given colormap entry to each cell of the histogram can
  173950. * be computed quickly using an incremental method: the differences between
  173951. * distances to adjacent cells themselves differ by a constant. This allows a
  173952. * fairly fast implementation of the "brute force" approach of computing the
  173953. * distance from every colormap entry to every histogram cell. Unfortunately,
  173954. * it needs a work array to hold the best-distance-so-far for each histogram
  173955. * cell (because the inner loop has to be over cells, not colormap entries).
  173956. * The work array elements have to be INT32s, so the work array would need
  173957. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  173958. *
  173959. * To get around these problems, we apply Thomas' method to compute the
  173960. * nearest colors for only the cells within a small subbox of the histogram.
  173961. * The work array need be only as big as the subbox, so the memory usage
  173962. * problem is solved. Furthermore, we need not fill subboxes that are never
  173963. * referenced in pass2; many images use only part of the color gamut, so a
  173964. * fair amount of work is saved. An additional advantage of this
  173965. * approach is that we can apply Heckbert's locality criterion to quickly
  173966. * eliminate colormap entries that are far away from the subbox; typically
  173967. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  173968. * and we need not compute their distances to individual cells in the subbox.
  173969. * The speed of this approach is heavily influenced by the subbox size: too
  173970. * small means too much overhead, too big loses because Heckbert's criterion
  173971. * can't eliminate as many colormap entries. Empirically the best subbox
  173972. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  173973. *
  173974. * Thomas' article also describes a refined method which is asymptotically
  173975. * faster than the brute-force method, but it is also far more complex and
  173976. * cannot efficiently be applied to small subboxes. It is therefore not
  173977. * useful for programs intended to be portable to DOS machines. On machines
  173978. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  173979. * refined method might be faster than the present code --- but then again,
  173980. * it might not be any faster, and it's certainly more complicated.
  173981. */
  173982. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  173983. #define BOX_C0_LOG (HIST_C0_BITS-3)
  173984. #define BOX_C1_LOG (HIST_C1_BITS-3)
  173985. #define BOX_C2_LOG (HIST_C2_BITS-3)
  173986. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  173987. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  173988. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  173989. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  173990. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  173991. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  173992. /*
  173993. * The next three routines implement inverse colormap filling. They could
  173994. * all be folded into one big routine, but splitting them up this way saves
  173995. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  173996. * and may allow some compilers to produce better code by registerizing more
  173997. * inner-loop variables.
  173998. */
  173999. LOCAL(int)
  174000. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  174001. JSAMPLE colorlist[])
  174002. /* Locate the colormap entries close enough to an update box to be candidates
  174003. * for the nearest entry to some cell(s) in the update box. The update box
  174004. * is specified by the center coordinates of its first cell. The number of
  174005. * candidate colormap entries is returned, and their colormap indexes are
  174006. * placed in colorlist[].
  174007. * This routine uses Heckbert's "locally sorted search" criterion to select
  174008. * the colors that need further consideration.
  174009. */
  174010. {
  174011. int numcolors = cinfo->actual_number_of_colors;
  174012. int maxc0, maxc1, maxc2;
  174013. int centerc0, centerc1, centerc2;
  174014. int i, x, ncolors;
  174015. INT32 minmaxdist, min_dist, max_dist, tdist;
  174016. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  174017. /* Compute true coordinates of update box's upper corner and center.
  174018. * Actually we compute the coordinates of the center of the upper-corner
  174019. * histogram cell, which are the upper bounds of the volume we care about.
  174020. * Note that since ">>" rounds down, the "center" values may be closer to
  174021. * min than to max; hence comparisons to them must be "<=", not "<".
  174022. */
  174023. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  174024. centerc0 = (minc0 + maxc0) >> 1;
  174025. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  174026. centerc1 = (minc1 + maxc1) >> 1;
  174027. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  174028. centerc2 = (minc2 + maxc2) >> 1;
  174029. /* For each color in colormap, find:
  174030. * 1. its minimum squared-distance to any point in the update box
  174031. * (zero if color is within update box);
  174032. * 2. its maximum squared-distance to any point in the update box.
  174033. * Both of these can be found by considering only the corners of the box.
  174034. * We save the minimum distance for each color in mindist[];
  174035. * only the smallest maximum distance is of interest.
  174036. */
  174037. minmaxdist = 0x7FFFFFFFL;
  174038. for (i = 0; i < numcolors; i++) {
  174039. /* We compute the squared-c0-distance term, then add in the other two. */
  174040. x = GETJSAMPLE(cinfo->colormap[0][i]);
  174041. if (x < minc0) {
  174042. tdist = (x - minc0) * C0_SCALE;
  174043. min_dist = tdist*tdist;
  174044. tdist = (x - maxc0) * C0_SCALE;
  174045. max_dist = tdist*tdist;
  174046. } else if (x > maxc0) {
  174047. tdist = (x - maxc0) * C0_SCALE;
  174048. min_dist = tdist*tdist;
  174049. tdist = (x - minc0) * C0_SCALE;
  174050. max_dist = tdist*tdist;
  174051. } else {
  174052. /* within cell range so no contribution to min_dist */
  174053. min_dist = 0;
  174054. if (x <= centerc0) {
  174055. tdist = (x - maxc0) * C0_SCALE;
  174056. max_dist = tdist*tdist;
  174057. } else {
  174058. tdist = (x - minc0) * C0_SCALE;
  174059. max_dist = tdist*tdist;
  174060. }
  174061. }
  174062. x = GETJSAMPLE(cinfo->colormap[1][i]);
  174063. if (x < minc1) {
  174064. tdist = (x - minc1) * C1_SCALE;
  174065. min_dist += tdist*tdist;
  174066. tdist = (x - maxc1) * C1_SCALE;
  174067. max_dist += tdist*tdist;
  174068. } else if (x > maxc1) {
  174069. tdist = (x - maxc1) * C1_SCALE;
  174070. min_dist += tdist*tdist;
  174071. tdist = (x - minc1) * C1_SCALE;
  174072. max_dist += tdist*tdist;
  174073. } else {
  174074. /* within cell range so no contribution to min_dist */
  174075. if (x <= centerc1) {
  174076. tdist = (x - maxc1) * C1_SCALE;
  174077. max_dist += tdist*tdist;
  174078. } else {
  174079. tdist = (x - minc1) * C1_SCALE;
  174080. max_dist += tdist*tdist;
  174081. }
  174082. }
  174083. x = GETJSAMPLE(cinfo->colormap[2][i]);
  174084. if (x < minc2) {
  174085. tdist = (x - minc2) * C2_SCALE;
  174086. min_dist += tdist*tdist;
  174087. tdist = (x - maxc2) * C2_SCALE;
  174088. max_dist += tdist*tdist;
  174089. } else if (x > maxc2) {
  174090. tdist = (x - maxc2) * C2_SCALE;
  174091. min_dist += tdist*tdist;
  174092. tdist = (x - minc2) * C2_SCALE;
  174093. max_dist += tdist*tdist;
  174094. } else {
  174095. /* within cell range so no contribution to min_dist */
  174096. if (x <= centerc2) {
  174097. tdist = (x - maxc2) * C2_SCALE;
  174098. max_dist += tdist*tdist;
  174099. } else {
  174100. tdist = (x - minc2) * C2_SCALE;
  174101. max_dist += tdist*tdist;
  174102. }
  174103. }
  174104. mindist[i] = min_dist; /* save away the results */
  174105. if (max_dist < minmaxdist)
  174106. minmaxdist = max_dist;
  174107. }
  174108. /* Now we know that no cell in the update box is more than minmaxdist
  174109. * away from some colormap entry. Therefore, only colors that are
  174110. * within minmaxdist of some part of the box need be considered.
  174111. */
  174112. ncolors = 0;
  174113. for (i = 0; i < numcolors; i++) {
  174114. if (mindist[i] <= minmaxdist)
  174115. colorlist[ncolors++] = (JSAMPLE) i;
  174116. }
  174117. return ncolors;
  174118. }
  174119. LOCAL(void)
  174120. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  174121. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  174122. /* Find the closest colormap entry for each cell in the update box,
  174123. * given the list of candidate colors prepared by find_nearby_colors.
  174124. * Return the indexes of the closest entries in the bestcolor[] array.
  174125. * This routine uses Thomas' incremental distance calculation method to
  174126. * find the distance from a colormap entry to successive cells in the box.
  174127. */
  174128. {
  174129. int ic0, ic1, ic2;
  174130. int i, icolor;
  174131. register INT32 * bptr; /* pointer into bestdist[] array */
  174132. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174133. INT32 dist0, dist1; /* initial distance values */
  174134. register INT32 dist2; /* current distance in inner loop */
  174135. INT32 xx0, xx1; /* distance increments */
  174136. register INT32 xx2;
  174137. INT32 inc0, inc1, inc2; /* initial values for increments */
  174138. /* This array holds the distance to the nearest-so-far color for each cell */
  174139. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174140. /* Initialize best-distance for each cell of the update box */
  174141. bptr = bestdist;
  174142. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  174143. *bptr++ = 0x7FFFFFFFL;
  174144. /* For each color selected by find_nearby_colors,
  174145. * compute its distance to the center of each cell in the box.
  174146. * If that's less than best-so-far, update best distance and color number.
  174147. */
  174148. /* Nominal steps between cell centers ("x" in Thomas article) */
  174149. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  174150. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  174151. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  174152. for (i = 0; i < numcolors; i++) {
  174153. icolor = GETJSAMPLE(colorlist[i]);
  174154. /* Compute (square of) distance from minc0/c1/c2 to this color */
  174155. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  174156. dist0 = inc0*inc0;
  174157. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  174158. dist0 += inc1*inc1;
  174159. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  174160. dist0 += inc2*inc2;
  174161. /* Form the initial difference increments */
  174162. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  174163. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  174164. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  174165. /* Now loop over all cells in box, updating distance per Thomas method */
  174166. bptr = bestdist;
  174167. cptr = bestcolor;
  174168. xx0 = inc0;
  174169. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  174170. dist1 = dist0;
  174171. xx1 = inc1;
  174172. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  174173. dist2 = dist1;
  174174. xx2 = inc2;
  174175. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  174176. if (dist2 < *bptr) {
  174177. *bptr = dist2;
  174178. *cptr = (JSAMPLE) icolor;
  174179. }
  174180. dist2 += xx2;
  174181. xx2 += 2 * STEP_C2 * STEP_C2;
  174182. bptr++;
  174183. cptr++;
  174184. }
  174185. dist1 += xx1;
  174186. xx1 += 2 * STEP_C1 * STEP_C1;
  174187. }
  174188. dist0 += xx0;
  174189. xx0 += 2 * STEP_C0 * STEP_C0;
  174190. }
  174191. }
  174192. }
  174193. LOCAL(void)
  174194. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  174195. /* Fill the inverse-colormap entries in the update box that contains */
  174196. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  174197. /* we can fill as many others as we wish.) */
  174198. {
  174199. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174200. hist3d histogram = cquantize->histogram;
  174201. int minc0, minc1, minc2; /* lower left corner of update box */
  174202. int ic0, ic1, ic2;
  174203. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174204. register histptr cachep; /* pointer into main cache array */
  174205. /* This array lists the candidate colormap indexes. */
  174206. JSAMPLE colorlist[MAXNUMCOLORS];
  174207. int numcolors; /* number of candidate colors */
  174208. /* This array holds the actually closest colormap index for each cell. */
  174209. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174210. /* Convert cell coordinates to update box ID */
  174211. c0 >>= BOX_C0_LOG;
  174212. c1 >>= BOX_C1_LOG;
  174213. c2 >>= BOX_C2_LOG;
  174214. /* Compute true coordinates of update box's origin corner.
  174215. * Actually we compute the coordinates of the center of the corner
  174216. * histogram cell, which are the lower bounds of the volume we care about.
  174217. */
  174218. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  174219. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  174220. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  174221. /* Determine which colormap entries are close enough to be candidates
  174222. * for the nearest entry to some cell in the update box.
  174223. */
  174224. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  174225. /* Determine the actually nearest colors. */
  174226. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  174227. bestcolor);
  174228. /* Save the best color numbers (plus 1) in the main cache array */
  174229. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  174230. c1 <<= BOX_C1_LOG;
  174231. c2 <<= BOX_C2_LOG;
  174232. cptr = bestcolor;
  174233. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  174234. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  174235. cachep = & histogram[c0+ic0][c1+ic1][c2];
  174236. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  174237. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  174238. }
  174239. }
  174240. }
  174241. }
  174242. /*
  174243. * Map some rows of pixels to the output colormapped representation.
  174244. */
  174245. METHODDEF(void)
  174246. pass2_no_dither (j_decompress_ptr cinfo,
  174247. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174248. /* This version performs no dithering */
  174249. {
  174250. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174251. hist3d histogram = cquantize->histogram;
  174252. register JSAMPROW inptr, outptr;
  174253. register histptr cachep;
  174254. register int c0, c1, c2;
  174255. int row;
  174256. JDIMENSION col;
  174257. JDIMENSION width = cinfo->output_width;
  174258. for (row = 0; row < num_rows; row++) {
  174259. inptr = input_buf[row];
  174260. outptr = output_buf[row];
  174261. for (col = width; col > 0; col--) {
  174262. /* get pixel value and index into the cache */
  174263. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  174264. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  174265. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  174266. cachep = & histogram[c0][c1][c2];
  174267. /* If we have not seen this color before, find nearest colormap entry */
  174268. /* and update the cache */
  174269. if (*cachep == 0)
  174270. fill_inverse_cmap(cinfo, c0,c1,c2);
  174271. /* Now emit the colormap index for this cell */
  174272. *outptr++ = (JSAMPLE) (*cachep - 1);
  174273. }
  174274. }
  174275. }
  174276. METHODDEF(void)
  174277. pass2_fs_dither (j_decompress_ptr cinfo,
  174278. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174279. /* This version performs Floyd-Steinberg dithering */
  174280. {
  174281. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174282. hist3d histogram = cquantize->histogram;
  174283. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  174284. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  174285. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  174286. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  174287. JSAMPROW inptr; /* => current input pixel */
  174288. JSAMPROW outptr; /* => current output pixel */
  174289. histptr cachep;
  174290. int dir; /* +1 or -1 depending on direction */
  174291. int dir3; /* 3*dir, for advancing inptr & errorptr */
  174292. int row;
  174293. JDIMENSION col;
  174294. JDIMENSION width = cinfo->output_width;
  174295. JSAMPLE *range_limit = cinfo->sample_range_limit;
  174296. int *error_limit = cquantize->error_limiter;
  174297. JSAMPROW colormap0 = cinfo->colormap[0];
  174298. JSAMPROW colormap1 = cinfo->colormap[1];
  174299. JSAMPROW colormap2 = cinfo->colormap[2];
  174300. SHIFT_TEMPS
  174301. for (row = 0; row < num_rows; row++) {
  174302. inptr = input_buf[row];
  174303. outptr = output_buf[row];
  174304. if (cquantize->on_odd_row) {
  174305. /* work right to left in this row */
  174306. inptr += (width-1) * 3; /* so point to rightmost pixel */
  174307. outptr += width-1;
  174308. dir = -1;
  174309. dir3 = -3;
  174310. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  174311. cquantize->on_odd_row = FALSE; /* flip for next time */
  174312. } else {
  174313. /* work left to right in this row */
  174314. dir = 1;
  174315. dir3 = 3;
  174316. errorptr = cquantize->fserrors; /* => entry before first real column */
  174317. cquantize->on_odd_row = TRUE; /* flip for next time */
  174318. }
  174319. /* Preset error values: no error propagated to first pixel from left */
  174320. cur0 = cur1 = cur2 = 0;
  174321. /* and no error propagated to row below yet */
  174322. belowerr0 = belowerr1 = belowerr2 = 0;
  174323. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  174324. for (col = width; col > 0; col--) {
  174325. /* curN holds the error propagated from the previous pixel on the
  174326. * current line. Add the error propagated from the previous line
  174327. * to form the complete error correction term for this pixel, and
  174328. * round the error term (which is expressed * 16) to an integer.
  174329. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  174330. * for either sign of the error value.
  174331. * Note: errorptr points to *previous* column's array entry.
  174332. */
  174333. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  174334. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  174335. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  174336. /* Limit the error using transfer function set by init_error_limit.
  174337. * See comments with init_error_limit for rationale.
  174338. */
  174339. cur0 = error_limit[cur0];
  174340. cur1 = error_limit[cur1];
  174341. cur2 = error_limit[cur2];
  174342. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  174343. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  174344. * this sets the required size of the range_limit array.
  174345. */
  174346. cur0 += GETJSAMPLE(inptr[0]);
  174347. cur1 += GETJSAMPLE(inptr[1]);
  174348. cur2 += GETJSAMPLE(inptr[2]);
  174349. cur0 = GETJSAMPLE(range_limit[cur0]);
  174350. cur1 = GETJSAMPLE(range_limit[cur1]);
  174351. cur2 = GETJSAMPLE(range_limit[cur2]);
  174352. /* Index into the cache with adjusted pixel value */
  174353. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  174354. /* If we have not seen this color before, find nearest colormap */
  174355. /* entry and update the cache */
  174356. if (*cachep == 0)
  174357. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  174358. /* Now emit the colormap index for this cell */
  174359. { register int pixcode = *cachep - 1;
  174360. *outptr = (JSAMPLE) pixcode;
  174361. /* Compute representation error for this pixel */
  174362. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  174363. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  174364. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  174365. }
  174366. /* Compute error fractions to be propagated to adjacent pixels.
  174367. * Add these into the running sums, and simultaneously shift the
  174368. * next-line error sums left by 1 column.
  174369. */
  174370. { register LOCFSERROR bnexterr, delta;
  174371. bnexterr = cur0; /* Process component 0 */
  174372. delta = cur0 * 2;
  174373. cur0 += delta; /* form error * 3 */
  174374. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  174375. cur0 += delta; /* form error * 5 */
  174376. bpreverr0 = belowerr0 + cur0;
  174377. belowerr0 = bnexterr;
  174378. cur0 += delta; /* form error * 7 */
  174379. bnexterr = cur1; /* Process component 1 */
  174380. delta = cur1 * 2;
  174381. cur1 += delta; /* form error * 3 */
  174382. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  174383. cur1 += delta; /* form error * 5 */
  174384. bpreverr1 = belowerr1 + cur1;
  174385. belowerr1 = bnexterr;
  174386. cur1 += delta; /* form error * 7 */
  174387. bnexterr = cur2; /* Process component 2 */
  174388. delta = cur2 * 2;
  174389. cur2 += delta; /* form error * 3 */
  174390. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  174391. cur2 += delta; /* form error * 5 */
  174392. bpreverr2 = belowerr2 + cur2;
  174393. belowerr2 = bnexterr;
  174394. cur2 += delta; /* form error * 7 */
  174395. }
  174396. /* At this point curN contains the 7/16 error value to be propagated
  174397. * to the next pixel on the current line, and all the errors for the
  174398. * next line have been shifted over. We are therefore ready to move on.
  174399. */
  174400. inptr += dir3; /* Advance pixel pointers to next column */
  174401. outptr += dir;
  174402. errorptr += dir3; /* advance errorptr to current column */
  174403. }
  174404. /* Post-loop cleanup: we must unload the final error values into the
  174405. * final fserrors[] entry. Note we need not unload belowerrN because
  174406. * it is for the dummy column before or after the actual array.
  174407. */
  174408. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  174409. errorptr[1] = (FSERROR) bpreverr1;
  174410. errorptr[2] = (FSERROR) bpreverr2;
  174411. }
  174412. }
  174413. /*
  174414. * Initialize the error-limiting transfer function (lookup table).
  174415. * The raw F-S error computation can potentially compute error values of up to
  174416. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  174417. * much less, otherwise obviously wrong pixels will be created. (Typical
  174418. * effects include weird fringes at color-area boundaries, isolated bright
  174419. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  174420. * is to ensure that the "corners" of the color cube are allocated as output
  174421. * colors; then repeated errors in the same direction cannot cause cascading
  174422. * error buildup. However, that only prevents the error from getting
  174423. * completely out of hand; Aaron Giles reports that error limiting improves
  174424. * the results even with corner colors allocated.
  174425. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  174426. * well, but the smoother transfer function used below is even better. Thanks
  174427. * to Aaron Giles for this idea.
  174428. */
  174429. LOCAL(void)
  174430. init_error_limit (j_decompress_ptr cinfo)
  174431. /* Allocate and fill in the error_limiter table */
  174432. {
  174433. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174434. int * table;
  174435. int in, out;
  174436. table = (int *) (*cinfo->mem->alloc_small)
  174437. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  174438. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  174439. cquantize->error_limiter = table;
  174440. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  174441. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  174442. out = 0;
  174443. for (in = 0; in < STEPSIZE; in++, out++) {
  174444. table[in] = out; table[-in] = -out;
  174445. }
  174446. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  174447. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  174448. table[in] = out; table[-in] = -out;
  174449. }
  174450. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  174451. for (; in <= MAXJSAMPLE; in++) {
  174452. table[in] = out; table[-in] = -out;
  174453. }
  174454. #undef STEPSIZE
  174455. }
  174456. /*
  174457. * Finish up at the end of each pass.
  174458. */
  174459. METHODDEF(void)
  174460. finish_pass1 (j_decompress_ptr cinfo)
  174461. {
  174462. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174463. /* Select the representative colors and fill in cinfo->colormap */
  174464. cinfo->colormap = cquantize->sv_colormap;
  174465. select_colors(cinfo, cquantize->desired);
  174466. /* Force next pass to zero the color index table */
  174467. cquantize->needs_zeroed = TRUE;
  174468. }
  174469. METHODDEF(void)
  174470. finish_pass2 (j_decompress_ptr cinfo)
  174471. {
  174472. /* no work */
  174473. }
  174474. /*
  174475. * Initialize for each processing pass.
  174476. */
  174477. METHODDEF(void)
  174478. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  174479. {
  174480. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174481. hist3d histogram = cquantize->histogram;
  174482. int i;
  174483. /* Only F-S dithering or no dithering is supported. */
  174484. /* If user asks for ordered dither, give him F-S. */
  174485. if (cinfo->dither_mode != JDITHER_NONE)
  174486. cinfo->dither_mode = JDITHER_FS;
  174487. if (is_pre_scan) {
  174488. /* Set up method pointers */
  174489. cquantize->pub.color_quantize = prescan_quantize;
  174490. cquantize->pub.finish_pass = finish_pass1;
  174491. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  174492. } else {
  174493. /* Set up method pointers */
  174494. if (cinfo->dither_mode == JDITHER_FS)
  174495. cquantize->pub.color_quantize = pass2_fs_dither;
  174496. else
  174497. cquantize->pub.color_quantize = pass2_no_dither;
  174498. cquantize->pub.finish_pass = finish_pass2;
  174499. /* Make sure color count is acceptable */
  174500. i = cinfo->actual_number_of_colors;
  174501. if (i < 1)
  174502. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  174503. if (i > MAXNUMCOLORS)
  174504. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174505. if (cinfo->dither_mode == JDITHER_FS) {
  174506. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  174507. (3 * SIZEOF(FSERROR)));
  174508. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  174509. if (cquantize->fserrors == NULL)
  174510. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174511. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174512. /* Initialize the propagated errors to zero. */
  174513. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  174514. /* Make the error-limit table if we didn't already. */
  174515. if (cquantize->error_limiter == NULL)
  174516. init_error_limit(cinfo);
  174517. cquantize->on_odd_row = FALSE;
  174518. }
  174519. }
  174520. /* Zero the histogram or inverse color map, if necessary */
  174521. if (cquantize->needs_zeroed) {
  174522. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174523. jzero_far((void FAR *) histogram[i],
  174524. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174525. }
  174526. cquantize->needs_zeroed = FALSE;
  174527. }
  174528. }
  174529. /*
  174530. * Switch to a new external colormap between output passes.
  174531. */
  174532. METHODDEF(void)
  174533. new_color_map_2_quant (j_decompress_ptr cinfo)
  174534. {
  174535. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174536. /* Reset the inverse color map */
  174537. cquantize->needs_zeroed = TRUE;
  174538. }
  174539. /*
  174540. * Module initialization routine for 2-pass color quantization.
  174541. */
  174542. GLOBAL(void)
  174543. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  174544. {
  174545. my_cquantize_ptr2 cquantize;
  174546. int i;
  174547. cquantize = (my_cquantize_ptr2)
  174548. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174549. SIZEOF(my_cquantizer2));
  174550. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174551. cquantize->pub.start_pass = start_pass_2_quant;
  174552. cquantize->pub.new_color_map = new_color_map_2_quant;
  174553. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  174554. cquantize->error_limiter = NULL;
  174555. /* Make sure jdmaster didn't give me a case I can't handle */
  174556. if (cinfo->out_color_components != 3)
  174557. ERREXIT(cinfo, JERR_NOTIMPL);
  174558. /* Allocate the histogram/inverse colormap storage */
  174559. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  174560. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  174561. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174562. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  174563. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174564. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174565. }
  174566. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  174567. /* Allocate storage for the completed colormap, if required.
  174568. * We do this now since it is FAR storage and may affect
  174569. * the memory manager's space calculations.
  174570. */
  174571. if (cinfo->enable_2pass_quant) {
  174572. /* Make sure color count is acceptable */
  174573. int desired = cinfo->desired_number_of_colors;
  174574. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  174575. if (desired < 8)
  174576. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  174577. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174578. if (desired > MAXNUMCOLORS)
  174579. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174580. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  174581. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  174582. cquantize->desired = desired;
  174583. } else
  174584. cquantize->sv_colormap = NULL;
  174585. /* Only F-S dithering or no dithering is supported. */
  174586. /* If user asks for ordered dither, give him F-S. */
  174587. if (cinfo->dither_mode != JDITHER_NONE)
  174588. cinfo->dither_mode = JDITHER_FS;
  174589. /* Allocate Floyd-Steinberg workspace if necessary.
  174590. * This isn't really needed until pass 2, but again it is FAR storage.
  174591. * Although we will cope with a later change in dither_mode,
  174592. * we do not promise to honor max_memory_to_use if dither_mode changes.
  174593. */
  174594. if (cinfo->dither_mode == JDITHER_FS) {
  174595. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174596. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174597. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  174598. /* Might as well create the error-limiting table too. */
  174599. init_error_limit(cinfo);
  174600. }
  174601. }
  174602. #endif /* QUANT_2PASS_SUPPORTED */
  174603. /********* End of inlined file: jquant2.c *********/
  174604. /********* Start of inlined file: jutils.c *********/
  174605. #define JPEG_INTERNALS
  174606. /*
  174607. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  174608. * of a DCT block read in natural order (left to right, top to bottom).
  174609. */
  174610. #if 0 /* This table is not actually needed in v6a */
  174611. const int jpeg_zigzag_order[DCTSIZE2] = {
  174612. 0, 1, 5, 6, 14, 15, 27, 28,
  174613. 2, 4, 7, 13, 16, 26, 29, 42,
  174614. 3, 8, 12, 17, 25, 30, 41, 43,
  174615. 9, 11, 18, 24, 31, 40, 44, 53,
  174616. 10, 19, 23, 32, 39, 45, 52, 54,
  174617. 20, 22, 33, 38, 46, 51, 55, 60,
  174618. 21, 34, 37, 47, 50, 56, 59, 61,
  174619. 35, 36, 48, 49, 57, 58, 62, 63
  174620. };
  174621. #endif
  174622. /*
  174623. * jpeg_natural_order[i] is the natural-order position of the i'th element
  174624. * of zigzag order.
  174625. *
  174626. * When reading corrupted data, the Huffman decoders could attempt
  174627. * to reference an entry beyond the end of this array (if the decoded
  174628. * zero run length reaches past the end of the block). To prevent
  174629. * wild stores without adding an inner-loop test, we put some extra
  174630. * "63"s after the real entries. This will cause the extra coefficient
  174631. * to be stored in location 63 of the block, not somewhere random.
  174632. * The worst case would be a run-length of 15, which means we need 16
  174633. * fake entries.
  174634. */
  174635. const int jpeg_natural_order[DCTSIZE2+16] = {
  174636. 0, 1, 8, 16, 9, 2, 3, 10,
  174637. 17, 24, 32, 25, 18, 11, 4, 5,
  174638. 12, 19, 26, 33, 40, 48, 41, 34,
  174639. 27, 20, 13, 6, 7, 14, 21, 28,
  174640. 35, 42, 49, 56, 57, 50, 43, 36,
  174641. 29, 22, 15, 23, 30, 37, 44, 51,
  174642. 58, 59, 52, 45, 38, 31, 39, 46,
  174643. 53, 60, 61, 54, 47, 55, 62, 63,
  174644. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  174645. 63, 63, 63, 63, 63, 63, 63, 63
  174646. };
  174647. /*
  174648. * Arithmetic utilities
  174649. */
  174650. GLOBAL(long)
  174651. jdiv_round_up (long a, long b)
  174652. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  174653. /* Assumes a >= 0, b > 0 */
  174654. {
  174655. return (a + b - 1L) / b;
  174656. }
  174657. GLOBAL(long)
  174658. jround_up (long a, long b)
  174659. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  174660. /* Assumes a >= 0, b > 0 */
  174661. {
  174662. a += b - 1L;
  174663. return a - (a % b);
  174664. }
  174665. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  174666. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  174667. * are FAR and we're assuming a small-pointer memory model. However, some
  174668. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  174669. * in the small-model libraries. These will be used if USE_FMEM is defined.
  174670. * Otherwise, the routines below do it the hard way. (The performance cost
  174671. * is not all that great, because these routines aren't very heavily used.)
  174672. */
  174673. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  174674. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  174675. #define FMEMZERO(target,size) MEMZERO(target,size)
  174676. #else /* 80x86 case, define if we can */
  174677. #ifdef USE_FMEM
  174678. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  174679. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  174680. #endif
  174681. #endif
  174682. GLOBAL(void)
  174683. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  174684. JSAMPARRAY output_array, int dest_row,
  174685. int num_rows, JDIMENSION num_cols)
  174686. /* Copy some rows of samples from one place to another.
  174687. * num_rows rows are copied from input_array[source_row++]
  174688. * to output_array[dest_row++]; these areas may overlap for duplication.
  174689. * The source and destination arrays must be at least as wide as num_cols.
  174690. */
  174691. {
  174692. register JSAMPROW inptr, outptr;
  174693. #ifdef FMEMCOPY
  174694. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  174695. #else
  174696. register JDIMENSION count;
  174697. #endif
  174698. register int row;
  174699. input_array += source_row;
  174700. output_array += dest_row;
  174701. for (row = num_rows; row > 0; row--) {
  174702. inptr = *input_array++;
  174703. outptr = *output_array++;
  174704. #ifdef FMEMCOPY
  174705. FMEMCOPY(outptr, inptr, count);
  174706. #else
  174707. for (count = num_cols; count > 0; count--)
  174708. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  174709. #endif
  174710. }
  174711. }
  174712. GLOBAL(void)
  174713. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  174714. JDIMENSION num_blocks)
  174715. /* Copy a row of coefficient blocks from one place to another. */
  174716. {
  174717. #ifdef FMEMCOPY
  174718. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  174719. #else
  174720. register JCOEFPTR inptr, outptr;
  174721. register long count;
  174722. inptr = (JCOEFPTR) input_row;
  174723. outptr = (JCOEFPTR) output_row;
  174724. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  174725. *outptr++ = *inptr++;
  174726. }
  174727. #endif
  174728. }
  174729. GLOBAL(void)
  174730. jzero_far (void FAR * target, size_t bytestozero)
  174731. /* Zero out a chunk of FAR memory. */
  174732. /* This might be sample-array data, block-array data, or alloc_large data. */
  174733. {
  174734. #ifdef FMEMZERO
  174735. FMEMZERO(target, bytestozero);
  174736. #else
  174737. register char FAR * ptr = (char FAR *) target;
  174738. register size_t count;
  174739. for (count = bytestozero; count > 0; count--) {
  174740. *ptr++ = 0;
  174741. }
  174742. #endif
  174743. }
  174744. /********* End of inlined file: jutils.c *********/
  174745. /********* Start of inlined file: transupp.c *********/
  174746. /* Although this file really shouldn't have access to the library internals,
  174747. * it's helpful to let it call jround_up() and jcopy_block_row().
  174748. */
  174749. #define JPEG_INTERNALS
  174750. /********* Start of inlined file: transupp.h *********/
  174751. /* If you happen not to want the image transform support, disable it here */
  174752. #ifndef TRANSFORMS_SUPPORTED
  174753. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  174754. #endif
  174755. /* Short forms of external names for systems with brain-damaged linkers. */
  174756. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174757. #define jtransform_request_workspace jTrRequest
  174758. #define jtransform_adjust_parameters jTrAdjust
  174759. #define jtransform_execute_transformation jTrExec
  174760. #define jcopy_markers_setup jCMrkSetup
  174761. #define jcopy_markers_execute jCMrkExec
  174762. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174763. /*
  174764. * Codes for supported types of image transformations.
  174765. */
  174766. typedef enum {
  174767. JXFORM_NONE, /* no transformation */
  174768. JXFORM_FLIP_H, /* horizontal flip */
  174769. JXFORM_FLIP_V, /* vertical flip */
  174770. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  174771. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  174772. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  174773. JXFORM_ROT_180, /* 180-degree rotation */
  174774. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  174775. } JXFORM_CODE;
  174776. /*
  174777. * Although rotating and flipping data expressed as DCT coefficients is not
  174778. * hard, there is an asymmetry in the JPEG format specification for images
  174779. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  174780. * image edges are padded out to the next iMCU boundary with junk data; but
  174781. * no padding is possible at the top and left edges. If we were to flip
  174782. * the whole image including the pad data, then pad garbage would become
  174783. * visible at the top and/or left, and real pixels would disappear into the
  174784. * pad margins --- perhaps permanently, since encoders & decoders may not
  174785. * bother to preserve DCT blocks that appear to be completely outside the
  174786. * nominal image area. So, we have to exclude any partial iMCUs from the
  174787. * basic transformation.
  174788. *
  174789. * Transpose is the only transformation that can handle partial iMCUs at the
  174790. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  174791. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  174792. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  174793. * The other transforms are defined as combinations of these basic transforms
  174794. * and process edge blocks in a way that preserves the equivalence.
  174795. *
  174796. * The "trim" option causes untransformable partial iMCUs to be dropped;
  174797. * this is not strictly lossless, but it usually gives the best-looking
  174798. * result for odd-size images. Note that when this option is active,
  174799. * the expected mathematical equivalences between the transforms may not hold.
  174800. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  174801. * followed by -rot 180 -trim trims both edges.)
  174802. *
  174803. * We also offer a "force to grayscale" option, which simply discards the
  174804. * chrominance channels of a YCbCr image. This is lossless in the sense that
  174805. * the luminance channel is preserved exactly. It's not the same kind of
  174806. * thing as the rotate/flip transformations, but it's convenient to handle it
  174807. * as part of this package, mainly because the transformation routines have to
  174808. * be aware of the option to know how many components to work on.
  174809. */
  174810. typedef struct {
  174811. /* Options: set by caller */
  174812. JXFORM_CODE transform; /* image transform operator */
  174813. boolean trim; /* if TRUE, trim partial MCUs as needed */
  174814. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  174815. /* Internal workspace: caller should not touch these */
  174816. int num_components; /* # of components in workspace */
  174817. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  174818. } jpeg_transform_info;
  174819. #if TRANSFORMS_SUPPORTED
  174820. /* Request any required workspace */
  174821. EXTERN(void) jtransform_request_workspace
  174822. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  174823. /* Adjust output image parameters */
  174824. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  174825. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174826. jvirt_barray_ptr *src_coef_arrays,
  174827. jpeg_transform_info *info));
  174828. /* Execute the actual transformation, if any */
  174829. EXTERN(void) jtransform_execute_transformation
  174830. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174831. jvirt_barray_ptr *src_coef_arrays,
  174832. jpeg_transform_info *info));
  174833. #endif /* TRANSFORMS_SUPPORTED */
  174834. /*
  174835. * Support for copying optional markers from source to destination file.
  174836. */
  174837. typedef enum {
  174838. JCOPYOPT_NONE, /* copy no optional markers */
  174839. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  174840. JCOPYOPT_ALL /* copy all optional markers */
  174841. } JCOPY_OPTION;
  174842. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  174843. /* Setup decompression object to save desired markers in memory */
  174844. EXTERN(void) jcopy_markers_setup
  174845. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  174846. /* Copy markers saved in the given source object to the destination object */
  174847. EXTERN(void) jcopy_markers_execute
  174848. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174849. JCOPY_OPTION option));
  174850. /********* End of inlined file: transupp.h *********/
  174851. /* My own external interface */
  174852. #if TRANSFORMS_SUPPORTED
  174853. /*
  174854. * Lossless image transformation routines. These routines work on DCT
  174855. * coefficient arrays and thus do not require any lossy decompression
  174856. * or recompression of the image.
  174857. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  174858. *
  174859. * Horizontal flipping is done in-place, using a single top-to-bottom
  174860. * pass through the virtual source array. It will thus be much the
  174861. * fastest option for images larger than main memory.
  174862. *
  174863. * The other routines require a set of destination virtual arrays, so they
  174864. * need twice as much memory as jpegtran normally does. The destination
  174865. * arrays are always written in normal scan order (top to bottom) because
  174866. * the virtual array manager expects this. The source arrays will be scanned
  174867. * in the corresponding order, which means multiple passes through the source
  174868. * arrays for most of the transforms. That could result in much thrashing
  174869. * if the image is larger than main memory.
  174870. *
  174871. * Some notes about the operating environment of the individual transform
  174872. * routines:
  174873. * 1. Both the source and destination virtual arrays are allocated from the
  174874. * source JPEG object, and therefore should be manipulated by calling the
  174875. * source's memory manager.
  174876. * 2. The destination's component count should be used. It may be smaller
  174877. * than the source's when forcing to grayscale.
  174878. * 3. Likewise the destination's sampling factors should be used. When
  174879. * forcing to grayscale the destination's sampling factors will be all 1,
  174880. * and we may as well take that as the effective iMCU size.
  174881. * 4. When "trim" is in effect, the destination's dimensions will be the
  174882. * trimmed values but the source's will be untrimmed.
  174883. * 5. All the routines assume that the source and destination buffers are
  174884. * padded out to a full iMCU boundary. This is true, although for the
  174885. * source buffer it is an undocumented property of jdcoefct.c.
  174886. * Notes 2,3,4 boil down to this: generally we should use the destination's
  174887. * dimensions and ignore the source's.
  174888. */
  174889. LOCAL(void)
  174890. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174891. jvirt_barray_ptr *src_coef_arrays)
  174892. /* Horizontal flip; done in-place, so no separate dest array is required */
  174893. {
  174894. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  174895. int ci, k, offset_y;
  174896. JBLOCKARRAY buffer;
  174897. JCOEFPTR ptr1, ptr2;
  174898. JCOEF temp1, temp2;
  174899. jpeg_component_info *compptr;
  174900. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  174901. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  174902. * mirroring by changing the signs of odd-numbered columns.
  174903. * Partial iMCUs at the right edge are left untouched.
  174904. */
  174905. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174906. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174907. compptr = dstinfo->comp_info + ci;
  174908. comp_width = MCU_cols * compptr->h_samp_factor;
  174909. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  174910. blk_y += compptr->v_samp_factor) {
  174911. buffer = (*srcinfo->mem->access_virt_barray)
  174912. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  174913. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174914. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174915. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  174916. ptr1 = buffer[offset_y][blk_x];
  174917. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  174918. /* this unrolled loop doesn't need to know which row it's on... */
  174919. for (k = 0; k < DCTSIZE2; k += 2) {
  174920. temp1 = *ptr1; /* swap even column */
  174921. temp2 = *ptr2;
  174922. *ptr1++ = temp2;
  174923. *ptr2++ = temp1;
  174924. temp1 = *ptr1; /* swap odd column with sign change */
  174925. temp2 = *ptr2;
  174926. *ptr1++ = -temp2;
  174927. *ptr2++ = -temp1;
  174928. }
  174929. }
  174930. }
  174931. }
  174932. }
  174933. }
  174934. LOCAL(void)
  174935. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174936. jvirt_barray_ptr *src_coef_arrays,
  174937. jvirt_barray_ptr *dst_coef_arrays)
  174938. /* Vertical flip */
  174939. {
  174940. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174941. int ci, i, j, offset_y;
  174942. JBLOCKARRAY src_buffer, dst_buffer;
  174943. JBLOCKROW src_row_ptr, dst_row_ptr;
  174944. JCOEFPTR src_ptr, dst_ptr;
  174945. jpeg_component_info *compptr;
  174946. /* We output into a separate array because we can't touch different
  174947. * rows of the source virtual array simultaneously. Otherwise, this
  174948. * is a pretty straightforward analog of horizontal flip.
  174949. * Within a DCT block, vertical mirroring is done by changing the signs
  174950. * of odd-numbered rows.
  174951. * Partial iMCUs at the bottom edge are copied verbatim.
  174952. */
  174953. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174954. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174955. compptr = dstinfo->comp_info + ci;
  174956. comp_height = MCU_rows * compptr->v_samp_factor;
  174957. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174958. dst_blk_y += compptr->v_samp_factor) {
  174959. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174960. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174961. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174962. if (dst_blk_y < comp_height) {
  174963. /* Row is within the mirrorable area. */
  174964. src_buffer = (*srcinfo->mem->access_virt_barray)
  174965. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174966. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174967. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174968. } else {
  174969. /* Bottom-edge blocks will be copied verbatim. */
  174970. src_buffer = (*srcinfo->mem->access_virt_barray)
  174971. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174972. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174973. }
  174974. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174975. if (dst_blk_y < comp_height) {
  174976. /* Row is within the mirrorable area. */
  174977. dst_row_ptr = dst_buffer[offset_y];
  174978. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174979. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174980. dst_blk_x++) {
  174981. dst_ptr = dst_row_ptr[dst_blk_x];
  174982. src_ptr = src_row_ptr[dst_blk_x];
  174983. for (i = 0; i < DCTSIZE; i += 2) {
  174984. /* copy even row */
  174985. for (j = 0; j < DCTSIZE; j++)
  174986. *dst_ptr++ = *src_ptr++;
  174987. /* copy odd row with sign change */
  174988. for (j = 0; j < DCTSIZE; j++)
  174989. *dst_ptr++ = - *src_ptr++;
  174990. }
  174991. }
  174992. } else {
  174993. /* Just copy row verbatim. */
  174994. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  174995. compptr->width_in_blocks);
  174996. }
  174997. }
  174998. }
  174999. }
  175000. }
  175001. LOCAL(void)
  175002. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175003. jvirt_barray_ptr *src_coef_arrays,
  175004. jvirt_barray_ptr *dst_coef_arrays)
  175005. /* Transpose source into destination */
  175006. {
  175007. JDIMENSION dst_blk_x, dst_blk_y;
  175008. int ci, i, j, offset_x, offset_y;
  175009. JBLOCKARRAY src_buffer, dst_buffer;
  175010. JCOEFPTR src_ptr, dst_ptr;
  175011. jpeg_component_info *compptr;
  175012. /* Transposing pixels within a block just requires transposing the
  175013. * DCT coefficients.
  175014. * Partial iMCUs at the edges require no special treatment; we simply
  175015. * process all the available DCT blocks for every component.
  175016. */
  175017. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175018. compptr = dstinfo->comp_info + ci;
  175019. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175020. dst_blk_y += compptr->v_samp_factor) {
  175021. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175022. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175023. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175024. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175025. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175026. dst_blk_x += compptr->h_samp_factor) {
  175027. src_buffer = (*srcinfo->mem->access_virt_barray)
  175028. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175029. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175030. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175031. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175032. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175033. for (i = 0; i < DCTSIZE; i++)
  175034. for (j = 0; j < DCTSIZE; j++)
  175035. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175036. }
  175037. }
  175038. }
  175039. }
  175040. }
  175041. }
  175042. LOCAL(void)
  175043. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175044. jvirt_barray_ptr *src_coef_arrays,
  175045. jvirt_barray_ptr *dst_coef_arrays)
  175046. /* 90 degree rotation is equivalent to
  175047. * 1. Transposing the image;
  175048. * 2. Horizontal mirroring.
  175049. * These two steps are merged into a single processing routine.
  175050. */
  175051. {
  175052. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  175053. int ci, i, j, offset_x, offset_y;
  175054. JBLOCKARRAY src_buffer, dst_buffer;
  175055. JCOEFPTR src_ptr, dst_ptr;
  175056. jpeg_component_info *compptr;
  175057. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175058. * at the (output) right edge properly. They just get transposed and
  175059. * not mirrored.
  175060. */
  175061. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175062. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175063. compptr = dstinfo->comp_info + ci;
  175064. comp_width = MCU_cols * compptr->h_samp_factor;
  175065. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175066. dst_blk_y += compptr->v_samp_factor) {
  175067. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175068. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175069. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175070. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175071. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175072. dst_blk_x += compptr->h_samp_factor) {
  175073. src_buffer = (*srcinfo->mem->access_virt_barray)
  175074. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175075. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175076. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175077. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175078. if (dst_blk_x < comp_width) {
  175079. /* Block is within the mirrorable area. */
  175080. dst_ptr = dst_buffer[offset_y]
  175081. [comp_width - dst_blk_x - offset_x - 1];
  175082. for (i = 0; i < DCTSIZE; i++) {
  175083. for (j = 0; j < DCTSIZE; j++)
  175084. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175085. i++;
  175086. for (j = 0; j < DCTSIZE; j++)
  175087. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175088. }
  175089. } else {
  175090. /* Edge blocks are transposed but not mirrored. */
  175091. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175092. for (i = 0; i < DCTSIZE; i++)
  175093. for (j = 0; j < DCTSIZE; j++)
  175094. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175095. }
  175096. }
  175097. }
  175098. }
  175099. }
  175100. }
  175101. }
  175102. LOCAL(void)
  175103. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175104. jvirt_barray_ptr *src_coef_arrays,
  175105. jvirt_barray_ptr *dst_coef_arrays)
  175106. /* 270 degree rotation is equivalent to
  175107. * 1. Horizontal mirroring;
  175108. * 2. Transposing the image.
  175109. * These two steps are merged into a single processing routine.
  175110. */
  175111. {
  175112. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  175113. int ci, i, j, offset_x, offset_y;
  175114. JBLOCKARRAY src_buffer, dst_buffer;
  175115. JCOEFPTR src_ptr, dst_ptr;
  175116. jpeg_component_info *compptr;
  175117. /* Because of the horizontal mirror step, we can't process partial iMCUs
  175118. * at the (output) bottom edge properly. They just get transposed and
  175119. * not mirrored.
  175120. */
  175121. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175122. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175123. compptr = dstinfo->comp_info + ci;
  175124. comp_height = MCU_rows * compptr->v_samp_factor;
  175125. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175126. dst_blk_y += compptr->v_samp_factor) {
  175127. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175128. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175129. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175130. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175131. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175132. dst_blk_x += compptr->h_samp_factor) {
  175133. src_buffer = (*srcinfo->mem->access_virt_barray)
  175134. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175135. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175136. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175137. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175138. if (dst_blk_y < comp_height) {
  175139. /* Block is within the mirrorable area. */
  175140. src_ptr = src_buffer[offset_x]
  175141. [comp_height - dst_blk_y - offset_y - 1];
  175142. for (i = 0; i < DCTSIZE; i++) {
  175143. for (j = 0; j < DCTSIZE; j++) {
  175144. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175145. j++;
  175146. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175147. }
  175148. }
  175149. } else {
  175150. /* Edge blocks are transposed but not mirrored. */
  175151. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175152. for (i = 0; i < DCTSIZE; i++)
  175153. for (j = 0; j < DCTSIZE; j++)
  175154. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175155. }
  175156. }
  175157. }
  175158. }
  175159. }
  175160. }
  175161. }
  175162. LOCAL(void)
  175163. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175164. jvirt_barray_ptr *src_coef_arrays,
  175165. jvirt_barray_ptr *dst_coef_arrays)
  175166. /* 180 degree rotation is equivalent to
  175167. * 1. Vertical mirroring;
  175168. * 2. Horizontal mirroring.
  175169. * These two steps are merged into a single processing routine.
  175170. */
  175171. {
  175172. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175173. int ci, i, j, offset_y;
  175174. JBLOCKARRAY src_buffer, dst_buffer;
  175175. JBLOCKROW src_row_ptr, dst_row_ptr;
  175176. JCOEFPTR src_ptr, dst_ptr;
  175177. jpeg_component_info *compptr;
  175178. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175179. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175180. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175181. compptr = dstinfo->comp_info + ci;
  175182. comp_width = MCU_cols * compptr->h_samp_factor;
  175183. comp_height = MCU_rows * compptr->v_samp_factor;
  175184. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175185. dst_blk_y += compptr->v_samp_factor) {
  175186. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175187. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175188. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175189. if (dst_blk_y < comp_height) {
  175190. /* Row is within the vertically mirrorable area. */
  175191. src_buffer = (*srcinfo->mem->access_virt_barray)
  175192. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  175193. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  175194. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175195. } else {
  175196. /* Bottom-edge rows are only mirrored horizontally. */
  175197. src_buffer = (*srcinfo->mem->access_virt_barray)
  175198. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175199. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175200. }
  175201. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175202. if (dst_blk_y < comp_height) {
  175203. /* Row is within the mirrorable area. */
  175204. dst_row_ptr = dst_buffer[offset_y];
  175205. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175206. /* Process the blocks that can be mirrored both ways. */
  175207. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175208. dst_ptr = dst_row_ptr[dst_blk_x];
  175209. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175210. for (i = 0; i < DCTSIZE; i += 2) {
  175211. /* For even row, negate every odd column. */
  175212. for (j = 0; j < DCTSIZE; j += 2) {
  175213. *dst_ptr++ = *src_ptr++;
  175214. *dst_ptr++ = - *src_ptr++;
  175215. }
  175216. /* For odd row, negate every even column. */
  175217. for (j = 0; j < DCTSIZE; j += 2) {
  175218. *dst_ptr++ = - *src_ptr++;
  175219. *dst_ptr++ = *src_ptr++;
  175220. }
  175221. }
  175222. }
  175223. /* Any remaining right-edge blocks are only mirrored vertically. */
  175224. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175225. dst_ptr = dst_row_ptr[dst_blk_x];
  175226. src_ptr = src_row_ptr[dst_blk_x];
  175227. for (i = 0; i < DCTSIZE; i += 2) {
  175228. for (j = 0; j < DCTSIZE; j++)
  175229. *dst_ptr++ = *src_ptr++;
  175230. for (j = 0; j < DCTSIZE; j++)
  175231. *dst_ptr++ = - *src_ptr++;
  175232. }
  175233. }
  175234. } else {
  175235. /* Remaining rows are just mirrored horizontally. */
  175236. dst_row_ptr = dst_buffer[offset_y];
  175237. src_row_ptr = src_buffer[offset_y];
  175238. /* Process the blocks that can be mirrored. */
  175239. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175240. dst_ptr = dst_row_ptr[dst_blk_x];
  175241. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175242. for (i = 0; i < DCTSIZE2; i += 2) {
  175243. *dst_ptr++ = *src_ptr++;
  175244. *dst_ptr++ = - *src_ptr++;
  175245. }
  175246. }
  175247. /* Any remaining right-edge blocks are only copied. */
  175248. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175249. dst_ptr = dst_row_ptr[dst_blk_x];
  175250. src_ptr = src_row_ptr[dst_blk_x];
  175251. for (i = 0; i < DCTSIZE2; i++)
  175252. *dst_ptr++ = *src_ptr++;
  175253. }
  175254. }
  175255. }
  175256. }
  175257. }
  175258. }
  175259. LOCAL(void)
  175260. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175261. jvirt_barray_ptr *src_coef_arrays,
  175262. jvirt_barray_ptr *dst_coef_arrays)
  175263. /* Transverse transpose is equivalent to
  175264. * 1. 180 degree rotation;
  175265. * 2. Transposition;
  175266. * or
  175267. * 1. Horizontal mirroring;
  175268. * 2. Transposition;
  175269. * 3. Horizontal mirroring.
  175270. * These steps are merged into a single processing routine.
  175271. */
  175272. {
  175273. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175274. int ci, i, j, offset_x, offset_y;
  175275. JBLOCKARRAY src_buffer, dst_buffer;
  175276. JCOEFPTR src_ptr, dst_ptr;
  175277. jpeg_component_info *compptr;
  175278. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175279. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175280. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175281. compptr = dstinfo->comp_info + ci;
  175282. comp_width = MCU_cols * compptr->h_samp_factor;
  175283. comp_height = MCU_rows * compptr->v_samp_factor;
  175284. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175285. dst_blk_y += compptr->v_samp_factor) {
  175286. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175287. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175288. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175289. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175290. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175291. dst_blk_x += compptr->h_samp_factor) {
  175292. src_buffer = (*srcinfo->mem->access_virt_barray)
  175293. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175294. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175295. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175296. if (dst_blk_y < comp_height) {
  175297. src_ptr = src_buffer[offset_x]
  175298. [comp_height - dst_blk_y - offset_y - 1];
  175299. if (dst_blk_x < comp_width) {
  175300. /* Block is within the mirrorable area. */
  175301. dst_ptr = dst_buffer[offset_y]
  175302. [comp_width - dst_blk_x - offset_x - 1];
  175303. for (i = 0; i < DCTSIZE; i++) {
  175304. for (j = 0; j < DCTSIZE; j++) {
  175305. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175306. j++;
  175307. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175308. }
  175309. i++;
  175310. for (j = 0; j < DCTSIZE; j++) {
  175311. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175312. j++;
  175313. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175314. }
  175315. }
  175316. } else {
  175317. /* Right-edge blocks are mirrored in y only */
  175318. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175319. for (i = 0; i < DCTSIZE; i++) {
  175320. for (j = 0; j < DCTSIZE; j++) {
  175321. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175322. j++;
  175323. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175324. }
  175325. }
  175326. }
  175327. } else {
  175328. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175329. if (dst_blk_x < comp_width) {
  175330. /* Bottom-edge blocks are mirrored in x only */
  175331. dst_ptr = dst_buffer[offset_y]
  175332. [comp_width - dst_blk_x - offset_x - 1];
  175333. for (i = 0; i < DCTSIZE; i++) {
  175334. for (j = 0; j < DCTSIZE; j++)
  175335. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175336. i++;
  175337. for (j = 0; j < DCTSIZE; j++)
  175338. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175339. }
  175340. } else {
  175341. /* At lower right corner, just transpose, no mirroring */
  175342. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175343. for (i = 0; i < DCTSIZE; i++)
  175344. for (j = 0; j < DCTSIZE; j++)
  175345. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175346. }
  175347. }
  175348. }
  175349. }
  175350. }
  175351. }
  175352. }
  175353. }
  175354. /* Request any required workspace.
  175355. *
  175356. * We allocate the workspace virtual arrays from the source decompression
  175357. * object, so that all the arrays (both the original data and the workspace)
  175358. * will be taken into account while making memory management decisions.
  175359. * Hence, this routine must be called after jpeg_read_header (which reads
  175360. * the image dimensions) and before jpeg_read_coefficients (which realizes
  175361. * the source's virtual arrays).
  175362. */
  175363. GLOBAL(void)
  175364. jtransform_request_workspace (j_decompress_ptr srcinfo,
  175365. jpeg_transform_info *info)
  175366. {
  175367. jvirt_barray_ptr *coef_arrays = NULL;
  175368. jpeg_component_info *compptr;
  175369. int ci;
  175370. if (info->force_grayscale &&
  175371. srcinfo->jpeg_color_space == JCS_YCbCr &&
  175372. srcinfo->num_components == 3) {
  175373. /* We'll only process the first component */
  175374. info->num_components = 1;
  175375. } else {
  175376. /* Process all the components */
  175377. info->num_components = srcinfo->num_components;
  175378. }
  175379. switch (info->transform) {
  175380. case JXFORM_NONE:
  175381. case JXFORM_FLIP_H:
  175382. /* Don't need a workspace array */
  175383. break;
  175384. case JXFORM_FLIP_V:
  175385. case JXFORM_ROT_180:
  175386. /* Need workspace arrays having same dimensions as source image.
  175387. * Note that we allocate arrays padded out to the next iMCU boundary,
  175388. * so that transform routines need not worry about missing edge blocks.
  175389. */
  175390. coef_arrays = (jvirt_barray_ptr *)
  175391. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  175392. SIZEOF(jvirt_barray_ptr) * info->num_components);
  175393. for (ci = 0; ci < info->num_components; ci++) {
  175394. compptr = srcinfo->comp_info + ci;
  175395. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  175396. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  175397. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175398. (long) compptr->h_samp_factor),
  175399. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  175400. (long) compptr->v_samp_factor),
  175401. (JDIMENSION) compptr->v_samp_factor);
  175402. }
  175403. break;
  175404. case JXFORM_TRANSPOSE:
  175405. case JXFORM_TRANSVERSE:
  175406. case JXFORM_ROT_90:
  175407. case JXFORM_ROT_270:
  175408. /* Need workspace arrays having transposed dimensions.
  175409. * Note that we allocate arrays padded out to the next iMCU boundary,
  175410. * so that transform routines need not worry about missing edge blocks.
  175411. */
  175412. coef_arrays = (jvirt_barray_ptr *)
  175413. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  175414. SIZEOF(jvirt_barray_ptr) * info->num_components);
  175415. for (ci = 0; ci < info->num_components; ci++) {
  175416. compptr = srcinfo->comp_info + ci;
  175417. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  175418. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  175419. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  175420. (long) compptr->v_samp_factor),
  175421. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175422. (long) compptr->h_samp_factor),
  175423. (JDIMENSION) compptr->h_samp_factor);
  175424. }
  175425. break;
  175426. }
  175427. info->workspace_coef_arrays = coef_arrays;
  175428. }
  175429. /* Transpose destination image parameters */
  175430. LOCAL(void)
  175431. transpose_critical_parameters (j_compress_ptr dstinfo)
  175432. {
  175433. int tblno, i, j, ci, itemp;
  175434. jpeg_component_info *compptr;
  175435. JQUANT_TBL *qtblptr;
  175436. JDIMENSION dtemp;
  175437. UINT16 qtemp;
  175438. /* Transpose basic image dimensions */
  175439. dtemp = dstinfo->image_width;
  175440. dstinfo->image_width = dstinfo->image_height;
  175441. dstinfo->image_height = dtemp;
  175442. /* Transpose sampling factors */
  175443. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175444. compptr = dstinfo->comp_info + ci;
  175445. itemp = compptr->h_samp_factor;
  175446. compptr->h_samp_factor = compptr->v_samp_factor;
  175447. compptr->v_samp_factor = itemp;
  175448. }
  175449. /* Transpose quantization tables */
  175450. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  175451. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  175452. if (qtblptr != NULL) {
  175453. for (i = 0; i < DCTSIZE; i++) {
  175454. for (j = 0; j < i; j++) {
  175455. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  175456. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  175457. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  175458. }
  175459. }
  175460. }
  175461. }
  175462. }
  175463. /* Trim off any partial iMCUs on the indicated destination edge */
  175464. LOCAL(void)
  175465. trim_right_edge (j_compress_ptr dstinfo)
  175466. {
  175467. int ci, max_h_samp_factor;
  175468. JDIMENSION MCU_cols;
  175469. /* We have to compute max_h_samp_factor ourselves,
  175470. * because it hasn't been set yet in the destination
  175471. * (and we don't want to use the source's value).
  175472. */
  175473. max_h_samp_factor = 1;
  175474. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175475. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  175476. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  175477. }
  175478. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  175479. if (MCU_cols > 0) /* can't trim to 0 pixels */
  175480. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  175481. }
  175482. LOCAL(void)
  175483. trim_bottom_edge (j_compress_ptr dstinfo)
  175484. {
  175485. int ci, max_v_samp_factor;
  175486. JDIMENSION MCU_rows;
  175487. /* We have to compute max_v_samp_factor ourselves,
  175488. * because it hasn't been set yet in the destination
  175489. * (and we don't want to use the source's value).
  175490. */
  175491. max_v_samp_factor = 1;
  175492. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175493. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  175494. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  175495. }
  175496. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  175497. if (MCU_rows > 0) /* can't trim to 0 pixels */
  175498. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  175499. }
  175500. /* Adjust output image parameters as needed.
  175501. *
  175502. * This must be called after jpeg_copy_critical_parameters()
  175503. * and before jpeg_write_coefficients().
  175504. *
  175505. * The return value is the set of virtual coefficient arrays to be written
  175506. * (either the ones allocated by jtransform_request_workspace, or the
  175507. * original source data arrays). The caller will need to pass this value
  175508. * to jpeg_write_coefficients().
  175509. */
  175510. GLOBAL(jvirt_barray_ptr *)
  175511. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  175512. j_compress_ptr dstinfo,
  175513. jvirt_barray_ptr *src_coef_arrays,
  175514. jpeg_transform_info *info)
  175515. {
  175516. /* If force-to-grayscale is requested, adjust destination parameters */
  175517. if (info->force_grayscale) {
  175518. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  175519. * properly. Among other things, the target h_samp_factor & v_samp_factor
  175520. * will get set to 1, which typically won't match the source.
  175521. * In fact we do this even if the source is already grayscale; that
  175522. * provides an easy way of coercing a grayscale JPEG with funny sampling
  175523. * factors to the customary 1,1. (Some decoders fail on other factors.)
  175524. */
  175525. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  175526. dstinfo->num_components == 3) ||
  175527. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  175528. dstinfo->num_components == 1)) {
  175529. /* We have to preserve the source's quantization table number. */
  175530. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  175531. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  175532. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  175533. } else {
  175534. /* Sorry, can't do it */
  175535. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  175536. }
  175537. }
  175538. /* Correct the destination's image dimensions etc if necessary */
  175539. switch (info->transform) {
  175540. case JXFORM_NONE:
  175541. /* Nothing to do */
  175542. break;
  175543. case JXFORM_FLIP_H:
  175544. if (info->trim)
  175545. trim_right_edge(dstinfo);
  175546. break;
  175547. case JXFORM_FLIP_V:
  175548. if (info->trim)
  175549. trim_bottom_edge(dstinfo);
  175550. break;
  175551. case JXFORM_TRANSPOSE:
  175552. transpose_critical_parameters(dstinfo);
  175553. /* transpose does NOT have to trim anything */
  175554. break;
  175555. case JXFORM_TRANSVERSE:
  175556. transpose_critical_parameters(dstinfo);
  175557. if (info->trim) {
  175558. trim_right_edge(dstinfo);
  175559. trim_bottom_edge(dstinfo);
  175560. }
  175561. break;
  175562. case JXFORM_ROT_90:
  175563. transpose_critical_parameters(dstinfo);
  175564. if (info->trim)
  175565. trim_right_edge(dstinfo);
  175566. break;
  175567. case JXFORM_ROT_180:
  175568. if (info->trim) {
  175569. trim_right_edge(dstinfo);
  175570. trim_bottom_edge(dstinfo);
  175571. }
  175572. break;
  175573. case JXFORM_ROT_270:
  175574. transpose_critical_parameters(dstinfo);
  175575. if (info->trim)
  175576. trim_bottom_edge(dstinfo);
  175577. break;
  175578. }
  175579. /* Return the appropriate output data set */
  175580. if (info->workspace_coef_arrays != NULL)
  175581. return info->workspace_coef_arrays;
  175582. return src_coef_arrays;
  175583. }
  175584. /* Execute the actual transformation, if any.
  175585. *
  175586. * This must be called *after* jpeg_write_coefficients, because it depends
  175587. * on jpeg_write_coefficients to have computed subsidiary values such as
  175588. * the per-component width and height fields in the destination object.
  175589. *
  175590. * Note that some transformations will modify the source data arrays!
  175591. */
  175592. GLOBAL(void)
  175593. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  175594. j_compress_ptr dstinfo,
  175595. jvirt_barray_ptr *src_coef_arrays,
  175596. jpeg_transform_info *info)
  175597. {
  175598. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  175599. switch (info->transform) {
  175600. case JXFORM_NONE:
  175601. break;
  175602. case JXFORM_FLIP_H:
  175603. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  175604. break;
  175605. case JXFORM_FLIP_V:
  175606. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175607. break;
  175608. case JXFORM_TRANSPOSE:
  175609. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175610. break;
  175611. case JXFORM_TRANSVERSE:
  175612. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175613. break;
  175614. case JXFORM_ROT_90:
  175615. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175616. break;
  175617. case JXFORM_ROT_180:
  175618. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175619. break;
  175620. case JXFORM_ROT_270:
  175621. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175622. break;
  175623. }
  175624. }
  175625. #endif /* TRANSFORMS_SUPPORTED */
  175626. /* Setup decompression object to save desired markers in memory.
  175627. * This must be called before jpeg_read_header() to have the desired effect.
  175628. */
  175629. GLOBAL(void)
  175630. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  175631. {
  175632. #ifdef SAVE_MARKERS_SUPPORTED
  175633. int m;
  175634. /* Save comments except under NONE option */
  175635. if (option != JCOPYOPT_NONE) {
  175636. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  175637. }
  175638. /* Save all types of APPn markers iff ALL option */
  175639. if (option == JCOPYOPT_ALL) {
  175640. for (m = 0; m < 16; m++)
  175641. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  175642. }
  175643. #endif /* SAVE_MARKERS_SUPPORTED */
  175644. }
  175645. /* Copy markers saved in the given source object to the destination object.
  175646. * This should be called just after jpeg_start_compress() or
  175647. * jpeg_write_coefficients().
  175648. * Note that those routines will have written the SOI, and also the
  175649. * JFIF APP0 or Adobe APP14 markers if selected.
  175650. */
  175651. GLOBAL(void)
  175652. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175653. JCOPY_OPTION option)
  175654. {
  175655. jpeg_saved_marker_ptr marker;
  175656. /* In the current implementation, we don't actually need to examine the
  175657. * option flag here; we just copy everything that got saved.
  175658. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  175659. * if the encoder library already wrote one.
  175660. */
  175661. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  175662. if (dstinfo->write_JFIF_header &&
  175663. marker->marker == JPEG_APP0 &&
  175664. marker->data_length >= 5 &&
  175665. GETJOCTET(marker->data[0]) == 0x4A &&
  175666. GETJOCTET(marker->data[1]) == 0x46 &&
  175667. GETJOCTET(marker->data[2]) == 0x49 &&
  175668. GETJOCTET(marker->data[3]) == 0x46 &&
  175669. GETJOCTET(marker->data[4]) == 0)
  175670. continue; /* reject duplicate JFIF */
  175671. if (dstinfo->write_Adobe_marker &&
  175672. marker->marker == JPEG_APP0+14 &&
  175673. marker->data_length >= 5 &&
  175674. GETJOCTET(marker->data[0]) == 0x41 &&
  175675. GETJOCTET(marker->data[1]) == 0x64 &&
  175676. GETJOCTET(marker->data[2]) == 0x6F &&
  175677. GETJOCTET(marker->data[3]) == 0x62 &&
  175678. GETJOCTET(marker->data[4]) == 0x65)
  175679. continue; /* reject duplicate Adobe */
  175680. #ifdef NEED_FAR_POINTERS
  175681. /* We could use jpeg_write_marker if the data weren't FAR... */
  175682. {
  175683. unsigned int i;
  175684. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  175685. for (i = 0; i < marker->data_length; i++)
  175686. jpeg_write_m_byte(dstinfo, marker->data[i]);
  175687. }
  175688. #else
  175689. jpeg_write_marker(dstinfo, marker->marker,
  175690. marker->data, marker->data_length);
  175691. #endif
  175692. }
  175693. }
  175694. /********* End of inlined file: transupp.c *********/
  175695. }
  175696. #else
  175697. #define JPEG_INTERNALS
  175698. #undef FAR
  175699. #include <jpeglib.h>
  175700. #endif
  175701. }
  175702. #if JUCE_MSVC
  175703. #pragma warning (pop)
  175704. #endif
  175705. BEGIN_JUCE_NAMESPACE
  175706. using namespace jpeglibNamespace;
  175707. #if ! JUCE_MSVC
  175708. using jpeglibNamespace::boolean;
  175709. #endif
  175710. struct JPEGDecodingFailure {};
  175711. static void fatalErrorHandler (j_common_ptr)
  175712. {
  175713. throw JPEGDecodingFailure();
  175714. }
  175715. static void silentErrorCallback1 (j_common_ptr) {}
  175716. static void silentErrorCallback2 (j_common_ptr, int) {}
  175717. static void silentErrorCallback3 (j_common_ptr, char*) {}
  175718. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  175719. {
  175720. zerostruct (err);
  175721. err.error_exit = fatalErrorHandler;
  175722. err.emit_message = silentErrorCallback2;
  175723. err.output_message = silentErrorCallback1;
  175724. err.format_message = silentErrorCallback3;
  175725. err.reset_error_mgr = silentErrorCallback1;
  175726. }
  175727. static void dummyCallback1 (j_decompress_ptr) throw()
  175728. {
  175729. }
  175730. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  175731. {
  175732. decompStruct->src->next_input_byte += num;
  175733. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  175734. decompStruct->src->bytes_in_buffer -= num;
  175735. }
  175736. static boolean jpegFill (j_decompress_ptr) throw()
  175737. {
  175738. return 0;
  175739. }
  175740. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  175741. {
  175742. MemoryBlock mb;
  175743. in.readIntoMemoryBlock (mb);
  175744. Image* image = 0;
  175745. if (mb.getSize() > 16)
  175746. {
  175747. struct jpeg_decompress_struct jpegDecompStruct;
  175748. struct jpeg_error_mgr jerr;
  175749. setupSilentErrorHandler (jerr);
  175750. jpegDecompStruct.err = &jerr;
  175751. jpeg_create_decompress (&jpegDecompStruct);
  175752. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  175753. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  175754. jpegDecompStruct.src->init_source = dummyCallback1;
  175755. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  175756. jpegDecompStruct.src->skip_input_data = jpegSkip;
  175757. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  175758. jpegDecompStruct.src->term_source = dummyCallback1;
  175759. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  175760. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  175761. try
  175762. {
  175763. jpeg_read_header (&jpegDecompStruct, TRUE);
  175764. jpeg_calc_output_dimensions (&jpegDecompStruct);
  175765. const int width = jpegDecompStruct.output_width;
  175766. const int height = jpegDecompStruct.output_height;
  175767. jpegDecompStruct.out_color_space = JCS_RGB;
  175768. JSAMPARRAY buffer
  175769. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  175770. JPOOL_IMAGE,
  175771. width * 3, 1);
  175772. if (jpeg_start_decompress (&jpegDecompStruct))
  175773. {
  175774. image = new Image (Image::RGB, width, height, false);
  175775. for (int y = 0; y < height; ++y)
  175776. {
  175777. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  175778. int stride, pixelStride;
  175779. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  175780. const uint8* src = *buffer;
  175781. uint8* dest = pixels;
  175782. for (int i = width; --i >= 0;)
  175783. {
  175784. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  175785. dest += pixelStride;
  175786. src += 3;
  175787. }
  175788. image->releasePixelDataReadWrite (pixels);
  175789. }
  175790. jpeg_finish_decompress (&jpegDecompStruct);
  175791. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  175792. }
  175793. jpeg_destroy_decompress (&jpegDecompStruct);
  175794. }
  175795. catch (...)
  175796. {}
  175797. }
  175798. return image;
  175799. }
  175800. static const int bufferSize = 512;
  175801. struct JuceJpegDest : public jpeg_destination_mgr
  175802. {
  175803. OutputStream* output;
  175804. char* buffer;
  175805. };
  175806. static void jpegWriteInit (j_compress_ptr) throw()
  175807. {
  175808. }
  175809. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  175810. {
  175811. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175812. const int numToWrite = bufferSize - dest->free_in_buffer;
  175813. dest->output->write (dest->buffer, numToWrite);
  175814. }
  175815. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  175816. {
  175817. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175818. const int numToWrite = bufferSize;
  175819. dest->next_output_byte = (JOCTET*) dest->buffer;
  175820. dest->free_in_buffer = bufferSize;
  175821. return dest->output->write (dest->buffer, numToWrite);
  175822. }
  175823. bool juce_writeJPEGImageToStream (const Image& image,
  175824. OutputStream& out,
  175825. float quality) throw()
  175826. {
  175827. if (image.hasAlphaChannel())
  175828. {
  175829. // this method could fill the background in white and still save the image..
  175830. jassertfalse
  175831. return true;
  175832. }
  175833. struct jpeg_compress_struct jpegCompStruct;
  175834. struct jpeg_error_mgr jerr;
  175835. setupSilentErrorHandler (jerr);
  175836. jpegCompStruct.err = &jerr;
  175837. jpeg_create_compress (&jpegCompStruct);
  175838. JuceJpegDest dest;
  175839. jpegCompStruct.dest = &dest;
  175840. dest.output = &out;
  175841. dest.buffer = (char*) juce_malloc (bufferSize);
  175842. dest.next_output_byte = (JOCTET*) dest.buffer;
  175843. dest.free_in_buffer = bufferSize;
  175844. dest.init_destination = jpegWriteInit;
  175845. dest.empty_output_buffer = jpegWriteFlush;
  175846. dest.term_destination = jpegWriteTerminate;
  175847. jpegCompStruct.image_width = image.getWidth();
  175848. jpegCompStruct.image_height = image.getHeight();
  175849. jpegCompStruct.input_components = 3;
  175850. jpegCompStruct.in_color_space = JCS_RGB;
  175851. jpegCompStruct.write_JFIF_header = 1;
  175852. jpegCompStruct.X_density = 72;
  175853. jpegCompStruct.Y_density = 72;
  175854. jpeg_set_defaults (&jpegCompStruct);
  175855. jpegCompStruct.dct_method = JDCT_FLOAT;
  175856. jpegCompStruct.optimize_coding = 1;
  175857. // jpegCompStruct.smoothing_factor = 10;
  175858. if (quality < 0.0f)
  175859. quality = 0.85f;
  175860. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  175861. jpeg_start_compress (&jpegCompStruct, TRUE);
  175862. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  175863. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  175864. JPOOL_IMAGE,
  175865. strideBytes, 1);
  175866. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  175867. {
  175868. int stride, pixelStride;
  175869. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  175870. const uint8* src = pixels;
  175871. uint8* dst = *buffer;
  175872. for (int i = jpegCompStruct.image_width; --i >= 0;)
  175873. {
  175874. *dst++ = ((const PixelRGB*) src)->getRed();
  175875. *dst++ = ((const PixelRGB*) src)->getGreen();
  175876. *dst++ = ((const PixelRGB*) src)->getBlue();
  175877. src += pixelStride;
  175878. }
  175879. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  175880. image.releasePixelDataReadOnly (pixels);
  175881. }
  175882. jpeg_finish_compress (&jpegCompStruct);
  175883. jpeg_destroy_compress (&jpegCompStruct);
  175884. juce_free (dest.buffer);
  175885. out.flush();
  175886. return true;
  175887. }
  175888. END_JUCE_NAMESPACE
  175889. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  175890. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  175891. #ifdef _MSC_VER
  175892. #pragma warning (push)
  175893. #pragma warning (disable: 4390 4611)
  175894. #endif
  175895. namespace zlibNamespace
  175896. {
  175897. #if JUCE_INCLUDE_ZLIB_CODE
  175898. #undef OS_CODE
  175899. #undef fdopen
  175900. #undef OS_CODE
  175901. #else
  175902. #include <zlib.h>
  175903. #endif
  175904. }
  175905. namespace pnglibNamespace
  175906. {
  175907. using namespace zlibNamespace;
  175908. #if JUCE_INCLUDE_PNGLIB_CODE
  175909. #if _MSC_VER != 1310
  175910. using ::calloc; // (causes conflict in VS.NET 2003)
  175911. using ::malloc;
  175912. using ::free;
  175913. #endif
  175914. extern "C"
  175915. {
  175916. using ::abs;
  175917. #define PNG_INTERNAL
  175918. #define NO_DUMMY_DECL
  175919. #define PNG_SETJMP_NOT_SUPPORTED
  175920. /********* Start of inlined file: png.h *********/
  175921. /* png.h - header file for PNG reference library
  175922. *
  175923. * libpng version 1.2.21 - October 4, 2007
  175924. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175925. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175926. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175927. *
  175928. * Authors and maintainers:
  175929. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  175930. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  175931. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  175932. * See also "Contributing Authors", below.
  175933. *
  175934. * Note about libpng version numbers:
  175935. *
  175936. * Due to various miscommunications, unforeseen code incompatibilities
  175937. * and occasional factors outside the authors' control, version numbering
  175938. * on the library has not always been consistent and straightforward.
  175939. * The following table summarizes matters since version 0.89c, which was
  175940. * the first widely used release:
  175941. *
  175942. * source png.h png.h shared-lib
  175943. * version string int version
  175944. * ------- ------ ----- ----------
  175945. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  175946. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  175947. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  175948. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  175949. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  175950. * 0.97c 0.97 97 2.0.97
  175951. * 0.98 0.98 98 2.0.98
  175952. * 0.99 0.99 98 2.0.99
  175953. * 0.99a-m 0.99 99 2.0.99
  175954. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  175955. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  175956. * 1.0.1 png.h string is 10001 2.1.0
  175957. * 1.0.1a-e identical to the 10002 from here on, the shared library
  175958. * 1.0.2 source version) 10002 is 2.V where V is the source code
  175959. * 1.0.2a-b 10003 version, except as noted.
  175960. * 1.0.3 10003
  175961. * 1.0.3a-d 10004
  175962. * 1.0.4 10004
  175963. * 1.0.4a-f 10005
  175964. * 1.0.5 (+ 2 patches) 10005
  175965. * 1.0.5a-d 10006
  175966. * 1.0.5e-r 10100 (not source compatible)
  175967. * 1.0.5s-v 10006 (not binary compatible)
  175968. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  175969. * 1.0.6d-f 10007 (still binary incompatible)
  175970. * 1.0.6g 10007
  175971. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  175972. * 1.0.6i 10007 10.6i
  175973. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  175974. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  175975. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  175976. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  175977. * 1.0.7 1 10007 (still compatible)
  175978. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  175979. * 1.0.8rc1 1 10008 2.1.0.8rc1
  175980. * 1.0.8 1 10008 2.1.0.8
  175981. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  175982. * 1.0.9rc1 1 10009 2.1.0.9rc1
  175983. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  175984. * 1.0.9rc2 1 10009 2.1.0.9rc2
  175985. * 1.0.9 1 10009 2.1.0.9
  175986. * 1.0.10beta1 1 10010 2.1.0.10beta1
  175987. * 1.0.10rc1 1 10010 2.1.0.10rc1
  175988. * 1.0.10 1 10010 2.1.0.10
  175989. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  175990. * 1.0.11rc1 1 10011 2.1.0.11rc1
  175991. * 1.0.11 1 10011 2.1.0.11
  175992. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  175993. * 1.0.12rc1 2 10012 2.1.0.12rc1
  175994. * 1.0.12 2 10012 2.1.0.12
  175995. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  175996. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  175997. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  175998. * 1.2.0rc1 3 10200 3.1.2.0rc1
  175999. * 1.2.0 3 10200 3.1.2.0
  176000. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  176001. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  176002. * 1.2.1 3 10201 3.1.2.1
  176003. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  176004. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  176005. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  176006. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  176007. * 1.0.13 10 10013 10.so.0.1.0.13
  176008. * 1.2.2 12 10202 12.so.0.1.2.2
  176009. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  176010. * 1.2.3 12 10203 12.so.0.1.2.3
  176011. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  176012. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  176013. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  176014. * 1.0.14 10 10014 10.so.0.1.0.14
  176015. * 1.2.4 13 10204 12.so.0.1.2.4
  176016. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  176017. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  176018. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  176019. * 1.0.15 10 10015 10.so.0.1.0.15
  176020. * 1.2.5 13 10205 12.so.0.1.2.5
  176021. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  176022. * 1.0.16 10 10016 10.so.0.1.0.16
  176023. * 1.2.6 13 10206 12.so.0.1.2.6
  176024. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  176025. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  176026. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  176027. * 1.0.17 10 10017 10.so.0.1.0.17
  176028. * 1.2.7 13 10207 12.so.0.1.2.7
  176029. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  176030. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  176031. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  176032. * 1.0.18 10 10018 10.so.0.1.0.18
  176033. * 1.2.8 13 10208 12.so.0.1.2.8
  176034. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  176035. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  176036. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  176037. * 1.2.9 13 10209 12.so.0.9[.0]
  176038. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  176039. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  176040. * 1.2.10 13 10210 12.so.0.10[.0]
  176041. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  176042. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  176043. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  176044. * 1.0.19 10 10019 10.so.0.19[.0]
  176045. * 1.2.11 13 10211 12.so.0.11[.0]
  176046. * 1.0.20 10 10020 10.so.0.20[.0]
  176047. * 1.2.12 13 10212 12.so.0.12[.0]
  176048. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  176049. * 1.0.21 10 10021 10.so.0.21[.0]
  176050. * 1.2.13 13 10213 12.so.0.13[.0]
  176051. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  176052. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  176053. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  176054. * 1.0.22 10 10022 10.so.0.22[.0]
  176055. * 1.2.14 13 10214 12.so.0.14[.0]
  176056. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  176057. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  176058. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  176059. * 1.0.23 10 10023 10.so.0.23[.0]
  176060. * 1.2.15 13 10215 12.so.0.15[.0]
  176061. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  176062. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  176063. * 1.0.24 10 10024 10.so.0.24[.0]
  176064. * 1.2.16 13 10216 12.so.0.16[.0]
  176065. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  176066. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  176067. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  176068. * 1.0.25 10 10025 10.so.0.25[.0]
  176069. * 1.2.17 13 10217 12.so.0.17[.0]
  176070. * 1.0.26 10 10026 10.so.0.26[.0]
  176071. * 1.2.18 13 10218 12.so.0.18[.0]
  176072. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  176073. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  176074. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  176075. * 1.0.27 10 10027 10.so.0.27[.0]
  176076. * 1.2.19 13 10219 12.so.0.19[.0]
  176077. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  176078. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  176079. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  176080. * 1.0.28 10 10028 10.so.0.28[.0]
  176081. * 1.2.20 13 10220 12.so.0.20[.0]
  176082. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  176083. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  176084. * 1.0.29 10 10029 10.so.0.29[.0]
  176085. * 1.2.21 13 10221 12.so.0.21[.0]
  176086. *
  176087. * Henceforth the source version will match the shared-library major
  176088. * and minor numbers; the shared-library major version number will be
  176089. * used for changes in backward compatibility, as it is intended. The
  176090. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  176091. * for applications, is an unsigned integer of the form xyyzz corresponding
  176092. * to the source version x.y.z (leading zeros in y and z). Beta versions
  176093. * were given the previous public release number plus a letter, until
  176094. * version 1.0.6j; from then on they were given the upcoming public
  176095. * release number plus "betaNN" or "rcN".
  176096. *
  176097. * Binary incompatibility exists only when applications make direct access
  176098. * to the info_ptr or png_ptr members through png.h, and the compiled
  176099. * application is loaded with a different version of the library.
  176100. *
  176101. * DLLNUM will change each time there are forward or backward changes
  176102. * in binary compatibility (e.g., when a new feature is added).
  176103. *
  176104. * See libpng.txt or libpng.3 for more information. The PNG specification
  176105. * is available as a W3C Recommendation and as an ISO Specification,
  176106. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  176107. */
  176108. /*
  176109. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  176110. *
  176111. * If you modify libpng you may insert additional notices immediately following
  176112. * this sentence.
  176113. *
  176114. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  176115. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  176116. * distributed according to the same disclaimer and license as libpng-1.2.5
  176117. * with the following individual added to the list of Contributing Authors:
  176118. *
  176119. * Cosmin Truta
  176120. *
  176121. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  176122. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  176123. * distributed according to the same disclaimer and license as libpng-1.0.6
  176124. * with the following individuals added to the list of Contributing Authors:
  176125. *
  176126. * Simon-Pierre Cadieux
  176127. * Eric S. Raymond
  176128. * Gilles Vollant
  176129. *
  176130. * and with the following additions to the disclaimer:
  176131. *
  176132. * There is no warranty against interference with your enjoyment of the
  176133. * library or against infringement. There is no warranty that our
  176134. * efforts or the library will fulfill any of your particular purposes
  176135. * or needs. This library is provided with all faults, and the entire
  176136. * risk of satisfactory quality, performance, accuracy, and effort is with
  176137. * the user.
  176138. *
  176139. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  176140. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  176141. * distributed according to the same disclaimer and license as libpng-0.96,
  176142. * with the following individuals added to the list of Contributing Authors:
  176143. *
  176144. * Tom Lane
  176145. * Glenn Randers-Pehrson
  176146. * Willem van Schaik
  176147. *
  176148. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  176149. * Copyright (c) 1996, 1997 Andreas Dilger
  176150. * Distributed according to the same disclaimer and license as libpng-0.88,
  176151. * with the following individuals added to the list of Contributing Authors:
  176152. *
  176153. * John Bowler
  176154. * Kevin Bracey
  176155. * Sam Bushell
  176156. * Magnus Holmgren
  176157. * Greg Roelofs
  176158. * Tom Tanner
  176159. *
  176160. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  176161. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  176162. *
  176163. * For the purposes of this copyright and license, "Contributing Authors"
  176164. * is defined as the following set of individuals:
  176165. *
  176166. * Andreas Dilger
  176167. * Dave Martindale
  176168. * Guy Eric Schalnat
  176169. * Paul Schmidt
  176170. * Tim Wegner
  176171. *
  176172. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  176173. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  176174. * including, without limitation, the warranties of merchantability and of
  176175. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  176176. * assume no liability for direct, indirect, incidental, special, exemplary,
  176177. * or consequential damages, which may result from the use of the PNG
  176178. * Reference Library, even if advised of the possibility of such damage.
  176179. *
  176180. * Permission is hereby granted to use, copy, modify, and distribute this
  176181. * source code, or portions hereof, for any purpose, without fee, subject
  176182. * to the following restrictions:
  176183. *
  176184. * 1. The origin of this source code must not be misrepresented.
  176185. *
  176186. * 2. Altered versions must be plainly marked as such and
  176187. * must not be misrepresented as being the original source.
  176188. *
  176189. * 3. This Copyright notice may not be removed or altered from
  176190. * any source or altered source distribution.
  176191. *
  176192. * The Contributing Authors and Group 42, Inc. specifically permit, without
  176193. * fee, and encourage the use of this source code as a component to
  176194. * supporting the PNG file format in commercial products. If you use this
  176195. * source code in a product, acknowledgment is not required but would be
  176196. * appreciated.
  176197. */
  176198. /*
  176199. * A "png_get_copyright" function is available, for convenient use in "about"
  176200. * boxes and the like:
  176201. *
  176202. * printf("%s",png_get_copyright(NULL));
  176203. *
  176204. * Also, the PNG logo (in PNG format, of course) is supplied in the
  176205. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  176206. */
  176207. /*
  176208. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  176209. * certification mark of the Open Source Initiative.
  176210. */
  176211. /*
  176212. * The contributing authors would like to thank all those who helped
  176213. * with testing, bug fixes, and patience. This wouldn't have been
  176214. * possible without all of you.
  176215. *
  176216. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  176217. */
  176218. /*
  176219. * Y2K compliance in libpng:
  176220. * =========================
  176221. *
  176222. * October 4, 2007
  176223. *
  176224. * Since the PNG Development group is an ad-hoc body, we can't make
  176225. * an official declaration.
  176226. *
  176227. * This is your unofficial assurance that libpng from version 0.71 and
  176228. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  176229. * versions were also Y2K compliant.
  176230. *
  176231. * Libpng only has three year fields. One is a 2-byte unsigned integer
  176232. * that will hold years up to 65535. The other two hold the date in text
  176233. * format, and will hold years up to 9999.
  176234. *
  176235. * The integer is
  176236. * "png_uint_16 year" in png_time_struct.
  176237. *
  176238. * The strings are
  176239. * "png_charp time_buffer" in png_struct and
  176240. * "near_time_buffer", which is a local character string in png.c.
  176241. *
  176242. * There are seven time-related functions:
  176243. * png.c: png_convert_to_rfc_1123() in png.c
  176244. * (formerly png_convert_to_rfc_1152() in error)
  176245. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  176246. * png_convert_from_time_t() in pngwrite.c
  176247. * png_get_tIME() in pngget.c
  176248. * png_handle_tIME() in pngrutil.c, called in pngread.c
  176249. * png_set_tIME() in pngset.c
  176250. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  176251. *
  176252. * All handle dates properly in a Y2K environment. The
  176253. * png_convert_from_time_t() function calls gmtime() to convert from system
  176254. * clock time, which returns (year - 1900), which we properly convert to
  176255. * the full 4-digit year. There is a possibility that applications using
  176256. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  176257. * function, or that they are incorrectly passing only a 2-digit year
  176258. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  176259. * but this is not under our control. The libpng documentation has always
  176260. * stated that it works with 4-digit years, and the APIs have been
  176261. * documented as such.
  176262. *
  176263. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  176264. * integer to hold the year, and can hold years as large as 65535.
  176265. *
  176266. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  176267. * no date-related code.
  176268. *
  176269. * Glenn Randers-Pehrson
  176270. * libpng maintainer
  176271. * PNG Development Group
  176272. */
  176273. #ifndef PNG_H
  176274. #define PNG_H
  176275. /* This is not the place to learn how to use libpng. The file libpng.txt
  176276. * describes how to use libpng, and the file example.c summarizes it
  176277. * with some code on which to build. This file is useful for looking
  176278. * at the actual function definitions and structure components.
  176279. */
  176280. /* Version information for png.h - this should match the version in png.c */
  176281. #define PNG_LIBPNG_VER_STRING "1.2.21"
  176282. #define PNG_HEADER_VERSION_STRING \
  176283. " libpng version 1.2.21 - October 4, 2007\n"
  176284. #define PNG_LIBPNG_VER_SONUM 0
  176285. #define PNG_LIBPNG_VER_DLLNUM 13
  176286. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  176287. #define PNG_LIBPNG_VER_MAJOR 1
  176288. #define PNG_LIBPNG_VER_MINOR 2
  176289. #define PNG_LIBPNG_VER_RELEASE 21
  176290. /* This should match the numeric part of the final component of
  176291. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  176292. #define PNG_LIBPNG_VER_BUILD 0
  176293. /* Release Status */
  176294. #define PNG_LIBPNG_BUILD_ALPHA 1
  176295. #define PNG_LIBPNG_BUILD_BETA 2
  176296. #define PNG_LIBPNG_BUILD_RC 3
  176297. #define PNG_LIBPNG_BUILD_STABLE 4
  176298. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  176299. /* Release-Specific Flags */
  176300. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  176301. PNG_LIBPNG_BUILD_STABLE only */
  176302. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  176303. PNG_LIBPNG_BUILD_SPECIAL */
  176304. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  176305. PNG_LIBPNG_BUILD_PRIVATE */
  176306. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  176307. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  176308. * We must not include leading zeros.
  176309. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  176310. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  176311. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  176312. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  176313. #ifndef PNG_VERSION_INFO_ONLY
  176314. /* include the compression library's header */
  176315. #endif
  176316. /* include all user configurable info, including optional assembler routines */
  176317. /********* Start of inlined file: pngconf.h *********/
  176318. /* pngconf.h - machine configurable file for libpng
  176319. *
  176320. * libpng version 1.2.21 - October 4, 2007
  176321. * For conditions of distribution and use, see copyright notice in png.h
  176322. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  176323. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  176324. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  176325. */
  176326. /* Any machine specific code is near the front of this file, so if you
  176327. * are configuring libpng for a machine, you may want to read the section
  176328. * starting here down to where it starts to typedef png_color, png_text,
  176329. * and png_info.
  176330. */
  176331. #ifndef PNGCONF_H
  176332. #define PNGCONF_H
  176333. #define PNG_1_2_X
  176334. // These are some Juce config settings that should remove any unnecessary code bloat..
  176335. #define PNG_NO_STDIO 1
  176336. #define PNG_DEBUG 0
  176337. #define PNG_NO_WARNINGS 1
  176338. #define PNG_NO_ERROR_TEXT 1
  176339. #define PNG_NO_ERROR_NUMBERS 1
  176340. #define PNG_NO_USER_MEM 1
  176341. #define PNG_NO_READ_iCCP 1
  176342. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  176343. #define PNG_NO_READ_USER_CHUNKS 1
  176344. #define PNG_NO_READ_iTXt 1
  176345. #define PNG_NO_READ_sCAL 1
  176346. #define PNG_NO_READ_sPLT 1
  176347. #define png_error(a, b) png_err(a)
  176348. #define png_warning(a, b)
  176349. #define png_chunk_error(a, b) png_err(a)
  176350. #define png_chunk_warning(a, b)
  176351. /*
  176352. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  176353. * includes the resource compiler for Windows DLL configurations.
  176354. */
  176355. #ifdef PNG_USER_CONFIG
  176356. # ifndef PNG_USER_PRIVATEBUILD
  176357. # define PNG_USER_PRIVATEBUILD
  176358. # endif
  176359. #include "pngusr.h"
  176360. #endif
  176361. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  176362. #ifdef PNG_CONFIGURE_LIBPNG
  176363. #ifdef HAVE_CONFIG_H
  176364. #include "config.h"
  176365. #endif
  176366. #endif
  176367. /*
  176368. * Added at libpng-1.2.8
  176369. *
  176370. * If you create a private DLL you need to define in "pngusr.h" the followings:
  176371. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  176372. * the DLL was built>
  176373. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  176374. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  176375. * distinguish your DLL from those of the official release. These
  176376. * correspond to the trailing letters that come after the version
  176377. * number and must match your private DLL name>
  176378. * e.g. // private DLL "libpng13gx.dll"
  176379. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  176380. *
  176381. * The following macros are also at your disposal if you want to complete the
  176382. * DLL VERSIONINFO structure.
  176383. * - PNG_USER_VERSIONINFO_COMMENTS
  176384. * - PNG_USER_VERSIONINFO_COMPANYNAME
  176385. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  176386. */
  176387. #ifdef __STDC__
  176388. #ifdef SPECIALBUILD
  176389. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  176390. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  176391. #endif
  176392. #ifdef PRIVATEBUILD
  176393. # pragma message("PRIVATEBUILD is deprecated.\
  176394. Use PNG_USER_PRIVATEBUILD instead.")
  176395. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  176396. #endif
  176397. #endif /* __STDC__ */
  176398. #ifndef PNG_VERSION_INFO_ONLY
  176399. /* End of material added to libpng-1.2.8 */
  176400. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  176401. Restored at libpng-1.2.21 */
  176402. # define PNG_WARN_UNINITIALIZED_ROW 1
  176403. /* End of material added at libpng-1.2.19/1.2.21 */
  176404. /* This is the size of the compression buffer, and thus the size of
  176405. * an IDAT chunk. Make this whatever size you feel is best for your
  176406. * machine. One of these will be allocated per png_struct. When this
  176407. * is full, it writes the data to the disk, and does some other
  176408. * calculations. Making this an extremely small size will slow
  176409. * the library down, but you may want to experiment to determine
  176410. * where it becomes significant, if you are concerned with memory
  176411. * usage. Note that zlib allocates at least 32Kb also. For readers,
  176412. * this describes the size of the buffer available to read the data in.
  176413. * Unless this gets smaller than the size of a row (compressed),
  176414. * it should not make much difference how big this is.
  176415. */
  176416. #ifndef PNG_ZBUF_SIZE
  176417. # define PNG_ZBUF_SIZE 8192
  176418. #endif
  176419. /* Enable if you want a write-only libpng */
  176420. #ifndef PNG_NO_READ_SUPPORTED
  176421. # define PNG_READ_SUPPORTED
  176422. #endif
  176423. /* Enable if you want a read-only libpng */
  176424. #ifndef PNG_NO_WRITE_SUPPORTED
  176425. # define PNG_WRITE_SUPPORTED
  176426. #endif
  176427. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  176428. support PNGs that are embedded in MNG datastreams */
  176429. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  176430. # ifndef PNG_MNG_FEATURES_SUPPORTED
  176431. # define PNG_MNG_FEATURES_SUPPORTED
  176432. # endif
  176433. #endif
  176434. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  176435. # ifndef PNG_FLOATING_POINT_SUPPORTED
  176436. # define PNG_FLOATING_POINT_SUPPORTED
  176437. # endif
  176438. #endif
  176439. /* If you are running on a machine where you cannot allocate more
  176440. * than 64K of memory at once, uncomment this. While libpng will not
  176441. * normally need that much memory in a chunk (unless you load up a very
  176442. * large file), zlib needs to know how big of a chunk it can use, and
  176443. * libpng thus makes sure to check any memory allocation to verify it
  176444. * will fit into memory.
  176445. #define PNG_MAX_MALLOC_64K
  176446. */
  176447. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  176448. # define PNG_MAX_MALLOC_64K
  176449. #endif
  176450. /* Special munging to support doing things the 'cygwin' way:
  176451. * 'Normal' png-on-win32 defines/defaults:
  176452. * PNG_BUILD_DLL -- building dll
  176453. * PNG_USE_DLL -- building an application, linking to dll
  176454. * (no define) -- building static library, or building an
  176455. * application and linking to the static lib
  176456. * 'Cygwin' defines/defaults:
  176457. * PNG_BUILD_DLL -- (ignored) building the dll
  176458. * (no define) -- (ignored) building an application, linking to the dll
  176459. * PNG_STATIC -- (ignored) building the static lib, or building an
  176460. * application that links to the static lib.
  176461. * ALL_STATIC -- (ignored) building various static libs, or building an
  176462. * application that links to the static libs.
  176463. * Thus,
  176464. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  176465. * this bit of #ifdefs will define the 'correct' config variables based on
  176466. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  176467. * unnecessary.
  176468. *
  176469. * Also, the precedence order is:
  176470. * ALL_STATIC (since we can't #undef something outside our namespace)
  176471. * PNG_BUILD_DLL
  176472. * PNG_STATIC
  176473. * (nothing) == PNG_USE_DLL
  176474. *
  176475. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  176476. * of auto-import in binutils, we no longer need to worry about
  176477. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  176478. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  176479. * to __declspec() stuff. However, we DO need to worry about
  176480. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  176481. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  176482. */
  176483. #if defined(__CYGWIN__)
  176484. # if defined(ALL_STATIC)
  176485. # if defined(PNG_BUILD_DLL)
  176486. # undef PNG_BUILD_DLL
  176487. # endif
  176488. # if defined(PNG_USE_DLL)
  176489. # undef PNG_USE_DLL
  176490. # endif
  176491. # if defined(PNG_DLL)
  176492. # undef PNG_DLL
  176493. # endif
  176494. # if !defined(PNG_STATIC)
  176495. # define PNG_STATIC
  176496. # endif
  176497. # else
  176498. # if defined (PNG_BUILD_DLL)
  176499. # if defined(PNG_STATIC)
  176500. # undef PNG_STATIC
  176501. # endif
  176502. # if defined(PNG_USE_DLL)
  176503. # undef PNG_USE_DLL
  176504. # endif
  176505. # if !defined(PNG_DLL)
  176506. # define PNG_DLL
  176507. # endif
  176508. # else
  176509. # if defined(PNG_STATIC)
  176510. # if defined(PNG_USE_DLL)
  176511. # undef PNG_USE_DLL
  176512. # endif
  176513. # if defined(PNG_DLL)
  176514. # undef PNG_DLL
  176515. # endif
  176516. # else
  176517. # if !defined(PNG_USE_DLL)
  176518. # define PNG_USE_DLL
  176519. # endif
  176520. # if !defined(PNG_DLL)
  176521. # define PNG_DLL
  176522. # endif
  176523. # endif
  176524. # endif
  176525. # endif
  176526. #endif
  176527. /* This protects us against compilers that run on a windowing system
  176528. * and thus don't have or would rather us not use the stdio types:
  176529. * stdin, stdout, and stderr. The only one currently used is stderr
  176530. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  176531. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  176532. * will also prevent these, plus will prevent the entire set of stdio
  176533. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  176534. * unless (PNG_DEBUG > 0) has been #defined.
  176535. *
  176536. * #define PNG_NO_CONSOLE_IO
  176537. * #define PNG_NO_STDIO
  176538. */
  176539. #if defined(_WIN32_WCE)
  176540. # include <windows.h>
  176541. /* Console I/O functions are not supported on WindowsCE */
  176542. # define PNG_NO_CONSOLE_IO
  176543. # ifdef PNG_DEBUG
  176544. # undef PNG_DEBUG
  176545. # endif
  176546. #endif
  176547. #ifdef PNG_BUILD_DLL
  176548. # ifndef PNG_CONSOLE_IO_SUPPORTED
  176549. # ifndef PNG_NO_CONSOLE_IO
  176550. # define PNG_NO_CONSOLE_IO
  176551. # endif
  176552. # endif
  176553. #endif
  176554. # ifdef PNG_NO_STDIO
  176555. # ifndef PNG_NO_CONSOLE_IO
  176556. # define PNG_NO_CONSOLE_IO
  176557. # endif
  176558. # ifdef PNG_DEBUG
  176559. # if (PNG_DEBUG > 0)
  176560. # include <stdio.h>
  176561. # endif
  176562. # endif
  176563. # else
  176564. # if !defined(_WIN32_WCE)
  176565. /* "stdio.h" functions are not supported on WindowsCE */
  176566. # include <stdio.h>
  176567. # endif
  176568. # endif
  176569. /* This macro protects us against machines that don't have function
  176570. * prototypes (ie K&R style headers). If your compiler does not handle
  176571. * function prototypes, define this macro and use the included ansi2knr.
  176572. * I've always been able to use _NO_PROTO as the indicator, but you may
  176573. * need to drag the empty declaration out in front of here, or change the
  176574. * ifdef to suit your own needs.
  176575. */
  176576. #ifndef PNGARG
  176577. #ifdef OF /* zlib prototype munger */
  176578. # define PNGARG(arglist) OF(arglist)
  176579. #else
  176580. #ifdef _NO_PROTO
  176581. # define PNGARG(arglist) ()
  176582. # ifndef PNG_TYPECAST_NULL
  176583. # define PNG_TYPECAST_NULL
  176584. # endif
  176585. #else
  176586. # define PNGARG(arglist) arglist
  176587. #endif /* _NO_PROTO */
  176588. #endif /* OF */
  176589. #endif /* PNGARG */
  176590. /* Try to determine if we are compiling on a Mac. Note that testing for
  176591. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  176592. * on non-Mac platforms.
  176593. */
  176594. #ifndef MACOS
  176595. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  176596. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  176597. # define MACOS
  176598. # endif
  176599. #endif
  176600. /* enough people need this for various reasons to include it here */
  176601. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  176602. # include <sys/types.h>
  176603. #endif
  176604. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  176605. # define PNG_SETJMP_SUPPORTED
  176606. #endif
  176607. #ifdef PNG_SETJMP_SUPPORTED
  176608. /* This is an attempt to force a single setjmp behaviour on Linux. If
  176609. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  176610. */
  176611. # ifdef __linux__
  176612. # ifdef _BSD_SOURCE
  176613. # define PNG_SAVE_BSD_SOURCE
  176614. # undef _BSD_SOURCE
  176615. # endif
  176616. # ifdef _SETJMP_H
  176617. /* If you encounter a compiler error here, see the explanation
  176618. * near the end of INSTALL.
  176619. */
  176620. __png.h__ already includes setjmp.h;
  176621. __dont__ include it again.;
  176622. # endif
  176623. # endif /* __linux__ */
  176624. /* include setjmp.h for error handling */
  176625. # include <setjmp.h>
  176626. # ifdef __linux__
  176627. # ifdef PNG_SAVE_BSD_SOURCE
  176628. # define _BSD_SOURCE
  176629. # undef PNG_SAVE_BSD_SOURCE
  176630. # endif
  176631. # endif /* __linux__ */
  176632. #endif /* PNG_SETJMP_SUPPORTED */
  176633. #ifdef BSD
  176634. #if ! JUCE_MAC
  176635. # include <strings.h>
  176636. #endif
  176637. #else
  176638. # include <string.h>
  176639. #endif
  176640. /* Other defines for things like memory and the like can go here. */
  176641. #ifdef PNG_INTERNAL
  176642. #include <stdlib.h>
  176643. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  176644. * aren't usually used outside the library (as far as I know), so it is
  176645. * debatable if they should be exported at all. In the future, when it is
  176646. * possible to have run-time registry of chunk-handling functions, some of
  176647. * these will be made available again.
  176648. #define PNG_EXTERN extern
  176649. */
  176650. #define PNG_EXTERN
  176651. /* Other defines specific to compilers can go here. Try to keep
  176652. * them inside an appropriate ifdef/endif pair for portability.
  176653. */
  176654. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  176655. # if defined(MACOS)
  176656. /* We need to check that <math.h> hasn't already been included earlier
  176657. * as it seems it doesn't agree with <fp.h>, yet we should really use
  176658. * <fp.h> if possible.
  176659. */
  176660. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  176661. # include <fp.h>
  176662. # endif
  176663. # else
  176664. # include <math.h>
  176665. # endif
  176666. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  176667. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  176668. * MATH=68881
  176669. */
  176670. # include <m68881.h>
  176671. # endif
  176672. #endif
  176673. /* Codewarrior on NT has linking problems without this. */
  176674. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  176675. # define PNG_ALWAYS_EXTERN
  176676. #endif
  176677. /* This provides the non-ANSI (far) memory allocation routines. */
  176678. #if defined(__TURBOC__) && defined(__MSDOS__)
  176679. # include <mem.h>
  176680. # include <alloc.h>
  176681. #endif
  176682. /* I have no idea why is this necessary... */
  176683. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  176684. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  176685. # include <malloc.h>
  176686. #endif
  176687. /* This controls how fine the dithering gets. As this allocates
  176688. * a largish chunk of memory (32K), those who are not as concerned
  176689. * with dithering quality can decrease some or all of these.
  176690. */
  176691. #ifndef PNG_DITHER_RED_BITS
  176692. # define PNG_DITHER_RED_BITS 5
  176693. #endif
  176694. #ifndef PNG_DITHER_GREEN_BITS
  176695. # define PNG_DITHER_GREEN_BITS 5
  176696. #endif
  176697. #ifndef PNG_DITHER_BLUE_BITS
  176698. # define PNG_DITHER_BLUE_BITS 5
  176699. #endif
  176700. /* This controls how fine the gamma correction becomes when you
  176701. * are only interested in 8 bits anyway. Increasing this value
  176702. * results in more memory being used, and more pow() functions
  176703. * being called to fill in the gamma tables. Don't set this value
  176704. * less then 8, and even that may not work (I haven't tested it).
  176705. */
  176706. #ifndef PNG_MAX_GAMMA_8
  176707. # define PNG_MAX_GAMMA_8 11
  176708. #endif
  176709. /* This controls how much a difference in gamma we can tolerate before
  176710. * we actually start doing gamma conversion.
  176711. */
  176712. #ifndef PNG_GAMMA_THRESHOLD
  176713. # define PNG_GAMMA_THRESHOLD 0.05
  176714. #endif
  176715. #endif /* PNG_INTERNAL */
  176716. /* The following uses const char * instead of char * for error
  176717. * and warning message functions, so some compilers won't complain.
  176718. * If you do not want to use const, define PNG_NO_CONST here.
  176719. */
  176720. #ifndef PNG_NO_CONST
  176721. # define PNG_CONST const
  176722. #else
  176723. # define PNG_CONST
  176724. #endif
  176725. /* The following defines give you the ability to remove code from the
  176726. * library that you will not be using. I wish I could figure out how to
  176727. * automate this, but I can't do that without making it seriously hard
  176728. * on the users. So if you are not using an ability, change the #define
  176729. * to and #undef, and that part of the library will not be compiled. If
  176730. * your linker can't find a function, you may want to make sure the
  176731. * ability is defined here. Some of these depend upon some others being
  176732. * defined. I haven't figured out all the interactions here, so you may
  176733. * have to experiment awhile to get everything to compile. If you are
  176734. * creating or using a shared library, you probably shouldn't touch this,
  176735. * as it will affect the size of the structures, and this will cause bad
  176736. * things to happen if the library and/or application ever change.
  176737. */
  176738. /* Any features you will not be using can be undef'ed here */
  176739. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  176740. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  176741. * on the compile line, then pick and choose which ones to define without
  176742. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  176743. * if you only want to have a png-compliant reader/writer but don't need
  176744. * any of the extra transformations. This saves about 80 kbytes in a
  176745. * typical installation of the library. (PNG_NO_* form added in version
  176746. * 1.0.1c, for consistency)
  176747. */
  176748. /* The size of the png_text structure changed in libpng-1.0.6 when
  176749. * iTXt support was added. iTXt support was turned off by default through
  176750. * libpng-1.2.x, to support old apps that malloc the png_text structure
  176751. * instead of calling png_set_text() and letting libpng malloc it. It
  176752. * was turned on by default in libpng-1.3.0.
  176753. */
  176754. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176755. # ifndef PNG_NO_iTXt_SUPPORTED
  176756. # define PNG_NO_iTXt_SUPPORTED
  176757. # endif
  176758. # ifndef PNG_NO_READ_iTXt
  176759. # define PNG_NO_READ_iTXt
  176760. # endif
  176761. # ifndef PNG_NO_WRITE_iTXt
  176762. # define PNG_NO_WRITE_iTXt
  176763. # endif
  176764. #endif
  176765. #if !defined(PNG_NO_iTXt_SUPPORTED)
  176766. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  176767. # define PNG_READ_iTXt
  176768. # endif
  176769. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  176770. # define PNG_WRITE_iTXt
  176771. # endif
  176772. #endif
  176773. /* The following support, added after version 1.0.0, can be turned off here en
  176774. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  176775. * with old applications that require the length of png_struct and png_info
  176776. * to remain unchanged.
  176777. */
  176778. #ifdef PNG_LEGACY_SUPPORTED
  176779. # define PNG_NO_FREE_ME
  176780. # define PNG_NO_READ_UNKNOWN_CHUNKS
  176781. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  176782. # define PNG_NO_READ_USER_CHUNKS
  176783. # define PNG_NO_READ_iCCP
  176784. # define PNG_NO_WRITE_iCCP
  176785. # define PNG_NO_READ_iTXt
  176786. # define PNG_NO_WRITE_iTXt
  176787. # define PNG_NO_READ_sCAL
  176788. # define PNG_NO_WRITE_sCAL
  176789. # define PNG_NO_READ_sPLT
  176790. # define PNG_NO_WRITE_sPLT
  176791. # define PNG_NO_INFO_IMAGE
  176792. # define PNG_NO_READ_RGB_TO_GRAY
  176793. # define PNG_NO_READ_USER_TRANSFORM
  176794. # define PNG_NO_WRITE_USER_TRANSFORM
  176795. # define PNG_NO_USER_MEM
  176796. # define PNG_NO_READ_EMPTY_PLTE
  176797. # define PNG_NO_MNG_FEATURES
  176798. # define PNG_NO_FIXED_POINT_SUPPORTED
  176799. #endif
  176800. /* Ignore attempt to turn off both floating and fixed point support */
  176801. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  176802. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  176803. # define PNG_FIXED_POINT_SUPPORTED
  176804. #endif
  176805. #ifndef PNG_NO_FREE_ME
  176806. # define PNG_FREE_ME_SUPPORTED
  176807. #endif
  176808. #if defined(PNG_READ_SUPPORTED)
  176809. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  176810. !defined(PNG_NO_READ_TRANSFORMS)
  176811. # define PNG_READ_TRANSFORMS_SUPPORTED
  176812. #endif
  176813. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  176814. # ifndef PNG_NO_READ_EXPAND
  176815. # define PNG_READ_EXPAND_SUPPORTED
  176816. # endif
  176817. # ifndef PNG_NO_READ_SHIFT
  176818. # define PNG_READ_SHIFT_SUPPORTED
  176819. # endif
  176820. # ifndef PNG_NO_READ_PACK
  176821. # define PNG_READ_PACK_SUPPORTED
  176822. # endif
  176823. # ifndef PNG_NO_READ_BGR
  176824. # define PNG_READ_BGR_SUPPORTED
  176825. # endif
  176826. # ifndef PNG_NO_READ_SWAP
  176827. # define PNG_READ_SWAP_SUPPORTED
  176828. # endif
  176829. # ifndef PNG_NO_READ_PACKSWAP
  176830. # define PNG_READ_PACKSWAP_SUPPORTED
  176831. # endif
  176832. # ifndef PNG_NO_READ_INVERT
  176833. # define PNG_READ_INVERT_SUPPORTED
  176834. # endif
  176835. # ifndef PNG_NO_READ_DITHER
  176836. # define PNG_READ_DITHER_SUPPORTED
  176837. # endif
  176838. # ifndef PNG_NO_READ_BACKGROUND
  176839. # define PNG_READ_BACKGROUND_SUPPORTED
  176840. # endif
  176841. # ifndef PNG_NO_READ_16_TO_8
  176842. # define PNG_READ_16_TO_8_SUPPORTED
  176843. # endif
  176844. # ifndef PNG_NO_READ_FILLER
  176845. # define PNG_READ_FILLER_SUPPORTED
  176846. # endif
  176847. # ifndef PNG_NO_READ_GAMMA
  176848. # define PNG_READ_GAMMA_SUPPORTED
  176849. # endif
  176850. # ifndef PNG_NO_READ_GRAY_TO_RGB
  176851. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  176852. # endif
  176853. # ifndef PNG_NO_READ_SWAP_ALPHA
  176854. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  176855. # endif
  176856. # ifndef PNG_NO_READ_INVERT_ALPHA
  176857. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  176858. # endif
  176859. # ifndef PNG_NO_READ_STRIP_ALPHA
  176860. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  176861. # endif
  176862. # ifndef PNG_NO_READ_USER_TRANSFORM
  176863. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  176864. # endif
  176865. # ifndef PNG_NO_READ_RGB_TO_GRAY
  176866. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  176867. # endif
  176868. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  176869. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  176870. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  176871. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  176872. #endif /* about interlacing capability! You'll */
  176873. /* still have interlacing unless you change the following line: */
  176874. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  176875. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  176876. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  176877. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  176878. # endif
  176879. #endif
  176880. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176881. /* Deprecated, will be removed from version 2.0.0.
  176882. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  176883. #ifndef PNG_NO_READ_EMPTY_PLTE
  176884. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  176885. #endif
  176886. #endif
  176887. #endif /* PNG_READ_SUPPORTED */
  176888. #if defined(PNG_WRITE_SUPPORTED)
  176889. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  176890. !defined(PNG_NO_WRITE_TRANSFORMS)
  176891. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  176892. #endif
  176893. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  176894. # ifndef PNG_NO_WRITE_SHIFT
  176895. # define PNG_WRITE_SHIFT_SUPPORTED
  176896. # endif
  176897. # ifndef PNG_NO_WRITE_PACK
  176898. # define PNG_WRITE_PACK_SUPPORTED
  176899. # endif
  176900. # ifndef PNG_NO_WRITE_BGR
  176901. # define PNG_WRITE_BGR_SUPPORTED
  176902. # endif
  176903. # ifndef PNG_NO_WRITE_SWAP
  176904. # define PNG_WRITE_SWAP_SUPPORTED
  176905. # endif
  176906. # ifndef PNG_NO_WRITE_PACKSWAP
  176907. # define PNG_WRITE_PACKSWAP_SUPPORTED
  176908. # endif
  176909. # ifndef PNG_NO_WRITE_INVERT
  176910. # define PNG_WRITE_INVERT_SUPPORTED
  176911. # endif
  176912. # ifndef PNG_NO_WRITE_FILLER
  176913. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  176914. # endif
  176915. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  176916. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  176917. # endif
  176918. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  176919. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  176920. # endif
  176921. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  176922. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  176923. # endif
  176924. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  176925. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  176926. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176927. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  176928. encoders, but can cause trouble
  176929. if left undefined */
  176930. #endif
  176931. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  176932. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  176933. defined(PNG_FLOATING_POINT_SUPPORTED)
  176934. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  176935. #endif
  176936. #ifndef PNG_NO_WRITE_FLUSH
  176937. # define PNG_WRITE_FLUSH_SUPPORTED
  176938. #endif
  176939. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176940. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  176941. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  176942. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  176943. #endif
  176944. #endif
  176945. #endif /* PNG_WRITE_SUPPORTED */
  176946. #ifndef PNG_1_0_X
  176947. # ifndef PNG_NO_ERROR_NUMBERS
  176948. # define PNG_ERROR_NUMBERS_SUPPORTED
  176949. # endif
  176950. #endif /* PNG_1_0_X */
  176951. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176952. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176953. # ifndef PNG_NO_USER_TRANSFORM_PTR
  176954. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  176955. # endif
  176956. #endif
  176957. #ifndef PNG_NO_STDIO
  176958. # define PNG_TIME_RFC1123_SUPPORTED
  176959. #endif
  176960. /* This adds extra functions in pngget.c for accessing data from the
  176961. * info pointer (added in version 0.99)
  176962. * png_get_image_width()
  176963. * png_get_image_height()
  176964. * png_get_bit_depth()
  176965. * png_get_color_type()
  176966. * png_get_compression_type()
  176967. * png_get_filter_type()
  176968. * png_get_interlace_type()
  176969. * png_get_pixel_aspect_ratio()
  176970. * png_get_pixels_per_meter()
  176971. * png_get_x_offset_pixels()
  176972. * png_get_y_offset_pixels()
  176973. * png_get_x_offset_microns()
  176974. * png_get_y_offset_microns()
  176975. */
  176976. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  176977. # define PNG_EASY_ACCESS_SUPPORTED
  176978. #endif
  176979. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  176980. * and removed from version 1.2.20. The following will be removed
  176981. * from libpng-1.4.0
  176982. */
  176983. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  176984. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  176985. # define PNG_OPTIMIZED_CODE_SUPPORTED
  176986. # endif
  176987. #endif
  176988. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  176989. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  176990. # define PNG_ASSEMBLER_CODE_SUPPORTED
  176991. # endif
  176992. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  176993. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  176994. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176995. # define PNG_NO_MMX_CODE
  176996. # endif
  176997. # endif
  176998. # if defined(__APPLE__)
  176999. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177000. # define PNG_NO_MMX_CODE
  177001. # endif
  177002. # endif
  177003. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  177004. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177005. # define PNG_NO_MMX_CODE
  177006. # endif
  177007. # endif
  177008. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  177009. # define PNG_MMX_CODE_SUPPORTED
  177010. # endif
  177011. #endif
  177012. /* end of obsolete code to be removed from libpng-1.4.0 */
  177013. #if !defined(PNG_1_0_X)
  177014. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  177015. # define PNG_USER_MEM_SUPPORTED
  177016. #endif
  177017. #endif /* PNG_1_0_X */
  177018. /* Added at libpng-1.2.6 */
  177019. #if !defined(PNG_1_0_X)
  177020. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  177021. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  177022. # define PNG_SET_USER_LIMITS_SUPPORTED
  177023. #endif
  177024. #endif
  177025. #endif /* PNG_1_0_X */
  177026. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  177027. * how large, set these limits to 0x7fffffffL
  177028. */
  177029. #ifndef PNG_USER_WIDTH_MAX
  177030. # define PNG_USER_WIDTH_MAX 1000000L
  177031. #endif
  177032. #ifndef PNG_USER_HEIGHT_MAX
  177033. # define PNG_USER_HEIGHT_MAX 1000000L
  177034. #endif
  177035. /* These are currently experimental features, define them if you want */
  177036. /* very little testing */
  177037. /*
  177038. #ifdef PNG_READ_SUPPORTED
  177039. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  177040. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  177041. # endif
  177042. #endif
  177043. */
  177044. /* This is only for PowerPC big-endian and 680x0 systems */
  177045. /* some testing */
  177046. /*
  177047. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  177048. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  177049. #endif
  177050. */
  177051. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  177052. /*
  177053. #define PNG_NO_POINTER_INDEXING
  177054. */
  177055. /* These functions are turned off by default, as they will be phased out. */
  177056. /*
  177057. #define PNG_USELESS_TESTS_SUPPORTED
  177058. #define PNG_CORRECT_PALETTE_SUPPORTED
  177059. */
  177060. /* Any chunks you are not interested in, you can undef here. The
  177061. * ones that allocate memory may be expecially important (hIST,
  177062. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  177063. * a bit smaller.
  177064. */
  177065. #if defined(PNG_READ_SUPPORTED) && \
  177066. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177067. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  177068. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177069. #endif
  177070. #if defined(PNG_WRITE_SUPPORTED) && \
  177071. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  177072. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  177073. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177074. #endif
  177075. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  177076. #ifdef PNG_NO_READ_TEXT
  177077. # define PNG_NO_READ_iTXt
  177078. # define PNG_NO_READ_tEXt
  177079. # define PNG_NO_READ_zTXt
  177080. #endif
  177081. #ifndef PNG_NO_READ_bKGD
  177082. # define PNG_READ_bKGD_SUPPORTED
  177083. # define PNG_bKGD_SUPPORTED
  177084. #endif
  177085. #ifndef PNG_NO_READ_cHRM
  177086. # define PNG_READ_cHRM_SUPPORTED
  177087. # define PNG_cHRM_SUPPORTED
  177088. #endif
  177089. #ifndef PNG_NO_READ_gAMA
  177090. # define PNG_READ_gAMA_SUPPORTED
  177091. # define PNG_gAMA_SUPPORTED
  177092. #endif
  177093. #ifndef PNG_NO_READ_hIST
  177094. # define PNG_READ_hIST_SUPPORTED
  177095. # define PNG_hIST_SUPPORTED
  177096. #endif
  177097. #ifndef PNG_NO_READ_iCCP
  177098. # define PNG_READ_iCCP_SUPPORTED
  177099. # define PNG_iCCP_SUPPORTED
  177100. #endif
  177101. #ifndef PNG_NO_READ_iTXt
  177102. # ifndef PNG_READ_iTXt_SUPPORTED
  177103. # define PNG_READ_iTXt_SUPPORTED
  177104. # endif
  177105. # ifndef PNG_iTXt_SUPPORTED
  177106. # define PNG_iTXt_SUPPORTED
  177107. # endif
  177108. #endif
  177109. #ifndef PNG_NO_READ_oFFs
  177110. # define PNG_READ_oFFs_SUPPORTED
  177111. # define PNG_oFFs_SUPPORTED
  177112. #endif
  177113. #ifndef PNG_NO_READ_pCAL
  177114. # define PNG_READ_pCAL_SUPPORTED
  177115. # define PNG_pCAL_SUPPORTED
  177116. #endif
  177117. #ifndef PNG_NO_READ_sCAL
  177118. # define PNG_READ_sCAL_SUPPORTED
  177119. # define PNG_sCAL_SUPPORTED
  177120. #endif
  177121. #ifndef PNG_NO_READ_pHYs
  177122. # define PNG_READ_pHYs_SUPPORTED
  177123. # define PNG_pHYs_SUPPORTED
  177124. #endif
  177125. #ifndef PNG_NO_READ_sBIT
  177126. # define PNG_READ_sBIT_SUPPORTED
  177127. # define PNG_sBIT_SUPPORTED
  177128. #endif
  177129. #ifndef PNG_NO_READ_sPLT
  177130. # define PNG_READ_sPLT_SUPPORTED
  177131. # define PNG_sPLT_SUPPORTED
  177132. #endif
  177133. #ifndef PNG_NO_READ_sRGB
  177134. # define PNG_READ_sRGB_SUPPORTED
  177135. # define PNG_sRGB_SUPPORTED
  177136. #endif
  177137. #ifndef PNG_NO_READ_tEXt
  177138. # define PNG_READ_tEXt_SUPPORTED
  177139. # define PNG_tEXt_SUPPORTED
  177140. #endif
  177141. #ifndef PNG_NO_READ_tIME
  177142. # define PNG_READ_tIME_SUPPORTED
  177143. # define PNG_tIME_SUPPORTED
  177144. #endif
  177145. #ifndef PNG_NO_READ_tRNS
  177146. # define PNG_READ_tRNS_SUPPORTED
  177147. # define PNG_tRNS_SUPPORTED
  177148. #endif
  177149. #ifndef PNG_NO_READ_zTXt
  177150. # define PNG_READ_zTXt_SUPPORTED
  177151. # define PNG_zTXt_SUPPORTED
  177152. #endif
  177153. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  177154. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  177155. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177156. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177157. # endif
  177158. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177159. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177160. # endif
  177161. #endif
  177162. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  177163. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  177164. # define PNG_READ_USER_CHUNKS_SUPPORTED
  177165. # define PNG_USER_CHUNKS_SUPPORTED
  177166. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  177167. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  177168. # endif
  177169. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  177170. # undef PNG_NO_HANDLE_AS_UNKNOWN
  177171. # endif
  177172. #endif
  177173. #ifndef PNG_NO_READ_OPT_PLTE
  177174. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  177175. #endif /* optional PLTE chunk in RGB and RGBA images */
  177176. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  177177. defined(PNG_READ_zTXt_SUPPORTED)
  177178. # define PNG_READ_TEXT_SUPPORTED
  177179. # define PNG_TEXT_SUPPORTED
  177180. #endif
  177181. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  177182. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177183. #ifdef PNG_NO_WRITE_TEXT
  177184. # define PNG_NO_WRITE_iTXt
  177185. # define PNG_NO_WRITE_tEXt
  177186. # define PNG_NO_WRITE_zTXt
  177187. #endif
  177188. #ifndef PNG_NO_WRITE_bKGD
  177189. # define PNG_WRITE_bKGD_SUPPORTED
  177190. # ifndef PNG_bKGD_SUPPORTED
  177191. # define PNG_bKGD_SUPPORTED
  177192. # endif
  177193. #endif
  177194. #ifndef PNG_NO_WRITE_cHRM
  177195. # define PNG_WRITE_cHRM_SUPPORTED
  177196. # ifndef PNG_cHRM_SUPPORTED
  177197. # define PNG_cHRM_SUPPORTED
  177198. # endif
  177199. #endif
  177200. #ifndef PNG_NO_WRITE_gAMA
  177201. # define PNG_WRITE_gAMA_SUPPORTED
  177202. # ifndef PNG_gAMA_SUPPORTED
  177203. # define PNG_gAMA_SUPPORTED
  177204. # endif
  177205. #endif
  177206. #ifndef PNG_NO_WRITE_hIST
  177207. # define PNG_WRITE_hIST_SUPPORTED
  177208. # ifndef PNG_hIST_SUPPORTED
  177209. # define PNG_hIST_SUPPORTED
  177210. # endif
  177211. #endif
  177212. #ifndef PNG_NO_WRITE_iCCP
  177213. # define PNG_WRITE_iCCP_SUPPORTED
  177214. # ifndef PNG_iCCP_SUPPORTED
  177215. # define PNG_iCCP_SUPPORTED
  177216. # endif
  177217. #endif
  177218. #ifndef PNG_NO_WRITE_iTXt
  177219. # ifndef PNG_WRITE_iTXt_SUPPORTED
  177220. # define PNG_WRITE_iTXt_SUPPORTED
  177221. # endif
  177222. # ifndef PNG_iTXt_SUPPORTED
  177223. # define PNG_iTXt_SUPPORTED
  177224. # endif
  177225. #endif
  177226. #ifndef PNG_NO_WRITE_oFFs
  177227. # define PNG_WRITE_oFFs_SUPPORTED
  177228. # ifndef PNG_oFFs_SUPPORTED
  177229. # define PNG_oFFs_SUPPORTED
  177230. # endif
  177231. #endif
  177232. #ifndef PNG_NO_WRITE_pCAL
  177233. # define PNG_WRITE_pCAL_SUPPORTED
  177234. # ifndef PNG_pCAL_SUPPORTED
  177235. # define PNG_pCAL_SUPPORTED
  177236. # endif
  177237. #endif
  177238. #ifndef PNG_NO_WRITE_sCAL
  177239. # define PNG_WRITE_sCAL_SUPPORTED
  177240. # ifndef PNG_sCAL_SUPPORTED
  177241. # define PNG_sCAL_SUPPORTED
  177242. # endif
  177243. #endif
  177244. #ifndef PNG_NO_WRITE_pHYs
  177245. # define PNG_WRITE_pHYs_SUPPORTED
  177246. # ifndef PNG_pHYs_SUPPORTED
  177247. # define PNG_pHYs_SUPPORTED
  177248. # endif
  177249. #endif
  177250. #ifndef PNG_NO_WRITE_sBIT
  177251. # define PNG_WRITE_sBIT_SUPPORTED
  177252. # ifndef PNG_sBIT_SUPPORTED
  177253. # define PNG_sBIT_SUPPORTED
  177254. # endif
  177255. #endif
  177256. #ifndef PNG_NO_WRITE_sPLT
  177257. # define PNG_WRITE_sPLT_SUPPORTED
  177258. # ifndef PNG_sPLT_SUPPORTED
  177259. # define PNG_sPLT_SUPPORTED
  177260. # endif
  177261. #endif
  177262. #ifndef PNG_NO_WRITE_sRGB
  177263. # define PNG_WRITE_sRGB_SUPPORTED
  177264. # ifndef PNG_sRGB_SUPPORTED
  177265. # define PNG_sRGB_SUPPORTED
  177266. # endif
  177267. #endif
  177268. #ifndef PNG_NO_WRITE_tEXt
  177269. # define PNG_WRITE_tEXt_SUPPORTED
  177270. # ifndef PNG_tEXt_SUPPORTED
  177271. # define PNG_tEXt_SUPPORTED
  177272. # endif
  177273. #endif
  177274. #ifndef PNG_NO_WRITE_tIME
  177275. # define PNG_WRITE_tIME_SUPPORTED
  177276. # ifndef PNG_tIME_SUPPORTED
  177277. # define PNG_tIME_SUPPORTED
  177278. # endif
  177279. #endif
  177280. #ifndef PNG_NO_WRITE_tRNS
  177281. # define PNG_WRITE_tRNS_SUPPORTED
  177282. # ifndef PNG_tRNS_SUPPORTED
  177283. # define PNG_tRNS_SUPPORTED
  177284. # endif
  177285. #endif
  177286. #ifndef PNG_NO_WRITE_zTXt
  177287. # define PNG_WRITE_zTXt_SUPPORTED
  177288. # ifndef PNG_zTXt_SUPPORTED
  177289. # define PNG_zTXt_SUPPORTED
  177290. # endif
  177291. #endif
  177292. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  177293. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  177294. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177295. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177296. # endif
  177297. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177298. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177299. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177300. # endif
  177301. # endif
  177302. #endif
  177303. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  177304. defined(PNG_WRITE_zTXt_SUPPORTED)
  177305. # define PNG_WRITE_TEXT_SUPPORTED
  177306. # ifndef PNG_TEXT_SUPPORTED
  177307. # define PNG_TEXT_SUPPORTED
  177308. # endif
  177309. #endif
  177310. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  177311. /* Turn this off to disable png_read_png() and
  177312. * png_write_png() and leave the row_pointers member
  177313. * out of the info structure.
  177314. */
  177315. #ifndef PNG_NO_INFO_IMAGE
  177316. # define PNG_INFO_IMAGE_SUPPORTED
  177317. #endif
  177318. /* need the time information for reading tIME chunks */
  177319. #if defined(PNG_tIME_SUPPORTED)
  177320. # if !defined(_WIN32_WCE)
  177321. /* "time.h" functions are not supported on WindowsCE */
  177322. # include <time.h>
  177323. # endif
  177324. #endif
  177325. /* Some typedefs to get us started. These should be safe on most of the
  177326. * common platforms. The typedefs should be at least as large as the
  177327. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  177328. * don't have to be exactly that size. Some compilers dislike passing
  177329. * unsigned shorts as function parameters, so you may be better off using
  177330. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  177331. * want to have unsigned int for png_uint_32 instead of unsigned long.
  177332. */
  177333. typedef unsigned long png_uint_32;
  177334. typedef long png_int_32;
  177335. typedef unsigned short png_uint_16;
  177336. typedef short png_int_16;
  177337. typedef unsigned char png_byte;
  177338. /* This is usually size_t. It is typedef'ed just in case you need it to
  177339. change (I'm not sure if you will or not, so I thought I'd be safe) */
  177340. #ifdef PNG_SIZE_T
  177341. typedef PNG_SIZE_T png_size_t;
  177342. # define png_sizeof(x) png_convert_size(sizeof (x))
  177343. #else
  177344. typedef size_t png_size_t;
  177345. # define png_sizeof(x) sizeof (x)
  177346. #endif
  177347. /* The following is needed for medium model support. It cannot be in the
  177348. * PNG_INTERNAL section. Needs modification for other compilers besides
  177349. * MSC. Model independent support declares all arrays and pointers to be
  177350. * large using the far keyword. The zlib version used must also support
  177351. * model independent data. As of version zlib 1.0.4, the necessary changes
  177352. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  177353. * changes that are needed. (Tim Wegner)
  177354. */
  177355. /* Separate compiler dependencies (problem here is that zlib.h always
  177356. defines FAR. (SJT) */
  177357. #ifdef __BORLANDC__
  177358. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  177359. # define LDATA 1
  177360. # else
  177361. # define LDATA 0
  177362. # endif
  177363. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  177364. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  177365. # define PNG_MAX_MALLOC_64K
  177366. # if (LDATA != 1)
  177367. # ifndef FAR
  177368. # define FAR __far
  177369. # endif
  177370. # define USE_FAR_KEYWORD
  177371. # endif /* LDATA != 1 */
  177372. /* Possibly useful for moving data out of default segment.
  177373. * Uncomment it if you want. Could also define FARDATA as
  177374. * const if your compiler supports it. (SJT)
  177375. # define FARDATA FAR
  177376. */
  177377. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  177378. #endif /* __BORLANDC__ */
  177379. /* Suggest testing for specific compiler first before testing for
  177380. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  177381. * making reliance oncertain keywords suspect. (SJT)
  177382. */
  177383. /* MSC Medium model */
  177384. #if defined(FAR)
  177385. # if defined(M_I86MM)
  177386. # define USE_FAR_KEYWORD
  177387. # define FARDATA FAR
  177388. # include <dos.h>
  177389. # endif
  177390. #endif
  177391. /* SJT: default case */
  177392. #ifndef FAR
  177393. # define FAR
  177394. #endif
  177395. /* At this point FAR is always defined */
  177396. #ifndef FARDATA
  177397. # define FARDATA
  177398. #endif
  177399. /* Typedef for floating-point numbers that are converted
  177400. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  177401. typedef png_int_32 png_fixed_point;
  177402. /* Add typedefs for pointers */
  177403. typedef void FAR * png_voidp;
  177404. typedef png_byte FAR * png_bytep;
  177405. typedef png_uint_32 FAR * png_uint_32p;
  177406. typedef png_int_32 FAR * png_int_32p;
  177407. typedef png_uint_16 FAR * png_uint_16p;
  177408. typedef png_int_16 FAR * png_int_16p;
  177409. typedef PNG_CONST char FAR * png_const_charp;
  177410. typedef char FAR * png_charp;
  177411. typedef png_fixed_point FAR * png_fixed_point_p;
  177412. #ifndef PNG_NO_STDIO
  177413. #if defined(_WIN32_WCE)
  177414. typedef HANDLE png_FILE_p;
  177415. #else
  177416. typedef FILE * png_FILE_p;
  177417. #endif
  177418. #endif
  177419. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177420. typedef double FAR * png_doublep;
  177421. #endif
  177422. /* Pointers to pointers; i.e. arrays */
  177423. typedef png_byte FAR * FAR * png_bytepp;
  177424. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  177425. typedef png_int_32 FAR * FAR * png_int_32pp;
  177426. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  177427. typedef png_int_16 FAR * FAR * png_int_16pp;
  177428. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  177429. typedef char FAR * FAR * png_charpp;
  177430. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  177431. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177432. typedef double FAR * FAR * png_doublepp;
  177433. #endif
  177434. /* Pointers to pointers to pointers; i.e., pointer to array */
  177435. typedef char FAR * FAR * FAR * png_charppp;
  177436. #if 0
  177437. /* SPC - Is this stuff deprecated? */
  177438. /* It'll be removed as of libpng-1.3.0 - GR-P */
  177439. /* libpng typedefs for types in zlib. If zlib changes
  177440. * or another compression library is used, then change these.
  177441. * Eliminates need to change all the source files.
  177442. */
  177443. typedef charf * png_zcharp;
  177444. typedef charf * FAR * png_zcharpp;
  177445. typedef z_stream FAR * png_zstreamp;
  177446. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  177447. /*
  177448. * Define PNG_BUILD_DLL if the module being built is a Windows
  177449. * LIBPNG DLL.
  177450. *
  177451. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  177452. * It is equivalent to Microsoft predefined macro _DLL that is
  177453. * automatically defined when you compile using the share
  177454. * version of the CRT (C Run-Time library)
  177455. *
  177456. * The cygwin mods make this behavior a little different:
  177457. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  177458. * Define PNG_STATIC if you are building a static library for use with cygwin,
  177459. * -or- if you are building an application that you want to link to the
  177460. * static library.
  177461. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  177462. * the other flags is defined.
  177463. */
  177464. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  177465. # define PNG_DLL
  177466. #endif
  177467. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  177468. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  177469. * command-line override
  177470. */
  177471. #if defined(__CYGWIN__)
  177472. # if !defined(PNG_STATIC)
  177473. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177474. # undef PNG_USE_GLOBAL_ARRAYS
  177475. # endif
  177476. # if !defined(PNG_USE_LOCAL_ARRAYS)
  177477. # define PNG_USE_LOCAL_ARRAYS
  177478. # endif
  177479. # else
  177480. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  177481. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177482. # undef PNG_USE_GLOBAL_ARRAYS
  177483. # endif
  177484. # endif
  177485. # endif
  177486. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177487. # define PNG_USE_LOCAL_ARRAYS
  177488. # endif
  177489. #endif
  177490. /* Do not use global arrays (helps with building DLL's)
  177491. * They are no longer used in libpng itself, since version 1.0.5c,
  177492. * but might be required for some pre-1.0.5c applications.
  177493. */
  177494. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177495. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  177496. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  177497. # define PNG_USE_LOCAL_ARRAYS
  177498. # else
  177499. # define PNG_USE_GLOBAL_ARRAYS
  177500. # endif
  177501. #endif
  177502. #if defined(__CYGWIN__)
  177503. # undef PNGAPI
  177504. # define PNGAPI __cdecl
  177505. # undef PNG_IMPEXP
  177506. # define PNG_IMPEXP
  177507. #endif
  177508. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  177509. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  177510. * Don't ignore those warnings; you must also reset the default calling
  177511. * convention in your compiler to match your PNGAPI, and you must build
  177512. * zlib and your applications the same way you build libpng.
  177513. */
  177514. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  177515. # ifndef PNG_NO_MODULEDEF
  177516. # define PNG_NO_MODULEDEF
  177517. # endif
  177518. #endif
  177519. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  177520. # define PNG_IMPEXP
  177521. #endif
  177522. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  177523. (( defined(_Windows) || defined(_WINDOWS) || \
  177524. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  177525. # ifndef PNGAPI
  177526. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  177527. # define PNGAPI __cdecl
  177528. # else
  177529. # define PNGAPI _cdecl
  177530. # endif
  177531. # endif
  177532. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  177533. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  177534. # define PNG_IMPEXP
  177535. # endif
  177536. # if !defined(PNG_IMPEXP)
  177537. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177538. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  177539. /* Borland/Microsoft */
  177540. # if defined(_MSC_VER) || defined(__BORLANDC__)
  177541. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  177542. # define PNG_EXPORT PNG_EXPORT_TYPE1
  177543. # else
  177544. # define PNG_EXPORT PNG_EXPORT_TYPE2
  177545. # if defined(PNG_BUILD_DLL)
  177546. # define PNG_IMPEXP __export
  177547. # else
  177548. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  177549. VC++ */
  177550. # endif /* Exists in Borland C++ for
  177551. C++ classes (== huge) */
  177552. # endif
  177553. # endif
  177554. # if !defined(PNG_IMPEXP)
  177555. # if defined(PNG_BUILD_DLL)
  177556. # define PNG_IMPEXP __declspec(dllexport)
  177557. # else
  177558. # define PNG_IMPEXP __declspec(dllimport)
  177559. # endif
  177560. # endif
  177561. # endif /* PNG_IMPEXP */
  177562. #else /* !(DLL || non-cygwin WINDOWS) */
  177563. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  177564. # ifndef PNGAPI
  177565. # define PNGAPI _System
  177566. # endif
  177567. # else
  177568. # if 0 /* ... other platforms, with other meanings */
  177569. # endif
  177570. # endif
  177571. #endif
  177572. #ifndef PNGAPI
  177573. # define PNGAPI
  177574. #endif
  177575. #ifndef PNG_IMPEXP
  177576. # define PNG_IMPEXP
  177577. #endif
  177578. #ifdef PNG_BUILDSYMS
  177579. # ifndef PNG_EXPORT
  177580. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  177581. # endif
  177582. # ifdef PNG_USE_GLOBAL_ARRAYS
  177583. # ifndef PNG_EXPORT_VAR
  177584. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  177585. # endif
  177586. # endif
  177587. #endif
  177588. #ifndef PNG_EXPORT
  177589. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177590. #endif
  177591. #ifdef PNG_USE_GLOBAL_ARRAYS
  177592. # ifndef PNG_EXPORT_VAR
  177593. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  177594. # endif
  177595. #endif
  177596. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  177597. * functions that are passed far data must be model independent.
  177598. */
  177599. #ifndef PNG_ABORT
  177600. # define PNG_ABORT() abort()
  177601. #endif
  177602. #ifdef PNG_SETJMP_SUPPORTED
  177603. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  177604. #else
  177605. # define png_jmpbuf(png_ptr) \
  177606. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  177607. #endif
  177608. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  177609. /* use this to make far-to-near assignments */
  177610. # define CHECK 1
  177611. # define NOCHECK 0
  177612. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  177613. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  177614. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  177615. # define png_strcpy _fstrcpy
  177616. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  177617. # define png_strlen _fstrlen
  177618. # define png_memcmp _fmemcmp /* SJT: added */
  177619. # define png_memcpy _fmemcpy
  177620. # define png_memset _fmemset
  177621. #else /* use the usual functions */
  177622. # define CVT_PTR(ptr) (ptr)
  177623. # define CVT_PTR_NOCHECK(ptr) (ptr)
  177624. # ifndef PNG_NO_SNPRINTF
  177625. # ifdef _MSC_VER
  177626. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  177627. # define png_snprintf2 _snprintf
  177628. # define png_snprintf6 _snprintf
  177629. # else
  177630. # define png_snprintf snprintf /* Added to v 1.2.19 */
  177631. # define png_snprintf2 snprintf
  177632. # define png_snprintf6 snprintf
  177633. # endif
  177634. # else
  177635. /* You don't have or don't want to use snprintf(). Caution: Using
  177636. * sprintf instead of snprintf exposes your application to accidental
  177637. * or malevolent buffer overflows. If you don't have snprintf()
  177638. * as a general rule you should provide one (you can get one from
  177639. * Portable OpenSSH). */
  177640. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  177641. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  177642. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  177643. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  177644. # endif
  177645. # define png_strcpy strcpy
  177646. # define png_strncpy strncpy /* Added to v 1.2.6 */
  177647. # define png_strlen strlen
  177648. # define png_memcmp memcmp /* SJT: added */
  177649. # define png_memcpy memcpy
  177650. # define png_memset memset
  177651. #endif
  177652. /* End of memory model independent support */
  177653. /* Just a little check that someone hasn't tried to define something
  177654. * contradictory.
  177655. */
  177656. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  177657. # undef PNG_ZBUF_SIZE
  177658. # define PNG_ZBUF_SIZE 65536L
  177659. #endif
  177660. /* Added at libpng-1.2.8 */
  177661. #endif /* PNG_VERSION_INFO_ONLY */
  177662. #endif /* PNGCONF_H */
  177663. /********* End of inlined file: pngconf.h *********/
  177664. #ifdef _MSC_VER
  177665. #pragma warning (disable: 4996 4100)
  177666. #endif
  177667. /*
  177668. * Added at libpng-1.2.8 */
  177669. /* Ref MSDN: Private as priority over Special
  177670. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  177671. * procedures. If this value is given, the StringFileInfo block must
  177672. * contain a PrivateBuild string.
  177673. *
  177674. * VS_FF_SPECIALBUILD File *was* built by the original company using
  177675. * standard release procedures but is a variation of the standard
  177676. * file of the same version number. If this value is given, the
  177677. * StringFileInfo block must contain a SpecialBuild string.
  177678. */
  177679. #if defined(PNG_USER_PRIVATEBUILD)
  177680. # define PNG_LIBPNG_BUILD_TYPE \
  177681. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  177682. #else
  177683. # if defined(PNG_LIBPNG_SPECIALBUILD)
  177684. # define PNG_LIBPNG_BUILD_TYPE \
  177685. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  177686. # else
  177687. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  177688. # endif
  177689. #endif
  177690. #ifndef PNG_VERSION_INFO_ONLY
  177691. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  177692. #ifdef __cplusplus
  177693. extern "C" {
  177694. #endif /* __cplusplus */
  177695. /* This file is arranged in several sections. The first section contains
  177696. * structure and type definitions. The second section contains the external
  177697. * library functions, while the third has the internal library functions,
  177698. * which applications aren't expected to use directly.
  177699. */
  177700. #ifndef PNG_NO_TYPECAST_NULL
  177701. #define int_p_NULL (int *)NULL
  177702. #define png_bytep_NULL (png_bytep)NULL
  177703. #define png_bytepp_NULL (png_bytepp)NULL
  177704. #define png_doublep_NULL (png_doublep)NULL
  177705. #define png_error_ptr_NULL (png_error_ptr)NULL
  177706. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  177707. #define png_free_ptr_NULL (png_free_ptr)NULL
  177708. #define png_infopp_NULL (png_infopp)NULL
  177709. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  177710. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  177711. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  177712. #define png_structp_NULL (png_structp)NULL
  177713. #define png_uint_16p_NULL (png_uint_16p)NULL
  177714. #define png_voidp_NULL (png_voidp)NULL
  177715. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  177716. #else
  177717. #define int_p_NULL NULL
  177718. #define png_bytep_NULL NULL
  177719. #define png_bytepp_NULL NULL
  177720. #define png_doublep_NULL NULL
  177721. #define png_error_ptr_NULL NULL
  177722. #define png_flush_ptr_NULL NULL
  177723. #define png_free_ptr_NULL NULL
  177724. #define png_infopp_NULL NULL
  177725. #define png_malloc_ptr_NULL NULL
  177726. #define png_read_status_ptr_NULL NULL
  177727. #define png_rw_ptr_NULL NULL
  177728. #define png_structp_NULL NULL
  177729. #define png_uint_16p_NULL NULL
  177730. #define png_voidp_NULL NULL
  177731. #define png_write_status_ptr_NULL NULL
  177732. #endif
  177733. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  177734. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  177735. /* Version information for C files, stored in png.c. This had better match
  177736. * the version above.
  177737. */
  177738. #ifdef PNG_USE_GLOBAL_ARRAYS
  177739. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  177740. /* need room for 99.99.99beta99z */
  177741. #else
  177742. #define png_libpng_ver png_get_header_ver(NULL)
  177743. #endif
  177744. #ifdef PNG_USE_GLOBAL_ARRAYS
  177745. /* This was removed in version 1.0.5c */
  177746. /* Structures to facilitate easy interlacing. See png.c for more details */
  177747. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  177748. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  177749. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  177750. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  177751. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  177752. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  177753. /* This isn't currently used. If you need it, see png.c for more details.
  177754. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  177755. */
  177756. #endif
  177757. #endif /* PNG_NO_EXTERN */
  177758. /* Three color definitions. The order of the red, green, and blue, (and the
  177759. * exact size) is not important, although the size of the fields need to
  177760. * be png_byte or png_uint_16 (as defined below).
  177761. */
  177762. typedef struct png_color_struct
  177763. {
  177764. png_byte red;
  177765. png_byte green;
  177766. png_byte blue;
  177767. } png_color;
  177768. typedef png_color FAR * png_colorp;
  177769. typedef png_color FAR * FAR * png_colorpp;
  177770. typedef struct png_color_16_struct
  177771. {
  177772. png_byte index; /* used for palette files */
  177773. png_uint_16 red; /* for use in red green blue files */
  177774. png_uint_16 green;
  177775. png_uint_16 blue;
  177776. png_uint_16 gray; /* for use in grayscale files */
  177777. } png_color_16;
  177778. typedef png_color_16 FAR * png_color_16p;
  177779. typedef png_color_16 FAR * FAR * png_color_16pp;
  177780. typedef struct png_color_8_struct
  177781. {
  177782. png_byte red; /* for use in red green blue files */
  177783. png_byte green;
  177784. png_byte blue;
  177785. png_byte gray; /* for use in grayscale files */
  177786. png_byte alpha; /* for alpha channel files */
  177787. } png_color_8;
  177788. typedef png_color_8 FAR * png_color_8p;
  177789. typedef png_color_8 FAR * FAR * png_color_8pp;
  177790. /*
  177791. * The following two structures are used for the in-core representation
  177792. * of sPLT chunks.
  177793. */
  177794. typedef struct png_sPLT_entry_struct
  177795. {
  177796. png_uint_16 red;
  177797. png_uint_16 green;
  177798. png_uint_16 blue;
  177799. png_uint_16 alpha;
  177800. png_uint_16 frequency;
  177801. } png_sPLT_entry;
  177802. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  177803. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  177804. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  177805. * occupy the LSB of their respective members, and the MSB of each member
  177806. * is zero-filled. The frequency member always occupies the full 16 bits.
  177807. */
  177808. typedef struct png_sPLT_struct
  177809. {
  177810. png_charp name; /* palette name */
  177811. png_byte depth; /* depth of palette samples */
  177812. png_sPLT_entryp entries; /* palette entries */
  177813. png_int_32 nentries; /* number of palette entries */
  177814. } png_sPLT_t;
  177815. typedef png_sPLT_t FAR * png_sPLT_tp;
  177816. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  177817. #ifdef PNG_TEXT_SUPPORTED
  177818. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  177819. * and whether that contents is compressed or not. The "key" field
  177820. * points to a regular zero-terminated C string. The "text", "lang", and
  177821. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  177822. * However, the * structure returned by png_get_text() will always contain
  177823. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  177824. * so they can be safely used in printf() and other string-handling functions.
  177825. */
  177826. typedef struct png_text_struct
  177827. {
  177828. int compression; /* compression value:
  177829. -1: tEXt, none
  177830. 0: zTXt, deflate
  177831. 1: iTXt, none
  177832. 2: iTXt, deflate */
  177833. png_charp key; /* keyword, 1-79 character description of "text" */
  177834. png_charp text; /* comment, may be an empty string (ie "")
  177835. or a NULL pointer */
  177836. png_size_t text_length; /* length of the text string */
  177837. #ifdef PNG_iTXt_SUPPORTED
  177838. png_size_t itxt_length; /* length of the itxt string */
  177839. png_charp lang; /* language code, 0-79 characters
  177840. or a NULL pointer */
  177841. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  177842. chars or a NULL pointer */
  177843. #endif
  177844. } png_text;
  177845. typedef png_text FAR * png_textp;
  177846. typedef png_text FAR * FAR * png_textpp;
  177847. #endif
  177848. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  177849. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  177850. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  177851. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  177852. #define PNG_TEXT_COMPRESSION_NONE -1
  177853. #define PNG_TEXT_COMPRESSION_zTXt 0
  177854. #define PNG_ITXT_COMPRESSION_NONE 1
  177855. #define PNG_ITXT_COMPRESSION_zTXt 2
  177856. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  177857. /* png_time is a way to hold the time in an machine independent way.
  177858. * Two conversions are provided, both from time_t and struct tm. There
  177859. * is no portable way to convert to either of these structures, as far
  177860. * as I know. If you know of a portable way, send it to me. As a side
  177861. * note - PNG has always been Year 2000 compliant!
  177862. */
  177863. typedef struct png_time_struct
  177864. {
  177865. png_uint_16 year; /* full year, as in, 1995 */
  177866. png_byte month; /* month of year, 1 - 12 */
  177867. png_byte day; /* day of month, 1 - 31 */
  177868. png_byte hour; /* hour of day, 0 - 23 */
  177869. png_byte minute; /* minute of hour, 0 - 59 */
  177870. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  177871. } png_time;
  177872. typedef png_time FAR * png_timep;
  177873. typedef png_time FAR * FAR * png_timepp;
  177874. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177875. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  177876. * no specific support. The idea is that we can use this to queue
  177877. * up private chunks for output even though the library doesn't actually
  177878. * know about their semantics.
  177879. */
  177880. typedef struct png_unknown_chunk_t
  177881. {
  177882. png_byte name[5];
  177883. png_byte *data;
  177884. png_size_t size;
  177885. /* libpng-using applications should NOT directly modify this byte. */
  177886. png_byte location; /* mode of operation at read time */
  177887. }
  177888. png_unknown_chunk;
  177889. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  177890. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  177891. #endif
  177892. /* png_info is a structure that holds the information in a PNG file so
  177893. * that the application can find out the characteristics of the image.
  177894. * If you are reading the file, this structure will tell you what is
  177895. * in the PNG file. If you are writing the file, fill in the information
  177896. * you want to put into the PNG file, then call png_write_info().
  177897. * The names chosen should be very close to the PNG specification, so
  177898. * consult that document for information about the meaning of each field.
  177899. *
  177900. * With libpng < 0.95, it was only possible to directly set and read the
  177901. * the values in the png_info_struct, which meant that the contents and
  177902. * order of the values had to remain fixed. With libpng 0.95 and later,
  177903. * however, there are now functions that abstract the contents of
  177904. * png_info_struct from the application, so this makes it easier to use
  177905. * libpng with dynamic libraries, and even makes it possible to use
  177906. * libraries that don't have all of the libpng ancillary chunk-handing
  177907. * functionality.
  177908. *
  177909. * In any case, the order of the parameters in png_info_struct should NOT
  177910. * be changed for as long as possible to keep compatibility with applications
  177911. * that use the old direct-access method with png_info_struct.
  177912. *
  177913. * The following members may have allocated storage attached that should be
  177914. * cleaned up before the structure is discarded: palette, trans, text,
  177915. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  177916. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  177917. * are automatically freed when the info structure is deallocated, if they were
  177918. * allocated internally by libpng. This behavior can be changed by means
  177919. * of the png_data_freer() function.
  177920. *
  177921. * More allocation details: all the chunk-reading functions that
  177922. * change these members go through the corresponding png_set_*
  177923. * functions. A function to clear these members is available: see
  177924. * png_free_data(). The png_set_* functions do not depend on being
  177925. * able to point info structure members to any of the storage they are
  177926. * passed (they make their own copies), EXCEPT that the png_set_text
  177927. * functions use the same storage passed to them in the text_ptr or
  177928. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  177929. * functions do not make their own copies.
  177930. */
  177931. typedef struct png_info_struct
  177932. {
  177933. /* the following are necessary for every PNG file */
  177934. png_uint_32 width; /* width of image in pixels (from IHDR) */
  177935. png_uint_32 height; /* height of image in pixels (from IHDR) */
  177936. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  177937. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  177938. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  177939. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  177940. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  177941. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  177942. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  177943. /* The following three should have been named *_method not *_type */
  177944. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  177945. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  177946. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177947. /* The following is informational only on read, and not used on writes. */
  177948. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  177949. png_byte pixel_depth; /* number of bits per pixel */
  177950. png_byte spare_byte; /* to align the data, and for future use */
  177951. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  177952. /* The rest of the data is optional. If you are reading, check the
  177953. * valid field to see if the information in these are valid. If you
  177954. * are writing, set the valid field to those chunks you want written,
  177955. * and initialize the appropriate fields below.
  177956. */
  177957. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177958. /* The gAMA chunk describes the gamma characteristics of the system
  177959. * on which the image was created, normally in the range [1.0, 2.5].
  177960. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  177961. */
  177962. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  177963. #endif
  177964. #if defined(PNG_sRGB_SUPPORTED)
  177965. /* GR-P, 0.96a */
  177966. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  177967. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  177968. #endif
  177969. #if defined(PNG_TEXT_SUPPORTED)
  177970. /* The tEXt, and zTXt chunks contain human-readable textual data in
  177971. * uncompressed, compressed, and optionally compressed forms, respectively.
  177972. * The data in "text" is an array of pointers to uncompressed,
  177973. * null-terminated C strings. Each chunk has a keyword that describes the
  177974. * textual data contained in that chunk. Keywords are not required to be
  177975. * unique, and the text string may be empty. Any number of text chunks may
  177976. * be in an image.
  177977. */
  177978. int num_text; /* number of comments read/to write */
  177979. int max_text; /* current size of text array */
  177980. png_textp text; /* array of comments read/to write */
  177981. #endif /* PNG_TEXT_SUPPORTED */
  177982. #if defined(PNG_tIME_SUPPORTED)
  177983. /* The tIME chunk holds the last time the displayed image data was
  177984. * modified. See the png_time struct for the contents of this struct.
  177985. */
  177986. png_time mod_time;
  177987. #endif
  177988. #if defined(PNG_sBIT_SUPPORTED)
  177989. /* The sBIT chunk specifies the number of significant high-order bits
  177990. * in the pixel data. Values are in the range [1, bit_depth], and are
  177991. * only specified for the channels in the pixel data. The contents of
  177992. * the low-order bits is not specified. Data is valid if
  177993. * (valid & PNG_INFO_sBIT) is non-zero.
  177994. */
  177995. png_color_8 sig_bit; /* significant bits in color channels */
  177996. #endif
  177997. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  177998. defined(PNG_READ_BACKGROUND_SUPPORTED)
  177999. /* The tRNS chunk supplies transparency data for paletted images and
  178000. * other image types that don't need a full alpha channel. There are
  178001. * "num_trans" transparency values for a paletted image, stored in the
  178002. * same order as the palette colors, starting from index 0. Values
  178003. * for the data are in the range [0, 255], ranging from fully transparent
  178004. * to fully opaque, respectively. For non-paletted images, there is a
  178005. * single color specified that should be treated as fully transparent.
  178006. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  178007. */
  178008. png_bytep trans; /* transparent values for paletted image */
  178009. png_color_16 trans_values; /* transparent color for non-palette image */
  178010. #endif
  178011. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178012. /* The bKGD chunk gives the suggested image background color if the
  178013. * display program does not have its own background color and the image
  178014. * is needs to composited onto a background before display. The colors
  178015. * in "background" are normally in the same color space/depth as the
  178016. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  178017. */
  178018. png_color_16 background;
  178019. #endif
  178020. #if defined(PNG_oFFs_SUPPORTED)
  178021. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  178022. * and downwards from the top-left corner of the display, page, or other
  178023. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  178024. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  178025. */
  178026. png_int_32 x_offset; /* x offset on page */
  178027. png_int_32 y_offset; /* y offset on page */
  178028. png_byte offset_unit_type; /* offset units type */
  178029. #endif
  178030. #if defined(PNG_pHYs_SUPPORTED)
  178031. /* The pHYs chunk gives the physical pixel density of the image for
  178032. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  178033. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  178034. */
  178035. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  178036. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  178037. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  178038. #endif
  178039. #if defined(PNG_hIST_SUPPORTED)
  178040. /* The hIST chunk contains the relative frequency or importance of the
  178041. * various palette entries, so that a viewer can intelligently select a
  178042. * reduced-color palette, if required. Data is an array of "num_palette"
  178043. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  178044. * is non-zero.
  178045. */
  178046. png_uint_16p hist;
  178047. #endif
  178048. #ifdef PNG_cHRM_SUPPORTED
  178049. /* The cHRM chunk describes the CIE color characteristics of the monitor
  178050. * on which the PNG was created. This data allows the viewer to do gamut
  178051. * mapping of the input image to ensure that the viewer sees the same
  178052. * colors in the image as the creator. Values are in the range
  178053. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  178054. */
  178055. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178056. float x_white;
  178057. float y_white;
  178058. float x_red;
  178059. float y_red;
  178060. float x_green;
  178061. float y_green;
  178062. float x_blue;
  178063. float y_blue;
  178064. #endif
  178065. #endif
  178066. #if defined(PNG_pCAL_SUPPORTED)
  178067. /* The pCAL chunk describes a transformation between the stored pixel
  178068. * values and original physical data values used to create the image.
  178069. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  178070. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  178071. * (possibly non-linear) transformation function given by "pcal_type"
  178072. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  178073. * defines below, and the PNG-Group's PNG extensions document for a
  178074. * complete description of the transformations and how they should be
  178075. * implemented, and for a description of the ASCII parameter strings.
  178076. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  178077. */
  178078. png_charp pcal_purpose; /* pCAL chunk description string */
  178079. png_int_32 pcal_X0; /* minimum value */
  178080. png_int_32 pcal_X1; /* maximum value */
  178081. png_charp pcal_units; /* Latin-1 string giving physical units */
  178082. png_charpp pcal_params; /* ASCII strings containing parameter values */
  178083. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  178084. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  178085. #endif
  178086. /* New members added in libpng-1.0.6 */
  178087. #ifdef PNG_FREE_ME_SUPPORTED
  178088. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178089. #endif
  178090. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178091. /* storage for unknown chunks that the library doesn't recognize. */
  178092. png_unknown_chunkp unknown_chunks;
  178093. png_size_t unknown_chunks_num;
  178094. #endif
  178095. #if defined(PNG_iCCP_SUPPORTED)
  178096. /* iCCP chunk data. */
  178097. png_charp iccp_name; /* profile name */
  178098. png_charp iccp_profile; /* International Color Consortium profile data */
  178099. /* Note to maintainer: should be png_bytep */
  178100. png_uint_32 iccp_proflen; /* ICC profile data length */
  178101. png_byte iccp_compression; /* Always zero */
  178102. #endif
  178103. #if defined(PNG_sPLT_SUPPORTED)
  178104. /* data on sPLT chunks (there may be more than one). */
  178105. png_sPLT_tp splt_palettes;
  178106. png_uint_32 splt_palettes_num;
  178107. #endif
  178108. #if defined(PNG_sCAL_SUPPORTED)
  178109. /* The sCAL chunk describes the actual physical dimensions of the
  178110. * subject matter of the graphic. The chunk contains a unit specification
  178111. * a byte value, and two ASCII strings representing floating-point
  178112. * values. The values are width and height corresponsing to one pixel
  178113. * in the image. This external representation is converted to double
  178114. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  178115. */
  178116. png_byte scal_unit; /* unit of physical scale */
  178117. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178118. double scal_pixel_width; /* width of one pixel */
  178119. double scal_pixel_height; /* height of one pixel */
  178120. #endif
  178121. #ifdef PNG_FIXED_POINT_SUPPORTED
  178122. png_charp scal_s_width; /* string containing height */
  178123. png_charp scal_s_height; /* string containing width */
  178124. #endif
  178125. #endif
  178126. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178127. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  178128. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  178129. png_bytepp row_pointers; /* the image bits */
  178130. #endif
  178131. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  178132. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  178133. #endif
  178134. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  178135. png_fixed_point int_x_white;
  178136. png_fixed_point int_y_white;
  178137. png_fixed_point int_x_red;
  178138. png_fixed_point int_y_red;
  178139. png_fixed_point int_x_green;
  178140. png_fixed_point int_y_green;
  178141. png_fixed_point int_x_blue;
  178142. png_fixed_point int_y_blue;
  178143. #endif
  178144. } png_info;
  178145. typedef png_info FAR * png_infop;
  178146. typedef png_info FAR * FAR * png_infopp;
  178147. /* Maximum positive integer used in PNG is (2^31)-1 */
  178148. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  178149. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  178150. #define PNG_SIZE_MAX ((png_size_t)(-1))
  178151. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178152. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  178153. #define PNG_MAX_UINT PNG_UINT_31_MAX
  178154. #endif
  178155. /* These describe the color_type field in png_info. */
  178156. /* color type masks */
  178157. #define PNG_COLOR_MASK_PALETTE 1
  178158. #define PNG_COLOR_MASK_COLOR 2
  178159. #define PNG_COLOR_MASK_ALPHA 4
  178160. /* color types. Note that not all combinations are legal */
  178161. #define PNG_COLOR_TYPE_GRAY 0
  178162. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  178163. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  178164. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  178165. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  178166. /* aliases */
  178167. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  178168. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  178169. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  178170. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  178171. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  178172. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  178173. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  178174. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  178175. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  178176. /* These are for the interlacing type. These values should NOT be changed. */
  178177. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  178178. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  178179. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  178180. /* These are for the oFFs chunk. These values should NOT be changed. */
  178181. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  178182. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  178183. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  178184. /* These are for the pCAL chunk. These values should NOT be changed. */
  178185. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  178186. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  178187. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  178188. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  178189. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  178190. /* These are for the sCAL chunk. These values should NOT be changed. */
  178191. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  178192. #define PNG_SCALE_METER 1 /* meters per pixel */
  178193. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  178194. #define PNG_SCALE_LAST 3 /* Not a valid value */
  178195. /* These are for the pHYs chunk. These values should NOT be changed. */
  178196. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  178197. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  178198. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  178199. /* These are for the sRGB chunk. These values should NOT be changed. */
  178200. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  178201. #define PNG_sRGB_INTENT_RELATIVE 1
  178202. #define PNG_sRGB_INTENT_SATURATION 2
  178203. #define PNG_sRGB_INTENT_ABSOLUTE 3
  178204. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  178205. /* This is for text chunks */
  178206. #define PNG_KEYWORD_MAX_LENGTH 79
  178207. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  178208. #define PNG_MAX_PALETTE_LENGTH 256
  178209. /* These determine if an ancillary chunk's data has been successfully read
  178210. * from the PNG header, or if the application has filled in the corresponding
  178211. * data in the info_struct to be written into the output file. The values
  178212. * of the PNG_INFO_<chunk> defines should NOT be changed.
  178213. */
  178214. #define PNG_INFO_gAMA 0x0001
  178215. #define PNG_INFO_sBIT 0x0002
  178216. #define PNG_INFO_cHRM 0x0004
  178217. #define PNG_INFO_PLTE 0x0008
  178218. #define PNG_INFO_tRNS 0x0010
  178219. #define PNG_INFO_bKGD 0x0020
  178220. #define PNG_INFO_hIST 0x0040
  178221. #define PNG_INFO_pHYs 0x0080
  178222. #define PNG_INFO_oFFs 0x0100
  178223. #define PNG_INFO_tIME 0x0200
  178224. #define PNG_INFO_pCAL 0x0400
  178225. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  178226. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  178227. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  178228. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  178229. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  178230. /* This is used for the transformation routines, as some of them
  178231. * change these values for the row. It also should enable using
  178232. * the routines for other purposes.
  178233. */
  178234. typedef struct png_row_info_struct
  178235. {
  178236. png_uint_32 width; /* width of row */
  178237. png_uint_32 rowbytes; /* number of bytes in row */
  178238. png_byte color_type; /* color type of row */
  178239. png_byte bit_depth; /* bit depth of row */
  178240. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  178241. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  178242. } png_row_info;
  178243. typedef png_row_info FAR * png_row_infop;
  178244. typedef png_row_info FAR * FAR * png_row_infopp;
  178245. /* These are the function types for the I/O functions and for the functions
  178246. * that allow the user to override the default I/O functions with his or her
  178247. * own. The png_error_ptr type should match that of user-supplied warning
  178248. * and error functions, while the png_rw_ptr type should match that of the
  178249. * user read/write data functions.
  178250. */
  178251. typedef struct png_struct_def png_struct;
  178252. typedef png_struct FAR * png_structp;
  178253. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  178254. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  178255. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  178256. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  178257. int));
  178258. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  178259. int));
  178260. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178261. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  178262. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  178263. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  178264. png_uint_32, int));
  178265. #endif
  178266. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178267. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178268. defined(PNG_LEGACY_SUPPORTED)
  178269. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  178270. png_row_infop, png_bytep));
  178271. #endif
  178272. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178273. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  178274. #endif
  178275. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178276. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  178277. #endif
  178278. /* Transform masks for the high-level interface */
  178279. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  178280. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  178281. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  178282. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  178283. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  178284. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  178285. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  178286. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  178287. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  178288. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  178289. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  178290. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  178291. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  178292. /* Flags for MNG supported features */
  178293. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  178294. #define PNG_FLAG_MNG_FILTER_64 0x04
  178295. #define PNG_ALL_MNG_FEATURES 0x05
  178296. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  178297. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  178298. /* The structure that holds the information to read and write PNG files.
  178299. * The only people who need to care about what is inside of this are the
  178300. * people who will be modifying the library for their own special needs.
  178301. * It should NOT be accessed directly by an application, except to store
  178302. * the jmp_buf.
  178303. */
  178304. struct png_struct_def
  178305. {
  178306. #ifdef PNG_SETJMP_SUPPORTED
  178307. jmp_buf jmpbuf; /* used in png_error */
  178308. #endif
  178309. png_error_ptr error_fn; /* function for printing errors and aborting */
  178310. png_error_ptr warning_fn; /* function for printing warnings */
  178311. png_voidp error_ptr; /* user supplied struct for error functions */
  178312. png_rw_ptr write_data_fn; /* function for writing output data */
  178313. png_rw_ptr read_data_fn; /* function for reading input data */
  178314. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  178315. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  178316. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  178317. #endif
  178318. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178319. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  178320. #endif
  178321. /* These were added in libpng-1.0.2 */
  178322. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  178323. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178324. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178325. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  178326. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  178327. png_byte user_transform_channels; /* channels in user transformed pixels */
  178328. #endif
  178329. #endif
  178330. png_uint_32 mode; /* tells us where we are in the PNG file */
  178331. png_uint_32 flags; /* flags indicating various things to libpng */
  178332. png_uint_32 transformations; /* which transformations to perform */
  178333. z_stream zstream; /* pointer to decompression structure (below) */
  178334. png_bytep zbuf; /* buffer for zlib */
  178335. png_size_t zbuf_size; /* size of zbuf */
  178336. int zlib_level; /* holds zlib compression level */
  178337. int zlib_method; /* holds zlib compression method */
  178338. int zlib_window_bits; /* holds zlib compression window bits */
  178339. int zlib_mem_level; /* holds zlib compression memory level */
  178340. int zlib_strategy; /* holds zlib compression strategy */
  178341. png_uint_32 width; /* width of image in pixels */
  178342. png_uint_32 height; /* height of image in pixels */
  178343. png_uint_32 num_rows; /* number of rows in current pass */
  178344. png_uint_32 usr_width; /* width of row at start of write */
  178345. png_uint_32 rowbytes; /* size of row in bytes */
  178346. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  178347. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  178348. png_uint_32 row_number; /* current row in interlace pass */
  178349. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  178350. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  178351. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  178352. png_bytep up_row; /* buffer to save "up" row when filtering */
  178353. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  178354. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  178355. png_row_info row_info; /* used for transformation routines */
  178356. png_uint_32 idat_size; /* current IDAT size for read */
  178357. png_uint_32 crc; /* current chunk CRC value */
  178358. png_colorp palette; /* palette from the input file */
  178359. png_uint_16 num_palette; /* number of color entries in palette */
  178360. png_uint_16 num_trans; /* number of transparency values */
  178361. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  178362. png_byte compression; /* file compression type (always 0) */
  178363. png_byte filter; /* file filter type (always 0) */
  178364. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  178365. png_byte pass; /* current interlace pass (0 - 6) */
  178366. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  178367. png_byte color_type; /* color type of file */
  178368. png_byte bit_depth; /* bit depth of file */
  178369. png_byte usr_bit_depth; /* bit depth of users row */
  178370. png_byte pixel_depth; /* number of bits per pixel */
  178371. png_byte channels; /* number of channels in file */
  178372. png_byte usr_channels; /* channels at start of write */
  178373. png_byte sig_bytes; /* magic bytes read/written from start of file */
  178374. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178375. #ifdef PNG_LEGACY_SUPPORTED
  178376. png_byte filler; /* filler byte for pixel expansion */
  178377. #else
  178378. png_uint_16 filler; /* filler bytes for pixel expansion */
  178379. #endif
  178380. #endif
  178381. #if defined(PNG_bKGD_SUPPORTED)
  178382. png_byte background_gamma_type;
  178383. # ifdef PNG_FLOATING_POINT_SUPPORTED
  178384. float background_gamma;
  178385. # endif
  178386. png_color_16 background; /* background color in screen gamma space */
  178387. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178388. png_color_16 background_1; /* background normalized to gamma 1.0 */
  178389. #endif
  178390. #endif /* PNG_bKGD_SUPPORTED */
  178391. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178392. png_flush_ptr output_flush_fn;/* Function for flushing output */
  178393. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  178394. png_uint_32 flush_rows; /* number of rows written since last flush */
  178395. #endif
  178396. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178397. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  178398. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178399. float gamma; /* file gamma value */
  178400. float screen_gamma; /* screen gamma value (display_exponent) */
  178401. #endif
  178402. #endif
  178403. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178404. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  178405. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  178406. png_bytep gamma_to_1; /* converts from file to 1.0 */
  178407. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  178408. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  178409. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  178410. #endif
  178411. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  178412. png_color_8 sig_bit; /* significant bits in each available channel */
  178413. #endif
  178414. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178415. png_color_8 shift; /* shift for significant bit tranformation */
  178416. #endif
  178417. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  178418. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178419. png_bytep trans; /* transparency values for paletted files */
  178420. png_color_16 trans_values; /* transparency values for non-paletted files */
  178421. #endif
  178422. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  178423. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  178424. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178425. png_progressive_info_ptr info_fn; /* called after header data fully read */
  178426. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  178427. png_progressive_end_ptr end_fn; /* called after image is complete */
  178428. png_bytep save_buffer_ptr; /* current location in save_buffer */
  178429. png_bytep save_buffer; /* buffer for previously read data */
  178430. png_bytep current_buffer_ptr; /* current location in current_buffer */
  178431. png_bytep current_buffer; /* buffer for recently used data */
  178432. png_uint_32 push_length; /* size of current input chunk */
  178433. png_uint_32 skip_length; /* bytes to skip in input data */
  178434. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  178435. png_size_t save_buffer_max; /* total size of save_buffer */
  178436. png_size_t buffer_size; /* total amount of available input data */
  178437. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  178438. int process_mode; /* what push library is currently doing */
  178439. int cur_palette; /* current push library palette index */
  178440. # if defined(PNG_TEXT_SUPPORTED)
  178441. png_size_t current_text_size; /* current size of text input data */
  178442. png_size_t current_text_left; /* how much text left to read in input */
  178443. png_charp current_text; /* current text chunk buffer */
  178444. png_charp current_text_ptr; /* current location in current_text */
  178445. # endif /* PNG_TEXT_SUPPORTED */
  178446. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178447. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  178448. /* for the Borland special 64K segment handler */
  178449. png_bytepp offset_table_ptr;
  178450. png_bytep offset_table;
  178451. png_uint_16 offset_table_number;
  178452. png_uint_16 offset_table_count;
  178453. png_uint_16 offset_table_count_free;
  178454. #endif
  178455. #if defined(PNG_READ_DITHER_SUPPORTED)
  178456. png_bytep palette_lookup; /* lookup table for dithering */
  178457. png_bytep dither_index; /* index translation for palette files */
  178458. #endif
  178459. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  178460. png_uint_16p hist; /* histogram */
  178461. #endif
  178462. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  178463. png_byte heuristic_method; /* heuristic for row filter selection */
  178464. png_byte num_prev_filters; /* number of weights for previous rows */
  178465. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  178466. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  178467. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  178468. png_uint_16p filter_costs; /* relative filter calculation cost */
  178469. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  178470. #endif
  178471. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178472. png_charp time_buffer; /* String to hold RFC 1123 time text */
  178473. #endif
  178474. /* New members added in libpng-1.0.6 */
  178475. #ifdef PNG_FREE_ME_SUPPORTED
  178476. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178477. #endif
  178478. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178479. png_voidp user_chunk_ptr;
  178480. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  178481. #endif
  178482. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178483. int num_chunk_list;
  178484. png_bytep chunk_list;
  178485. #endif
  178486. /* New members added in libpng-1.0.3 */
  178487. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178488. png_byte rgb_to_gray_status;
  178489. /* These were changed from png_byte in libpng-1.0.6 */
  178490. png_uint_16 rgb_to_gray_red_coeff;
  178491. png_uint_16 rgb_to_gray_green_coeff;
  178492. png_uint_16 rgb_to_gray_blue_coeff;
  178493. #endif
  178494. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  178495. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  178496. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178497. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178498. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  178499. #ifdef PNG_1_0_X
  178500. png_byte mng_features_permitted;
  178501. #else
  178502. png_uint_32 mng_features_permitted;
  178503. #endif /* PNG_1_0_X */
  178504. #endif
  178505. /* New member added in libpng-1.0.7 */
  178506. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178507. png_fixed_point int_gamma;
  178508. #endif
  178509. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  178510. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  178511. png_byte filter_type;
  178512. #endif
  178513. #if defined(PNG_1_0_X)
  178514. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  178515. png_uint_32 row_buf_size;
  178516. #endif
  178517. /* New members added in libpng-1.2.0 */
  178518. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178519. # if !defined(PNG_1_0_X)
  178520. # if defined(PNG_MMX_CODE_SUPPORTED)
  178521. png_byte mmx_bitdepth_threshold;
  178522. png_uint_32 mmx_rowbytes_threshold;
  178523. # endif
  178524. png_uint_32 asm_flags;
  178525. # endif
  178526. #endif
  178527. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  178528. #ifdef PNG_USER_MEM_SUPPORTED
  178529. png_voidp mem_ptr; /* user supplied struct for mem functions */
  178530. png_malloc_ptr malloc_fn; /* function for allocating memory */
  178531. png_free_ptr free_fn; /* function for freeing memory */
  178532. #endif
  178533. /* New member added in libpng-1.0.13 and 1.2.0 */
  178534. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  178535. #if defined(PNG_READ_DITHER_SUPPORTED)
  178536. /* The following three members were added at version 1.0.14 and 1.2.4 */
  178537. png_bytep dither_sort; /* working sort array */
  178538. png_bytep index_to_palette; /* where the original index currently is */
  178539. /* in the palette */
  178540. png_bytep palette_to_index; /* which original index points to this */
  178541. /* palette color */
  178542. #endif
  178543. /* New members added in libpng-1.0.16 and 1.2.6 */
  178544. png_byte compression_type;
  178545. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  178546. png_uint_32 user_width_max;
  178547. png_uint_32 user_height_max;
  178548. #endif
  178549. /* New member added in libpng-1.0.25 and 1.2.17 */
  178550. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178551. /* storage for unknown chunk that the library doesn't recognize. */
  178552. png_unknown_chunk unknown_chunk;
  178553. #endif
  178554. };
  178555. /* This triggers a compiler error in png.c, if png.c and png.h
  178556. * do not agree upon the version number.
  178557. */
  178558. typedef png_structp version_1_2_21;
  178559. typedef png_struct FAR * FAR * png_structpp;
  178560. /* Here are the function definitions most commonly used. This is not
  178561. * the place to find out how to use libpng. See libpng.txt for the
  178562. * full explanation, see example.c for the summary. This just provides
  178563. * a simple one line description of the use of each function.
  178564. */
  178565. /* Returns the version number of the library */
  178566. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  178567. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  178568. * Handling more than 8 bytes from the beginning of the file is an error.
  178569. */
  178570. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  178571. int num_bytes));
  178572. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  178573. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  178574. * signature, and non-zero otherwise. Having num_to_check == 0 or
  178575. * start > 7 will always fail (ie return non-zero).
  178576. */
  178577. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  178578. png_size_t num_to_check));
  178579. /* Simple signature checking function. This is the same as calling
  178580. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  178581. */
  178582. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  178583. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  178584. extern PNG_EXPORT(png_structp,png_create_read_struct)
  178585. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178586. png_error_ptr error_fn, png_error_ptr warn_fn));
  178587. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  178588. extern PNG_EXPORT(png_structp,png_create_write_struct)
  178589. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178590. png_error_ptr error_fn, png_error_ptr warn_fn));
  178591. #ifdef PNG_WRITE_SUPPORTED
  178592. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  178593. PNGARG((png_structp png_ptr));
  178594. #endif
  178595. #ifdef PNG_WRITE_SUPPORTED
  178596. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  178597. PNGARG((png_structp png_ptr, png_uint_32 size));
  178598. #endif
  178599. /* Reset the compression stream */
  178600. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  178601. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  178602. #ifdef PNG_USER_MEM_SUPPORTED
  178603. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  178604. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178605. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178606. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178607. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  178608. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178609. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178610. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178611. #endif
  178612. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  178613. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  178614. png_bytep chunk_name, png_bytep data, png_size_t length));
  178615. /* Write the start of a PNG chunk - length and chunk name. */
  178616. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  178617. png_bytep chunk_name, png_uint_32 length));
  178618. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  178619. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  178620. png_bytep data, png_size_t length));
  178621. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  178622. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  178623. /* Allocate and initialize the info structure */
  178624. extern PNG_EXPORT(png_infop,png_create_info_struct)
  178625. PNGARG((png_structp png_ptr));
  178626. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178627. /* Initialize the info structure (old interface - DEPRECATED) */
  178628. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  178629. #undef png_info_init
  178630. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  178631. png_sizeof(png_info));
  178632. #endif
  178633. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  178634. png_size_t png_info_struct_size));
  178635. /* Writes all the PNG information before the image. */
  178636. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  178637. png_infop info_ptr));
  178638. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  178639. png_infop info_ptr));
  178640. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178641. /* read the information before the actual image data. */
  178642. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  178643. png_infop info_ptr));
  178644. #endif
  178645. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178646. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  178647. PNGARG((png_structp png_ptr, png_timep ptime));
  178648. #endif
  178649. #if !defined(_WIN32_WCE)
  178650. /* "time.h" functions are not supported on WindowsCE */
  178651. #if defined(PNG_WRITE_tIME_SUPPORTED)
  178652. /* convert from a struct tm to png_time */
  178653. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  178654. struct tm FAR * ttime));
  178655. /* convert from time_t to png_time. Uses gmtime() */
  178656. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  178657. time_t ttime));
  178658. #endif /* PNG_WRITE_tIME_SUPPORTED */
  178659. #endif /* _WIN32_WCE */
  178660. #if defined(PNG_READ_EXPAND_SUPPORTED)
  178661. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  178662. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  178663. #if !defined(PNG_1_0_X)
  178664. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  178665. png_ptr));
  178666. #endif
  178667. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  178668. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  178669. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178670. /* Deprecated */
  178671. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  178672. #endif
  178673. #endif
  178674. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  178675. /* Use blue, green, red order for pixels. */
  178676. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  178677. #endif
  178678. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  178679. /* Expand the grayscale to 24-bit RGB if necessary. */
  178680. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  178681. #endif
  178682. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178683. /* Reduce RGB to grayscale. */
  178684. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178685. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  178686. int error_action, double red, double green ));
  178687. #endif
  178688. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  178689. int error_action, png_fixed_point red, png_fixed_point green ));
  178690. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  178691. png_ptr));
  178692. #endif
  178693. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  178694. png_colorp palette));
  178695. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178696. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  178697. #endif
  178698. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  178699. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178700. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  178701. #endif
  178702. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  178703. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178704. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  178705. #endif
  178706. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178707. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  178708. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  178709. png_uint_32 filler, int flags));
  178710. /* The values of the PNG_FILLER_ defines should NOT be changed */
  178711. #define PNG_FILLER_BEFORE 0
  178712. #define PNG_FILLER_AFTER 1
  178713. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  178714. #if !defined(PNG_1_0_X)
  178715. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  178716. png_uint_32 filler, int flags));
  178717. #endif
  178718. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  178719. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178720. /* Swap bytes in 16-bit depth files. */
  178721. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  178722. #endif
  178723. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  178724. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  178725. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  178726. #endif
  178727. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178728. /* Swap packing order of pixels in bytes. */
  178729. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  178730. #endif
  178731. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178732. /* Converts files to legal bit depths. */
  178733. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  178734. png_color_8p true_bits));
  178735. #endif
  178736. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  178737. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178738. /* Have the code handle the interlacing. Returns the number of passes. */
  178739. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  178740. #endif
  178741. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178742. /* Invert monochrome files */
  178743. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  178744. #endif
  178745. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178746. /* Handle alpha and tRNS by replacing with a background color. */
  178747. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178748. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  178749. png_color_16p background_color, int background_gamma_code,
  178750. int need_expand, double background_gamma));
  178751. #endif
  178752. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  178753. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  178754. #define PNG_BACKGROUND_GAMMA_FILE 2
  178755. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  178756. #endif
  178757. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178758. /* strip the second byte of information from a 16-bit depth file. */
  178759. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  178760. #endif
  178761. #if defined(PNG_READ_DITHER_SUPPORTED)
  178762. /* Turn on dithering, and reduce the palette to the number of colors available. */
  178763. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  178764. png_colorp palette, int num_palette, int maximum_colors,
  178765. png_uint_16p histogram, int full_dither));
  178766. #endif
  178767. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178768. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  178769. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178770. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  178771. double screen_gamma, double default_file_gamma));
  178772. #endif
  178773. #endif
  178774. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178775. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178776. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178777. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  178778. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  178779. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  178780. int empty_plte_permitted));
  178781. #endif
  178782. #endif
  178783. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178784. /* Set how many lines between output flushes - 0 for no flushing */
  178785. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  178786. /* Flush the current PNG output buffer */
  178787. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  178788. #endif
  178789. /* optional update palette with requested transformations */
  178790. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  178791. /* optional call to update the users info structure */
  178792. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  178793. png_infop info_ptr));
  178794. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178795. /* read one or more rows of image data. */
  178796. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  178797. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  178798. #endif
  178799. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178800. /* read a row of data. */
  178801. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  178802. png_bytep row,
  178803. png_bytep display_row));
  178804. #endif
  178805. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178806. /* read the whole image into memory at once. */
  178807. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  178808. png_bytepp image));
  178809. #endif
  178810. /* write a row of image data */
  178811. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  178812. png_bytep row));
  178813. /* write a few rows of image data */
  178814. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  178815. png_bytepp row, png_uint_32 num_rows));
  178816. /* write the image data */
  178817. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  178818. png_bytepp image));
  178819. /* writes the end of the PNG file. */
  178820. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  178821. png_infop info_ptr));
  178822. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178823. /* read the end of the PNG file. */
  178824. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  178825. png_infop info_ptr));
  178826. #endif
  178827. /* free any memory associated with the png_info_struct */
  178828. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  178829. png_infopp info_ptr_ptr));
  178830. /* free any memory associated with the png_struct and the png_info_structs */
  178831. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  178832. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  178833. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  178834. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  178835. png_infop end_info_ptr));
  178836. /* free any memory associated with the png_struct and the png_info_structs */
  178837. extern PNG_EXPORT(void,png_destroy_write_struct)
  178838. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  178839. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  178840. extern void png_write_destroy PNGARG((png_structp png_ptr));
  178841. /* set the libpng method of handling chunk CRC errors */
  178842. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  178843. int crit_action, int ancil_action));
  178844. /* Values for png_set_crc_action() to say how to handle CRC errors in
  178845. * ancillary and critical chunks, and whether to use the data contained
  178846. * therein. Note that it is impossible to "discard" data in a critical
  178847. * chunk. For versions prior to 0.90, the action was always error/quit,
  178848. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  178849. * chunks is warn/discard. These values should NOT be changed.
  178850. *
  178851. * value action:critical action:ancillary
  178852. */
  178853. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  178854. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  178855. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  178856. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  178857. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  178858. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  178859. /* These functions give the user control over the scan-line filtering in
  178860. * libpng and the compression methods used by zlib. These functions are
  178861. * mainly useful for testing, as the defaults should work with most users.
  178862. * Those users who are tight on memory or want faster performance at the
  178863. * expense of compression can modify them. See the compression library
  178864. * header file (zlib.h) for an explination of the compression functions.
  178865. */
  178866. /* set the filtering method(s) used by libpng. Currently, the only valid
  178867. * value for "method" is 0.
  178868. */
  178869. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  178870. int filters));
  178871. /* Flags for png_set_filter() to say which filters to use. The flags
  178872. * are chosen so that they don't conflict with real filter types
  178873. * below, in case they are supplied instead of the #defined constants.
  178874. * These values should NOT be changed.
  178875. */
  178876. #define PNG_NO_FILTERS 0x00
  178877. #define PNG_FILTER_NONE 0x08
  178878. #define PNG_FILTER_SUB 0x10
  178879. #define PNG_FILTER_UP 0x20
  178880. #define PNG_FILTER_AVG 0x40
  178881. #define PNG_FILTER_PAETH 0x80
  178882. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  178883. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  178884. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  178885. * These defines should NOT be changed.
  178886. */
  178887. #define PNG_FILTER_VALUE_NONE 0
  178888. #define PNG_FILTER_VALUE_SUB 1
  178889. #define PNG_FILTER_VALUE_UP 2
  178890. #define PNG_FILTER_VALUE_AVG 3
  178891. #define PNG_FILTER_VALUE_PAETH 4
  178892. #define PNG_FILTER_VALUE_LAST 5
  178893. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  178894. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  178895. * defines, either the default (minimum-sum-of-absolute-differences), or
  178896. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  178897. *
  178898. * Weights are factors >= 1.0, indicating how important it is to keep the
  178899. * filter type consistent between rows. Larger numbers mean the current
  178900. * filter is that many times as likely to be the same as the "num_weights"
  178901. * previous filters. This is cumulative for each previous row with a weight.
  178902. * There needs to be "num_weights" values in "filter_weights", or it can be
  178903. * NULL if the weights aren't being specified. Weights have no influence on
  178904. * the selection of the first row filter. Well chosen weights can (in theory)
  178905. * improve the compression for a given image.
  178906. *
  178907. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  178908. * filter type. Higher costs indicate more decoding expense, and are
  178909. * therefore less likely to be selected over a filter with lower computational
  178910. * costs. There needs to be a value in "filter_costs" for each valid filter
  178911. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  178912. * setting the costs. Costs try to improve the speed of decompression without
  178913. * unduly increasing the compressed image size.
  178914. *
  178915. * A negative weight or cost indicates the default value is to be used, and
  178916. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  178917. * The default values for both weights and costs are currently 1.0, but may
  178918. * change if good general weighting/cost heuristics can be found. If both
  178919. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  178920. * to the UNWEIGHTED method, but with added encoding time/computation.
  178921. */
  178922. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178923. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  178924. int heuristic_method, int num_weights, png_doublep filter_weights,
  178925. png_doublep filter_costs));
  178926. #endif
  178927. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  178928. /* Heuristic used for row filter selection. These defines should NOT be
  178929. * changed.
  178930. */
  178931. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  178932. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  178933. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  178934. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  178935. /* Set the library compression level. Currently, valid values range from
  178936. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  178937. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  178938. * shown that zlib compression levels 3-6 usually perform as well as level 9
  178939. * for PNG images, and do considerably fewer caclulations. In the future,
  178940. * these values may not correspond directly to the zlib compression levels.
  178941. */
  178942. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  178943. int level));
  178944. extern PNG_EXPORT(void,png_set_compression_mem_level)
  178945. PNGARG((png_structp png_ptr, int mem_level));
  178946. extern PNG_EXPORT(void,png_set_compression_strategy)
  178947. PNGARG((png_structp png_ptr, int strategy));
  178948. extern PNG_EXPORT(void,png_set_compression_window_bits)
  178949. PNGARG((png_structp png_ptr, int window_bits));
  178950. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  178951. int method));
  178952. /* These next functions are called for input/output, memory, and error
  178953. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  178954. * and call standard C I/O routines such as fread(), fwrite(), and
  178955. * fprintf(). These functions can be made to use other I/O routines
  178956. * at run time for those applications that need to handle I/O in a
  178957. * different manner by calling png_set_???_fn(). See libpng.txt for
  178958. * more information.
  178959. */
  178960. #if !defined(PNG_NO_STDIO)
  178961. /* Initialize the input/output for the PNG file to the default functions. */
  178962. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  178963. #endif
  178964. /* Replace the (error and abort), and warning functions with user
  178965. * supplied functions. If no messages are to be printed you must still
  178966. * write and use replacement functions. The replacement error_fn should
  178967. * still do a longjmp to the last setjmp location if you are using this
  178968. * method of error handling. If error_fn or warning_fn is NULL, the
  178969. * default function will be used.
  178970. */
  178971. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  178972. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  178973. /* Return the user pointer associated with the error functions */
  178974. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  178975. /* Replace the default data output functions with a user supplied one(s).
  178976. * If buffered output is not used, then output_flush_fn can be set to NULL.
  178977. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  178978. * output_flush_fn will be ignored (and thus can be NULL).
  178979. */
  178980. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  178981. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  178982. /* Replace the default data input function with a user supplied one. */
  178983. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  178984. png_voidp io_ptr, png_rw_ptr read_data_fn));
  178985. /* Return the user pointer associated with the I/O functions */
  178986. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  178987. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  178988. png_read_status_ptr read_row_fn));
  178989. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  178990. png_write_status_ptr write_row_fn));
  178991. #ifdef PNG_USER_MEM_SUPPORTED
  178992. /* Replace the default memory allocation functions with user supplied one(s). */
  178993. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  178994. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178995. /* Return the user pointer associated with the memory functions */
  178996. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  178997. #endif
  178998. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178999. defined(PNG_LEGACY_SUPPORTED)
  179000. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  179001. png_ptr, png_user_transform_ptr read_user_transform_fn));
  179002. #endif
  179003. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179004. defined(PNG_LEGACY_SUPPORTED)
  179005. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  179006. png_ptr, png_user_transform_ptr write_user_transform_fn));
  179007. #endif
  179008. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  179009. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  179010. defined(PNG_LEGACY_SUPPORTED)
  179011. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  179012. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  179013. int user_transform_channels));
  179014. /* Return the user pointer associated with the user transform functions */
  179015. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  179016. PNGARG((png_structp png_ptr));
  179017. #endif
  179018. #ifdef PNG_USER_CHUNKS_SUPPORTED
  179019. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  179020. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  179021. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  179022. png_ptr));
  179023. #endif
  179024. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179025. /* Sets the function callbacks for the push reader, and a pointer to a
  179026. * user-defined structure available to the callback functions.
  179027. */
  179028. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  179029. png_voidp progressive_ptr,
  179030. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  179031. png_progressive_end_ptr end_fn));
  179032. /* returns the user pointer associated with the push read functions */
  179033. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  179034. PNGARG((png_structp png_ptr));
  179035. /* function to be called when data becomes available */
  179036. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  179037. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  179038. /* function that combines rows. Not very much different than the
  179039. * png_combine_row() call. Is this even used?????
  179040. */
  179041. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  179042. png_bytep old_row, png_bytep new_row));
  179043. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179044. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  179045. png_uint_32 size));
  179046. #if defined(PNG_1_0_X)
  179047. # define png_malloc_warn png_malloc
  179048. #else
  179049. /* Added at libpng version 1.2.4 */
  179050. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  179051. png_uint_32 size));
  179052. #endif
  179053. /* frees a pointer allocated by png_malloc() */
  179054. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  179055. #if defined(PNG_1_0_X)
  179056. /* Function to allocate memory for zlib. */
  179057. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  179058. uInt size));
  179059. /* Function to free memory for zlib */
  179060. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  179061. #endif
  179062. /* Free data that was allocated internally */
  179063. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  179064. png_infop info_ptr, png_uint_32 free_me, int num));
  179065. #ifdef PNG_FREE_ME_SUPPORTED
  179066. /* Reassign responsibility for freeing existing data, whether allocated
  179067. * by libpng or by the application */
  179068. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  179069. png_infop info_ptr, int freer, png_uint_32 mask));
  179070. #endif
  179071. /* assignments for png_data_freer */
  179072. #define PNG_DESTROY_WILL_FREE_DATA 1
  179073. #define PNG_SET_WILL_FREE_DATA 1
  179074. #define PNG_USER_WILL_FREE_DATA 2
  179075. /* Flags for png_ptr->free_me and info_ptr->free_me */
  179076. #define PNG_FREE_HIST 0x0008
  179077. #define PNG_FREE_ICCP 0x0010
  179078. #define PNG_FREE_SPLT 0x0020
  179079. #define PNG_FREE_ROWS 0x0040
  179080. #define PNG_FREE_PCAL 0x0080
  179081. #define PNG_FREE_SCAL 0x0100
  179082. #define PNG_FREE_UNKN 0x0200
  179083. #define PNG_FREE_LIST 0x0400
  179084. #define PNG_FREE_PLTE 0x1000
  179085. #define PNG_FREE_TRNS 0x2000
  179086. #define PNG_FREE_TEXT 0x4000
  179087. #define PNG_FREE_ALL 0x7fff
  179088. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  179089. #ifdef PNG_USER_MEM_SUPPORTED
  179090. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  179091. png_uint_32 size));
  179092. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  179093. png_voidp ptr));
  179094. #endif
  179095. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  179096. png_voidp s1, png_voidp s2, png_uint_32 size));
  179097. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  179098. png_voidp s1, int value, png_uint_32 size));
  179099. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  179100. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  179101. int check));
  179102. #endif /* USE_FAR_KEYWORD */
  179103. #ifndef PNG_NO_ERROR_TEXT
  179104. /* Fatal error in PNG image of libpng - can't continue */
  179105. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  179106. png_const_charp error_message));
  179107. /* The same, but the chunk name is prepended to the error string. */
  179108. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  179109. png_const_charp error_message));
  179110. #else
  179111. /* Fatal error in PNG image of libpng - can't continue */
  179112. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  179113. #endif
  179114. #ifndef PNG_NO_WARNINGS
  179115. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  179116. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  179117. png_const_charp warning_message));
  179118. #ifdef PNG_READ_SUPPORTED
  179119. /* Non-fatal error in libpng, chunk name is prepended to message. */
  179120. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  179121. png_const_charp warning_message));
  179122. #endif /* PNG_READ_SUPPORTED */
  179123. #endif /* PNG_NO_WARNINGS */
  179124. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  179125. * Similarly, the png_get_<chunk> calls are used to read values from the
  179126. * png_info_struct, either storing the parameters in the passed variables, or
  179127. * setting pointers into the png_info_struct where the data is stored. The
  179128. * png_get_<chunk> functions return a non-zero value if the data was available
  179129. * in info_ptr, or return zero and do not change any of the parameters if the
  179130. * data was not available.
  179131. *
  179132. * These functions should be used instead of directly accessing png_info
  179133. * to avoid problems with future changes in the size and internal layout of
  179134. * png_info_struct.
  179135. */
  179136. /* Returns "flag" if chunk data is valid in info_ptr. */
  179137. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  179138. png_infop info_ptr, png_uint_32 flag));
  179139. /* Returns number of bytes needed to hold a transformed row. */
  179140. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  179141. png_infop info_ptr));
  179142. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179143. /* Returns row_pointers, which is an array of pointers to scanlines that was
  179144. returned from png_read_png(). */
  179145. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  179146. png_infop info_ptr));
  179147. /* Set row_pointers, which is an array of pointers to scanlines for use
  179148. by png_write_png(). */
  179149. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  179150. png_infop info_ptr, png_bytepp row_pointers));
  179151. #endif
  179152. /* Returns number of color channels in image. */
  179153. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  179154. png_infop info_ptr));
  179155. #ifdef PNG_EASY_ACCESS_SUPPORTED
  179156. /* Returns image width in pixels. */
  179157. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  179158. png_ptr, png_infop info_ptr));
  179159. /* Returns image height in pixels. */
  179160. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  179161. png_ptr, png_infop info_ptr));
  179162. /* Returns image bit_depth. */
  179163. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  179164. png_ptr, png_infop info_ptr));
  179165. /* Returns image color_type. */
  179166. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  179167. png_ptr, png_infop info_ptr));
  179168. /* Returns image filter_type. */
  179169. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  179170. png_ptr, png_infop info_ptr));
  179171. /* Returns image interlace_type. */
  179172. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  179173. png_ptr, png_infop info_ptr));
  179174. /* Returns image compression_type. */
  179175. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  179176. png_ptr, png_infop info_ptr));
  179177. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  179178. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  179179. png_ptr, png_infop info_ptr));
  179180. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  179181. png_ptr, png_infop info_ptr));
  179182. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  179183. png_ptr, png_infop info_ptr));
  179184. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  179185. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179186. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  179187. png_ptr, png_infop info_ptr));
  179188. #endif
  179189. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  179190. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  179191. png_ptr, png_infop info_ptr));
  179192. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  179193. png_ptr, png_infop info_ptr));
  179194. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  179195. png_ptr, png_infop info_ptr));
  179196. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  179197. png_ptr, png_infop info_ptr));
  179198. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179199. /* Returns pointer to signature string read from PNG header */
  179200. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  179201. png_infop info_ptr));
  179202. #if defined(PNG_bKGD_SUPPORTED)
  179203. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  179204. png_infop info_ptr, png_color_16p *background));
  179205. #endif
  179206. #if defined(PNG_bKGD_SUPPORTED)
  179207. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  179208. png_infop info_ptr, png_color_16p background));
  179209. #endif
  179210. #if defined(PNG_cHRM_SUPPORTED)
  179211. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179212. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  179213. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  179214. double *red_y, double *green_x, double *green_y, double *blue_x,
  179215. double *blue_y));
  179216. #endif
  179217. #ifdef PNG_FIXED_POINT_SUPPORTED
  179218. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  179219. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  179220. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  179221. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  179222. *int_blue_x, png_fixed_point *int_blue_y));
  179223. #endif
  179224. #endif
  179225. #if defined(PNG_cHRM_SUPPORTED)
  179226. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179227. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  179228. png_infop info_ptr, double white_x, double white_y, double red_x,
  179229. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  179230. #endif
  179231. #ifdef PNG_FIXED_POINT_SUPPORTED
  179232. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  179233. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  179234. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179235. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179236. png_fixed_point int_blue_y));
  179237. #endif
  179238. #endif
  179239. #if defined(PNG_gAMA_SUPPORTED)
  179240. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179241. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  179242. png_infop info_ptr, double *file_gamma));
  179243. #endif
  179244. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  179245. png_infop info_ptr, png_fixed_point *int_file_gamma));
  179246. #endif
  179247. #if defined(PNG_gAMA_SUPPORTED)
  179248. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179249. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  179250. png_infop info_ptr, double file_gamma));
  179251. #endif
  179252. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  179253. png_infop info_ptr, png_fixed_point int_file_gamma));
  179254. #endif
  179255. #if defined(PNG_hIST_SUPPORTED)
  179256. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  179257. png_infop info_ptr, png_uint_16p *hist));
  179258. #endif
  179259. #if defined(PNG_hIST_SUPPORTED)
  179260. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  179261. png_infop info_ptr, png_uint_16p hist));
  179262. #endif
  179263. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  179264. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  179265. int *bit_depth, int *color_type, int *interlace_method,
  179266. int *compression_method, int *filter_method));
  179267. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  179268. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  179269. int color_type, int interlace_method, int compression_method,
  179270. int filter_method));
  179271. #if defined(PNG_oFFs_SUPPORTED)
  179272. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  179273. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  179274. int *unit_type));
  179275. #endif
  179276. #if defined(PNG_oFFs_SUPPORTED)
  179277. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  179278. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  179279. int unit_type));
  179280. #endif
  179281. #if defined(PNG_pCAL_SUPPORTED)
  179282. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  179283. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  179284. int *type, int *nparams, png_charp *units, png_charpp *params));
  179285. #endif
  179286. #if defined(PNG_pCAL_SUPPORTED)
  179287. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  179288. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  179289. int type, int nparams, png_charp units, png_charpp params));
  179290. #endif
  179291. #if defined(PNG_pHYs_SUPPORTED)
  179292. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  179293. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  179294. #endif
  179295. #if defined(PNG_pHYs_SUPPORTED)
  179296. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  179297. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  179298. #endif
  179299. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  179300. png_infop info_ptr, png_colorp *palette, int *num_palette));
  179301. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  179302. png_infop info_ptr, png_colorp palette, int num_palette));
  179303. #if defined(PNG_sBIT_SUPPORTED)
  179304. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  179305. png_infop info_ptr, png_color_8p *sig_bit));
  179306. #endif
  179307. #if defined(PNG_sBIT_SUPPORTED)
  179308. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  179309. png_infop info_ptr, png_color_8p sig_bit));
  179310. #endif
  179311. #if defined(PNG_sRGB_SUPPORTED)
  179312. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  179313. png_infop info_ptr, int *intent));
  179314. #endif
  179315. #if defined(PNG_sRGB_SUPPORTED)
  179316. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  179317. png_infop info_ptr, int intent));
  179318. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  179319. png_infop info_ptr, int intent));
  179320. #endif
  179321. #if defined(PNG_iCCP_SUPPORTED)
  179322. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  179323. png_infop info_ptr, png_charpp name, int *compression_type,
  179324. png_charpp profile, png_uint_32 *proflen));
  179325. /* Note to maintainer: profile should be png_bytepp */
  179326. #endif
  179327. #if defined(PNG_iCCP_SUPPORTED)
  179328. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  179329. png_infop info_ptr, png_charp name, int compression_type,
  179330. png_charp profile, png_uint_32 proflen));
  179331. /* Note to maintainer: profile should be png_bytep */
  179332. #endif
  179333. #if defined(PNG_sPLT_SUPPORTED)
  179334. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  179335. png_infop info_ptr, png_sPLT_tpp entries));
  179336. #endif
  179337. #if defined(PNG_sPLT_SUPPORTED)
  179338. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  179339. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  179340. #endif
  179341. #if defined(PNG_TEXT_SUPPORTED)
  179342. /* png_get_text also returns the number of text chunks in *num_text */
  179343. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  179344. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  179345. #endif
  179346. /*
  179347. * Note while png_set_text() will accept a structure whose text,
  179348. * language, and translated keywords are NULL pointers, the structure
  179349. * returned by png_get_text will always contain regular
  179350. * zero-terminated C strings. They might be empty strings but
  179351. * they will never be NULL pointers.
  179352. */
  179353. #if defined(PNG_TEXT_SUPPORTED)
  179354. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  179355. png_infop info_ptr, png_textp text_ptr, int num_text));
  179356. #endif
  179357. #if defined(PNG_tIME_SUPPORTED)
  179358. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  179359. png_infop info_ptr, png_timep *mod_time));
  179360. #endif
  179361. #if defined(PNG_tIME_SUPPORTED)
  179362. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  179363. png_infop info_ptr, png_timep mod_time));
  179364. #endif
  179365. #if defined(PNG_tRNS_SUPPORTED)
  179366. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  179367. png_infop info_ptr, png_bytep *trans, int *num_trans,
  179368. png_color_16p *trans_values));
  179369. #endif
  179370. #if defined(PNG_tRNS_SUPPORTED)
  179371. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  179372. png_infop info_ptr, png_bytep trans, int num_trans,
  179373. png_color_16p trans_values));
  179374. #endif
  179375. #if defined(PNG_tRNS_SUPPORTED)
  179376. #endif
  179377. #if defined(PNG_sCAL_SUPPORTED)
  179378. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179379. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  179380. png_infop info_ptr, int *unit, double *width, double *height));
  179381. #else
  179382. #ifdef PNG_FIXED_POINT_SUPPORTED
  179383. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  179384. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  179385. #endif
  179386. #endif
  179387. #endif /* PNG_sCAL_SUPPORTED */
  179388. #if defined(PNG_sCAL_SUPPORTED)
  179389. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179390. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  179391. png_infop info_ptr, int unit, double width, double height));
  179392. #else
  179393. #ifdef PNG_FIXED_POINT_SUPPORTED
  179394. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  179395. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  179396. #endif
  179397. #endif
  179398. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  179399. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179400. /* provide a list of chunks and how they are to be handled, if the built-in
  179401. handling or default unknown chunk handling is not desired. Any chunks not
  179402. listed will be handled in the default manner. The IHDR and IEND chunks
  179403. must not be listed.
  179404. keep = 0: follow default behaviour
  179405. = 1: do not keep
  179406. = 2: keep only if safe-to-copy
  179407. = 3: keep even if unsafe-to-copy
  179408. */
  179409. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  179410. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  179411. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  179412. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  179413. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  179414. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  179415. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  179416. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  179417. #endif
  179418. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  179419. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  179420. chunk_name));
  179421. #endif
  179422. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  179423. If you need to turn it off for a chunk that your application has freed,
  179424. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  179425. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  179426. png_infop info_ptr, int mask));
  179427. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179428. /* The "params" pointer is currently not used and is for future expansion. */
  179429. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  179430. png_infop info_ptr,
  179431. int transforms,
  179432. png_voidp params));
  179433. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  179434. png_infop info_ptr,
  179435. int transforms,
  179436. png_voidp params));
  179437. #endif
  179438. /* Define PNG_DEBUG at compile time for debugging information. Higher
  179439. * numbers for PNG_DEBUG mean more debugging information. This has
  179440. * only been added since version 0.95 so it is not implemented throughout
  179441. * libpng yet, but more support will be added as needed.
  179442. */
  179443. #ifdef PNG_DEBUG
  179444. #if (PNG_DEBUG > 0)
  179445. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  179446. #include <crtdbg.h>
  179447. #if (PNG_DEBUG > 1)
  179448. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  179449. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  179450. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  179451. #endif
  179452. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  179453. #ifndef PNG_DEBUG_FILE
  179454. #define PNG_DEBUG_FILE stderr
  179455. #endif /* PNG_DEBUG_FILE */
  179456. #if (PNG_DEBUG > 1)
  179457. #define png_debug(l,m) \
  179458. { \
  179459. int num_tabs=l; \
  179460. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179461. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  179462. }
  179463. #define png_debug1(l,m,p1) \
  179464. { \
  179465. int num_tabs=l; \
  179466. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179467. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  179468. }
  179469. #define png_debug2(l,m,p1,p2) \
  179470. { \
  179471. int num_tabs=l; \
  179472. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179473. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  179474. }
  179475. #endif /* (PNG_DEBUG > 1) */
  179476. #endif /* _MSC_VER */
  179477. #endif /* (PNG_DEBUG > 0) */
  179478. #endif /* PNG_DEBUG */
  179479. #ifndef png_debug
  179480. #define png_debug(l, m)
  179481. #endif
  179482. #ifndef png_debug1
  179483. #define png_debug1(l, m, p1)
  179484. #endif
  179485. #ifndef png_debug2
  179486. #define png_debug2(l, m, p1, p2)
  179487. #endif
  179488. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  179489. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  179490. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  179491. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  179492. #ifdef PNG_MNG_FEATURES_SUPPORTED
  179493. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  179494. png_ptr, png_uint_32 mng_features_permitted));
  179495. #endif
  179496. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  179497. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  179498. #define PNG_HANDLE_CHUNK_NEVER 1
  179499. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  179500. #define PNG_HANDLE_CHUNK_ALWAYS 3
  179501. /* Added to version 1.2.0 */
  179502. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179503. #if defined(PNG_MMX_CODE_SUPPORTED)
  179504. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  179505. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  179506. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  179507. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  179508. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  179509. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  179510. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  179511. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  179512. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  179513. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  179514. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  179515. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  179516. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  179517. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  179518. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  179519. #define PNG_MMX_WRITE_FLAGS ( 0 )
  179520. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  179521. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  179522. | PNG_MMX_READ_FLAGS \
  179523. | PNG_MMX_WRITE_FLAGS )
  179524. #define PNG_SELECT_READ 1
  179525. #define PNG_SELECT_WRITE 2
  179526. #endif /* PNG_MMX_CODE_SUPPORTED */
  179527. #if !defined(PNG_1_0_X)
  179528. /* pngget.c */
  179529. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  179530. PNGARG((int flag_select, int *compilerID));
  179531. /* pngget.c */
  179532. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  179533. PNGARG((int flag_select));
  179534. /* pngget.c */
  179535. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  179536. PNGARG((png_structp png_ptr));
  179537. /* pngget.c */
  179538. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  179539. PNGARG((png_structp png_ptr));
  179540. /* pngget.c */
  179541. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  179542. PNGARG((png_structp png_ptr));
  179543. /* pngset.c */
  179544. extern PNG_EXPORT(void,png_set_asm_flags)
  179545. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  179546. /* pngset.c */
  179547. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  179548. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  179549. png_uint_32 mmx_rowbytes_threshold));
  179550. #endif /* PNG_1_0_X */
  179551. #if !defined(PNG_1_0_X)
  179552. /* png.c, pnggccrd.c, or pngvcrd.c */
  179553. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  179554. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  179555. /* Strip the prepended error numbers ("#nnn ") from error and warning
  179556. * messages before passing them to the error or warning handler. */
  179557. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179558. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  179559. png_ptr, png_uint_32 strip_mode));
  179560. #endif
  179561. #endif /* PNG_1_0_X */
  179562. /* Added at libpng-1.2.6 */
  179563. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179564. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  179565. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  179566. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  179567. png_ptr));
  179568. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  179569. png_ptr));
  179570. #endif
  179571. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  179572. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  179573. /* With these routines we avoid an integer divide, which will be slower on
  179574. * most machines. However, it does take more operations than the corresponding
  179575. * divide method, so it may be slower on a few RISC systems. There are two
  179576. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  179577. *
  179578. * Note that the rounding factors are NOT supposed to be the same! 128 and
  179579. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  179580. * standard method.
  179581. *
  179582. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  179583. */
  179584. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  179585. # define png_composite(composite, fg, alpha, bg) \
  179586. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  179587. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  179588. (png_uint_16)(alpha)) + (png_uint_16)128); \
  179589. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  179590. # define png_composite_16(composite, fg, alpha, bg) \
  179591. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  179592. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  179593. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  179594. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  179595. #else /* standard method using integer division */
  179596. # define png_composite(composite, fg, alpha, bg) \
  179597. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  179598. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  179599. (png_uint_16)127) / 255)
  179600. # define png_composite_16(composite, fg, alpha, bg) \
  179601. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  179602. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  179603. (png_uint_32)32767) / (png_uint_32)65535L)
  179604. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  179605. /* Inline macros to do direct reads of bytes from the input buffer. These
  179606. * require that you are using an architecture that uses PNG byte ordering
  179607. * (MSB first) and supports unaligned data storage. I think that PowerPC
  179608. * in big-endian mode and 680x0 are the only ones that will support this.
  179609. * The x86 line of processors definitely do not. The png_get_int_32()
  179610. * routine also assumes we are using two's complement format for negative
  179611. * values, which is almost certainly true.
  179612. */
  179613. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  179614. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  179615. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  179616. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  179617. #else
  179618. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  179619. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  179620. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  179621. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  179622. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  179623. PNGARG((png_structp png_ptr, png_bytep buf));
  179624. /* No png_get_int_16 -- may be added if there's a real need for it. */
  179625. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  179626. */
  179627. extern PNG_EXPORT(void,png_save_uint_32)
  179628. PNGARG((png_bytep buf, png_uint_32 i));
  179629. extern PNG_EXPORT(void,png_save_int_32)
  179630. PNGARG((png_bytep buf, png_int_32 i));
  179631. /* Place a 16-bit number into a buffer in PNG byte order.
  179632. * The parameter is declared unsigned int, not png_uint_16,
  179633. * just to avoid potential problems on pre-ANSI C compilers.
  179634. */
  179635. extern PNG_EXPORT(void,png_save_uint_16)
  179636. PNGARG((png_bytep buf, unsigned int i));
  179637. /* No png_save_int_16 -- may be added if there's a real need for it. */
  179638. /* ************************************************************************* */
  179639. /* These next functions are used internally in the code. They generally
  179640. * shouldn't be used unless you are writing code to add or replace some
  179641. * functionality in libpng. More information about most functions can
  179642. * be found in the files where the functions are located.
  179643. */
  179644. /* Various modes of operation, that are visible to applications because
  179645. * they are used for unknown chunk location.
  179646. */
  179647. #define PNG_HAVE_IHDR 0x01
  179648. #define PNG_HAVE_PLTE 0x02
  179649. #define PNG_HAVE_IDAT 0x04
  179650. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  179651. #define PNG_HAVE_IEND 0x10
  179652. #if defined(PNG_INTERNAL)
  179653. /* More modes of operation. Note that after an init, mode is set to
  179654. * zero automatically when the structure is created.
  179655. */
  179656. #define PNG_HAVE_gAMA 0x20
  179657. #define PNG_HAVE_cHRM 0x40
  179658. #define PNG_HAVE_sRGB 0x80
  179659. #define PNG_HAVE_CHUNK_HEADER 0x100
  179660. #define PNG_WROTE_tIME 0x200
  179661. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  179662. #define PNG_BACKGROUND_IS_GRAY 0x800
  179663. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  179664. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  179665. /* flags for the transformations the PNG library does on the image data */
  179666. #define PNG_BGR 0x0001
  179667. #define PNG_INTERLACE 0x0002
  179668. #define PNG_PACK 0x0004
  179669. #define PNG_SHIFT 0x0008
  179670. #define PNG_SWAP_BYTES 0x0010
  179671. #define PNG_INVERT_MONO 0x0020
  179672. #define PNG_DITHER 0x0040
  179673. #define PNG_BACKGROUND 0x0080
  179674. #define PNG_BACKGROUND_EXPAND 0x0100
  179675. /* 0x0200 unused */
  179676. #define PNG_16_TO_8 0x0400
  179677. #define PNG_RGBA 0x0800
  179678. #define PNG_EXPAND 0x1000
  179679. #define PNG_GAMMA 0x2000
  179680. #define PNG_GRAY_TO_RGB 0x4000
  179681. #define PNG_FILLER 0x8000L
  179682. #define PNG_PACKSWAP 0x10000L
  179683. #define PNG_SWAP_ALPHA 0x20000L
  179684. #define PNG_STRIP_ALPHA 0x40000L
  179685. #define PNG_INVERT_ALPHA 0x80000L
  179686. #define PNG_USER_TRANSFORM 0x100000L
  179687. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  179688. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  179689. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  179690. /* 0x800000L Unused */
  179691. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  179692. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  179693. /* 0x4000000L unused */
  179694. /* 0x8000000L unused */
  179695. /* 0x10000000L unused */
  179696. /* 0x20000000L unused */
  179697. /* 0x40000000L unused */
  179698. /* flags for png_create_struct */
  179699. #define PNG_STRUCT_PNG 0x0001
  179700. #define PNG_STRUCT_INFO 0x0002
  179701. /* Scaling factor for filter heuristic weighting calculations */
  179702. #define PNG_WEIGHT_SHIFT 8
  179703. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  179704. #define PNG_COST_SHIFT 3
  179705. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  179706. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  179707. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  179708. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  179709. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  179710. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  179711. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  179712. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  179713. #define PNG_FLAG_ROW_INIT 0x0040
  179714. #define PNG_FLAG_FILLER_AFTER 0x0080
  179715. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  179716. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  179717. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  179718. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  179719. #define PNG_FLAG_FREE_PLTE 0x1000
  179720. #define PNG_FLAG_FREE_TRNS 0x2000
  179721. #define PNG_FLAG_FREE_HIST 0x4000
  179722. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  179723. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  179724. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  179725. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  179726. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  179727. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  179728. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  179729. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  179730. /* 0x800000L unused */
  179731. /* 0x1000000L unused */
  179732. /* 0x2000000L unused */
  179733. /* 0x4000000L unused */
  179734. /* 0x8000000L unused */
  179735. /* 0x10000000L unused */
  179736. /* 0x20000000L unused */
  179737. /* 0x40000000L unused */
  179738. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  179739. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  179740. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  179741. PNG_FLAG_CRC_CRITICAL_IGNORE)
  179742. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  179743. PNG_FLAG_CRC_CRITICAL_MASK)
  179744. /* save typing and make code easier to understand */
  179745. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  179746. abs((int)((c1).green) - (int)((c2).green)) + \
  179747. abs((int)((c1).blue) - (int)((c2).blue)))
  179748. /* Added to libpng-1.2.6 JB */
  179749. #define PNG_ROWBYTES(pixel_bits, width) \
  179750. ((pixel_bits) >= 8 ? \
  179751. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  179752. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  179753. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  179754. ideal-delta..ideal+delta. Each argument is evaluated twice.
  179755. "ideal" and "delta" should be constants, normally simple
  179756. integers, "value" a variable. Added to libpng-1.2.6 JB */
  179757. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  179758. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  179759. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  179760. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  179761. /* place to hold the signature string for a PNG file. */
  179762. #ifdef PNG_USE_GLOBAL_ARRAYS
  179763. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  179764. #else
  179765. #endif
  179766. #endif /* PNG_NO_EXTERN */
  179767. /* Constant strings for known chunk types. If you need to add a chunk,
  179768. * define the name here, and add an invocation of the macro in png.c and
  179769. * wherever it's needed.
  179770. */
  179771. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  179772. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  179773. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  179774. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  179775. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  179776. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  179777. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  179778. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  179779. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  179780. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  179781. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  179782. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  179783. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  179784. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  179785. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  179786. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  179787. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  179788. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  179789. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  179790. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  179791. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  179792. #ifdef PNG_USE_GLOBAL_ARRAYS
  179793. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  179794. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  179795. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  179796. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  179797. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  179798. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  179799. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  179800. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  179801. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  179802. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  179803. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  179804. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  179805. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  179806. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  179807. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  179808. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  179809. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  179810. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  179811. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  179812. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  179813. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  179814. #endif /* PNG_USE_GLOBAL_ARRAYS */
  179815. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179816. /* Initialize png_ptr struct for reading, and allocate any other memory.
  179817. * (old interface - DEPRECATED - use png_create_read_struct instead).
  179818. */
  179819. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  179820. #undef png_read_init
  179821. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  179822. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179823. #endif
  179824. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  179825. png_const_charp user_png_ver, png_size_t png_struct_size));
  179826. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179827. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  179828. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179829. png_info_size));
  179830. #endif
  179831. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179832. /* Initialize png_ptr struct for writing, and allocate any other memory.
  179833. * (old interface - DEPRECATED - use png_create_write_struct instead).
  179834. */
  179835. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  179836. #undef png_write_init
  179837. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  179838. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179839. #endif
  179840. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  179841. png_const_charp user_png_ver, png_size_t png_struct_size));
  179842. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  179843. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179844. png_info_size));
  179845. /* Allocate memory for an internal libpng struct */
  179846. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  179847. /* Free memory from internal libpng struct */
  179848. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  179849. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  179850. malloc_fn, png_voidp mem_ptr));
  179851. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  179852. png_free_ptr free_fn, png_voidp mem_ptr));
  179853. /* Free any memory that info_ptr points to and reset struct. */
  179854. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  179855. png_infop info_ptr));
  179856. #ifndef PNG_1_0_X
  179857. /* Function to allocate memory for zlib. */
  179858. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  179859. /* Function to free memory for zlib */
  179860. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  179861. #ifdef PNG_SIZE_T
  179862. /* Function to convert a sizeof an item to png_sizeof item */
  179863. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179864. #endif
  179865. /* Next four functions are used internally as callbacks. PNGAPI is required
  179866. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  179867. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  179868. png_bytep data, png_size_t length));
  179869. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179870. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  179871. png_bytep buffer, png_size_t length));
  179872. #endif
  179873. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  179874. png_bytep data, png_size_t length));
  179875. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179876. #if !defined(PNG_NO_STDIO)
  179877. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  179878. #endif
  179879. #endif
  179880. #else /* PNG_1_0_X */
  179881. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179882. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  179883. png_bytep buffer, png_size_t length));
  179884. #endif
  179885. #endif /* PNG_1_0_X */
  179886. /* Reset the CRC variable */
  179887. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  179888. /* Write the "data" buffer to whatever output you are using. */
  179889. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  179890. png_size_t length));
  179891. /* Read data from whatever input you are using into the "data" buffer */
  179892. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  179893. png_size_t length));
  179894. /* Read bytes into buf, and update png_ptr->crc */
  179895. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  179896. png_size_t length));
  179897. /* Decompress data in a chunk that uses compression */
  179898. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  179899. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  179900. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  179901. int comp_type, png_charp chunkdata, png_size_t chunklength,
  179902. png_size_t prefix_length, png_size_t *data_length));
  179903. #endif
  179904. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  179905. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  179906. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  179907. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  179908. /* Calculate the CRC over a section of data. Note that we are only
  179909. * passing a maximum of 64K on systems that have this as a memory limit,
  179910. * since this is the maximum buffer size we can specify.
  179911. */
  179912. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  179913. png_size_t length));
  179914. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179915. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  179916. #endif
  179917. /* simple function to write the signature */
  179918. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  179919. /* write various chunks */
  179920. /* Write the IHDR chunk, and update the png_struct with the necessary
  179921. * information.
  179922. */
  179923. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  179924. png_uint_32 height,
  179925. int bit_depth, int color_type, int compression_method, int filter_method,
  179926. int interlace_method));
  179927. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  179928. png_uint_32 num_pal));
  179929. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  179930. png_size_t length));
  179931. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  179932. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  179933. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179934. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  179935. #endif
  179936. #ifdef PNG_FIXED_POINT_SUPPORTED
  179937. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  179938. file_gamma));
  179939. #endif
  179940. #endif
  179941. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  179942. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  179943. int color_type));
  179944. #endif
  179945. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  179946. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179947. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  179948. double white_x, double white_y,
  179949. double red_x, double red_y, double green_x, double green_y,
  179950. double blue_x, double blue_y));
  179951. #endif
  179952. #ifdef PNG_FIXED_POINT_SUPPORTED
  179953. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  179954. png_fixed_point int_white_x, png_fixed_point int_white_y,
  179955. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179956. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179957. png_fixed_point int_blue_y));
  179958. #endif
  179959. #endif
  179960. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  179961. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  179962. int intent));
  179963. #endif
  179964. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  179965. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  179966. png_charp name, int compression_type,
  179967. png_charp profile, int proflen));
  179968. /* Note to maintainer: profile should be png_bytep */
  179969. #endif
  179970. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  179971. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  179972. png_sPLT_tp palette));
  179973. #endif
  179974. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  179975. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  179976. png_color_16p values, int number, int color_type));
  179977. #endif
  179978. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  179979. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  179980. png_color_16p values, int color_type));
  179981. #endif
  179982. #if defined(PNG_WRITE_hIST_SUPPORTED)
  179983. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  179984. int num_hist));
  179985. #endif
  179986. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  179987. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  179988. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  179989. png_charp key, png_charpp new_key));
  179990. #endif
  179991. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  179992. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  179993. png_charp text, png_size_t text_len));
  179994. #endif
  179995. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  179996. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  179997. png_charp text, png_size_t text_len, int compression));
  179998. #endif
  179999. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  180000. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  180001. int compression, png_charp key, png_charp lang, png_charp lang_key,
  180002. png_charp text));
  180003. #endif
  180004. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  180005. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  180006. png_infop info_ptr, png_textp text_ptr, int num_text));
  180007. #endif
  180008. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  180009. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  180010. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  180011. #endif
  180012. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  180013. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  180014. png_int_32 X0, png_int_32 X1, int type, int nparams,
  180015. png_charp units, png_charpp params));
  180016. #endif
  180017. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  180018. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  180019. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  180020. int unit_type));
  180021. #endif
  180022. #if defined(PNG_WRITE_tIME_SUPPORTED)
  180023. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  180024. png_timep mod_time));
  180025. #endif
  180026. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  180027. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  180028. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  180029. int unit, double width, double height));
  180030. #else
  180031. #ifdef PNG_FIXED_POINT_SUPPORTED
  180032. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  180033. int unit, png_charp width, png_charp height));
  180034. #endif
  180035. #endif
  180036. #endif
  180037. /* Called when finished processing a row of data */
  180038. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  180039. /* Internal use only. Called before first row of data */
  180040. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  180041. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180042. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  180043. #endif
  180044. /* combine a row of data, dealing with alpha, etc. if requested */
  180045. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  180046. int mask));
  180047. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  180048. /* expand an interlaced row */
  180049. /* OLD pre-1.0.9 interface:
  180050. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  180051. png_bytep row, int pass, png_uint_32 transformations));
  180052. */
  180053. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  180054. #endif
  180055. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  180056. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180057. /* grab pixels out of a row for an interlaced pass */
  180058. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  180059. png_bytep row, int pass));
  180060. #endif
  180061. /* unfilter a row */
  180062. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  180063. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  180064. /* Choose the best filter to use and filter the row data */
  180065. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  180066. png_row_infop row_info));
  180067. /* Write out the filtered row. */
  180068. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  180069. png_bytep filtered_row));
  180070. /* finish a row while reading, dealing with interlacing passes, etc. */
  180071. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  180072. /* initialize the row buffers, etc. */
  180073. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  180074. /* optional call to update the users info structure */
  180075. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  180076. png_infop info_ptr));
  180077. /* these are the functions that do the transformations */
  180078. #if defined(PNG_READ_FILLER_SUPPORTED)
  180079. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  180080. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  180081. #endif
  180082. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  180083. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  180084. png_bytep row));
  180085. #endif
  180086. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  180087. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  180088. png_bytep row));
  180089. #endif
  180090. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  180091. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  180092. png_bytep row));
  180093. #endif
  180094. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  180095. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  180096. png_bytep row));
  180097. #endif
  180098. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  180099. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  180100. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  180101. png_bytep row, png_uint_32 flags));
  180102. #endif
  180103. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  180104. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  180105. #endif
  180106. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  180107. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  180108. #endif
  180109. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180110. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  180111. row_info, png_bytep row));
  180112. #endif
  180113. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  180114. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  180115. png_bytep row));
  180116. #endif
  180117. #if defined(PNG_READ_PACK_SUPPORTED)
  180118. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  180119. #endif
  180120. #if defined(PNG_READ_SHIFT_SUPPORTED)
  180121. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  180122. png_color_8p sig_bits));
  180123. #endif
  180124. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  180125. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  180126. #endif
  180127. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  180128. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  180129. #endif
  180130. #if defined(PNG_READ_DITHER_SUPPORTED)
  180131. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  180132. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  180133. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  180134. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  180135. png_colorp palette, int num_palette));
  180136. # endif
  180137. #endif
  180138. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  180139. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  180140. #endif
  180141. #if defined(PNG_WRITE_PACK_SUPPORTED)
  180142. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  180143. png_bytep row, png_uint_32 bit_depth));
  180144. #endif
  180145. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  180146. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  180147. png_color_8p bit_depth));
  180148. #endif
  180149. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  180150. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180151. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180152. png_color_16p trans_values, png_color_16p background,
  180153. png_color_16p background_1,
  180154. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  180155. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  180156. png_uint_16pp gamma_16_to_1, int gamma_shift));
  180157. #else
  180158. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  180159. png_color_16p trans_values, png_color_16p background));
  180160. #endif
  180161. #endif
  180162. #if defined(PNG_READ_GAMMA_SUPPORTED)
  180163. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  180164. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  180165. int gamma_shift));
  180166. #endif
  180167. #if defined(PNG_READ_EXPAND_SUPPORTED)
  180168. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  180169. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  180170. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  180171. png_bytep row, png_color_16p trans_value));
  180172. #endif
  180173. /* The following decodes the appropriate chunks, and does error correction,
  180174. * then calls the appropriate callback for the chunk if it is valid.
  180175. */
  180176. /* decode the IHDR chunk */
  180177. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  180178. png_uint_32 length));
  180179. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  180180. png_uint_32 length));
  180181. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  180182. png_uint_32 length));
  180183. #if defined(PNG_READ_bKGD_SUPPORTED)
  180184. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  180185. png_uint_32 length));
  180186. #endif
  180187. #if defined(PNG_READ_cHRM_SUPPORTED)
  180188. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  180189. png_uint_32 length));
  180190. #endif
  180191. #if defined(PNG_READ_gAMA_SUPPORTED)
  180192. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  180193. png_uint_32 length));
  180194. #endif
  180195. #if defined(PNG_READ_hIST_SUPPORTED)
  180196. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  180197. png_uint_32 length));
  180198. #endif
  180199. #if defined(PNG_READ_iCCP_SUPPORTED)
  180200. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  180201. png_uint_32 length));
  180202. #endif /* PNG_READ_iCCP_SUPPORTED */
  180203. #if defined(PNG_READ_iTXt_SUPPORTED)
  180204. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180205. png_uint_32 length));
  180206. #endif
  180207. #if defined(PNG_READ_oFFs_SUPPORTED)
  180208. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180209. png_uint_32 length));
  180210. #endif
  180211. #if defined(PNG_READ_pCAL_SUPPORTED)
  180212. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180213. png_uint_32 length));
  180214. #endif
  180215. #if defined(PNG_READ_pHYs_SUPPORTED)
  180216. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180217. png_uint_32 length));
  180218. #endif
  180219. #if defined(PNG_READ_sBIT_SUPPORTED)
  180220. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180221. png_uint_32 length));
  180222. #endif
  180223. #if defined(PNG_READ_sCAL_SUPPORTED)
  180224. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180225. png_uint_32 length));
  180226. #endif
  180227. #if defined(PNG_READ_sPLT_SUPPORTED)
  180228. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180229. png_uint_32 length));
  180230. #endif /* PNG_READ_sPLT_SUPPORTED */
  180231. #if defined(PNG_READ_sRGB_SUPPORTED)
  180232. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  180233. png_uint_32 length));
  180234. #endif
  180235. #if defined(PNG_READ_tEXt_SUPPORTED)
  180236. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180237. png_uint_32 length));
  180238. #endif
  180239. #if defined(PNG_READ_tIME_SUPPORTED)
  180240. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  180241. png_uint_32 length));
  180242. #endif
  180243. #if defined(PNG_READ_tRNS_SUPPORTED)
  180244. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  180245. png_uint_32 length));
  180246. #endif
  180247. #if defined(PNG_READ_zTXt_SUPPORTED)
  180248. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180249. png_uint_32 length));
  180250. #endif
  180251. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  180252. png_infop info_ptr, png_uint_32 length));
  180253. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  180254. png_bytep chunk_name));
  180255. /* handle the transformations for reading and writing */
  180256. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  180257. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  180258. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  180259. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180260. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  180261. png_infop info_ptr));
  180262. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  180263. png_infop info_ptr));
  180264. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  180265. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  180266. png_uint_32 length));
  180267. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  180268. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  180269. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  180270. png_bytep buffer, png_size_t buffer_length));
  180271. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  180272. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  180273. png_bytep buffer, png_size_t buffer_length));
  180274. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  180275. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  180276. png_infop info_ptr, png_uint_32 length));
  180277. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  180278. png_infop info_ptr));
  180279. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  180280. png_infop info_ptr));
  180281. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  180282. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  180283. png_infop info_ptr));
  180284. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  180285. png_infop info_ptr));
  180286. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  180287. #if defined(PNG_READ_tEXt_SUPPORTED)
  180288. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  180289. png_infop info_ptr, png_uint_32 length));
  180290. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  180291. png_infop info_ptr));
  180292. #endif
  180293. #if defined(PNG_READ_zTXt_SUPPORTED)
  180294. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  180295. png_infop info_ptr, png_uint_32 length));
  180296. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  180297. png_infop info_ptr));
  180298. #endif
  180299. #if defined(PNG_READ_iTXt_SUPPORTED)
  180300. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  180301. png_infop info_ptr, png_uint_32 length));
  180302. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  180303. png_infop info_ptr));
  180304. #endif
  180305. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  180306. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180307. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  180308. png_bytep row));
  180309. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  180310. png_bytep row));
  180311. #endif
  180312. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180313. #if defined(PNG_MMX_CODE_SUPPORTED)
  180314. /* png.c */ /* PRIVATE */
  180315. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  180316. #endif
  180317. #endif
  180318. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  180319. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  180320. png_infop info_ptr));
  180321. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  180322. png_infop info_ptr));
  180323. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  180324. png_infop info_ptr));
  180325. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  180326. png_infop info_ptr));
  180327. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  180328. png_infop info_ptr));
  180329. #if defined(PNG_pHYs_SUPPORTED)
  180330. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  180331. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180332. #endif /* PNG_pHYs_SUPPORTED */
  180333. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  180334. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  180335. #endif /* PNG_INTERNAL */
  180336. #ifdef __cplusplus
  180337. }
  180338. #endif
  180339. #endif /* PNG_VERSION_INFO_ONLY */
  180340. /* do not put anything past this line */
  180341. #endif /* PNG_H */
  180342. /********* End of inlined file: png.h *********/
  180343. #define PNG_NO_EXTERN
  180344. /********* Start of inlined file: png.c *********/
  180345. /* png.c - location for general purpose libpng functions
  180346. *
  180347. * Last changed in libpng 1.2.21 [October 4, 2007]
  180348. * For conditions of distribution and use, see copyright notice in png.h
  180349. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180350. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180351. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180352. */
  180353. #define PNG_INTERNAL
  180354. #define PNG_NO_EXTERN
  180355. /* Generate a compiler error if there is an old png.h in the search path. */
  180356. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  180357. /* Version information for C files. This had better match the version
  180358. * string defined in png.h. */
  180359. #ifdef PNG_USE_GLOBAL_ARRAYS
  180360. /* png_libpng_ver was changed to a function in version 1.0.5c */
  180361. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  180362. #ifdef PNG_READ_SUPPORTED
  180363. /* png_sig was changed to a function in version 1.0.5c */
  180364. /* Place to hold the signature string for a PNG file. */
  180365. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180366. #endif /* PNG_READ_SUPPORTED */
  180367. /* Invoke global declarations for constant strings for known chunk types */
  180368. PNG_IHDR;
  180369. PNG_IDAT;
  180370. PNG_IEND;
  180371. PNG_PLTE;
  180372. PNG_bKGD;
  180373. PNG_cHRM;
  180374. PNG_gAMA;
  180375. PNG_hIST;
  180376. PNG_iCCP;
  180377. PNG_iTXt;
  180378. PNG_oFFs;
  180379. PNG_pCAL;
  180380. PNG_sCAL;
  180381. PNG_pHYs;
  180382. PNG_sBIT;
  180383. PNG_sPLT;
  180384. PNG_sRGB;
  180385. PNG_tEXt;
  180386. PNG_tIME;
  180387. PNG_tRNS;
  180388. PNG_zTXt;
  180389. #ifdef PNG_READ_SUPPORTED
  180390. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  180391. /* start of interlace block */
  180392. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  180393. /* offset to next interlace block */
  180394. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  180395. /* start of interlace block in the y direction */
  180396. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  180397. /* offset to next interlace block in the y direction */
  180398. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  180399. /* Height of interlace block. This is not currently used - if you need
  180400. * it, uncomment it here and in png.h
  180401. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  180402. */
  180403. /* Mask to determine which pixels are valid in a pass */
  180404. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  180405. /* Mask to determine which pixels to overwrite while displaying */
  180406. PNG_CONST int FARDATA png_pass_dsp_mask[]
  180407. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  180408. #endif /* PNG_READ_SUPPORTED */
  180409. #endif /* PNG_USE_GLOBAL_ARRAYS */
  180410. /* Tells libpng that we have already handled the first "num_bytes" bytes
  180411. * of the PNG file signature. If the PNG data is embedded into another
  180412. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  180413. * or write any of the magic bytes before it starts on the IHDR.
  180414. */
  180415. #ifdef PNG_READ_SUPPORTED
  180416. void PNGAPI
  180417. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  180418. {
  180419. if(png_ptr == NULL) return;
  180420. png_debug(1, "in png_set_sig_bytes\n");
  180421. if (num_bytes > 8)
  180422. png_error(png_ptr, "Too many bytes for PNG signature.");
  180423. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  180424. }
  180425. /* Checks whether the supplied bytes match the PNG signature. We allow
  180426. * checking less than the full 8-byte signature so that those apps that
  180427. * already read the first few bytes of a file to determine the file type
  180428. * can simply check the remaining bytes for extra assurance. Returns
  180429. * an integer less than, equal to, or greater than zero if sig is found,
  180430. * respectively, to be less than, to match, or be greater than the correct
  180431. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  180432. */
  180433. int PNGAPI
  180434. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  180435. {
  180436. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180437. if (num_to_check > 8)
  180438. num_to_check = 8;
  180439. else if (num_to_check < 1)
  180440. return (-1);
  180441. if (start > 7)
  180442. return (-1);
  180443. if (start + num_to_check > 8)
  180444. num_to_check = 8 - start;
  180445. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  180446. }
  180447. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180448. /* (Obsolete) function to check signature bytes. It does not allow one
  180449. * to check a partial signature. This function might be removed in the
  180450. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  180451. */
  180452. int PNGAPI
  180453. png_check_sig(png_bytep sig, int num)
  180454. {
  180455. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  180456. }
  180457. #endif
  180458. #endif /* PNG_READ_SUPPORTED */
  180459. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180460. /* Function to allocate memory for zlib and clear it to 0. */
  180461. #ifdef PNG_1_0_X
  180462. voidpf PNGAPI
  180463. #else
  180464. voidpf /* private */
  180465. #endif
  180466. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  180467. {
  180468. png_voidp ptr;
  180469. png_structp p=(png_structp)png_ptr;
  180470. png_uint_32 save_flags=p->flags;
  180471. png_uint_32 num_bytes;
  180472. if(png_ptr == NULL) return (NULL);
  180473. if (items > PNG_UINT_32_MAX/size)
  180474. {
  180475. png_warning (p, "Potential overflow in png_zalloc()");
  180476. return (NULL);
  180477. }
  180478. num_bytes = (png_uint_32)items * size;
  180479. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180480. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  180481. p->flags=save_flags;
  180482. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  180483. if (ptr == NULL)
  180484. return ((voidpf)ptr);
  180485. if (num_bytes > (png_uint_32)0x8000L)
  180486. {
  180487. png_memset(ptr, 0, (png_size_t)0x8000L);
  180488. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  180489. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  180490. }
  180491. else
  180492. {
  180493. png_memset(ptr, 0, (png_size_t)num_bytes);
  180494. }
  180495. #endif
  180496. return ((voidpf)ptr);
  180497. }
  180498. /* function to free memory for zlib */
  180499. #ifdef PNG_1_0_X
  180500. void PNGAPI
  180501. #else
  180502. void /* private */
  180503. #endif
  180504. png_zfree(voidpf png_ptr, voidpf ptr)
  180505. {
  180506. png_free((png_structp)png_ptr, (png_voidp)ptr);
  180507. }
  180508. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  180509. * in case CRC is > 32 bits to leave the top bits 0.
  180510. */
  180511. void /* PRIVATE */
  180512. png_reset_crc(png_structp png_ptr)
  180513. {
  180514. png_ptr->crc = crc32(0, Z_NULL, 0);
  180515. }
  180516. /* Calculate the CRC over a section of data. We can only pass as
  180517. * much data to this routine as the largest single buffer size. We
  180518. * also check that this data will actually be used before going to the
  180519. * trouble of calculating it.
  180520. */
  180521. void /* PRIVATE */
  180522. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  180523. {
  180524. int need_crc = 1;
  180525. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  180526. {
  180527. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  180528. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  180529. need_crc = 0;
  180530. }
  180531. else /* critical */
  180532. {
  180533. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  180534. need_crc = 0;
  180535. }
  180536. if (need_crc)
  180537. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  180538. }
  180539. /* Allocate the memory for an info_struct for the application. We don't
  180540. * really need the png_ptr, but it could potentially be useful in the
  180541. * future. This should be used in favour of malloc(png_sizeof(png_info))
  180542. * and png_info_init() so that applications that want to use a shared
  180543. * libpng don't have to be recompiled if png_info changes size.
  180544. */
  180545. png_infop PNGAPI
  180546. png_create_info_struct(png_structp png_ptr)
  180547. {
  180548. png_infop info_ptr;
  180549. png_debug(1, "in png_create_info_struct\n");
  180550. if(png_ptr == NULL) return (NULL);
  180551. #ifdef PNG_USER_MEM_SUPPORTED
  180552. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  180553. png_ptr->malloc_fn, png_ptr->mem_ptr);
  180554. #else
  180555. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180556. #endif
  180557. if (info_ptr != NULL)
  180558. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180559. return (info_ptr);
  180560. }
  180561. /* This function frees the memory associated with a single info struct.
  180562. * Normally, one would use either png_destroy_read_struct() or
  180563. * png_destroy_write_struct() to free an info struct, but this may be
  180564. * useful for some applications.
  180565. */
  180566. void PNGAPI
  180567. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  180568. {
  180569. png_infop info_ptr = NULL;
  180570. if(png_ptr == NULL) return;
  180571. png_debug(1, "in png_destroy_info_struct\n");
  180572. if (info_ptr_ptr != NULL)
  180573. info_ptr = *info_ptr_ptr;
  180574. if (info_ptr != NULL)
  180575. {
  180576. png_info_destroy(png_ptr, info_ptr);
  180577. #ifdef PNG_USER_MEM_SUPPORTED
  180578. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  180579. png_ptr->mem_ptr);
  180580. #else
  180581. png_destroy_struct((png_voidp)info_ptr);
  180582. #endif
  180583. *info_ptr_ptr = NULL;
  180584. }
  180585. }
  180586. /* Initialize the info structure. This is now an internal function (0.89)
  180587. * and applications using it are urged to use png_create_info_struct()
  180588. * instead.
  180589. */
  180590. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180591. #undef png_info_init
  180592. void PNGAPI
  180593. png_info_init(png_infop info_ptr)
  180594. {
  180595. /* We only come here via pre-1.0.12-compiled applications */
  180596. png_info_init_3(&info_ptr, 0);
  180597. }
  180598. #endif
  180599. void PNGAPI
  180600. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  180601. {
  180602. png_infop info_ptr = *ptr_ptr;
  180603. if(info_ptr == NULL) return;
  180604. png_debug(1, "in png_info_init_3\n");
  180605. if(png_sizeof(png_info) > png_info_struct_size)
  180606. {
  180607. png_destroy_struct(info_ptr);
  180608. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180609. *ptr_ptr = info_ptr;
  180610. }
  180611. /* set everything to 0 */
  180612. png_memset(info_ptr, 0, png_sizeof (png_info));
  180613. }
  180614. #ifdef PNG_FREE_ME_SUPPORTED
  180615. void PNGAPI
  180616. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  180617. int freer, png_uint_32 mask)
  180618. {
  180619. png_debug(1, "in png_data_freer\n");
  180620. if (png_ptr == NULL || info_ptr == NULL)
  180621. return;
  180622. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  180623. info_ptr->free_me |= mask;
  180624. else if(freer == PNG_USER_WILL_FREE_DATA)
  180625. info_ptr->free_me &= ~mask;
  180626. else
  180627. png_warning(png_ptr,
  180628. "Unknown freer parameter in png_data_freer.");
  180629. }
  180630. #endif
  180631. void PNGAPI
  180632. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  180633. int num)
  180634. {
  180635. png_debug(1, "in png_free_data\n");
  180636. if (png_ptr == NULL || info_ptr == NULL)
  180637. return;
  180638. #if defined(PNG_TEXT_SUPPORTED)
  180639. /* free text item num or (if num == -1) all text items */
  180640. #ifdef PNG_FREE_ME_SUPPORTED
  180641. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  180642. #else
  180643. if (mask & PNG_FREE_TEXT)
  180644. #endif
  180645. {
  180646. if (num != -1)
  180647. {
  180648. if (info_ptr->text && info_ptr->text[num].key)
  180649. {
  180650. png_free(png_ptr, info_ptr->text[num].key);
  180651. info_ptr->text[num].key = NULL;
  180652. }
  180653. }
  180654. else
  180655. {
  180656. int i;
  180657. for (i = 0; i < info_ptr->num_text; i++)
  180658. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  180659. png_free(png_ptr, info_ptr->text);
  180660. info_ptr->text = NULL;
  180661. info_ptr->num_text=0;
  180662. }
  180663. }
  180664. #endif
  180665. #if defined(PNG_tRNS_SUPPORTED)
  180666. /* free any tRNS entry */
  180667. #ifdef PNG_FREE_ME_SUPPORTED
  180668. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  180669. #else
  180670. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  180671. #endif
  180672. {
  180673. png_free(png_ptr, info_ptr->trans);
  180674. info_ptr->valid &= ~PNG_INFO_tRNS;
  180675. #ifndef PNG_FREE_ME_SUPPORTED
  180676. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  180677. #endif
  180678. info_ptr->trans = NULL;
  180679. }
  180680. #endif
  180681. #if defined(PNG_sCAL_SUPPORTED)
  180682. /* free any sCAL entry */
  180683. #ifdef PNG_FREE_ME_SUPPORTED
  180684. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  180685. #else
  180686. if (mask & PNG_FREE_SCAL)
  180687. #endif
  180688. {
  180689. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  180690. png_free(png_ptr, info_ptr->scal_s_width);
  180691. png_free(png_ptr, info_ptr->scal_s_height);
  180692. info_ptr->scal_s_width = NULL;
  180693. info_ptr->scal_s_height = NULL;
  180694. #endif
  180695. info_ptr->valid &= ~PNG_INFO_sCAL;
  180696. }
  180697. #endif
  180698. #if defined(PNG_pCAL_SUPPORTED)
  180699. /* free any pCAL entry */
  180700. #ifdef PNG_FREE_ME_SUPPORTED
  180701. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  180702. #else
  180703. if (mask & PNG_FREE_PCAL)
  180704. #endif
  180705. {
  180706. png_free(png_ptr, info_ptr->pcal_purpose);
  180707. png_free(png_ptr, info_ptr->pcal_units);
  180708. info_ptr->pcal_purpose = NULL;
  180709. info_ptr->pcal_units = NULL;
  180710. if (info_ptr->pcal_params != NULL)
  180711. {
  180712. int i;
  180713. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  180714. {
  180715. png_free(png_ptr, info_ptr->pcal_params[i]);
  180716. info_ptr->pcal_params[i]=NULL;
  180717. }
  180718. png_free(png_ptr, info_ptr->pcal_params);
  180719. info_ptr->pcal_params = NULL;
  180720. }
  180721. info_ptr->valid &= ~PNG_INFO_pCAL;
  180722. }
  180723. #endif
  180724. #if defined(PNG_iCCP_SUPPORTED)
  180725. /* free any iCCP entry */
  180726. #ifdef PNG_FREE_ME_SUPPORTED
  180727. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  180728. #else
  180729. if (mask & PNG_FREE_ICCP)
  180730. #endif
  180731. {
  180732. png_free(png_ptr, info_ptr->iccp_name);
  180733. png_free(png_ptr, info_ptr->iccp_profile);
  180734. info_ptr->iccp_name = NULL;
  180735. info_ptr->iccp_profile = NULL;
  180736. info_ptr->valid &= ~PNG_INFO_iCCP;
  180737. }
  180738. #endif
  180739. #if defined(PNG_sPLT_SUPPORTED)
  180740. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  180741. #ifdef PNG_FREE_ME_SUPPORTED
  180742. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  180743. #else
  180744. if (mask & PNG_FREE_SPLT)
  180745. #endif
  180746. {
  180747. if (num != -1)
  180748. {
  180749. if(info_ptr->splt_palettes)
  180750. {
  180751. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  180752. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  180753. info_ptr->splt_palettes[num].name = NULL;
  180754. info_ptr->splt_palettes[num].entries = NULL;
  180755. }
  180756. }
  180757. else
  180758. {
  180759. if(info_ptr->splt_palettes_num)
  180760. {
  180761. int i;
  180762. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  180763. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  180764. png_free(png_ptr, info_ptr->splt_palettes);
  180765. info_ptr->splt_palettes = NULL;
  180766. info_ptr->splt_palettes_num = 0;
  180767. }
  180768. info_ptr->valid &= ~PNG_INFO_sPLT;
  180769. }
  180770. }
  180771. #endif
  180772. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180773. if(png_ptr->unknown_chunk.data)
  180774. {
  180775. png_free(png_ptr, png_ptr->unknown_chunk.data);
  180776. png_ptr->unknown_chunk.data = NULL;
  180777. }
  180778. #ifdef PNG_FREE_ME_SUPPORTED
  180779. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  180780. #else
  180781. if (mask & PNG_FREE_UNKN)
  180782. #endif
  180783. {
  180784. if (num != -1)
  180785. {
  180786. if(info_ptr->unknown_chunks)
  180787. {
  180788. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  180789. info_ptr->unknown_chunks[num].data = NULL;
  180790. }
  180791. }
  180792. else
  180793. {
  180794. int i;
  180795. if(info_ptr->unknown_chunks_num)
  180796. {
  180797. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  180798. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  180799. png_free(png_ptr, info_ptr->unknown_chunks);
  180800. info_ptr->unknown_chunks = NULL;
  180801. info_ptr->unknown_chunks_num = 0;
  180802. }
  180803. }
  180804. }
  180805. #endif
  180806. #if defined(PNG_hIST_SUPPORTED)
  180807. /* free any hIST entry */
  180808. #ifdef PNG_FREE_ME_SUPPORTED
  180809. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  180810. #else
  180811. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  180812. #endif
  180813. {
  180814. png_free(png_ptr, info_ptr->hist);
  180815. info_ptr->hist = NULL;
  180816. info_ptr->valid &= ~PNG_INFO_hIST;
  180817. #ifndef PNG_FREE_ME_SUPPORTED
  180818. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  180819. #endif
  180820. }
  180821. #endif
  180822. /* free any PLTE entry that was internally allocated */
  180823. #ifdef PNG_FREE_ME_SUPPORTED
  180824. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  180825. #else
  180826. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  180827. #endif
  180828. {
  180829. png_zfree(png_ptr, info_ptr->palette);
  180830. info_ptr->palette = NULL;
  180831. info_ptr->valid &= ~PNG_INFO_PLTE;
  180832. #ifndef PNG_FREE_ME_SUPPORTED
  180833. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  180834. #endif
  180835. info_ptr->num_palette = 0;
  180836. }
  180837. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180838. /* free any image bits attached to the info structure */
  180839. #ifdef PNG_FREE_ME_SUPPORTED
  180840. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  180841. #else
  180842. if (mask & PNG_FREE_ROWS)
  180843. #endif
  180844. {
  180845. if(info_ptr->row_pointers)
  180846. {
  180847. int row;
  180848. for (row = 0; row < (int)info_ptr->height; row++)
  180849. {
  180850. png_free(png_ptr, info_ptr->row_pointers[row]);
  180851. info_ptr->row_pointers[row]=NULL;
  180852. }
  180853. png_free(png_ptr, info_ptr->row_pointers);
  180854. info_ptr->row_pointers=NULL;
  180855. }
  180856. info_ptr->valid &= ~PNG_INFO_IDAT;
  180857. }
  180858. #endif
  180859. #ifdef PNG_FREE_ME_SUPPORTED
  180860. if(num == -1)
  180861. info_ptr->free_me &= ~mask;
  180862. else
  180863. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  180864. #endif
  180865. }
  180866. /* This is an internal routine to free any memory that the info struct is
  180867. * pointing to before re-using it or freeing the struct itself. Recall
  180868. * that png_free() checks for NULL pointers for us.
  180869. */
  180870. void /* PRIVATE */
  180871. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  180872. {
  180873. png_debug(1, "in png_info_destroy\n");
  180874. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  180875. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180876. if (png_ptr->num_chunk_list)
  180877. {
  180878. png_free(png_ptr, png_ptr->chunk_list);
  180879. png_ptr->chunk_list=NULL;
  180880. png_ptr->num_chunk_list=0;
  180881. }
  180882. #endif
  180883. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180884. }
  180885. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180886. /* This function returns a pointer to the io_ptr associated with the user
  180887. * functions. The application should free any memory associated with this
  180888. * pointer before png_write_destroy() or png_read_destroy() are called.
  180889. */
  180890. png_voidp PNGAPI
  180891. png_get_io_ptr(png_structp png_ptr)
  180892. {
  180893. if(png_ptr == NULL) return (NULL);
  180894. return (png_ptr->io_ptr);
  180895. }
  180896. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180897. #if !defined(PNG_NO_STDIO)
  180898. /* Initialize the default input/output functions for the PNG file. If you
  180899. * use your own read or write routines, you can call either png_set_read_fn()
  180900. * or png_set_write_fn() instead of png_init_io(). If you have defined
  180901. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  180902. * necessarily available.
  180903. */
  180904. void PNGAPI
  180905. png_init_io(png_structp png_ptr, png_FILE_p fp)
  180906. {
  180907. png_debug(1, "in png_init_io\n");
  180908. if(png_ptr == NULL) return;
  180909. png_ptr->io_ptr = (png_voidp)fp;
  180910. }
  180911. #endif
  180912. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  180913. /* Convert the supplied time into an RFC 1123 string suitable for use in
  180914. * a "Creation Time" or other text-based time string.
  180915. */
  180916. png_charp PNGAPI
  180917. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  180918. {
  180919. static PNG_CONST char short_months[12][4] =
  180920. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  180921. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  180922. if(png_ptr == NULL) return (NULL);
  180923. if (png_ptr->time_buffer == NULL)
  180924. {
  180925. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  180926. png_sizeof(char)));
  180927. }
  180928. #if defined(_WIN32_WCE)
  180929. {
  180930. wchar_t time_buf[29];
  180931. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  180932. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180933. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180934. ptime->second % 61);
  180935. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  180936. NULL, NULL);
  180937. }
  180938. #else
  180939. #ifdef USE_FAR_KEYWORD
  180940. {
  180941. char near_time_buf[29];
  180942. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  180943. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180944. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180945. ptime->second % 61);
  180946. png_memcpy(png_ptr->time_buffer, near_time_buf,
  180947. 29*png_sizeof(char));
  180948. }
  180949. #else
  180950. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  180951. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180952. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180953. ptime->second % 61);
  180954. #endif
  180955. #endif /* _WIN32_WCE */
  180956. return ((png_charp)png_ptr->time_buffer);
  180957. }
  180958. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  180959. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180960. png_charp PNGAPI
  180961. png_get_copyright(png_structp png_ptr)
  180962. {
  180963. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180964. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  180965. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  180966. Copyright (c) 1996-1997 Andreas Dilger\n\
  180967. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  180968. }
  180969. /* The following return the library version as a short string in the
  180970. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  180971. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  180972. * is defined in png.h.
  180973. * Note: now there is no difference between png_get_libpng_ver() and
  180974. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  180975. * it is guaranteed that png.c uses the correct version of png.h.
  180976. */
  180977. png_charp PNGAPI
  180978. png_get_libpng_ver(png_structp png_ptr)
  180979. {
  180980. /* Version of *.c files used when building libpng */
  180981. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180982. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180983. }
  180984. png_charp PNGAPI
  180985. png_get_header_ver(png_structp png_ptr)
  180986. {
  180987. /* Version of *.h files used when building libpng */
  180988. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180989. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180990. }
  180991. png_charp PNGAPI
  180992. png_get_header_version(png_structp png_ptr)
  180993. {
  180994. /* Returns longer string containing both version and date */
  180995. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180996. return ((png_charp) PNG_HEADER_VERSION_STRING
  180997. #ifndef PNG_READ_SUPPORTED
  180998. " (NO READ SUPPORT)"
  180999. #endif
  181000. "\n");
  181001. }
  181002. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181003. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181004. int PNGAPI
  181005. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  181006. {
  181007. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  181008. int i;
  181009. png_bytep p;
  181010. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  181011. return 0;
  181012. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  181013. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  181014. if (!png_memcmp(chunk_name, p, 4))
  181015. return ((int)*(p+4));
  181016. return 0;
  181017. }
  181018. #endif
  181019. /* This function, added to libpng-1.0.6g, is untested. */
  181020. int PNGAPI
  181021. png_reset_zstream(png_structp png_ptr)
  181022. {
  181023. if (png_ptr == NULL) return Z_STREAM_ERROR;
  181024. return (inflateReset(&png_ptr->zstream));
  181025. }
  181026. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181027. /* This function was added to libpng-1.0.7 */
  181028. png_uint_32 PNGAPI
  181029. png_access_version_number(void)
  181030. {
  181031. /* Version of *.c files used when building libpng */
  181032. return((png_uint_32) PNG_LIBPNG_VER);
  181033. }
  181034. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181035. #if !defined(PNG_1_0_X)
  181036. /* this function was added to libpng 1.2.0 */
  181037. int PNGAPI
  181038. png_mmx_support(void)
  181039. {
  181040. /* obsolete, to be removed from libpng-1.4.0 */
  181041. return -1;
  181042. }
  181043. #endif /* PNG_1_0_X */
  181044. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  181045. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181046. #ifdef PNG_SIZE_T
  181047. /* Added at libpng version 1.2.6 */
  181048. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  181049. png_size_t PNGAPI
  181050. png_convert_size(size_t size)
  181051. {
  181052. if (size > (png_size_t)-1)
  181053. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  181054. return ((png_size_t)size);
  181055. }
  181056. #endif /* PNG_SIZE_T */
  181057. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  181058. /********* End of inlined file: png.c *********/
  181059. /********* Start of inlined file: pngerror.c *********/
  181060. /* pngerror.c - stub functions for i/o and memory allocation
  181061. *
  181062. * Last changed in libpng 1.2.20 October 4, 2007
  181063. * For conditions of distribution and use, see copyright notice in png.h
  181064. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181065. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181066. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181067. *
  181068. * This file provides a location for all error handling. Users who
  181069. * need special error handling are expected to write replacement functions
  181070. * and use png_set_error_fn() to use those functions. See the instructions
  181071. * at each function.
  181072. */
  181073. #define PNG_INTERNAL
  181074. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181075. static void /* PRIVATE */
  181076. png_default_error PNGARG((png_structp png_ptr,
  181077. png_const_charp error_message));
  181078. #ifndef PNG_NO_WARNINGS
  181079. static void /* PRIVATE */
  181080. png_default_warning PNGARG((png_structp png_ptr,
  181081. png_const_charp warning_message));
  181082. #endif /* PNG_NO_WARNINGS */
  181083. /* This function is called whenever there is a fatal error. This function
  181084. * should not be changed. If there is a need to handle errors differently,
  181085. * you should supply a replacement error function and use png_set_error_fn()
  181086. * to replace the error function at run-time.
  181087. */
  181088. #ifndef PNG_NO_ERROR_TEXT
  181089. void PNGAPI
  181090. png_error(png_structp png_ptr, png_const_charp error_message)
  181091. {
  181092. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181093. char msg[16];
  181094. if (png_ptr != NULL)
  181095. {
  181096. if (png_ptr->flags&
  181097. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181098. {
  181099. if (*error_message == '#')
  181100. {
  181101. int offset;
  181102. for (offset=1; offset<15; offset++)
  181103. if (*(error_message+offset) == ' ')
  181104. break;
  181105. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181106. {
  181107. int i;
  181108. for (i=0; i<offset-1; i++)
  181109. msg[i]=error_message[i+1];
  181110. msg[i]='\0';
  181111. error_message=msg;
  181112. }
  181113. else
  181114. error_message+=offset;
  181115. }
  181116. else
  181117. {
  181118. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  181119. {
  181120. msg[0]='0';
  181121. msg[1]='\0';
  181122. error_message=msg;
  181123. }
  181124. }
  181125. }
  181126. }
  181127. #endif
  181128. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181129. (*(png_ptr->error_fn))(png_ptr, error_message);
  181130. /* If the custom handler doesn't exist, or if it returns,
  181131. use the default handler, which will not return. */
  181132. png_default_error(png_ptr, error_message);
  181133. }
  181134. #else
  181135. void PNGAPI
  181136. png_err(png_structp png_ptr)
  181137. {
  181138. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  181139. (*(png_ptr->error_fn))(png_ptr, '\0');
  181140. /* If the custom handler doesn't exist, or if it returns,
  181141. use the default handler, which will not return. */
  181142. png_default_error(png_ptr, '\0');
  181143. }
  181144. #endif /* PNG_NO_ERROR_TEXT */
  181145. #ifndef PNG_NO_WARNINGS
  181146. /* This function is called whenever there is a non-fatal error. This function
  181147. * should not be changed. If there is a need to handle warnings differently,
  181148. * you should supply a replacement warning function and use
  181149. * png_set_error_fn() to replace the warning function at run-time.
  181150. */
  181151. void PNGAPI
  181152. png_warning(png_structp png_ptr, png_const_charp warning_message)
  181153. {
  181154. int offset = 0;
  181155. if (png_ptr != NULL)
  181156. {
  181157. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181158. if (png_ptr->flags&
  181159. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  181160. #endif
  181161. {
  181162. if (*warning_message == '#')
  181163. {
  181164. for (offset=1; offset<15; offset++)
  181165. if (*(warning_message+offset) == ' ')
  181166. break;
  181167. }
  181168. }
  181169. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  181170. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  181171. }
  181172. else
  181173. png_default_warning(png_ptr, warning_message+offset);
  181174. }
  181175. #endif /* PNG_NO_WARNINGS */
  181176. /* These utilities are used internally to build an error message that relates
  181177. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  181178. * this is used to prefix the message. The message is limited in length
  181179. * to 63 bytes, the name characters are output as hex digits wrapped in []
  181180. * if the character is invalid.
  181181. */
  181182. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  181183. /*static PNG_CONST char png_digit[16] = {
  181184. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  181185. 'A', 'B', 'C', 'D', 'E', 'F'
  181186. };*/
  181187. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  181188. static void /* PRIVATE */
  181189. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  181190. error_message)
  181191. {
  181192. int iout = 0, iin = 0;
  181193. while (iin < 4)
  181194. {
  181195. int c = png_ptr->chunk_name[iin++];
  181196. if (isnonalpha(c))
  181197. {
  181198. buffer[iout++] = '[';
  181199. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  181200. buffer[iout++] = png_digit[c & 0x0f];
  181201. buffer[iout++] = ']';
  181202. }
  181203. else
  181204. {
  181205. buffer[iout++] = (png_byte)c;
  181206. }
  181207. }
  181208. if (error_message == NULL)
  181209. buffer[iout] = 0;
  181210. else
  181211. {
  181212. buffer[iout++] = ':';
  181213. buffer[iout++] = ' ';
  181214. png_strncpy(buffer+iout, error_message, 63);
  181215. buffer[iout+63] = 0;
  181216. }
  181217. }
  181218. #ifdef PNG_READ_SUPPORTED
  181219. void PNGAPI
  181220. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  181221. {
  181222. char msg[18+64];
  181223. if (png_ptr == NULL)
  181224. png_error(png_ptr, error_message);
  181225. else
  181226. {
  181227. png_format_buffer(png_ptr, msg, error_message);
  181228. png_error(png_ptr, msg);
  181229. }
  181230. }
  181231. #endif /* PNG_READ_SUPPORTED */
  181232. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  181233. #ifndef PNG_NO_WARNINGS
  181234. void PNGAPI
  181235. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  181236. {
  181237. char msg[18+64];
  181238. if (png_ptr == NULL)
  181239. png_warning(png_ptr, warning_message);
  181240. else
  181241. {
  181242. png_format_buffer(png_ptr, msg, warning_message);
  181243. png_warning(png_ptr, msg);
  181244. }
  181245. }
  181246. #endif /* PNG_NO_WARNINGS */
  181247. /* This is the default error handling function. Note that replacements for
  181248. * this function MUST NOT RETURN, or the program will likely crash. This
  181249. * function is used by default, or if the program supplies NULL for the
  181250. * error function pointer in png_set_error_fn().
  181251. */
  181252. static void /* PRIVATE */
  181253. png_default_error(png_structp png_ptr, png_const_charp error_message)
  181254. {
  181255. #ifndef PNG_NO_CONSOLE_IO
  181256. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181257. if (*error_message == '#')
  181258. {
  181259. int offset;
  181260. char error_number[16];
  181261. for (offset=0; offset<15; offset++)
  181262. {
  181263. error_number[offset] = *(error_message+offset+1);
  181264. if (*(error_message+offset) == ' ')
  181265. break;
  181266. }
  181267. if((offset > 1) && (offset < 15))
  181268. {
  181269. error_number[offset-1]='\0';
  181270. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  181271. error_message+offset);
  181272. }
  181273. else
  181274. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  181275. }
  181276. else
  181277. #endif
  181278. fprintf(stderr, "libpng error: %s\n", error_message);
  181279. #endif
  181280. #ifdef PNG_SETJMP_SUPPORTED
  181281. if (png_ptr)
  181282. {
  181283. # ifdef USE_FAR_KEYWORD
  181284. {
  181285. jmp_buf jmpbuf;
  181286. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  181287. longjmp(jmpbuf, 1);
  181288. }
  181289. # else
  181290. longjmp(png_ptr->jmpbuf, 1);
  181291. # endif
  181292. }
  181293. #else
  181294. PNG_ABORT();
  181295. #endif
  181296. #ifdef PNG_NO_CONSOLE_IO
  181297. error_message = error_message; /* make compiler happy */
  181298. #endif
  181299. }
  181300. #ifndef PNG_NO_WARNINGS
  181301. /* This function is called when there is a warning, but the library thinks
  181302. * it can continue anyway. Replacement functions don't have to do anything
  181303. * here if you don't want them to. In the default configuration, png_ptr is
  181304. * not used, but it is passed in case it may be useful.
  181305. */
  181306. static void /* PRIVATE */
  181307. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  181308. {
  181309. #ifndef PNG_NO_CONSOLE_IO
  181310. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181311. if (*warning_message == '#')
  181312. {
  181313. int offset;
  181314. char warning_number[16];
  181315. for (offset=0; offset<15; offset++)
  181316. {
  181317. warning_number[offset]=*(warning_message+offset+1);
  181318. if (*(warning_message+offset) == ' ')
  181319. break;
  181320. }
  181321. if((offset > 1) && (offset < 15))
  181322. {
  181323. warning_number[offset-1]='\0';
  181324. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  181325. warning_message+offset);
  181326. }
  181327. else
  181328. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181329. }
  181330. else
  181331. # endif
  181332. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181333. #else
  181334. warning_message = warning_message; /* make compiler happy */
  181335. #endif
  181336. png_ptr = png_ptr; /* make compiler happy */
  181337. }
  181338. #endif /* PNG_NO_WARNINGS */
  181339. /* This function is called when the application wants to use another method
  181340. * of handling errors and warnings. Note that the error function MUST NOT
  181341. * return to the calling routine or serious problems will occur. The return
  181342. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  181343. */
  181344. void PNGAPI
  181345. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  181346. png_error_ptr error_fn, png_error_ptr warning_fn)
  181347. {
  181348. if (png_ptr == NULL)
  181349. return;
  181350. png_ptr->error_ptr = error_ptr;
  181351. png_ptr->error_fn = error_fn;
  181352. png_ptr->warning_fn = warning_fn;
  181353. }
  181354. /* This function returns a pointer to the error_ptr associated with the user
  181355. * functions. The application should free any memory associated with this
  181356. * pointer before png_write_destroy and png_read_destroy are called.
  181357. */
  181358. png_voidp PNGAPI
  181359. png_get_error_ptr(png_structp png_ptr)
  181360. {
  181361. if (png_ptr == NULL)
  181362. return NULL;
  181363. return ((png_voidp)png_ptr->error_ptr);
  181364. }
  181365. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181366. void PNGAPI
  181367. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  181368. {
  181369. if(png_ptr != NULL)
  181370. {
  181371. png_ptr->flags &=
  181372. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  181373. }
  181374. }
  181375. #endif
  181376. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181377. /********* End of inlined file: pngerror.c *********/
  181378. /********* Start of inlined file: pngget.c *********/
  181379. /* pngget.c - retrieval of values from info struct
  181380. *
  181381. * Last changed in libpng 1.2.15 January 5, 2007
  181382. * For conditions of distribution and use, see copyright notice in png.h
  181383. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181384. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181385. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181386. */
  181387. #define PNG_INTERNAL
  181388. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181389. png_uint_32 PNGAPI
  181390. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  181391. {
  181392. if (png_ptr != NULL && info_ptr != NULL)
  181393. return(info_ptr->valid & flag);
  181394. else
  181395. return(0);
  181396. }
  181397. png_uint_32 PNGAPI
  181398. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  181399. {
  181400. if (png_ptr != NULL && info_ptr != NULL)
  181401. return(info_ptr->rowbytes);
  181402. else
  181403. return(0);
  181404. }
  181405. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181406. png_bytepp PNGAPI
  181407. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  181408. {
  181409. if (png_ptr != NULL && info_ptr != NULL)
  181410. return(info_ptr->row_pointers);
  181411. else
  181412. return(0);
  181413. }
  181414. #endif
  181415. #ifdef PNG_EASY_ACCESS_SUPPORTED
  181416. /* easy access to info, added in libpng-0.99 */
  181417. png_uint_32 PNGAPI
  181418. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  181419. {
  181420. if (png_ptr != NULL && info_ptr != NULL)
  181421. {
  181422. return info_ptr->width;
  181423. }
  181424. return (0);
  181425. }
  181426. png_uint_32 PNGAPI
  181427. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  181428. {
  181429. if (png_ptr != NULL && info_ptr != NULL)
  181430. {
  181431. return info_ptr->height;
  181432. }
  181433. return (0);
  181434. }
  181435. png_byte PNGAPI
  181436. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  181437. {
  181438. if (png_ptr != NULL && info_ptr != NULL)
  181439. {
  181440. return info_ptr->bit_depth;
  181441. }
  181442. return (0);
  181443. }
  181444. png_byte PNGAPI
  181445. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  181446. {
  181447. if (png_ptr != NULL && info_ptr != NULL)
  181448. {
  181449. return info_ptr->color_type;
  181450. }
  181451. return (0);
  181452. }
  181453. png_byte PNGAPI
  181454. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  181455. {
  181456. if (png_ptr != NULL && info_ptr != NULL)
  181457. {
  181458. return info_ptr->filter_type;
  181459. }
  181460. return (0);
  181461. }
  181462. png_byte PNGAPI
  181463. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  181464. {
  181465. if (png_ptr != NULL && info_ptr != NULL)
  181466. {
  181467. return info_ptr->interlace_type;
  181468. }
  181469. return (0);
  181470. }
  181471. png_byte PNGAPI
  181472. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  181473. {
  181474. if (png_ptr != NULL && info_ptr != NULL)
  181475. {
  181476. return info_ptr->compression_type;
  181477. }
  181478. return (0);
  181479. }
  181480. png_uint_32 PNGAPI
  181481. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181482. {
  181483. if (png_ptr != NULL && info_ptr != NULL)
  181484. #if defined(PNG_pHYs_SUPPORTED)
  181485. if (info_ptr->valid & PNG_INFO_pHYs)
  181486. {
  181487. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  181488. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181489. return (0);
  181490. else return (info_ptr->x_pixels_per_unit);
  181491. }
  181492. #else
  181493. return (0);
  181494. #endif
  181495. return (0);
  181496. }
  181497. png_uint_32 PNGAPI
  181498. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181499. {
  181500. if (png_ptr != NULL && info_ptr != NULL)
  181501. #if defined(PNG_pHYs_SUPPORTED)
  181502. if (info_ptr->valid & PNG_INFO_pHYs)
  181503. {
  181504. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  181505. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181506. return (0);
  181507. else return (info_ptr->y_pixels_per_unit);
  181508. }
  181509. #else
  181510. return (0);
  181511. #endif
  181512. return (0);
  181513. }
  181514. png_uint_32 PNGAPI
  181515. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181516. {
  181517. if (png_ptr != NULL && info_ptr != NULL)
  181518. #if defined(PNG_pHYs_SUPPORTED)
  181519. if (info_ptr->valid & PNG_INFO_pHYs)
  181520. {
  181521. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  181522. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  181523. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  181524. return (0);
  181525. else return (info_ptr->x_pixels_per_unit);
  181526. }
  181527. #else
  181528. return (0);
  181529. #endif
  181530. return (0);
  181531. }
  181532. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181533. float PNGAPI
  181534. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  181535. {
  181536. if (png_ptr != NULL && info_ptr != NULL)
  181537. #if defined(PNG_pHYs_SUPPORTED)
  181538. if (info_ptr->valid & PNG_INFO_pHYs)
  181539. {
  181540. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  181541. if (info_ptr->x_pixels_per_unit == 0)
  181542. return ((float)0.0);
  181543. else
  181544. return ((float)((float)info_ptr->y_pixels_per_unit
  181545. /(float)info_ptr->x_pixels_per_unit));
  181546. }
  181547. #else
  181548. return (0.0);
  181549. #endif
  181550. return ((float)0.0);
  181551. }
  181552. #endif
  181553. png_int_32 PNGAPI
  181554. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181555. {
  181556. if (png_ptr != NULL && info_ptr != NULL)
  181557. #if defined(PNG_oFFs_SUPPORTED)
  181558. if (info_ptr->valid & PNG_INFO_oFFs)
  181559. {
  181560. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181561. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181562. return (0);
  181563. else return (info_ptr->x_offset);
  181564. }
  181565. #else
  181566. return (0);
  181567. #endif
  181568. return (0);
  181569. }
  181570. png_int_32 PNGAPI
  181571. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181572. {
  181573. if (png_ptr != NULL && info_ptr != NULL)
  181574. #if defined(PNG_oFFs_SUPPORTED)
  181575. if (info_ptr->valid & PNG_INFO_oFFs)
  181576. {
  181577. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181578. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181579. return (0);
  181580. else return (info_ptr->y_offset);
  181581. }
  181582. #else
  181583. return (0);
  181584. #endif
  181585. return (0);
  181586. }
  181587. png_int_32 PNGAPI
  181588. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181589. {
  181590. if (png_ptr != NULL && info_ptr != NULL)
  181591. #if defined(PNG_oFFs_SUPPORTED)
  181592. if (info_ptr->valid & PNG_INFO_oFFs)
  181593. {
  181594. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181595. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181596. return (0);
  181597. else return (info_ptr->x_offset);
  181598. }
  181599. #else
  181600. return (0);
  181601. #endif
  181602. return (0);
  181603. }
  181604. png_int_32 PNGAPI
  181605. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181606. {
  181607. if (png_ptr != NULL && info_ptr != NULL)
  181608. #if defined(PNG_oFFs_SUPPORTED)
  181609. if (info_ptr->valid & PNG_INFO_oFFs)
  181610. {
  181611. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181612. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181613. return (0);
  181614. else return (info_ptr->y_offset);
  181615. }
  181616. #else
  181617. return (0);
  181618. #endif
  181619. return (0);
  181620. }
  181621. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181622. png_uint_32 PNGAPI
  181623. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181624. {
  181625. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  181626. *.0254 +.5));
  181627. }
  181628. png_uint_32 PNGAPI
  181629. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181630. {
  181631. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  181632. *.0254 +.5));
  181633. }
  181634. png_uint_32 PNGAPI
  181635. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181636. {
  181637. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  181638. *.0254 +.5));
  181639. }
  181640. float PNGAPI
  181641. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181642. {
  181643. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  181644. *.00003937);
  181645. }
  181646. float PNGAPI
  181647. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181648. {
  181649. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  181650. *.00003937);
  181651. }
  181652. #if defined(PNG_pHYs_SUPPORTED)
  181653. png_uint_32 PNGAPI
  181654. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  181655. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181656. {
  181657. png_uint_32 retval = 0;
  181658. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  181659. {
  181660. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181661. if (res_x != NULL)
  181662. {
  181663. *res_x = info_ptr->x_pixels_per_unit;
  181664. retval |= PNG_INFO_pHYs;
  181665. }
  181666. if (res_y != NULL)
  181667. {
  181668. *res_y = info_ptr->y_pixels_per_unit;
  181669. retval |= PNG_INFO_pHYs;
  181670. }
  181671. if (unit_type != NULL)
  181672. {
  181673. *unit_type = (int)info_ptr->phys_unit_type;
  181674. retval |= PNG_INFO_pHYs;
  181675. if(*unit_type == 1)
  181676. {
  181677. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  181678. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  181679. }
  181680. }
  181681. }
  181682. return (retval);
  181683. }
  181684. #endif /* PNG_pHYs_SUPPORTED */
  181685. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181686. /* png_get_channels really belongs in here, too, but it's been around longer */
  181687. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  181688. png_byte PNGAPI
  181689. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  181690. {
  181691. if (png_ptr != NULL && info_ptr != NULL)
  181692. return(info_ptr->channels);
  181693. else
  181694. return (0);
  181695. }
  181696. png_bytep PNGAPI
  181697. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  181698. {
  181699. if (png_ptr != NULL && info_ptr != NULL)
  181700. return(info_ptr->signature);
  181701. else
  181702. return (NULL);
  181703. }
  181704. #if defined(PNG_bKGD_SUPPORTED)
  181705. png_uint_32 PNGAPI
  181706. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  181707. png_color_16p *background)
  181708. {
  181709. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  181710. && background != NULL)
  181711. {
  181712. png_debug1(1, "in %s retrieval function\n", "bKGD");
  181713. *background = &(info_ptr->background);
  181714. return (PNG_INFO_bKGD);
  181715. }
  181716. return (0);
  181717. }
  181718. #endif
  181719. #if defined(PNG_cHRM_SUPPORTED)
  181720. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181721. png_uint_32 PNGAPI
  181722. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  181723. double *white_x, double *white_y, double *red_x, double *red_y,
  181724. double *green_x, double *green_y, double *blue_x, double *blue_y)
  181725. {
  181726. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181727. {
  181728. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181729. if (white_x != NULL)
  181730. *white_x = (double)info_ptr->x_white;
  181731. if (white_y != NULL)
  181732. *white_y = (double)info_ptr->y_white;
  181733. if (red_x != NULL)
  181734. *red_x = (double)info_ptr->x_red;
  181735. if (red_y != NULL)
  181736. *red_y = (double)info_ptr->y_red;
  181737. if (green_x != NULL)
  181738. *green_x = (double)info_ptr->x_green;
  181739. if (green_y != NULL)
  181740. *green_y = (double)info_ptr->y_green;
  181741. if (blue_x != NULL)
  181742. *blue_x = (double)info_ptr->x_blue;
  181743. if (blue_y != NULL)
  181744. *blue_y = (double)info_ptr->y_blue;
  181745. return (PNG_INFO_cHRM);
  181746. }
  181747. return (0);
  181748. }
  181749. #endif
  181750. #ifdef PNG_FIXED_POINT_SUPPORTED
  181751. png_uint_32 PNGAPI
  181752. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  181753. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  181754. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  181755. png_fixed_point *blue_x, png_fixed_point *blue_y)
  181756. {
  181757. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181758. {
  181759. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181760. if (white_x != NULL)
  181761. *white_x = info_ptr->int_x_white;
  181762. if (white_y != NULL)
  181763. *white_y = info_ptr->int_y_white;
  181764. if (red_x != NULL)
  181765. *red_x = info_ptr->int_x_red;
  181766. if (red_y != NULL)
  181767. *red_y = info_ptr->int_y_red;
  181768. if (green_x != NULL)
  181769. *green_x = info_ptr->int_x_green;
  181770. if (green_y != NULL)
  181771. *green_y = info_ptr->int_y_green;
  181772. if (blue_x != NULL)
  181773. *blue_x = info_ptr->int_x_blue;
  181774. if (blue_y != NULL)
  181775. *blue_y = info_ptr->int_y_blue;
  181776. return (PNG_INFO_cHRM);
  181777. }
  181778. return (0);
  181779. }
  181780. #endif
  181781. #endif
  181782. #if defined(PNG_gAMA_SUPPORTED)
  181783. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181784. png_uint_32 PNGAPI
  181785. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  181786. {
  181787. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181788. && file_gamma != NULL)
  181789. {
  181790. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181791. *file_gamma = (double)info_ptr->gamma;
  181792. return (PNG_INFO_gAMA);
  181793. }
  181794. return (0);
  181795. }
  181796. #endif
  181797. #ifdef PNG_FIXED_POINT_SUPPORTED
  181798. png_uint_32 PNGAPI
  181799. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  181800. png_fixed_point *int_file_gamma)
  181801. {
  181802. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181803. && int_file_gamma != NULL)
  181804. {
  181805. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181806. *int_file_gamma = info_ptr->int_gamma;
  181807. return (PNG_INFO_gAMA);
  181808. }
  181809. return (0);
  181810. }
  181811. #endif
  181812. #endif
  181813. #if defined(PNG_sRGB_SUPPORTED)
  181814. png_uint_32 PNGAPI
  181815. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  181816. {
  181817. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  181818. && file_srgb_intent != NULL)
  181819. {
  181820. png_debug1(1, "in %s retrieval function\n", "sRGB");
  181821. *file_srgb_intent = (int)info_ptr->srgb_intent;
  181822. return (PNG_INFO_sRGB);
  181823. }
  181824. return (0);
  181825. }
  181826. #endif
  181827. #if defined(PNG_iCCP_SUPPORTED)
  181828. png_uint_32 PNGAPI
  181829. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  181830. png_charpp name, int *compression_type,
  181831. png_charpp profile, png_uint_32 *proflen)
  181832. {
  181833. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  181834. && name != NULL && profile != NULL && proflen != NULL)
  181835. {
  181836. png_debug1(1, "in %s retrieval function\n", "iCCP");
  181837. *name = info_ptr->iccp_name;
  181838. *profile = info_ptr->iccp_profile;
  181839. /* compression_type is a dummy so the API won't have to change
  181840. if we introduce multiple compression types later. */
  181841. *proflen = (int)info_ptr->iccp_proflen;
  181842. *compression_type = (int)info_ptr->iccp_compression;
  181843. return (PNG_INFO_iCCP);
  181844. }
  181845. return (0);
  181846. }
  181847. #endif
  181848. #if defined(PNG_sPLT_SUPPORTED)
  181849. png_uint_32 PNGAPI
  181850. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  181851. png_sPLT_tpp spalettes)
  181852. {
  181853. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  181854. {
  181855. *spalettes = info_ptr->splt_palettes;
  181856. return ((png_uint_32)info_ptr->splt_palettes_num);
  181857. }
  181858. return (0);
  181859. }
  181860. #endif
  181861. #if defined(PNG_hIST_SUPPORTED)
  181862. png_uint_32 PNGAPI
  181863. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  181864. {
  181865. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  181866. && hist != NULL)
  181867. {
  181868. png_debug1(1, "in %s retrieval function\n", "hIST");
  181869. *hist = info_ptr->hist;
  181870. return (PNG_INFO_hIST);
  181871. }
  181872. return (0);
  181873. }
  181874. #endif
  181875. png_uint_32 PNGAPI
  181876. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  181877. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  181878. int *color_type, int *interlace_type, int *compression_type,
  181879. int *filter_type)
  181880. {
  181881. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  181882. bit_depth != NULL && color_type != NULL)
  181883. {
  181884. png_debug1(1, "in %s retrieval function\n", "IHDR");
  181885. *width = info_ptr->width;
  181886. *height = info_ptr->height;
  181887. *bit_depth = info_ptr->bit_depth;
  181888. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  181889. png_error(png_ptr, "Invalid bit depth");
  181890. *color_type = info_ptr->color_type;
  181891. if (info_ptr->color_type > 6)
  181892. png_error(png_ptr, "Invalid color type");
  181893. if (compression_type != NULL)
  181894. *compression_type = info_ptr->compression_type;
  181895. if (filter_type != NULL)
  181896. *filter_type = info_ptr->filter_type;
  181897. if (interlace_type != NULL)
  181898. *interlace_type = info_ptr->interlace_type;
  181899. /* check for potential overflow of rowbytes */
  181900. if (*width == 0 || *width > PNG_UINT_31_MAX)
  181901. png_error(png_ptr, "Invalid image width");
  181902. if (*height == 0 || *height > PNG_UINT_31_MAX)
  181903. png_error(png_ptr, "Invalid image height");
  181904. if (info_ptr->width > (PNG_UINT_32_MAX
  181905. >> 3) /* 8-byte RGBA pixels */
  181906. - 64 /* bigrowbuf hack */
  181907. - 1 /* filter byte */
  181908. - 7*8 /* rounding of width to multiple of 8 pixels */
  181909. - 8) /* extra max_pixel_depth pad */
  181910. {
  181911. png_warning(png_ptr,
  181912. "Width too large for libpng to process image data.");
  181913. }
  181914. return (1);
  181915. }
  181916. return (0);
  181917. }
  181918. #if defined(PNG_oFFs_SUPPORTED)
  181919. png_uint_32 PNGAPI
  181920. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  181921. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  181922. {
  181923. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  181924. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  181925. {
  181926. png_debug1(1, "in %s retrieval function\n", "oFFs");
  181927. *offset_x = info_ptr->x_offset;
  181928. *offset_y = info_ptr->y_offset;
  181929. *unit_type = (int)info_ptr->offset_unit_type;
  181930. return (PNG_INFO_oFFs);
  181931. }
  181932. return (0);
  181933. }
  181934. #endif
  181935. #if defined(PNG_pCAL_SUPPORTED)
  181936. png_uint_32 PNGAPI
  181937. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  181938. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  181939. png_charp *units, png_charpp *params)
  181940. {
  181941. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  181942. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  181943. nparams != NULL && units != NULL && params != NULL)
  181944. {
  181945. png_debug1(1, "in %s retrieval function\n", "pCAL");
  181946. *purpose = info_ptr->pcal_purpose;
  181947. *X0 = info_ptr->pcal_X0;
  181948. *X1 = info_ptr->pcal_X1;
  181949. *type = (int)info_ptr->pcal_type;
  181950. *nparams = (int)info_ptr->pcal_nparams;
  181951. *units = info_ptr->pcal_units;
  181952. *params = info_ptr->pcal_params;
  181953. return (PNG_INFO_pCAL);
  181954. }
  181955. return (0);
  181956. }
  181957. #endif
  181958. #if defined(PNG_sCAL_SUPPORTED)
  181959. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181960. png_uint_32 PNGAPI
  181961. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  181962. int *unit, double *width, double *height)
  181963. {
  181964. if (png_ptr != NULL && info_ptr != NULL &&
  181965. (info_ptr->valid & PNG_INFO_sCAL))
  181966. {
  181967. *unit = info_ptr->scal_unit;
  181968. *width = info_ptr->scal_pixel_width;
  181969. *height = info_ptr->scal_pixel_height;
  181970. return (PNG_INFO_sCAL);
  181971. }
  181972. return(0);
  181973. }
  181974. #else
  181975. #ifdef PNG_FIXED_POINT_SUPPORTED
  181976. png_uint_32 PNGAPI
  181977. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  181978. int *unit, png_charpp width, png_charpp height)
  181979. {
  181980. if (png_ptr != NULL && info_ptr != NULL &&
  181981. (info_ptr->valid & PNG_INFO_sCAL))
  181982. {
  181983. *unit = info_ptr->scal_unit;
  181984. *width = info_ptr->scal_s_width;
  181985. *height = info_ptr->scal_s_height;
  181986. return (PNG_INFO_sCAL);
  181987. }
  181988. return(0);
  181989. }
  181990. #endif
  181991. #endif
  181992. #endif
  181993. #if defined(PNG_pHYs_SUPPORTED)
  181994. png_uint_32 PNGAPI
  181995. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  181996. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181997. {
  181998. png_uint_32 retval = 0;
  181999. if (png_ptr != NULL && info_ptr != NULL &&
  182000. (info_ptr->valid & PNG_INFO_pHYs))
  182001. {
  182002. png_debug1(1, "in %s retrieval function\n", "pHYs");
  182003. if (res_x != NULL)
  182004. {
  182005. *res_x = info_ptr->x_pixels_per_unit;
  182006. retval |= PNG_INFO_pHYs;
  182007. }
  182008. if (res_y != NULL)
  182009. {
  182010. *res_y = info_ptr->y_pixels_per_unit;
  182011. retval |= PNG_INFO_pHYs;
  182012. }
  182013. if (unit_type != NULL)
  182014. {
  182015. *unit_type = (int)info_ptr->phys_unit_type;
  182016. retval |= PNG_INFO_pHYs;
  182017. }
  182018. }
  182019. return (retval);
  182020. }
  182021. #endif
  182022. png_uint_32 PNGAPI
  182023. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  182024. int *num_palette)
  182025. {
  182026. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  182027. && palette != NULL)
  182028. {
  182029. png_debug1(1, "in %s retrieval function\n", "PLTE");
  182030. *palette = info_ptr->palette;
  182031. *num_palette = info_ptr->num_palette;
  182032. png_debug1(3, "num_palette = %d\n", *num_palette);
  182033. return (PNG_INFO_PLTE);
  182034. }
  182035. return (0);
  182036. }
  182037. #if defined(PNG_sBIT_SUPPORTED)
  182038. png_uint_32 PNGAPI
  182039. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  182040. {
  182041. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  182042. && sig_bit != NULL)
  182043. {
  182044. png_debug1(1, "in %s retrieval function\n", "sBIT");
  182045. *sig_bit = &(info_ptr->sig_bit);
  182046. return (PNG_INFO_sBIT);
  182047. }
  182048. return (0);
  182049. }
  182050. #endif
  182051. #if defined(PNG_TEXT_SUPPORTED)
  182052. png_uint_32 PNGAPI
  182053. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  182054. int *num_text)
  182055. {
  182056. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  182057. {
  182058. png_debug1(1, "in %s retrieval function\n",
  182059. (png_ptr->chunk_name[0] == '\0' ? "text"
  182060. : (png_const_charp)png_ptr->chunk_name));
  182061. if (text_ptr != NULL)
  182062. *text_ptr = info_ptr->text;
  182063. if (num_text != NULL)
  182064. *num_text = info_ptr->num_text;
  182065. return ((png_uint_32)info_ptr->num_text);
  182066. }
  182067. if (num_text != NULL)
  182068. *num_text = 0;
  182069. return(0);
  182070. }
  182071. #endif
  182072. #if defined(PNG_tIME_SUPPORTED)
  182073. png_uint_32 PNGAPI
  182074. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  182075. {
  182076. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  182077. && mod_time != NULL)
  182078. {
  182079. png_debug1(1, "in %s retrieval function\n", "tIME");
  182080. *mod_time = &(info_ptr->mod_time);
  182081. return (PNG_INFO_tIME);
  182082. }
  182083. return (0);
  182084. }
  182085. #endif
  182086. #if defined(PNG_tRNS_SUPPORTED)
  182087. png_uint_32 PNGAPI
  182088. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  182089. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  182090. {
  182091. png_uint_32 retval = 0;
  182092. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  182093. {
  182094. png_debug1(1, "in %s retrieval function\n", "tRNS");
  182095. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  182096. {
  182097. if (trans != NULL)
  182098. {
  182099. *trans = info_ptr->trans;
  182100. retval |= PNG_INFO_tRNS;
  182101. }
  182102. if (trans_values != NULL)
  182103. *trans_values = &(info_ptr->trans_values);
  182104. }
  182105. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  182106. {
  182107. if (trans_values != NULL)
  182108. {
  182109. *trans_values = &(info_ptr->trans_values);
  182110. retval |= PNG_INFO_tRNS;
  182111. }
  182112. if(trans != NULL)
  182113. *trans = NULL;
  182114. }
  182115. if(num_trans != NULL)
  182116. {
  182117. *num_trans = info_ptr->num_trans;
  182118. retval |= PNG_INFO_tRNS;
  182119. }
  182120. }
  182121. return (retval);
  182122. }
  182123. #endif
  182124. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182125. png_uint_32 PNGAPI
  182126. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  182127. png_unknown_chunkpp unknowns)
  182128. {
  182129. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  182130. {
  182131. *unknowns = info_ptr->unknown_chunks;
  182132. return ((png_uint_32)info_ptr->unknown_chunks_num);
  182133. }
  182134. return (0);
  182135. }
  182136. #endif
  182137. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182138. png_byte PNGAPI
  182139. png_get_rgb_to_gray_status (png_structp png_ptr)
  182140. {
  182141. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  182142. }
  182143. #endif
  182144. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182145. png_voidp PNGAPI
  182146. png_get_user_chunk_ptr(png_structp png_ptr)
  182147. {
  182148. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  182149. }
  182150. #endif
  182151. #ifdef PNG_WRITE_SUPPORTED
  182152. png_uint_32 PNGAPI
  182153. png_get_compression_buffer_size(png_structp png_ptr)
  182154. {
  182155. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  182156. }
  182157. #endif
  182158. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  182159. #ifndef PNG_1_0_X
  182160. /* this function was added to libpng 1.2.0 and should exist by default */
  182161. png_uint_32 PNGAPI
  182162. png_get_asm_flags (png_structp png_ptr)
  182163. {
  182164. /* obsolete, to be removed from libpng-1.4.0 */
  182165. return (png_ptr? 0L: 0L);
  182166. }
  182167. /* this function was added to libpng 1.2.0 and should exist by default */
  182168. png_uint_32 PNGAPI
  182169. png_get_asm_flagmask (int flag_select)
  182170. {
  182171. /* obsolete, to be removed from libpng-1.4.0 */
  182172. flag_select=flag_select;
  182173. return 0L;
  182174. }
  182175. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  182176. /* this function was added to libpng 1.2.0 */
  182177. png_uint_32 PNGAPI
  182178. png_get_mmx_flagmask (int flag_select, int *compilerID)
  182179. {
  182180. /* obsolete, to be removed from libpng-1.4.0 */
  182181. flag_select=flag_select;
  182182. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  182183. return 0L;
  182184. }
  182185. /* this function was added to libpng 1.2.0 */
  182186. png_byte PNGAPI
  182187. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  182188. {
  182189. /* obsolete, to be removed from libpng-1.4.0 */
  182190. return (png_ptr? 0: 0);
  182191. }
  182192. /* this function was added to libpng 1.2.0 */
  182193. png_uint_32 PNGAPI
  182194. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  182195. {
  182196. /* obsolete, to be removed from libpng-1.4.0 */
  182197. return (png_ptr? 0L: 0L);
  182198. }
  182199. #endif /* ?PNG_1_0_X */
  182200. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  182201. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182202. /* these functions were added to libpng 1.2.6 */
  182203. png_uint_32 PNGAPI
  182204. png_get_user_width_max (png_structp png_ptr)
  182205. {
  182206. return (png_ptr? png_ptr->user_width_max : 0);
  182207. }
  182208. png_uint_32 PNGAPI
  182209. png_get_user_height_max (png_structp png_ptr)
  182210. {
  182211. return (png_ptr? png_ptr->user_height_max : 0);
  182212. }
  182213. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  182214. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182215. /********* End of inlined file: pngget.c *********/
  182216. /********* Start of inlined file: pngmem.c *********/
  182217. /* pngmem.c - stub functions for memory allocation
  182218. *
  182219. * Last changed in libpng 1.2.13 November 13, 2006
  182220. * For conditions of distribution and use, see copyright notice in png.h
  182221. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  182222. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182223. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182224. *
  182225. * This file provides a location for all memory allocation. Users who
  182226. * need special memory handling are expected to supply replacement
  182227. * functions for png_malloc() and png_free(), and to use
  182228. * png_create_read_struct_2() and png_create_write_struct_2() to
  182229. * identify the replacement functions.
  182230. */
  182231. #define PNG_INTERNAL
  182232. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182233. /* Borland DOS special memory handler */
  182234. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182235. /* if you change this, be sure to change the one in png.h also */
  182236. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  182237. by a single call to calloc() if this is thought to improve performance. */
  182238. png_voidp /* PRIVATE */
  182239. png_create_struct(int type)
  182240. {
  182241. #ifdef PNG_USER_MEM_SUPPORTED
  182242. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182243. }
  182244. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  182245. png_voidp /* PRIVATE */
  182246. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182247. {
  182248. #endif /* PNG_USER_MEM_SUPPORTED */
  182249. png_size_t size;
  182250. png_voidp struct_ptr;
  182251. if (type == PNG_STRUCT_INFO)
  182252. size = png_sizeof(png_info);
  182253. else if (type == PNG_STRUCT_PNG)
  182254. size = png_sizeof(png_struct);
  182255. else
  182256. return (png_get_copyright(NULL));
  182257. #ifdef PNG_USER_MEM_SUPPORTED
  182258. if(malloc_fn != NULL)
  182259. {
  182260. png_struct dummy_struct;
  182261. png_structp png_ptr = &dummy_struct;
  182262. png_ptr->mem_ptr=mem_ptr;
  182263. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  182264. }
  182265. else
  182266. #endif /* PNG_USER_MEM_SUPPORTED */
  182267. struct_ptr = (png_voidp)farmalloc(size);
  182268. if (struct_ptr != NULL)
  182269. png_memset(struct_ptr, 0, size);
  182270. return (struct_ptr);
  182271. }
  182272. /* Free memory allocated by a png_create_struct() call */
  182273. void /* PRIVATE */
  182274. png_destroy_struct(png_voidp struct_ptr)
  182275. {
  182276. #ifdef PNG_USER_MEM_SUPPORTED
  182277. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182278. }
  182279. /* Free memory allocated by a png_create_struct() call */
  182280. void /* PRIVATE */
  182281. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182282. png_voidp mem_ptr)
  182283. {
  182284. #endif
  182285. if (struct_ptr != NULL)
  182286. {
  182287. #ifdef PNG_USER_MEM_SUPPORTED
  182288. if(free_fn != NULL)
  182289. {
  182290. png_struct dummy_struct;
  182291. png_structp png_ptr = &dummy_struct;
  182292. png_ptr->mem_ptr=mem_ptr;
  182293. (*(free_fn))(png_ptr, struct_ptr);
  182294. return;
  182295. }
  182296. #endif /* PNG_USER_MEM_SUPPORTED */
  182297. farfree (struct_ptr);
  182298. }
  182299. }
  182300. /* Allocate memory. For reasonable files, size should never exceed
  182301. * 64K. However, zlib may allocate more then 64K if you don't tell
  182302. * it not to. See zconf.h and png.h for more information. zlib does
  182303. * need to allocate exactly 64K, so whatever you call here must
  182304. * have the ability to do that.
  182305. *
  182306. * Borland seems to have a problem in DOS mode for exactly 64K.
  182307. * It gives you a segment with an offset of 8 (perhaps to store its
  182308. * memory stuff). zlib doesn't like this at all, so we have to
  182309. * detect and deal with it. This code should not be needed in
  182310. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  182311. * been updated by Alexander Lehmann for version 0.89 to waste less
  182312. * memory.
  182313. *
  182314. * Note that we can't use png_size_t for the "size" declaration,
  182315. * since on some systems a png_size_t is a 16-bit quantity, and as a
  182316. * result, we would be truncating potentially larger memory requests
  182317. * (which should cause a fatal error) and introducing major problems.
  182318. */
  182319. png_voidp PNGAPI
  182320. png_malloc(png_structp png_ptr, png_uint_32 size)
  182321. {
  182322. png_voidp ret;
  182323. if (png_ptr == NULL || size == 0)
  182324. return (NULL);
  182325. #ifdef PNG_USER_MEM_SUPPORTED
  182326. if(png_ptr->malloc_fn != NULL)
  182327. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182328. else
  182329. ret = (png_malloc_default(png_ptr, size));
  182330. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182331. png_error(png_ptr, "Out of memory!");
  182332. return (ret);
  182333. }
  182334. png_voidp PNGAPI
  182335. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182336. {
  182337. png_voidp ret;
  182338. #endif /* PNG_USER_MEM_SUPPORTED */
  182339. if (png_ptr == NULL || size == 0)
  182340. return (NULL);
  182341. #ifdef PNG_MAX_MALLOC_64K
  182342. if (size > (png_uint_32)65536L)
  182343. {
  182344. png_warning(png_ptr, "Cannot Allocate > 64K");
  182345. ret = NULL;
  182346. }
  182347. else
  182348. #endif
  182349. if (size != (size_t)size)
  182350. ret = NULL;
  182351. else if (size == (png_uint_32)65536L)
  182352. {
  182353. if (png_ptr->offset_table == NULL)
  182354. {
  182355. /* try to see if we need to do any of this fancy stuff */
  182356. ret = farmalloc(size);
  182357. if (ret == NULL || ((png_size_t)ret & 0xffff))
  182358. {
  182359. int num_blocks;
  182360. png_uint_32 total_size;
  182361. png_bytep table;
  182362. int i;
  182363. png_byte huge * hptr;
  182364. if (ret != NULL)
  182365. {
  182366. farfree(ret);
  182367. ret = NULL;
  182368. }
  182369. if(png_ptr->zlib_window_bits > 14)
  182370. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  182371. else
  182372. num_blocks = 1;
  182373. if (png_ptr->zlib_mem_level >= 7)
  182374. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  182375. else
  182376. num_blocks++;
  182377. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  182378. table = farmalloc(total_size);
  182379. if (table == NULL)
  182380. {
  182381. #ifndef PNG_USER_MEM_SUPPORTED
  182382. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182383. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  182384. else
  182385. png_warning(png_ptr, "Out Of Memory.");
  182386. #endif
  182387. return (NULL);
  182388. }
  182389. if ((png_size_t)table & 0xfff0)
  182390. {
  182391. #ifndef PNG_USER_MEM_SUPPORTED
  182392. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182393. png_error(png_ptr,
  182394. "Farmalloc didn't return normalized pointer");
  182395. else
  182396. png_warning(png_ptr,
  182397. "Farmalloc didn't return normalized pointer");
  182398. #endif
  182399. return (NULL);
  182400. }
  182401. png_ptr->offset_table = table;
  182402. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  182403. png_sizeof (png_bytep));
  182404. if (png_ptr->offset_table_ptr == NULL)
  182405. {
  182406. #ifndef PNG_USER_MEM_SUPPORTED
  182407. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182408. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  182409. else
  182410. png_warning(png_ptr, "Out Of memory.");
  182411. #endif
  182412. return (NULL);
  182413. }
  182414. hptr = (png_byte huge *)table;
  182415. if ((png_size_t)hptr & 0xf)
  182416. {
  182417. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  182418. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  182419. }
  182420. for (i = 0; i < num_blocks; i++)
  182421. {
  182422. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  182423. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  182424. }
  182425. png_ptr->offset_table_number = num_blocks;
  182426. png_ptr->offset_table_count = 0;
  182427. png_ptr->offset_table_count_free = 0;
  182428. }
  182429. }
  182430. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  182431. {
  182432. #ifndef PNG_USER_MEM_SUPPORTED
  182433. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182434. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  182435. else
  182436. png_warning(png_ptr, "Out of Memory.");
  182437. #endif
  182438. return (NULL);
  182439. }
  182440. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  182441. }
  182442. else
  182443. ret = farmalloc(size);
  182444. #ifndef PNG_USER_MEM_SUPPORTED
  182445. if (ret == NULL)
  182446. {
  182447. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182448. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182449. else
  182450. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182451. }
  182452. #endif
  182453. return (ret);
  182454. }
  182455. /* free a pointer allocated by png_malloc(). In the default
  182456. configuration, png_ptr is not used, but is passed in case it
  182457. is needed. If ptr is NULL, return without taking any action. */
  182458. void PNGAPI
  182459. png_free(png_structp png_ptr, png_voidp ptr)
  182460. {
  182461. if (png_ptr == NULL || ptr == NULL)
  182462. return;
  182463. #ifdef PNG_USER_MEM_SUPPORTED
  182464. if (png_ptr->free_fn != NULL)
  182465. {
  182466. (*(png_ptr->free_fn))(png_ptr, ptr);
  182467. return;
  182468. }
  182469. else png_free_default(png_ptr, ptr);
  182470. }
  182471. void PNGAPI
  182472. png_free_default(png_structp png_ptr, png_voidp ptr)
  182473. {
  182474. #endif /* PNG_USER_MEM_SUPPORTED */
  182475. if(png_ptr == NULL) return;
  182476. if (png_ptr->offset_table != NULL)
  182477. {
  182478. int i;
  182479. for (i = 0; i < png_ptr->offset_table_count; i++)
  182480. {
  182481. if (ptr == png_ptr->offset_table_ptr[i])
  182482. {
  182483. ptr = NULL;
  182484. png_ptr->offset_table_count_free++;
  182485. break;
  182486. }
  182487. }
  182488. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  182489. {
  182490. farfree(png_ptr->offset_table);
  182491. farfree(png_ptr->offset_table_ptr);
  182492. png_ptr->offset_table = NULL;
  182493. png_ptr->offset_table_ptr = NULL;
  182494. }
  182495. }
  182496. if (ptr != NULL)
  182497. {
  182498. farfree(ptr);
  182499. }
  182500. }
  182501. #else /* Not the Borland DOS special memory handler */
  182502. /* Allocate memory for a png_struct or a png_info. The malloc and
  182503. memset can be replaced by a single call to calloc() if this is thought
  182504. to improve performance noticably. */
  182505. png_voidp /* PRIVATE */
  182506. png_create_struct(int type)
  182507. {
  182508. #ifdef PNG_USER_MEM_SUPPORTED
  182509. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182510. }
  182511. /* Allocate memory for a png_struct or a png_info. The malloc and
  182512. memset can be replaced by a single call to calloc() if this is thought
  182513. to improve performance noticably. */
  182514. png_voidp /* PRIVATE */
  182515. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182516. {
  182517. #endif /* PNG_USER_MEM_SUPPORTED */
  182518. png_size_t size;
  182519. png_voidp struct_ptr;
  182520. if (type == PNG_STRUCT_INFO)
  182521. size = png_sizeof(png_info);
  182522. else if (type == PNG_STRUCT_PNG)
  182523. size = png_sizeof(png_struct);
  182524. else
  182525. return (NULL);
  182526. #ifdef PNG_USER_MEM_SUPPORTED
  182527. if(malloc_fn != NULL)
  182528. {
  182529. png_struct dummy_struct;
  182530. png_structp png_ptr = &dummy_struct;
  182531. png_ptr->mem_ptr=mem_ptr;
  182532. struct_ptr = (*(malloc_fn))(png_ptr, size);
  182533. if (struct_ptr != NULL)
  182534. png_memset(struct_ptr, 0, size);
  182535. return (struct_ptr);
  182536. }
  182537. #endif /* PNG_USER_MEM_SUPPORTED */
  182538. #if defined(__TURBOC__) && !defined(__FLAT__)
  182539. struct_ptr = (png_voidp)farmalloc(size);
  182540. #else
  182541. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182542. struct_ptr = (png_voidp)halloc(size,1);
  182543. # else
  182544. struct_ptr = (png_voidp)malloc(size);
  182545. # endif
  182546. #endif
  182547. if (struct_ptr != NULL)
  182548. png_memset(struct_ptr, 0, size);
  182549. return (struct_ptr);
  182550. }
  182551. /* Free memory allocated by a png_create_struct() call */
  182552. void /* PRIVATE */
  182553. png_destroy_struct(png_voidp struct_ptr)
  182554. {
  182555. #ifdef PNG_USER_MEM_SUPPORTED
  182556. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182557. }
  182558. /* Free memory allocated by a png_create_struct() call */
  182559. void /* PRIVATE */
  182560. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182561. png_voidp mem_ptr)
  182562. {
  182563. #endif /* PNG_USER_MEM_SUPPORTED */
  182564. if (struct_ptr != NULL)
  182565. {
  182566. #ifdef PNG_USER_MEM_SUPPORTED
  182567. if(free_fn != NULL)
  182568. {
  182569. png_struct dummy_struct;
  182570. png_structp png_ptr = &dummy_struct;
  182571. png_ptr->mem_ptr=mem_ptr;
  182572. (*(free_fn))(png_ptr, struct_ptr);
  182573. return;
  182574. }
  182575. #endif /* PNG_USER_MEM_SUPPORTED */
  182576. #if defined(__TURBOC__) && !defined(__FLAT__)
  182577. farfree(struct_ptr);
  182578. #else
  182579. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182580. hfree(struct_ptr);
  182581. # else
  182582. free(struct_ptr);
  182583. # endif
  182584. #endif
  182585. }
  182586. }
  182587. /* Allocate memory. For reasonable files, size should never exceed
  182588. 64K. However, zlib may allocate more then 64K if you don't tell
  182589. it not to. See zconf.h and png.h for more information. zlib does
  182590. need to allocate exactly 64K, so whatever you call here must
  182591. have the ability to do that. */
  182592. png_voidp PNGAPI
  182593. png_malloc(png_structp png_ptr, png_uint_32 size)
  182594. {
  182595. png_voidp ret;
  182596. #ifdef PNG_USER_MEM_SUPPORTED
  182597. if (png_ptr == NULL || size == 0)
  182598. return (NULL);
  182599. if(png_ptr->malloc_fn != NULL)
  182600. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182601. else
  182602. ret = (png_malloc_default(png_ptr, size));
  182603. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182604. png_error(png_ptr, "Out of Memory!");
  182605. return (ret);
  182606. }
  182607. png_voidp PNGAPI
  182608. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182609. {
  182610. png_voidp ret;
  182611. #endif /* PNG_USER_MEM_SUPPORTED */
  182612. if (png_ptr == NULL || size == 0)
  182613. return (NULL);
  182614. #ifdef PNG_MAX_MALLOC_64K
  182615. if (size > (png_uint_32)65536L)
  182616. {
  182617. #ifndef PNG_USER_MEM_SUPPORTED
  182618. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182619. png_error(png_ptr, "Cannot Allocate > 64K");
  182620. else
  182621. #endif
  182622. return NULL;
  182623. }
  182624. #endif
  182625. /* Check for overflow */
  182626. #if defined(__TURBOC__) && !defined(__FLAT__)
  182627. if (size != (unsigned long)size)
  182628. ret = NULL;
  182629. else
  182630. ret = farmalloc(size);
  182631. #else
  182632. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182633. if (size != (unsigned long)size)
  182634. ret = NULL;
  182635. else
  182636. ret = halloc(size, 1);
  182637. # else
  182638. if (size != (size_t)size)
  182639. ret = NULL;
  182640. else
  182641. ret = malloc((size_t)size);
  182642. # endif
  182643. #endif
  182644. #ifndef PNG_USER_MEM_SUPPORTED
  182645. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182646. png_error(png_ptr, "Out of Memory");
  182647. #endif
  182648. return (ret);
  182649. }
  182650. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  182651. without taking any action. */
  182652. void PNGAPI
  182653. png_free(png_structp png_ptr, png_voidp ptr)
  182654. {
  182655. if (png_ptr == NULL || ptr == NULL)
  182656. return;
  182657. #ifdef PNG_USER_MEM_SUPPORTED
  182658. if (png_ptr->free_fn != NULL)
  182659. {
  182660. (*(png_ptr->free_fn))(png_ptr, ptr);
  182661. return;
  182662. }
  182663. else png_free_default(png_ptr, ptr);
  182664. }
  182665. void PNGAPI
  182666. png_free_default(png_structp png_ptr, png_voidp ptr)
  182667. {
  182668. if (png_ptr == NULL || ptr == NULL)
  182669. return;
  182670. #endif /* PNG_USER_MEM_SUPPORTED */
  182671. #if defined(__TURBOC__) && !defined(__FLAT__)
  182672. farfree(ptr);
  182673. #else
  182674. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182675. hfree(ptr);
  182676. # else
  182677. free(ptr);
  182678. # endif
  182679. #endif
  182680. }
  182681. #endif /* Not Borland DOS special memory handler */
  182682. #if defined(PNG_1_0_X)
  182683. # define png_malloc_warn png_malloc
  182684. #else
  182685. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  182686. * function will set up png_malloc() to issue a png_warning and return NULL
  182687. * instead of issuing a png_error, if it fails to allocate the requested
  182688. * memory.
  182689. */
  182690. png_voidp PNGAPI
  182691. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  182692. {
  182693. png_voidp ptr;
  182694. png_uint_32 save_flags;
  182695. if(png_ptr == NULL) return (NULL);
  182696. save_flags=png_ptr->flags;
  182697. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  182698. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  182699. png_ptr->flags=save_flags;
  182700. return(ptr);
  182701. }
  182702. #endif
  182703. png_voidp PNGAPI
  182704. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  182705. png_uint_32 length)
  182706. {
  182707. png_size_t size;
  182708. size = (png_size_t)length;
  182709. if ((png_uint_32)size != length)
  182710. png_error(png_ptr,"Overflow in png_memcpy_check.");
  182711. return(png_memcpy (s1, s2, size));
  182712. }
  182713. png_voidp PNGAPI
  182714. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  182715. png_uint_32 length)
  182716. {
  182717. png_size_t size;
  182718. size = (png_size_t)length;
  182719. if ((png_uint_32)size != length)
  182720. png_error(png_ptr,"Overflow in png_memset_check.");
  182721. return (png_memset (s1, value, size));
  182722. }
  182723. #ifdef PNG_USER_MEM_SUPPORTED
  182724. /* This function is called when the application wants to use another method
  182725. * of allocating and freeing memory.
  182726. */
  182727. void PNGAPI
  182728. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  182729. malloc_fn, png_free_ptr free_fn)
  182730. {
  182731. if(png_ptr != NULL) {
  182732. png_ptr->mem_ptr = mem_ptr;
  182733. png_ptr->malloc_fn = malloc_fn;
  182734. png_ptr->free_fn = free_fn;
  182735. }
  182736. }
  182737. /* This function returns a pointer to the mem_ptr associated with the user
  182738. * functions. The application should free any memory associated with this
  182739. * pointer before png_write_destroy and png_read_destroy are called.
  182740. */
  182741. png_voidp PNGAPI
  182742. png_get_mem_ptr(png_structp png_ptr)
  182743. {
  182744. if(png_ptr == NULL) return (NULL);
  182745. return ((png_voidp)png_ptr->mem_ptr);
  182746. }
  182747. #endif /* PNG_USER_MEM_SUPPORTED */
  182748. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182749. /********* End of inlined file: pngmem.c *********/
  182750. /********* Start of inlined file: pngread.c *********/
  182751. /* pngread.c - read a PNG file
  182752. *
  182753. * Last changed in libpng 1.2.20 September 7, 2007
  182754. * For conditions of distribution and use, see copyright notice in png.h
  182755. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182756. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182757. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182758. *
  182759. * This file contains routines that an application calls directly to
  182760. * read a PNG file or stream.
  182761. */
  182762. #define PNG_INTERNAL
  182763. #if defined(PNG_READ_SUPPORTED)
  182764. /* Create a PNG structure for reading, and allocate any memory needed. */
  182765. png_structp PNGAPI
  182766. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  182767. png_error_ptr error_fn, png_error_ptr warn_fn)
  182768. {
  182769. #ifdef PNG_USER_MEM_SUPPORTED
  182770. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  182771. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  182772. }
  182773. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  182774. png_structp PNGAPI
  182775. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  182776. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182777. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  182778. {
  182779. #endif /* PNG_USER_MEM_SUPPORTED */
  182780. png_structp png_ptr;
  182781. #ifdef PNG_SETJMP_SUPPORTED
  182782. #ifdef USE_FAR_KEYWORD
  182783. jmp_buf jmpbuf;
  182784. #endif
  182785. #endif
  182786. int i;
  182787. png_debug(1, "in png_create_read_struct\n");
  182788. #ifdef PNG_USER_MEM_SUPPORTED
  182789. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  182790. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  182791. #else
  182792. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182793. #endif
  182794. if (png_ptr == NULL)
  182795. return (NULL);
  182796. /* added at libpng-1.2.6 */
  182797. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182798. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182799. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182800. #endif
  182801. #ifdef PNG_SETJMP_SUPPORTED
  182802. #ifdef USE_FAR_KEYWORD
  182803. if (setjmp(jmpbuf))
  182804. #else
  182805. if (setjmp(png_ptr->jmpbuf))
  182806. #endif
  182807. {
  182808. png_free(png_ptr, png_ptr->zbuf);
  182809. png_ptr->zbuf=NULL;
  182810. #ifdef PNG_USER_MEM_SUPPORTED
  182811. png_destroy_struct_2((png_voidp)png_ptr,
  182812. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  182813. #else
  182814. png_destroy_struct((png_voidp)png_ptr);
  182815. #endif
  182816. return (NULL);
  182817. }
  182818. #ifdef USE_FAR_KEYWORD
  182819. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182820. #endif
  182821. #endif
  182822. #ifdef PNG_USER_MEM_SUPPORTED
  182823. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  182824. #endif
  182825. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  182826. i=0;
  182827. do
  182828. {
  182829. if(user_png_ver[i] != png_libpng_ver[i])
  182830. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182831. } while (png_libpng_ver[i++]);
  182832. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  182833. {
  182834. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  182835. * we must recompile any applications that use any older library version.
  182836. * For versions after libpng 1.0, we will be compatible, so we need
  182837. * only check the first digit.
  182838. */
  182839. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  182840. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  182841. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  182842. {
  182843. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182844. char msg[80];
  182845. if (user_png_ver)
  182846. {
  182847. png_snprintf(msg, 80,
  182848. "Application was compiled with png.h from libpng-%.20s",
  182849. user_png_ver);
  182850. png_warning(png_ptr, msg);
  182851. }
  182852. png_snprintf(msg, 80,
  182853. "Application is running with png.c from libpng-%.20s",
  182854. png_libpng_ver);
  182855. png_warning(png_ptr, msg);
  182856. #endif
  182857. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182858. png_ptr->flags=0;
  182859. #endif
  182860. png_error(png_ptr,
  182861. "Incompatible libpng version in application and library");
  182862. }
  182863. }
  182864. /* initialize zbuf - compression buffer */
  182865. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182866. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182867. (png_uint_32)png_ptr->zbuf_size);
  182868. png_ptr->zstream.zalloc = png_zalloc;
  182869. png_ptr->zstream.zfree = png_zfree;
  182870. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182871. switch (inflateInit(&png_ptr->zstream))
  182872. {
  182873. case Z_OK: /* Do nothing */ break;
  182874. case Z_MEM_ERROR:
  182875. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  182876. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  182877. default: png_error(png_ptr, "Unknown zlib error");
  182878. }
  182879. png_ptr->zstream.next_out = png_ptr->zbuf;
  182880. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182881. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182882. #ifdef PNG_SETJMP_SUPPORTED
  182883. /* Applications that neglect to set up their own setjmp() and then encounter
  182884. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  182885. abort instead of returning. */
  182886. #ifdef USE_FAR_KEYWORD
  182887. if (setjmp(jmpbuf))
  182888. PNG_ABORT();
  182889. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182890. #else
  182891. if (setjmp(png_ptr->jmpbuf))
  182892. PNG_ABORT();
  182893. #endif
  182894. #endif
  182895. return (png_ptr);
  182896. }
  182897. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  182898. /* Initialize PNG structure for reading, and allocate any memory needed.
  182899. This interface is deprecated in favour of the png_create_read_struct(),
  182900. and it will disappear as of libpng-1.3.0. */
  182901. #undef png_read_init
  182902. void PNGAPI
  182903. png_read_init(png_structp png_ptr)
  182904. {
  182905. /* We only come here via pre-1.0.7-compiled applications */
  182906. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  182907. }
  182908. void PNGAPI
  182909. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  182910. png_size_t png_struct_size, png_size_t png_info_size)
  182911. {
  182912. /* We only come here via pre-1.0.12-compiled applications */
  182913. if(png_ptr == NULL) return;
  182914. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182915. if(png_sizeof(png_struct) > png_struct_size ||
  182916. png_sizeof(png_info) > png_info_size)
  182917. {
  182918. char msg[80];
  182919. png_ptr->warning_fn=NULL;
  182920. if (user_png_ver)
  182921. {
  182922. png_snprintf(msg, 80,
  182923. "Application was compiled with png.h from libpng-%.20s",
  182924. user_png_ver);
  182925. png_warning(png_ptr, msg);
  182926. }
  182927. png_snprintf(msg, 80,
  182928. "Application is running with png.c from libpng-%.20s",
  182929. png_libpng_ver);
  182930. png_warning(png_ptr, msg);
  182931. }
  182932. #endif
  182933. if(png_sizeof(png_struct) > png_struct_size)
  182934. {
  182935. png_ptr->error_fn=NULL;
  182936. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182937. png_ptr->flags=0;
  182938. #endif
  182939. png_error(png_ptr,
  182940. "The png struct allocated by the application for reading is too small.");
  182941. }
  182942. if(png_sizeof(png_info) > png_info_size)
  182943. {
  182944. png_ptr->error_fn=NULL;
  182945. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182946. png_ptr->flags=0;
  182947. #endif
  182948. png_error(png_ptr,
  182949. "The info struct allocated by application for reading is too small.");
  182950. }
  182951. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  182952. }
  182953. #endif /* PNG_1_0_X || PNG_1_2_X */
  182954. void PNGAPI
  182955. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  182956. png_size_t png_struct_size)
  182957. {
  182958. #ifdef PNG_SETJMP_SUPPORTED
  182959. jmp_buf tmp_jmp; /* to save current jump buffer */
  182960. #endif
  182961. int i=0;
  182962. png_structp png_ptr=*ptr_ptr;
  182963. if(png_ptr == NULL) return;
  182964. do
  182965. {
  182966. if(user_png_ver[i] != png_libpng_ver[i])
  182967. {
  182968. #ifdef PNG_LEGACY_SUPPORTED
  182969. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182970. #else
  182971. png_ptr->warning_fn=NULL;
  182972. png_warning(png_ptr,
  182973. "Application uses deprecated png_read_init() and should be recompiled.");
  182974. break;
  182975. #endif
  182976. }
  182977. } while (png_libpng_ver[i++]);
  182978. png_debug(1, "in png_read_init_3\n");
  182979. #ifdef PNG_SETJMP_SUPPORTED
  182980. /* save jump buffer and error functions */
  182981. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182982. #endif
  182983. if(png_sizeof(png_struct) > png_struct_size)
  182984. {
  182985. png_destroy_struct(png_ptr);
  182986. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182987. png_ptr = *ptr_ptr;
  182988. }
  182989. /* reset all variables to 0 */
  182990. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182991. #ifdef PNG_SETJMP_SUPPORTED
  182992. /* restore jump buffer */
  182993. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182994. #endif
  182995. /* added at libpng-1.2.6 */
  182996. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182997. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182998. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182999. #endif
  183000. /* initialize zbuf - compression buffer */
  183001. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  183002. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  183003. (png_uint_32)png_ptr->zbuf_size);
  183004. png_ptr->zstream.zalloc = png_zalloc;
  183005. png_ptr->zstream.zfree = png_zfree;
  183006. png_ptr->zstream.opaque = (voidpf)png_ptr;
  183007. switch (inflateInit(&png_ptr->zstream))
  183008. {
  183009. case Z_OK: /* Do nothing */ break;
  183010. case Z_MEM_ERROR:
  183011. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  183012. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  183013. default: png_error(png_ptr, "Unknown zlib error");
  183014. }
  183015. png_ptr->zstream.next_out = png_ptr->zbuf;
  183016. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183017. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  183018. }
  183019. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183020. /* Read the information before the actual image data. This has been
  183021. * changed in v0.90 to allow reading a file that already has the magic
  183022. * bytes read from the stream. You can tell libpng how many bytes have
  183023. * been read from the beginning of the stream (up to the maximum of 8)
  183024. * via png_set_sig_bytes(), and we will only check the remaining bytes
  183025. * here. The application can then have access to the signature bytes we
  183026. * read if it is determined that this isn't a valid PNG file.
  183027. */
  183028. void PNGAPI
  183029. png_read_info(png_structp png_ptr, png_infop info_ptr)
  183030. {
  183031. if(png_ptr == NULL) return;
  183032. png_debug(1, "in png_read_info\n");
  183033. /* If we haven't checked all of the PNG signature bytes, do so now. */
  183034. if (png_ptr->sig_bytes < 8)
  183035. {
  183036. png_size_t num_checked = png_ptr->sig_bytes,
  183037. num_to_check = 8 - num_checked;
  183038. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  183039. png_ptr->sig_bytes = 8;
  183040. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  183041. {
  183042. if (num_checked < 4 &&
  183043. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  183044. png_error(png_ptr, "Not a PNG file");
  183045. else
  183046. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  183047. }
  183048. if (num_checked < 3)
  183049. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  183050. }
  183051. for(;;)
  183052. {
  183053. #ifdef PNG_USE_LOCAL_ARRAYS
  183054. PNG_CONST PNG_IHDR;
  183055. PNG_CONST PNG_IDAT;
  183056. PNG_CONST PNG_IEND;
  183057. PNG_CONST PNG_PLTE;
  183058. #if defined(PNG_READ_bKGD_SUPPORTED)
  183059. PNG_CONST PNG_bKGD;
  183060. #endif
  183061. #if defined(PNG_READ_cHRM_SUPPORTED)
  183062. PNG_CONST PNG_cHRM;
  183063. #endif
  183064. #if defined(PNG_READ_gAMA_SUPPORTED)
  183065. PNG_CONST PNG_gAMA;
  183066. #endif
  183067. #if defined(PNG_READ_hIST_SUPPORTED)
  183068. PNG_CONST PNG_hIST;
  183069. #endif
  183070. #if defined(PNG_READ_iCCP_SUPPORTED)
  183071. PNG_CONST PNG_iCCP;
  183072. #endif
  183073. #if defined(PNG_READ_iTXt_SUPPORTED)
  183074. PNG_CONST PNG_iTXt;
  183075. #endif
  183076. #if defined(PNG_READ_oFFs_SUPPORTED)
  183077. PNG_CONST PNG_oFFs;
  183078. #endif
  183079. #if defined(PNG_READ_pCAL_SUPPORTED)
  183080. PNG_CONST PNG_pCAL;
  183081. #endif
  183082. #if defined(PNG_READ_pHYs_SUPPORTED)
  183083. PNG_CONST PNG_pHYs;
  183084. #endif
  183085. #if defined(PNG_READ_sBIT_SUPPORTED)
  183086. PNG_CONST PNG_sBIT;
  183087. #endif
  183088. #if defined(PNG_READ_sCAL_SUPPORTED)
  183089. PNG_CONST PNG_sCAL;
  183090. #endif
  183091. #if defined(PNG_READ_sPLT_SUPPORTED)
  183092. PNG_CONST PNG_sPLT;
  183093. #endif
  183094. #if defined(PNG_READ_sRGB_SUPPORTED)
  183095. PNG_CONST PNG_sRGB;
  183096. #endif
  183097. #if defined(PNG_READ_tEXt_SUPPORTED)
  183098. PNG_CONST PNG_tEXt;
  183099. #endif
  183100. #if defined(PNG_READ_tIME_SUPPORTED)
  183101. PNG_CONST PNG_tIME;
  183102. #endif
  183103. #if defined(PNG_READ_tRNS_SUPPORTED)
  183104. PNG_CONST PNG_tRNS;
  183105. #endif
  183106. #if defined(PNG_READ_zTXt_SUPPORTED)
  183107. PNG_CONST PNG_zTXt;
  183108. #endif
  183109. #endif /* PNG_USE_LOCAL_ARRAYS */
  183110. png_byte chunk_length[4];
  183111. png_uint_32 length;
  183112. png_read_data(png_ptr, chunk_length, 4);
  183113. length = png_get_uint_31(png_ptr,chunk_length);
  183114. png_reset_crc(png_ptr);
  183115. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183116. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  183117. length);
  183118. /* This should be a binary subdivision search or a hash for
  183119. * matching the chunk name rather than a linear search.
  183120. */
  183121. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183122. if(png_ptr->mode & PNG_AFTER_IDAT)
  183123. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  183124. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183125. png_handle_IHDR(png_ptr, info_ptr, length);
  183126. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183127. png_handle_IEND(png_ptr, info_ptr, length);
  183128. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183129. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183130. {
  183131. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183132. png_ptr->mode |= PNG_HAVE_IDAT;
  183133. png_handle_unknown(png_ptr, info_ptr, length);
  183134. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183135. png_ptr->mode |= PNG_HAVE_PLTE;
  183136. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183137. {
  183138. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183139. png_error(png_ptr, "Missing IHDR before IDAT");
  183140. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183141. !(png_ptr->mode & PNG_HAVE_PLTE))
  183142. png_error(png_ptr, "Missing PLTE before IDAT");
  183143. break;
  183144. }
  183145. }
  183146. #endif
  183147. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183148. png_handle_PLTE(png_ptr, info_ptr, length);
  183149. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183150. {
  183151. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183152. png_error(png_ptr, "Missing IHDR before IDAT");
  183153. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183154. !(png_ptr->mode & PNG_HAVE_PLTE))
  183155. png_error(png_ptr, "Missing PLTE before IDAT");
  183156. png_ptr->idat_size = length;
  183157. png_ptr->mode |= PNG_HAVE_IDAT;
  183158. break;
  183159. }
  183160. #if defined(PNG_READ_bKGD_SUPPORTED)
  183161. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183162. png_handle_bKGD(png_ptr, info_ptr, length);
  183163. #endif
  183164. #if defined(PNG_READ_cHRM_SUPPORTED)
  183165. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183166. png_handle_cHRM(png_ptr, info_ptr, length);
  183167. #endif
  183168. #if defined(PNG_READ_gAMA_SUPPORTED)
  183169. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183170. png_handle_gAMA(png_ptr, info_ptr, length);
  183171. #endif
  183172. #if defined(PNG_READ_hIST_SUPPORTED)
  183173. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183174. png_handle_hIST(png_ptr, info_ptr, length);
  183175. #endif
  183176. #if defined(PNG_READ_oFFs_SUPPORTED)
  183177. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183178. png_handle_oFFs(png_ptr, info_ptr, length);
  183179. #endif
  183180. #if defined(PNG_READ_pCAL_SUPPORTED)
  183181. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183182. png_handle_pCAL(png_ptr, info_ptr, length);
  183183. #endif
  183184. #if defined(PNG_READ_sCAL_SUPPORTED)
  183185. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183186. png_handle_sCAL(png_ptr, info_ptr, length);
  183187. #endif
  183188. #if defined(PNG_READ_pHYs_SUPPORTED)
  183189. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183190. png_handle_pHYs(png_ptr, info_ptr, length);
  183191. #endif
  183192. #if defined(PNG_READ_sBIT_SUPPORTED)
  183193. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183194. png_handle_sBIT(png_ptr, info_ptr, length);
  183195. #endif
  183196. #if defined(PNG_READ_sRGB_SUPPORTED)
  183197. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183198. png_handle_sRGB(png_ptr, info_ptr, length);
  183199. #endif
  183200. #if defined(PNG_READ_iCCP_SUPPORTED)
  183201. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183202. png_handle_iCCP(png_ptr, info_ptr, length);
  183203. #endif
  183204. #if defined(PNG_READ_sPLT_SUPPORTED)
  183205. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183206. png_handle_sPLT(png_ptr, info_ptr, length);
  183207. #endif
  183208. #if defined(PNG_READ_tEXt_SUPPORTED)
  183209. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183210. png_handle_tEXt(png_ptr, info_ptr, length);
  183211. #endif
  183212. #if defined(PNG_READ_tIME_SUPPORTED)
  183213. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183214. png_handle_tIME(png_ptr, info_ptr, length);
  183215. #endif
  183216. #if defined(PNG_READ_tRNS_SUPPORTED)
  183217. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183218. png_handle_tRNS(png_ptr, info_ptr, length);
  183219. #endif
  183220. #if defined(PNG_READ_zTXt_SUPPORTED)
  183221. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183222. png_handle_zTXt(png_ptr, info_ptr, length);
  183223. #endif
  183224. #if defined(PNG_READ_iTXt_SUPPORTED)
  183225. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183226. png_handle_iTXt(png_ptr, info_ptr, length);
  183227. #endif
  183228. else
  183229. png_handle_unknown(png_ptr, info_ptr, length);
  183230. }
  183231. }
  183232. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183233. /* optional call to update the users info_ptr structure */
  183234. void PNGAPI
  183235. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  183236. {
  183237. png_debug(1, "in png_read_update_info\n");
  183238. if(png_ptr == NULL) return;
  183239. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183240. png_read_start_row(png_ptr);
  183241. else
  183242. png_warning(png_ptr,
  183243. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  183244. png_read_transform_info(png_ptr, info_ptr);
  183245. }
  183246. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183247. /* Initialize palette, background, etc, after transformations
  183248. * are set, but before any reading takes place. This allows
  183249. * the user to obtain a gamma-corrected palette, for example.
  183250. * If the user doesn't call this, we will do it ourselves.
  183251. */
  183252. void PNGAPI
  183253. png_start_read_image(png_structp png_ptr)
  183254. {
  183255. png_debug(1, "in png_start_read_image\n");
  183256. if(png_ptr == NULL) return;
  183257. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183258. png_read_start_row(png_ptr);
  183259. }
  183260. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183261. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183262. void PNGAPI
  183263. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  183264. {
  183265. #ifdef PNG_USE_LOCAL_ARRAYS
  183266. PNG_CONST PNG_IDAT;
  183267. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  183268. 0xff};
  183269. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183270. #endif
  183271. int ret;
  183272. if(png_ptr == NULL) return;
  183273. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  183274. png_ptr->row_number, png_ptr->pass);
  183275. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183276. png_read_start_row(png_ptr);
  183277. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  183278. {
  183279. /* check for transforms that have been set but were defined out */
  183280. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  183281. if (png_ptr->transformations & PNG_INVERT_MONO)
  183282. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  183283. #endif
  183284. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  183285. if (png_ptr->transformations & PNG_FILLER)
  183286. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  183287. #endif
  183288. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  183289. if (png_ptr->transformations & PNG_PACKSWAP)
  183290. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  183291. #endif
  183292. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  183293. if (png_ptr->transformations & PNG_PACK)
  183294. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  183295. #endif
  183296. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  183297. if (png_ptr->transformations & PNG_SHIFT)
  183298. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  183299. #endif
  183300. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  183301. if (png_ptr->transformations & PNG_BGR)
  183302. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  183303. #endif
  183304. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  183305. if (png_ptr->transformations & PNG_SWAP_BYTES)
  183306. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  183307. #endif
  183308. }
  183309. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183310. /* if interlaced and we do not need a new row, combine row and return */
  183311. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183312. {
  183313. switch (png_ptr->pass)
  183314. {
  183315. case 0:
  183316. if (png_ptr->row_number & 0x07)
  183317. {
  183318. if (dsp_row != NULL)
  183319. png_combine_row(png_ptr, dsp_row,
  183320. png_pass_dsp_mask[png_ptr->pass]);
  183321. png_read_finish_row(png_ptr);
  183322. return;
  183323. }
  183324. break;
  183325. case 1:
  183326. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  183327. {
  183328. if (dsp_row != NULL)
  183329. png_combine_row(png_ptr, dsp_row,
  183330. png_pass_dsp_mask[png_ptr->pass]);
  183331. png_read_finish_row(png_ptr);
  183332. return;
  183333. }
  183334. break;
  183335. case 2:
  183336. if ((png_ptr->row_number & 0x07) != 4)
  183337. {
  183338. if (dsp_row != NULL && (png_ptr->row_number & 4))
  183339. png_combine_row(png_ptr, dsp_row,
  183340. png_pass_dsp_mask[png_ptr->pass]);
  183341. png_read_finish_row(png_ptr);
  183342. return;
  183343. }
  183344. break;
  183345. case 3:
  183346. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  183347. {
  183348. if (dsp_row != NULL)
  183349. png_combine_row(png_ptr, dsp_row,
  183350. png_pass_dsp_mask[png_ptr->pass]);
  183351. png_read_finish_row(png_ptr);
  183352. return;
  183353. }
  183354. break;
  183355. case 4:
  183356. if ((png_ptr->row_number & 3) != 2)
  183357. {
  183358. if (dsp_row != NULL && (png_ptr->row_number & 2))
  183359. png_combine_row(png_ptr, dsp_row,
  183360. png_pass_dsp_mask[png_ptr->pass]);
  183361. png_read_finish_row(png_ptr);
  183362. return;
  183363. }
  183364. break;
  183365. case 5:
  183366. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  183367. {
  183368. if (dsp_row != NULL)
  183369. png_combine_row(png_ptr, dsp_row,
  183370. png_pass_dsp_mask[png_ptr->pass]);
  183371. png_read_finish_row(png_ptr);
  183372. return;
  183373. }
  183374. break;
  183375. case 6:
  183376. if (!(png_ptr->row_number & 1))
  183377. {
  183378. png_read_finish_row(png_ptr);
  183379. return;
  183380. }
  183381. break;
  183382. }
  183383. }
  183384. #endif
  183385. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  183386. png_error(png_ptr, "Invalid attempt to read row data");
  183387. png_ptr->zstream.next_out = png_ptr->row_buf;
  183388. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183389. do
  183390. {
  183391. if (!(png_ptr->zstream.avail_in))
  183392. {
  183393. while (!png_ptr->idat_size)
  183394. {
  183395. png_byte chunk_length[4];
  183396. png_crc_finish(png_ptr, 0);
  183397. png_read_data(png_ptr, chunk_length, 4);
  183398. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  183399. png_reset_crc(png_ptr);
  183400. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183401. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183402. png_error(png_ptr, "Not enough image data");
  183403. }
  183404. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  183405. png_ptr->zstream.next_in = png_ptr->zbuf;
  183406. if (png_ptr->zbuf_size > png_ptr->idat_size)
  183407. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  183408. png_crc_read(png_ptr, png_ptr->zbuf,
  183409. (png_size_t)png_ptr->zstream.avail_in);
  183410. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  183411. }
  183412. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183413. if (ret == Z_STREAM_END)
  183414. {
  183415. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  183416. png_ptr->idat_size)
  183417. png_error(png_ptr, "Extra compressed data");
  183418. png_ptr->mode |= PNG_AFTER_IDAT;
  183419. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183420. break;
  183421. }
  183422. if (ret != Z_OK)
  183423. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  183424. "Decompression error");
  183425. } while (png_ptr->zstream.avail_out);
  183426. png_ptr->row_info.color_type = png_ptr->color_type;
  183427. png_ptr->row_info.width = png_ptr->iwidth;
  183428. png_ptr->row_info.channels = png_ptr->channels;
  183429. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183430. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183431. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183432. png_ptr->row_info.width);
  183433. if(png_ptr->row_buf[0])
  183434. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183435. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183436. (int)(png_ptr->row_buf[0]));
  183437. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183438. png_ptr->rowbytes + 1);
  183439. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183440. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  183441. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  183442. {
  183443. /* Intrapixel differencing */
  183444. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  183445. }
  183446. #endif
  183447. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183448. png_do_read_transformations(png_ptr);
  183449. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183450. /* blow up interlaced rows to full size */
  183451. if (png_ptr->interlaced &&
  183452. (png_ptr->transformations & PNG_INTERLACE))
  183453. {
  183454. if (png_ptr->pass < 6)
  183455. /* old interface (pre-1.0.9):
  183456. png_do_read_interlace(&(png_ptr->row_info),
  183457. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183458. */
  183459. png_do_read_interlace(png_ptr);
  183460. if (dsp_row != NULL)
  183461. png_combine_row(png_ptr, dsp_row,
  183462. png_pass_dsp_mask[png_ptr->pass]);
  183463. if (row != NULL)
  183464. png_combine_row(png_ptr, row,
  183465. png_pass_mask[png_ptr->pass]);
  183466. }
  183467. else
  183468. #endif
  183469. {
  183470. if (row != NULL)
  183471. png_combine_row(png_ptr, row, 0xff);
  183472. if (dsp_row != NULL)
  183473. png_combine_row(png_ptr, dsp_row, 0xff);
  183474. }
  183475. png_read_finish_row(png_ptr);
  183476. if (png_ptr->read_row_fn != NULL)
  183477. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  183478. }
  183479. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183480. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183481. /* Read one or more rows of image data. If the image is interlaced,
  183482. * and png_set_interlace_handling() has been called, the rows need to
  183483. * contain the contents of the rows from the previous pass. If the
  183484. * image has alpha or transparency, and png_handle_alpha()[*] has been
  183485. * called, the rows contents must be initialized to the contents of the
  183486. * screen.
  183487. *
  183488. * "row" holds the actual image, and pixels are placed in it
  183489. * as they arrive. If the image is displayed after each pass, it will
  183490. * appear to "sparkle" in. "display_row" can be used to display a
  183491. * "chunky" progressive image, with finer detail added as it becomes
  183492. * available. If you do not want this "chunky" display, you may pass
  183493. * NULL for display_row. If you do not want the sparkle display, and
  183494. * you have not called png_handle_alpha(), you may pass NULL for rows.
  183495. * If you have called png_handle_alpha(), and the image has either an
  183496. * alpha channel or a transparency chunk, you must provide a buffer for
  183497. * rows. In this case, you do not have to provide a display_row buffer
  183498. * also, but you may. If the image is not interlaced, or if you have
  183499. * not called png_set_interlace_handling(), the display_row buffer will
  183500. * be ignored, so pass NULL to it.
  183501. *
  183502. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183503. */
  183504. void PNGAPI
  183505. png_read_rows(png_structp png_ptr, png_bytepp row,
  183506. png_bytepp display_row, png_uint_32 num_rows)
  183507. {
  183508. png_uint_32 i;
  183509. png_bytepp rp;
  183510. png_bytepp dp;
  183511. png_debug(1, "in png_read_rows\n");
  183512. if(png_ptr == NULL) return;
  183513. rp = row;
  183514. dp = display_row;
  183515. if (rp != NULL && dp != NULL)
  183516. for (i = 0; i < num_rows; i++)
  183517. {
  183518. png_bytep rptr = *rp++;
  183519. png_bytep dptr = *dp++;
  183520. png_read_row(png_ptr, rptr, dptr);
  183521. }
  183522. else if(rp != NULL)
  183523. for (i = 0; i < num_rows; i++)
  183524. {
  183525. png_bytep rptr = *rp;
  183526. png_read_row(png_ptr, rptr, png_bytep_NULL);
  183527. rp++;
  183528. }
  183529. else if(dp != NULL)
  183530. for (i = 0; i < num_rows; i++)
  183531. {
  183532. png_bytep dptr = *dp;
  183533. png_read_row(png_ptr, png_bytep_NULL, dptr);
  183534. dp++;
  183535. }
  183536. }
  183537. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183538. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183539. /* Read the entire image. If the image has an alpha channel or a tRNS
  183540. * chunk, and you have called png_handle_alpha()[*], you will need to
  183541. * initialize the image to the current image that PNG will be overlaying.
  183542. * We set the num_rows again here, in case it was incorrectly set in
  183543. * png_read_start_row() by a call to png_read_update_info() or
  183544. * png_start_read_image() if png_set_interlace_handling() wasn't called
  183545. * prior to either of these functions like it should have been. You can
  183546. * only call this function once. If you desire to have an image for
  183547. * each pass of a interlaced image, use png_read_rows() instead.
  183548. *
  183549. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183550. */
  183551. void PNGAPI
  183552. png_read_image(png_structp png_ptr, png_bytepp image)
  183553. {
  183554. png_uint_32 i,image_height;
  183555. int pass, j;
  183556. png_bytepp rp;
  183557. png_debug(1, "in png_read_image\n");
  183558. if(png_ptr == NULL) return;
  183559. #ifdef PNG_READ_INTERLACING_SUPPORTED
  183560. pass = png_set_interlace_handling(png_ptr);
  183561. #else
  183562. if (png_ptr->interlaced)
  183563. png_error(png_ptr,
  183564. "Cannot read interlaced image -- interlace handler disabled.");
  183565. pass = 1;
  183566. #endif
  183567. image_height=png_ptr->height;
  183568. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  183569. for (j = 0; j < pass; j++)
  183570. {
  183571. rp = image;
  183572. for (i = 0; i < image_height; i++)
  183573. {
  183574. png_read_row(png_ptr, *rp, png_bytep_NULL);
  183575. rp++;
  183576. }
  183577. }
  183578. }
  183579. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183580. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183581. /* Read the end of the PNG file. Will not read past the end of the
  183582. * file, will verify the end is accurate, and will read any comments
  183583. * or time information at the end of the file, if info is not NULL.
  183584. */
  183585. void PNGAPI
  183586. png_read_end(png_structp png_ptr, png_infop info_ptr)
  183587. {
  183588. png_byte chunk_length[4];
  183589. png_uint_32 length;
  183590. png_debug(1, "in png_read_end\n");
  183591. if(png_ptr == NULL) return;
  183592. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  183593. do
  183594. {
  183595. #ifdef PNG_USE_LOCAL_ARRAYS
  183596. PNG_CONST PNG_IHDR;
  183597. PNG_CONST PNG_IDAT;
  183598. PNG_CONST PNG_IEND;
  183599. PNG_CONST PNG_PLTE;
  183600. #if defined(PNG_READ_bKGD_SUPPORTED)
  183601. PNG_CONST PNG_bKGD;
  183602. #endif
  183603. #if defined(PNG_READ_cHRM_SUPPORTED)
  183604. PNG_CONST PNG_cHRM;
  183605. #endif
  183606. #if defined(PNG_READ_gAMA_SUPPORTED)
  183607. PNG_CONST PNG_gAMA;
  183608. #endif
  183609. #if defined(PNG_READ_hIST_SUPPORTED)
  183610. PNG_CONST PNG_hIST;
  183611. #endif
  183612. #if defined(PNG_READ_iCCP_SUPPORTED)
  183613. PNG_CONST PNG_iCCP;
  183614. #endif
  183615. #if defined(PNG_READ_iTXt_SUPPORTED)
  183616. PNG_CONST PNG_iTXt;
  183617. #endif
  183618. #if defined(PNG_READ_oFFs_SUPPORTED)
  183619. PNG_CONST PNG_oFFs;
  183620. #endif
  183621. #if defined(PNG_READ_pCAL_SUPPORTED)
  183622. PNG_CONST PNG_pCAL;
  183623. #endif
  183624. #if defined(PNG_READ_pHYs_SUPPORTED)
  183625. PNG_CONST PNG_pHYs;
  183626. #endif
  183627. #if defined(PNG_READ_sBIT_SUPPORTED)
  183628. PNG_CONST PNG_sBIT;
  183629. #endif
  183630. #if defined(PNG_READ_sCAL_SUPPORTED)
  183631. PNG_CONST PNG_sCAL;
  183632. #endif
  183633. #if defined(PNG_READ_sPLT_SUPPORTED)
  183634. PNG_CONST PNG_sPLT;
  183635. #endif
  183636. #if defined(PNG_READ_sRGB_SUPPORTED)
  183637. PNG_CONST PNG_sRGB;
  183638. #endif
  183639. #if defined(PNG_READ_tEXt_SUPPORTED)
  183640. PNG_CONST PNG_tEXt;
  183641. #endif
  183642. #if defined(PNG_READ_tIME_SUPPORTED)
  183643. PNG_CONST PNG_tIME;
  183644. #endif
  183645. #if defined(PNG_READ_tRNS_SUPPORTED)
  183646. PNG_CONST PNG_tRNS;
  183647. #endif
  183648. #if defined(PNG_READ_zTXt_SUPPORTED)
  183649. PNG_CONST PNG_zTXt;
  183650. #endif
  183651. #endif /* PNG_USE_LOCAL_ARRAYS */
  183652. png_read_data(png_ptr, chunk_length, 4);
  183653. length = png_get_uint_31(png_ptr,chunk_length);
  183654. png_reset_crc(png_ptr);
  183655. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183656. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  183657. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183658. png_handle_IHDR(png_ptr, info_ptr, length);
  183659. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183660. png_handle_IEND(png_ptr, info_ptr, length);
  183661. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183662. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183663. {
  183664. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183665. {
  183666. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183667. png_error(png_ptr, "Too many IDAT's found");
  183668. }
  183669. png_handle_unknown(png_ptr, info_ptr, length);
  183670. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183671. png_ptr->mode |= PNG_HAVE_PLTE;
  183672. }
  183673. #endif
  183674. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183675. {
  183676. /* Zero length IDATs are legal after the last IDAT has been
  183677. * read, but not after other chunks have been read.
  183678. */
  183679. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183680. png_error(png_ptr, "Too many IDAT's found");
  183681. png_crc_finish(png_ptr, length);
  183682. }
  183683. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183684. png_handle_PLTE(png_ptr, info_ptr, length);
  183685. #if defined(PNG_READ_bKGD_SUPPORTED)
  183686. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183687. png_handle_bKGD(png_ptr, info_ptr, length);
  183688. #endif
  183689. #if defined(PNG_READ_cHRM_SUPPORTED)
  183690. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183691. png_handle_cHRM(png_ptr, info_ptr, length);
  183692. #endif
  183693. #if defined(PNG_READ_gAMA_SUPPORTED)
  183694. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183695. png_handle_gAMA(png_ptr, info_ptr, length);
  183696. #endif
  183697. #if defined(PNG_READ_hIST_SUPPORTED)
  183698. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183699. png_handle_hIST(png_ptr, info_ptr, length);
  183700. #endif
  183701. #if defined(PNG_READ_oFFs_SUPPORTED)
  183702. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183703. png_handle_oFFs(png_ptr, info_ptr, length);
  183704. #endif
  183705. #if defined(PNG_READ_pCAL_SUPPORTED)
  183706. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183707. png_handle_pCAL(png_ptr, info_ptr, length);
  183708. #endif
  183709. #if defined(PNG_READ_sCAL_SUPPORTED)
  183710. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183711. png_handle_sCAL(png_ptr, info_ptr, length);
  183712. #endif
  183713. #if defined(PNG_READ_pHYs_SUPPORTED)
  183714. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183715. png_handle_pHYs(png_ptr, info_ptr, length);
  183716. #endif
  183717. #if defined(PNG_READ_sBIT_SUPPORTED)
  183718. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183719. png_handle_sBIT(png_ptr, info_ptr, length);
  183720. #endif
  183721. #if defined(PNG_READ_sRGB_SUPPORTED)
  183722. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183723. png_handle_sRGB(png_ptr, info_ptr, length);
  183724. #endif
  183725. #if defined(PNG_READ_iCCP_SUPPORTED)
  183726. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183727. png_handle_iCCP(png_ptr, info_ptr, length);
  183728. #endif
  183729. #if defined(PNG_READ_sPLT_SUPPORTED)
  183730. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183731. png_handle_sPLT(png_ptr, info_ptr, length);
  183732. #endif
  183733. #if defined(PNG_READ_tEXt_SUPPORTED)
  183734. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183735. png_handle_tEXt(png_ptr, info_ptr, length);
  183736. #endif
  183737. #if defined(PNG_READ_tIME_SUPPORTED)
  183738. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183739. png_handle_tIME(png_ptr, info_ptr, length);
  183740. #endif
  183741. #if defined(PNG_READ_tRNS_SUPPORTED)
  183742. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183743. png_handle_tRNS(png_ptr, info_ptr, length);
  183744. #endif
  183745. #if defined(PNG_READ_zTXt_SUPPORTED)
  183746. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183747. png_handle_zTXt(png_ptr, info_ptr, length);
  183748. #endif
  183749. #if defined(PNG_READ_iTXt_SUPPORTED)
  183750. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183751. png_handle_iTXt(png_ptr, info_ptr, length);
  183752. #endif
  183753. else
  183754. png_handle_unknown(png_ptr, info_ptr, length);
  183755. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  183756. }
  183757. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183758. /* free all memory used by the read */
  183759. void PNGAPI
  183760. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  183761. png_infopp end_info_ptr_ptr)
  183762. {
  183763. png_structp png_ptr = NULL;
  183764. png_infop info_ptr = NULL, end_info_ptr = NULL;
  183765. #ifdef PNG_USER_MEM_SUPPORTED
  183766. png_free_ptr free_fn;
  183767. png_voidp mem_ptr;
  183768. #endif
  183769. png_debug(1, "in png_destroy_read_struct\n");
  183770. if (png_ptr_ptr != NULL)
  183771. png_ptr = *png_ptr_ptr;
  183772. if (info_ptr_ptr != NULL)
  183773. info_ptr = *info_ptr_ptr;
  183774. if (end_info_ptr_ptr != NULL)
  183775. end_info_ptr = *end_info_ptr_ptr;
  183776. #ifdef PNG_USER_MEM_SUPPORTED
  183777. free_fn = png_ptr->free_fn;
  183778. mem_ptr = png_ptr->mem_ptr;
  183779. #endif
  183780. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  183781. if (info_ptr != NULL)
  183782. {
  183783. #if defined(PNG_TEXT_SUPPORTED)
  183784. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  183785. #endif
  183786. #ifdef PNG_USER_MEM_SUPPORTED
  183787. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  183788. (png_voidp)mem_ptr);
  183789. #else
  183790. png_destroy_struct((png_voidp)info_ptr);
  183791. #endif
  183792. *info_ptr_ptr = NULL;
  183793. }
  183794. if (end_info_ptr != NULL)
  183795. {
  183796. #if defined(PNG_READ_TEXT_SUPPORTED)
  183797. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  183798. #endif
  183799. #ifdef PNG_USER_MEM_SUPPORTED
  183800. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  183801. (png_voidp)mem_ptr);
  183802. #else
  183803. png_destroy_struct((png_voidp)end_info_ptr);
  183804. #endif
  183805. *end_info_ptr_ptr = NULL;
  183806. }
  183807. if (png_ptr != NULL)
  183808. {
  183809. #ifdef PNG_USER_MEM_SUPPORTED
  183810. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  183811. (png_voidp)mem_ptr);
  183812. #else
  183813. png_destroy_struct((png_voidp)png_ptr);
  183814. #endif
  183815. *png_ptr_ptr = NULL;
  183816. }
  183817. }
  183818. /* free all memory used by the read (old method) */
  183819. void /* PRIVATE */
  183820. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  183821. {
  183822. #ifdef PNG_SETJMP_SUPPORTED
  183823. jmp_buf tmp_jmp;
  183824. #endif
  183825. png_error_ptr error_fn;
  183826. png_error_ptr warning_fn;
  183827. png_voidp error_ptr;
  183828. #ifdef PNG_USER_MEM_SUPPORTED
  183829. png_free_ptr free_fn;
  183830. #endif
  183831. png_debug(1, "in png_read_destroy\n");
  183832. if (info_ptr != NULL)
  183833. png_info_destroy(png_ptr, info_ptr);
  183834. if (end_info_ptr != NULL)
  183835. png_info_destroy(png_ptr, end_info_ptr);
  183836. png_free(png_ptr, png_ptr->zbuf);
  183837. png_free(png_ptr, png_ptr->big_row_buf);
  183838. png_free(png_ptr, png_ptr->prev_row);
  183839. #if defined(PNG_READ_DITHER_SUPPORTED)
  183840. png_free(png_ptr, png_ptr->palette_lookup);
  183841. png_free(png_ptr, png_ptr->dither_index);
  183842. #endif
  183843. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183844. png_free(png_ptr, png_ptr->gamma_table);
  183845. #endif
  183846. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183847. png_free(png_ptr, png_ptr->gamma_from_1);
  183848. png_free(png_ptr, png_ptr->gamma_to_1);
  183849. #endif
  183850. #ifdef PNG_FREE_ME_SUPPORTED
  183851. if (png_ptr->free_me & PNG_FREE_PLTE)
  183852. png_zfree(png_ptr, png_ptr->palette);
  183853. png_ptr->free_me &= ~PNG_FREE_PLTE;
  183854. #else
  183855. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  183856. png_zfree(png_ptr, png_ptr->palette);
  183857. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  183858. #endif
  183859. #if defined(PNG_tRNS_SUPPORTED) || \
  183860. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183861. #ifdef PNG_FREE_ME_SUPPORTED
  183862. if (png_ptr->free_me & PNG_FREE_TRNS)
  183863. png_free(png_ptr, png_ptr->trans);
  183864. png_ptr->free_me &= ~PNG_FREE_TRNS;
  183865. #else
  183866. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  183867. png_free(png_ptr, png_ptr->trans);
  183868. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  183869. #endif
  183870. #endif
  183871. #if defined(PNG_READ_hIST_SUPPORTED)
  183872. #ifdef PNG_FREE_ME_SUPPORTED
  183873. if (png_ptr->free_me & PNG_FREE_HIST)
  183874. png_free(png_ptr, png_ptr->hist);
  183875. png_ptr->free_me &= ~PNG_FREE_HIST;
  183876. #else
  183877. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  183878. png_free(png_ptr, png_ptr->hist);
  183879. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  183880. #endif
  183881. #endif
  183882. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183883. if (png_ptr->gamma_16_table != NULL)
  183884. {
  183885. int i;
  183886. int istop = (1 << (8 - png_ptr->gamma_shift));
  183887. for (i = 0; i < istop; i++)
  183888. {
  183889. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  183890. }
  183891. png_free(png_ptr, png_ptr->gamma_16_table);
  183892. }
  183893. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183894. if (png_ptr->gamma_16_from_1 != NULL)
  183895. {
  183896. int i;
  183897. int istop = (1 << (8 - png_ptr->gamma_shift));
  183898. for (i = 0; i < istop; i++)
  183899. {
  183900. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  183901. }
  183902. png_free(png_ptr, png_ptr->gamma_16_from_1);
  183903. }
  183904. if (png_ptr->gamma_16_to_1 != NULL)
  183905. {
  183906. int i;
  183907. int istop = (1 << (8 - png_ptr->gamma_shift));
  183908. for (i = 0; i < istop; i++)
  183909. {
  183910. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  183911. }
  183912. png_free(png_ptr, png_ptr->gamma_16_to_1);
  183913. }
  183914. #endif
  183915. #endif
  183916. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183917. png_free(png_ptr, png_ptr->time_buffer);
  183918. #endif
  183919. inflateEnd(&png_ptr->zstream);
  183920. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183921. png_free(png_ptr, png_ptr->save_buffer);
  183922. #endif
  183923. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183924. #ifdef PNG_TEXT_SUPPORTED
  183925. png_free(png_ptr, png_ptr->current_text);
  183926. #endif /* PNG_TEXT_SUPPORTED */
  183927. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183928. /* Save the important info out of the png_struct, in case it is
  183929. * being used again.
  183930. */
  183931. #ifdef PNG_SETJMP_SUPPORTED
  183932. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183933. #endif
  183934. error_fn = png_ptr->error_fn;
  183935. warning_fn = png_ptr->warning_fn;
  183936. error_ptr = png_ptr->error_ptr;
  183937. #ifdef PNG_USER_MEM_SUPPORTED
  183938. free_fn = png_ptr->free_fn;
  183939. #endif
  183940. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183941. png_ptr->error_fn = error_fn;
  183942. png_ptr->warning_fn = warning_fn;
  183943. png_ptr->error_ptr = error_ptr;
  183944. #ifdef PNG_USER_MEM_SUPPORTED
  183945. png_ptr->free_fn = free_fn;
  183946. #endif
  183947. #ifdef PNG_SETJMP_SUPPORTED
  183948. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183949. #endif
  183950. }
  183951. void PNGAPI
  183952. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  183953. {
  183954. if(png_ptr == NULL) return;
  183955. png_ptr->read_row_fn = read_row_fn;
  183956. }
  183957. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183958. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183959. void PNGAPI
  183960. png_read_png(png_structp png_ptr, png_infop info_ptr,
  183961. int transforms,
  183962. voidp params)
  183963. {
  183964. int row;
  183965. if(png_ptr == NULL) return;
  183966. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183967. /* invert the alpha channel from opacity to transparency
  183968. */
  183969. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  183970. png_set_invert_alpha(png_ptr);
  183971. #endif
  183972. /* png_read_info() gives us all of the information from the
  183973. * PNG file before the first IDAT (image data chunk).
  183974. */
  183975. png_read_info(png_ptr, info_ptr);
  183976. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  183977. png_error(png_ptr,"Image is too high to process with png_read_png()");
  183978. /* -------------- image transformations start here ------------------- */
  183979. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183980. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  183981. */
  183982. if (transforms & PNG_TRANSFORM_STRIP_16)
  183983. png_set_strip_16(png_ptr);
  183984. #endif
  183985. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183986. /* Strip alpha bytes from the input data without combining with
  183987. * the background (not recommended).
  183988. */
  183989. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  183990. png_set_strip_alpha(png_ptr);
  183991. #endif
  183992. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  183993. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  183994. * byte into separate bytes (useful for paletted and grayscale images).
  183995. */
  183996. if (transforms & PNG_TRANSFORM_PACKING)
  183997. png_set_packing(png_ptr);
  183998. #endif
  183999. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  184000. /* Change the order of packed pixels to least significant bit first
  184001. * (not useful if you are using png_set_packing).
  184002. */
  184003. if (transforms & PNG_TRANSFORM_PACKSWAP)
  184004. png_set_packswap(png_ptr);
  184005. #endif
  184006. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184007. /* Expand paletted colors into true RGB triplets
  184008. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  184009. * Expand paletted or RGB images with transparency to full alpha
  184010. * channels so the data will be available as RGBA quartets.
  184011. */
  184012. if (transforms & PNG_TRANSFORM_EXPAND)
  184013. if ((png_ptr->bit_depth < 8) ||
  184014. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  184015. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  184016. png_set_expand(png_ptr);
  184017. #endif
  184018. /* We don't handle background color or gamma transformation or dithering.
  184019. */
  184020. #if defined(PNG_READ_INVERT_SUPPORTED)
  184021. /* invert monochrome files to have 0 as white and 1 as black
  184022. */
  184023. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  184024. png_set_invert_mono(png_ptr);
  184025. #endif
  184026. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184027. /* If you want to shift the pixel values from the range [0,255] or
  184028. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  184029. * colors were originally in:
  184030. */
  184031. if ((transforms & PNG_TRANSFORM_SHIFT)
  184032. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  184033. {
  184034. png_color_8p sig_bit;
  184035. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  184036. png_set_shift(png_ptr, sig_bit);
  184037. }
  184038. #endif
  184039. #if defined(PNG_READ_BGR_SUPPORTED)
  184040. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  184041. */
  184042. if (transforms & PNG_TRANSFORM_BGR)
  184043. png_set_bgr(png_ptr);
  184044. #endif
  184045. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184046. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  184047. */
  184048. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  184049. png_set_swap_alpha(png_ptr);
  184050. #endif
  184051. #if defined(PNG_READ_SWAP_SUPPORTED)
  184052. /* swap bytes of 16 bit files to least significant byte first
  184053. */
  184054. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  184055. png_set_swap(png_ptr);
  184056. #endif
  184057. /* We don't handle adding filler bytes */
  184058. /* Optional call to gamma correct and add the background to the palette
  184059. * and update info structure. REQUIRED if you are expecting libpng to
  184060. * update the palette for you (i.e., you selected such a transform above).
  184061. */
  184062. png_read_update_info(png_ptr, info_ptr);
  184063. /* -------------- image transformations end here ------------------- */
  184064. #ifdef PNG_FREE_ME_SUPPORTED
  184065. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  184066. #endif
  184067. if(info_ptr->row_pointers == NULL)
  184068. {
  184069. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  184070. info_ptr->height * png_sizeof(png_bytep));
  184071. #ifdef PNG_FREE_ME_SUPPORTED
  184072. info_ptr->free_me |= PNG_FREE_ROWS;
  184073. #endif
  184074. for (row = 0; row < (int)info_ptr->height; row++)
  184075. {
  184076. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  184077. png_get_rowbytes(png_ptr, info_ptr));
  184078. }
  184079. }
  184080. png_read_image(png_ptr, info_ptr->row_pointers);
  184081. info_ptr->valid |= PNG_INFO_IDAT;
  184082. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  184083. png_read_end(png_ptr, info_ptr);
  184084. transforms = transforms; /* quiet compiler warnings */
  184085. params = params;
  184086. }
  184087. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  184088. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  184089. #endif /* PNG_READ_SUPPORTED */
  184090. /********* End of inlined file: pngread.c *********/
  184091. /********* Start of inlined file: pngpread.c *********/
  184092. /* pngpread.c - read a png file in push mode
  184093. *
  184094. * Last changed in libpng 1.2.21 October 4, 2007
  184095. * For conditions of distribution and use, see copyright notice in png.h
  184096. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184097. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184098. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184099. */
  184100. #define PNG_INTERNAL
  184101. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184102. /* push model modes */
  184103. #define PNG_READ_SIG_MODE 0
  184104. #define PNG_READ_CHUNK_MODE 1
  184105. #define PNG_READ_IDAT_MODE 2
  184106. #define PNG_SKIP_MODE 3
  184107. #define PNG_READ_tEXt_MODE 4
  184108. #define PNG_READ_zTXt_MODE 5
  184109. #define PNG_READ_DONE_MODE 6
  184110. #define PNG_READ_iTXt_MODE 7
  184111. #define PNG_ERROR_MODE 8
  184112. void PNGAPI
  184113. png_process_data(png_structp png_ptr, png_infop info_ptr,
  184114. png_bytep buffer, png_size_t buffer_size)
  184115. {
  184116. if(png_ptr == NULL) return;
  184117. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  184118. while (png_ptr->buffer_size)
  184119. {
  184120. png_process_some_data(png_ptr, info_ptr);
  184121. }
  184122. }
  184123. /* What we do with the incoming data depends on what we were previously
  184124. * doing before we ran out of data...
  184125. */
  184126. void /* PRIVATE */
  184127. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  184128. {
  184129. if(png_ptr == NULL) return;
  184130. switch (png_ptr->process_mode)
  184131. {
  184132. case PNG_READ_SIG_MODE:
  184133. {
  184134. png_push_read_sig(png_ptr, info_ptr);
  184135. break;
  184136. }
  184137. case PNG_READ_CHUNK_MODE:
  184138. {
  184139. png_push_read_chunk(png_ptr, info_ptr);
  184140. break;
  184141. }
  184142. case PNG_READ_IDAT_MODE:
  184143. {
  184144. png_push_read_IDAT(png_ptr);
  184145. break;
  184146. }
  184147. #if defined(PNG_READ_tEXt_SUPPORTED)
  184148. case PNG_READ_tEXt_MODE:
  184149. {
  184150. png_push_read_tEXt(png_ptr, info_ptr);
  184151. break;
  184152. }
  184153. #endif
  184154. #if defined(PNG_READ_zTXt_SUPPORTED)
  184155. case PNG_READ_zTXt_MODE:
  184156. {
  184157. png_push_read_zTXt(png_ptr, info_ptr);
  184158. break;
  184159. }
  184160. #endif
  184161. #if defined(PNG_READ_iTXt_SUPPORTED)
  184162. case PNG_READ_iTXt_MODE:
  184163. {
  184164. png_push_read_iTXt(png_ptr, info_ptr);
  184165. break;
  184166. }
  184167. #endif
  184168. case PNG_SKIP_MODE:
  184169. {
  184170. png_push_crc_finish(png_ptr);
  184171. break;
  184172. }
  184173. default:
  184174. {
  184175. png_ptr->buffer_size = 0;
  184176. break;
  184177. }
  184178. }
  184179. }
  184180. /* Read any remaining signature bytes from the stream and compare them with
  184181. * the correct PNG signature. It is possible that this routine is called
  184182. * with bytes already read from the signature, either because they have been
  184183. * checked by the calling application, or because of multiple calls to this
  184184. * routine.
  184185. */
  184186. void /* PRIVATE */
  184187. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  184188. {
  184189. png_size_t num_checked = png_ptr->sig_bytes,
  184190. num_to_check = 8 - num_checked;
  184191. if (png_ptr->buffer_size < num_to_check)
  184192. {
  184193. num_to_check = png_ptr->buffer_size;
  184194. }
  184195. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  184196. num_to_check);
  184197. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  184198. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184199. {
  184200. if (num_checked < 4 &&
  184201. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184202. png_error(png_ptr, "Not a PNG file");
  184203. else
  184204. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184205. }
  184206. else
  184207. {
  184208. if (png_ptr->sig_bytes >= 8)
  184209. {
  184210. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184211. }
  184212. }
  184213. }
  184214. void /* PRIVATE */
  184215. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  184216. {
  184217. #ifdef PNG_USE_LOCAL_ARRAYS
  184218. PNG_CONST PNG_IHDR;
  184219. PNG_CONST PNG_IDAT;
  184220. PNG_CONST PNG_IEND;
  184221. PNG_CONST PNG_PLTE;
  184222. #if defined(PNG_READ_bKGD_SUPPORTED)
  184223. PNG_CONST PNG_bKGD;
  184224. #endif
  184225. #if defined(PNG_READ_cHRM_SUPPORTED)
  184226. PNG_CONST PNG_cHRM;
  184227. #endif
  184228. #if defined(PNG_READ_gAMA_SUPPORTED)
  184229. PNG_CONST PNG_gAMA;
  184230. #endif
  184231. #if defined(PNG_READ_hIST_SUPPORTED)
  184232. PNG_CONST PNG_hIST;
  184233. #endif
  184234. #if defined(PNG_READ_iCCP_SUPPORTED)
  184235. PNG_CONST PNG_iCCP;
  184236. #endif
  184237. #if defined(PNG_READ_iTXt_SUPPORTED)
  184238. PNG_CONST PNG_iTXt;
  184239. #endif
  184240. #if defined(PNG_READ_oFFs_SUPPORTED)
  184241. PNG_CONST PNG_oFFs;
  184242. #endif
  184243. #if defined(PNG_READ_pCAL_SUPPORTED)
  184244. PNG_CONST PNG_pCAL;
  184245. #endif
  184246. #if defined(PNG_READ_pHYs_SUPPORTED)
  184247. PNG_CONST PNG_pHYs;
  184248. #endif
  184249. #if defined(PNG_READ_sBIT_SUPPORTED)
  184250. PNG_CONST PNG_sBIT;
  184251. #endif
  184252. #if defined(PNG_READ_sCAL_SUPPORTED)
  184253. PNG_CONST PNG_sCAL;
  184254. #endif
  184255. #if defined(PNG_READ_sRGB_SUPPORTED)
  184256. PNG_CONST PNG_sRGB;
  184257. #endif
  184258. #if defined(PNG_READ_sPLT_SUPPORTED)
  184259. PNG_CONST PNG_sPLT;
  184260. #endif
  184261. #if defined(PNG_READ_tEXt_SUPPORTED)
  184262. PNG_CONST PNG_tEXt;
  184263. #endif
  184264. #if defined(PNG_READ_tIME_SUPPORTED)
  184265. PNG_CONST PNG_tIME;
  184266. #endif
  184267. #if defined(PNG_READ_tRNS_SUPPORTED)
  184268. PNG_CONST PNG_tRNS;
  184269. #endif
  184270. #if defined(PNG_READ_zTXt_SUPPORTED)
  184271. PNG_CONST PNG_zTXt;
  184272. #endif
  184273. #endif /* PNG_USE_LOCAL_ARRAYS */
  184274. /* First we make sure we have enough data for the 4 byte chunk name
  184275. * and the 4 byte chunk length before proceeding with decoding the
  184276. * chunk data. To fully decode each of these chunks, we also make
  184277. * sure we have enough data in the buffer for the 4 byte CRC at the
  184278. * end of every chunk (except IDAT, which is handled separately).
  184279. */
  184280. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184281. {
  184282. png_byte chunk_length[4];
  184283. if (png_ptr->buffer_size < 8)
  184284. {
  184285. png_push_save_buffer(png_ptr);
  184286. return;
  184287. }
  184288. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184289. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184290. png_reset_crc(png_ptr);
  184291. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184292. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184293. }
  184294. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184295. if(png_ptr->mode & PNG_AFTER_IDAT)
  184296. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  184297. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184298. {
  184299. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184300. {
  184301. png_push_save_buffer(png_ptr);
  184302. return;
  184303. }
  184304. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  184305. }
  184306. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184307. {
  184308. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184309. {
  184310. png_push_save_buffer(png_ptr);
  184311. return;
  184312. }
  184313. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  184314. png_ptr->process_mode = PNG_READ_DONE_MODE;
  184315. png_push_have_end(png_ptr, info_ptr);
  184316. }
  184317. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184318. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184319. {
  184320. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184321. {
  184322. png_push_save_buffer(png_ptr);
  184323. return;
  184324. }
  184325. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184326. png_ptr->mode |= PNG_HAVE_IDAT;
  184327. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184328. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184329. png_ptr->mode |= PNG_HAVE_PLTE;
  184330. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184331. {
  184332. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184333. png_error(png_ptr, "Missing IHDR before IDAT");
  184334. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184335. !(png_ptr->mode & PNG_HAVE_PLTE))
  184336. png_error(png_ptr, "Missing PLTE before IDAT");
  184337. }
  184338. }
  184339. #endif
  184340. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184341. {
  184342. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184343. {
  184344. png_push_save_buffer(png_ptr);
  184345. return;
  184346. }
  184347. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  184348. }
  184349. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184350. {
  184351. /* If we reach an IDAT chunk, this means we have read all of the
  184352. * header chunks, and we can start reading the image (or if this
  184353. * is called after the image has been read - we have an error).
  184354. */
  184355. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184356. png_error(png_ptr, "Missing IHDR before IDAT");
  184357. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184358. !(png_ptr->mode & PNG_HAVE_PLTE))
  184359. png_error(png_ptr, "Missing PLTE before IDAT");
  184360. if (png_ptr->mode & PNG_HAVE_IDAT)
  184361. {
  184362. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184363. if (png_ptr->push_length == 0)
  184364. return;
  184365. if (png_ptr->mode & PNG_AFTER_IDAT)
  184366. png_error(png_ptr, "Too many IDAT's found");
  184367. }
  184368. png_ptr->idat_size = png_ptr->push_length;
  184369. png_ptr->mode |= PNG_HAVE_IDAT;
  184370. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  184371. png_push_have_info(png_ptr, info_ptr);
  184372. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184373. png_ptr->zstream.next_out = png_ptr->row_buf;
  184374. return;
  184375. }
  184376. #if defined(PNG_READ_gAMA_SUPPORTED)
  184377. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184378. {
  184379. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184380. {
  184381. png_push_save_buffer(png_ptr);
  184382. return;
  184383. }
  184384. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  184385. }
  184386. #endif
  184387. #if defined(PNG_READ_sBIT_SUPPORTED)
  184388. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184389. {
  184390. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184391. {
  184392. png_push_save_buffer(png_ptr);
  184393. return;
  184394. }
  184395. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  184396. }
  184397. #endif
  184398. #if defined(PNG_READ_cHRM_SUPPORTED)
  184399. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184400. {
  184401. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184402. {
  184403. png_push_save_buffer(png_ptr);
  184404. return;
  184405. }
  184406. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  184407. }
  184408. #endif
  184409. #if defined(PNG_READ_sRGB_SUPPORTED)
  184410. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  184411. {
  184412. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184413. {
  184414. png_push_save_buffer(png_ptr);
  184415. return;
  184416. }
  184417. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  184418. }
  184419. #endif
  184420. #if defined(PNG_READ_iCCP_SUPPORTED)
  184421. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  184422. {
  184423. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184424. {
  184425. png_push_save_buffer(png_ptr);
  184426. return;
  184427. }
  184428. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  184429. }
  184430. #endif
  184431. #if defined(PNG_READ_sPLT_SUPPORTED)
  184432. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  184433. {
  184434. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184435. {
  184436. png_push_save_buffer(png_ptr);
  184437. return;
  184438. }
  184439. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  184440. }
  184441. #endif
  184442. #if defined(PNG_READ_tRNS_SUPPORTED)
  184443. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  184444. {
  184445. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184446. {
  184447. png_push_save_buffer(png_ptr);
  184448. return;
  184449. }
  184450. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  184451. }
  184452. #endif
  184453. #if defined(PNG_READ_bKGD_SUPPORTED)
  184454. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184455. {
  184456. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184457. {
  184458. png_push_save_buffer(png_ptr);
  184459. return;
  184460. }
  184461. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  184462. }
  184463. #endif
  184464. #if defined(PNG_READ_hIST_SUPPORTED)
  184465. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184466. {
  184467. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184468. {
  184469. png_push_save_buffer(png_ptr);
  184470. return;
  184471. }
  184472. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  184473. }
  184474. #endif
  184475. #if defined(PNG_READ_pHYs_SUPPORTED)
  184476. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184477. {
  184478. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184479. {
  184480. png_push_save_buffer(png_ptr);
  184481. return;
  184482. }
  184483. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  184484. }
  184485. #endif
  184486. #if defined(PNG_READ_oFFs_SUPPORTED)
  184487. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184488. {
  184489. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184490. {
  184491. png_push_save_buffer(png_ptr);
  184492. return;
  184493. }
  184494. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  184495. }
  184496. #endif
  184497. #if defined(PNG_READ_pCAL_SUPPORTED)
  184498. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184499. {
  184500. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184501. {
  184502. png_push_save_buffer(png_ptr);
  184503. return;
  184504. }
  184505. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  184506. }
  184507. #endif
  184508. #if defined(PNG_READ_sCAL_SUPPORTED)
  184509. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184510. {
  184511. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184512. {
  184513. png_push_save_buffer(png_ptr);
  184514. return;
  184515. }
  184516. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  184517. }
  184518. #endif
  184519. #if defined(PNG_READ_tIME_SUPPORTED)
  184520. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  184521. {
  184522. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184523. {
  184524. png_push_save_buffer(png_ptr);
  184525. return;
  184526. }
  184527. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  184528. }
  184529. #endif
  184530. #if defined(PNG_READ_tEXt_SUPPORTED)
  184531. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  184532. {
  184533. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184534. {
  184535. png_push_save_buffer(png_ptr);
  184536. return;
  184537. }
  184538. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  184539. }
  184540. #endif
  184541. #if defined(PNG_READ_zTXt_SUPPORTED)
  184542. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  184543. {
  184544. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184545. {
  184546. png_push_save_buffer(png_ptr);
  184547. return;
  184548. }
  184549. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  184550. }
  184551. #endif
  184552. #if defined(PNG_READ_iTXt_SUPPORTED)
  184553. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184554. {
  184555. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184556. {
  184557. png_push_save_buffer(png_ptr);
  184558. return;
  184559. }
  184560. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  184561. }
  184562. #endif
  184563. else
  184564. {
  184565. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184566. {
  184567. png_push_save_buffer(png_ptr);
  184568. return;
  184569. }
  184570. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184571. }
  184572. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184573. }
  184574. void /* PRIVATE */
  184575. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  184576. {
  184577. png_ptr->process_mode = PNG_SKIP_MODE;
  184578. png_ptr->skip_length = skip;
  184579. }
  184580. void /* PRIVATE */
  184581. png_push_crc_finish(png_structp png_ptr)
  184582. {
  184583. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  184584. {
  184585. png_size_t save_size;
  184586. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  184587. save_size = (png_size_t)png_ptr->skip_length;
  184588. else
  184589. save_size = png_ptr->save_buffer_size;
  184590. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184591. png_ptr->skip_length -= save_size;
  184592. png_ptr->buffer_size -= save_size;
  184593. png_ptr->save_buffer_size -= save_size;
  184594. png_ptr->save_buffer_ptr += save_size;
  184595. }
  184596. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  184597. {
  184598. png_size_t save_size;
  184599. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  184600. save_size = (png_size_t)png_ptr->skip_length;
  184601. else
  184602. save_size = png_ptr->current_buffer_size;
  184603. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184604. png_ptr->skip_length -= save_size;
  184605. png_ptr->buffer_size -= save_size;
  184606. png_ptr->current_buffer_size -= save_size;
  184607. png_ptr->current_buffer_ptr += save_size;
  184608. }
  184609. if (!png_ptr->skip_length)
  184610. {
  184611. if (png_ptr->buffer_size < 4)
  184612. {
  184613. png_push_save_buffer(png_ptr);
  184614. return;
  184615. }
  184616. png_crc_finish(png_ptr, 0);
  184617. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184618. }
  184619. }
  184620. void PNGAPI
  184621. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  184622. {
  184623. png_bytep ptr;
  184624. if(png_ptr == NULL) return;
  184625. ptr = buffer;
  184626. if (png_ptr->save_buffer_size)
  184627. {
  184628. png_size_t save_size;
  184629. if (length < png_ptr->save_buffer_size)
  184630. save_size = length;
  184631. else
  184632. save_size = png_ptr->save_buffer_size;
  184633. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  184634. length -= save_size;
  184635. ptr += save_size;
  184636. png_ptr->buffer_size -= save_size;
  184637. png_ptr->save_buffer_size -= save_size;
  184638. png_ptr->save_buffer_ptr += save_size;
  184639. }
  184640. if (length && png_ptr->current_buffer_size)
  184641. {
  184642. png_size_t save_size;
  184643. if (length < png_ptr->current_buffer_size)
  184644. save_size = length;
  184645. else
  184646. save_size = png_ptr->current_buffer_size;
  184647. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  184648. png_ptr->buffer_size -= save_size;
  184649. png_ptr->current_buffer_size -= save_size;
  184650. png_ptr->current_buffer_ptr += save_size;
  184651. }
  184652. }
  184653. void /* PRIVATE */
  184654. png_push_save_buffer(png_structp png_ptr)
  184655. {
  184656. if (png_ptr->save_buffer_size)
  184657. {
  184658. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  184659. {
  184660. png_size_t i,istop;
  184661. png_bytep sp;
  184662. png_bytep dp;
  184663. istop = png_ptr->save_buffer_size;
  184664. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  184665. i < istop; i++, sp++, dp++)
  184666. {
  184667. *dp = *sp;
  184668. }
  184669. }
  184670. }
  184671. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  184672. png_ptr->save_buffer_max)
  184673. {
  184674. png_size_t new_max;
  184675. png_bytep old_buffer;
  184676. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  184677. (png_ptr->current_buffer_size + 256))
  184678. {
  184679. png_error(png_ptr, "Potential overflow of save_buffer");
  184680. }
  184681. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  184682. old_buffer = png_ptr->save_buffer;
  184683. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  184684. (png_uint_32)new_max);
  184685. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  184686. png_free(png_ptr, old_buffer);
  184687. png_ptr->save_buffer_max = new_max;
  184688. }
  184689. if (png_ptr->current_buffer_size)
  184690. {
  184691. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  184692. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  184693. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  184694. png_ptr->current_buffer_size = 0;
  184695. }
  184696. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  184697. png_ptr->buffer_size = 0;
  184698. }
  184699. void /* PRIVATE */
  184700. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  184701. png_size_t buffer_length)
  184702. {
  184703. png_ptr->current_buffer = buffer;
  184704. png_ptr->current_buffer_size = buffer_length;
  184705. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  184706. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  184707. }
  184708. void /* PRIVATE */
  184709. png_push_read_IDAT(png_structp png_ptr)
  184710. {
  184711. #ifdef PNG_USE_LOCAL_ARRAYS
  184712. PNG_CONST PNG_IDAT;
  184713. #endif
  184714. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184715. {
  184716. png_byte chunk_length[4];
  184717. if (png_ptr->buffer_size < 8)
  184718. {
  184719. png_push_save_buffer(png_ptr);
  184720. return;
  184721. }
  184722. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184723. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184724. png_reset_crc(png_ptr);
  184725. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184726. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184727. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184728. {
  184729. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184730. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184731. png_error(png_ptr, "Not enough compressed data");
  184732. return;
  184733. }
  184734. png_ptr->idat_size = png_ptr->push_length;
  184735. }
  184736. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  184737. {
  184738. png_size_t save_size;
  184739. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  184740. {
  184741. save_size = (png_size_t)png_ptr->idat_size;
  184742. /* check for overflow */
  184743. if((png_uint_32)save_size != png_ptr->idat_size)
  184744. png_error(png_ptr, "save_size overflowed in pngpread");
  184745. }
  184746. else
  184747. save_size = png_ptr->save_buffer_size;
  184748. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184749. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184750. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184751. png_ptr->idat_size -= save_size;
  184752. png_ptr->buffer_size -= save_size;
  184753. png_ptr->save_buffer_size -= save_size;
  184754. png_ptr->save_buffer_ptr += save_size;
  184755. }
  184756. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  184757. {
  184758. png_size_t save_size;
  184759. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  184760. {
  184761. save_size = (png_size_t)png_ptr->idat_size;
  184762. /* check for overflow */
  184763. if((png_uint_32)save_size != png_ptr->idat_size)
  184764. png_error(png_ptr, "save_size overflowed in pngpread");
  184765. }
  184766. else
  184767. save_size = png_ptr->current_buffer_size;
  184768. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184769. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184770. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184771. png_ptr->idat_size -= save_size;
  184772. png_ptr->buffer_size -= save_size;
  184773. png_ptr->current_buffer_size -= save_size;
  184774. png_ptr->current_buffer_ptr += save_size;
  184775. }
  184776. if (!png_ptr->idat_size)
  184777. {
  184778. if (png_ptr->buffer_size < 4)
  184779. {
  184780. png_push_save_buffer(png_ptr);
  184781. return;
  184782. }
  184783. png_crc_finish(png_ptr, 0);
  184784. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184785. png_ptr->mode |= PNG_AFTER_IDAT;
  184786. }
  184787. }
  184788. void /* PRIVATE */
  184789. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  184790. png_size_t buffer_length)
  184791. {
  184792. int ret;
  184793. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  184794. png_error(png_ptr, "Extra compression data");
  184795. png_ptr->zstream.next_in = buffer;
  184796. png_ptr->zstream.avail_in = (uInt)buffer_length;
  184797. for(;;)
  184798. {
  184799. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184800. if (ret != Z_OK)
  184801. {
  184802. if (ret == Z_STREAM_END)
  184803. {
  184804. if (png_ptr->zstream.avail_in)
  184805. png_error(png_ptr, "Extra compressed data");
  184806. if (!(png_ptr->zstream.avail_out))
  184807. {
  184808. png_push_process_row(png_ptr);
  184809. }
  184810. png_ptr->mode |= PNG_AFTER_IDAT;
  184811. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184812. break;
  184813. }
  184814. else if (ret == Z_BUF_ERROR)
  184815. break;
  184816. else
  184817. png_error(png_ptr, "Decompression Error");
  184818. }
  184819. if (!(png_ptr->zstream.avail_out))
  184820. {
  184821. if ((
  184822. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184823. png_ptr->interlaced && png_ptr->pass > 6) ||
  184824. (!png_ptr->interlaced &&
  184825. #endif
  184826. png_ptr->row_number == png_ptr->num_rows))
  184827. {
  184828. if (png_ptr->zstream.avail_in)
  184829. {
  184830. png_warning(png_ptr, "Too much data in IDAT chunks");
  184831. }
  184832. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184833. break;
  184834. }
  184835. png_push_process_row(png_ptr);
  184836. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184837. png_ptr->zstream.next_out = png_ptr->row_buf;
  184838. }
  184839. else
  184840. break;
  184841. }
  184842. }
  184843. void /* PRIVATE */
  184844. png_push_process_row(png_structp png_ptr)
  184845. {
  184846. png_ptr->row_info.color_type = png_ptr->color_type;
  184847. png_ptr->row_info.width = png_ptr->iwidth;
  184848. png_ptr->row_info.channels = png_ptr->channels;
  184849. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184850. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184851. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184852. png_ptr->row_info.width);
  184853. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184854. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184855. (int)(png_ptr->row_buf[0]));
  184856. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184857. png_ptr->rowbytes + 1);
  184858. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184859. png_do_read_transformations(png_ptr);
  184860. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184861. /* blow up interlaced rows to full size */
  184862. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184863. {
  184864. if (png_ptr->pass < 6)
  184865. /* old interface (pre-1.0.9):
  184866. png_do_read_interlace(&(png_ptr->row_info),
  184867. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184868. */
  184869. png_do_read_interlace(png_ptr);
  184870. switch (png_ptr->pass)
  184871. {
  184872. case 0:
  184873. {
  184874. int i;
  184875. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  184876. {
  184877. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184878. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  184879. }
  184880. if (png_ptr->pass == 2) /* pass 1 might be empty */
  184881. {
  184882. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184883. {
  184884. png_push_have_row(png_ptr, png_bytep_NULL);
  184885. png_read_push_finish_row(png_ptr);
  184886. }
  184887. }
  184888. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  184889. {
  184890. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184891. {
  184892. png_push_have_row(png_ptr, png_bytep_NULL);
  184893. png_read_push_finish_row(png_ptr);
  184894. }
  184895. }
  184896. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  184897. {
  184898. png_push_have_row(png_ptr, png_bytep_NULL);
  184899. png_read_push_finish_row(png_ptr);
  184900. }
  184901. break;
  184902. }
  184903. case 1:
  184904. {
  184905. int i;
  184906. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  184907. {
  184908. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184909. png_read_push_finish_row(png_ptr);
  184910. }
  184911. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  184912. {
  184913. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184914. {
  184915. png_push_have_row(png_ptr, png_bytep_NULL);
  184916. png_read_push_finish_row(png_ptr);
  184917. }
  184918. }
  184919. break;
  184920. }
  184921. case 2:
  184922. {
  184923. int i;
  184924. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184925. {
  184926. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184927. png_read_push_finish_row(png_ptr);
  184928. }
  184929. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184930. {
  184931. png_push_have_row(png_ptr, png_bytep_NULL);
  184932. png_read_push_finish_row(png_ptr);
  184933. }
  184934. if (png_ptr->pass == 4) /* pass 3 might be empty */
  184935. {
  184936. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184937. {
  184938. png_push_have_row(png_ptr, png_bytep_NULL);
  184939. png_read_push_finish_row(png_ptr);
  184940. }
  184941. }
  184942. break;
  184943. }
  184944. case 3:
  184945. {
  184946. int i;
  184947. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  184948. {
  184949. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184950. png_read_push_finish_row(png_ptr);
  184951. }
  184952. if (png_ptr->pass == 4) /* skip top two generated rows */
  184953. {
  184954. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184955. {
  184956. png_push_have_row(png_ptr, png_bytep_NULL);
  184957. png_read_push_finish_row(png_ptr);
  184958. }
  184959. }
  184960. break;
  184961. }
  184962. case 4:
  184963. {
  184964. int i;
  184965. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184966. {
  184967. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184968. png_read_push_finish_row(png_ptr);
  184969. }
  184970. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184971. {
  184972. png_push_have_row(png_ptr, png_bytep_NULL);
  184973. png_read_push_finish_row(png_ptr);
  184974. }
  184975. if (png_ptr->pass == 6) /* pass 5 might be empty */
  184976. {
  184977. png_push_have_row(png_ptr, png_bytep_NULL);
  184978. png_read_push_finish_row(png_ptr);
  184979. }
  184980. break;
  184981. }
  184982. case 5:
  184983. {
  184984. int i;
  184985. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  184986. {
  184987. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184988. png_read_push_finish_row(png_ptr);
  184989. }
  184990. if (png_ptr->pass == 6) /* skip top generated row */
  184991. {
  184992. png_push_have_row(png_ptr, png_bytep_NULL);
  184993. png_read_push_finish_row(png_ptr);
  184994. }
  184995. break;
  184996. }
  184997. case 6:
  184998. {
  184999. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185000. png_read_push_finish_row(png_ptr);
  185001. if (png_ptr->pass != 6)
  185002. break;
  185003. png_push_have_row(png_ptr, png_bytep_NULL);
  185004. png_read_push_finish_row(png_ptr);
  185005. }
  185006. }
  185007. }
  185008. else
  185009. #endif
  185010. {
  185011. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  185012. png_read_push_finish_row(png_ptr);
  185013. }
  185014. }
  185015. void /* PRIVATE */
  185016. png_read_push_finish_row(png_structp png_ptr)
  185017. {
  185018. #ifdef PNG_USE_LOCAL_ARRAYS
  185019. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  185020. /* start of interlace block */
  185021. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  185022. /* offset to next interlace block */
  185023. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  185024. /* start of interlace block in the y direction */
  185025. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  185026. /* offset to next interlace block in the y direction */
  185027. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  185028. /* Height of interlace block. This is not currently used - if you need
  185029. * it, uncomment it here and in png.h
  185030. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  185031. */
  185032. #endif
  185033. png_ptr->row_number++;
  185034. if (png_ptr->row_number < png_ptr->num_rows)
  185035. return;
  185036. if (png_ptr->interlaced)
  185037. {
  185038. png_ptr->row_number = 0;
  185039. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  185040. png_ptr->rowbytes + 1);
  185041. do
  185042. {
  185043. png_ptr->pass++;
  185044. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  185045. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  185046. (png_ptr->pass == 5 && png_ptr->width < 2))
  185047. png_ptr->pass++;
  185048. if (png_ptr->pass > 7)
  185049. png_ptr->pass--;
  185050. if (png_ptr->pass >= 7)
  185051. break;
  185052. png_ptr->iwidth = (png_ptr->width +
  185053. png_pass_inc[png_ptr->pass] - 1 -
  185054. png_pass_start[png_ptr->pass]) /
  185055. png_pass_inc[png_ptr->pass];
  185056. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  185057. png_ptr->iwidth) + 1;
  185058. if (png_ptr->transformations & PNG_INTERLACE)
  185059. break;
  185060. png_ptr->num_rows = (png_ptr->height +
  185061. png_pass_yinc[png_ptr->pass] - 1 -
  185062. png_pass_ystart[png_ptr->pass]) /
  185063. png_pass_yinc[png_ptr->pass];
  185064. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  185065. }
  185066. }
  185067. #if defined(PNG_READ_tEXt_SUPPORTED)
  185068. void /* PRIVATE */
  185069. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185070. length)
  185071. {
  185072. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185073. {
  185074. png_error(png_ptr, "Out of place tEXt");
  185075. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185076. }
  185077. #ifdef PNG_MAX_MALLOC_64K
  185078. png_ptr->skip_length = 0; /* This may not be necessary */
  185079. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185080. {
  185081. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  185082. png_ptr->skip_length = length - (png_uint_32)65535L;
  185083. length = (png_uint_32)65535L;
  185084. }
  185085. #endif
  185086. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185087. (png_uint_32)(length+1));
  185088. png_ptr->current_text[length] = '\0';
  185089. png_ptr->current_text_ptr = png_ptr->current_text;
  185090. png_ptr->current_text_size = (png_size_t)length;
  185091. png_ptr->current_text_left = (png_size_t)length;
  185092. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  185093. }
  185094. void /* PRIVATE */
  185095. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  185096. {
  185097. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185098. {
  185099. png_size_t text_size;
  185100. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185101. text_size = png_ptr->buffer_size;
  185102. else
  185103. text_size = png_ptr->current_text_left;
  185104. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185105. png_ptr->current_text_left -= text_size;
  185106. png_ptr->current_text_ptr += text_size;
  185107. }
  185108. if (!(png_ptr->current_text_left))
  185109. {
  185110. png_textp text_ptr;
  185111. png_charp text;
  185112. png_charp key;
  185113. int ret;
  185114. if (png_ptr->buffer_size < 4)
  185115. {
  185116. png_push_save_buffer(png_ptr);
  185117. return;
  185118. }
  185119. png_push_crc_finish(png_ptr);
  185120. #if defined(PNG_MAX_MALLOC_64K)
  185121. if (png_ptr->skip_length)
  185122. return;
  185123. #endif
  185124. key = png_ptr->current_text;
  185125. for (text = key; *text; text++)
  185126. /* empty loop */ ;
  185127. if (text < key + png_ptr->current_text_size)
  185128. text++;
  185129. text_ptr = (png_textp)png_malloc(png_ptr,
  185130. (png_uint_32)png_sizeof(png_text));
  185131. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  185132. text_ptr->key = key;
  185133. #ifdef PNG_iTXt_SUPPORTED
  185134. text_ptr->lang = NULL;
  185135. text_ptr->lang_key = NULL;
  185136. #endif
  185137. text_ptr->text = text;
  185138. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185139. png_free(png_ptr, key);
  185140. png_free(png_ptr, text_ptr);
  185141. png_ptr->current_text = NULL;
  185142. if (ret)
  185143. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185144. }
  185145. }
  185146. #endif
  185147. #if defined(PNG_READ_zTXt_SUPPORTED)
  185148. void /* PRIVATE */
  185149. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185150. length)
  185151. {
  185152. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185153. {
  185154. png_error(png_ptr, "Out of place zTXt");
  185155. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185156. }
  185157. #ifdef PNG_MAX_MALLOC_64K
  185158. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  185159. * to be able to store the uncompressed data. Actually, the threshold
  185160. * is probably around 32K, but it isn't as definite as 64K is.
  185161. */
  185162. if (length > (png_uint_32)65535L)
  185163. {
  185164. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  185165. png_push_crc_skip(png_ptr, length);
  185166. return;
  185167. }
  185168. #endif
  185169. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185170. (png_uint_32)(length+1));
  185171. png_ptr->current_text[length] = '\0';
  185172. png_ptr->current_text_ptr = png_ptr->current_text;
  185173. png_ptr->current_text_size = (png_size_t)length;
  185174. png_ptr->current_text_left = (png_size_t)length;
  185175. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  185176. }
  185177. void /* PRIVATE */
  185178. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  185179. {
  185180. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185181. {
  185182. png_size_t text_size;
  185183. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  185184. text_size = png_ptr->buffer_size;
  185185. else
  185186. text_size = png_ptr->current_text_left;
  185187. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185188. png_ptr->current_text_left -= text_size;
  185189. png_ptr->current_text_ptr += text_size;
  185190. }
  185191. if (!(png_ptr->current_text_left))
  185192. {
  185193. png_textp text_ptr;
  185194. png_charp text;
  185195. png_charp key;
  185196. int ret;
  185197. png_size_t text_size, key_size;
  185198. if (png_ptr->buffer_size < 4)
  185199. {
  185200. png_push_save_buffer(png_ptr);
  185201. return;
  185202. }
  185203. png_push_crc_finish(png_ptr);
  185204. key = png_ptr->current_text;
  185205. for (text = key; *text; text++)
  185206. /* empty loop */ ;
  185207. /* zTXt can't have zero text */
  185208. if (text >= key + png_ptr->current_text_size)
  185209. {
  185210. png_ptr->current_text = NULL;
  185211. png_free(png_ptr, key);
  185212. return;
  185213. }
  185214. text++;
  185215. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  185216. {
  185217. png_ptr->current_text = NULL;
  185218. png_free(png_ptr, key);
  185219. return;
  185220. }
  185221. text++;
  185222. png_ptr->zstream.next_in = (png_bytep )text;
  185223. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  185224. (text - key));
  185225. png_ptr->zstream.next_out = png_ptr->zbuf;
  185226. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185227. key_size = text - key;
  185228. text_size = 0;
  185229. text = NULL;
  185230. ret = Z_STREAM_END;
  185231. while (png_ptr->zstream.avail_in)
  185232. {
  185233. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  185234. if (ret != Z_OK && ret != Z_STREAM_END)
  185235. {
  185236. inflateReset(&png_ptr->zstream);
  185237. png_ptr->zstream.avail_in = 0;
  185238. png_ptr->current_text = NULL;
  185239. png_free(png_ptr, key);
  185240. png_free(png_ptr, text);
  185241. return;
  185242. }
  185243. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  185244. {
  185245. if (text == NULL)
  185246. {
  185247. text = (png_charp)png_malloc(png_ptr,
  185248. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185249. + key_size + 1));
  185250. png_memcpy(text + key_size, png_ptr->zbuf,
  185251. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185252. png_memcpy(text, key, key_size);
  185253. text_size = key_size + png_ptr->zbuf_size -
  185254. png_ptr->zstream.avail_out;
  185255. *(text + text_size) = '\0';
  185256. }
  185257. else
  185258. {
  185259. png_charp tmp;
  185260. tmp = text;
  185261. text = (png_charp)png_malloc(png_ptr, text_size +
  185262. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185263. + 1));
  185264. png_memcpy(text, tmp, text_size);
  185265. png_free(png_ptr, tmp);
  185266. png_memcpy(text + text_size, png_ptr->zbuf,
  185267. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185268. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  185269. *(text + text_size) = '\0';
  185270. }
  185271. if (ret != Z_STREAM_END)
  185272. {
  185273. png_ptr->zstream.next_out = png_ptr->zbuf;
  185274. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185275. }
  185276. }
  185277. else
  185278. {
  185279. break;
  185280. }
  185281. if (ret == Z_STREAM_END)
  185282. break;
  185283. }
  185284. inflateReset(&png_ptr->zstream);
  185285. png_ptr->zstream.avail_in = 0;
  185286. if (ret != Z_STREAM_END)
  185287. {
  185288. png_ptr->current_text = NULL;
  185289. png_free(png_ptr, key);
  185290. png_free(png_ptr, text);
  185291. return;
  185292. }
  185293. png_ptr->current_text = NULL;
  185294. png_free(png_ptr, key);
  185295. key = text;
  185296. text += key_size;
  185297. text_ptr = (png_textp)png_malloc(png_ptr,
  185298. (png_uint_32)png_sizeof(png_text));
  185299. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  185300. text_ptr->key = key;
  185301. #ifdef PNG_iTXt_SUPPORTED
  185302. text_ptr->lang = NULL;
  185303. text_ptr->lang_key = NULL;
  185304. #endif
  185305. text_ptr->text = text;
  185306. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185307. png_free(png_ptr, key);
  185308. png_free(png_ptr, text_ptr);
  185309. if (ret)
  185310. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185311. }
  185312. }
  185313. #endif
  185314. #if defined(PNG_READ_iTXt_SUPPORTED)
  185315. void /* PRIVATE */
  185316. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185317. length)
  185318. {
  185319. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185320. {
  185321. png_error(png_ptr, "Out of place iTXt");
  185322. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185323. }
  185324. #ifdef PNG_MAX_MALLOC_64K
  185325. png_ptr->skip_length = 0; /* This may not be necessary */
  185326. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185327. {
  185328. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  185329. png_ptr->skip_length = length - (png_uint_32)65535L;
  185330. length = (png_uint_32)65535L;
  185331. }
  185332. #endif
  185333. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185334. (png_uint_32)(length+1));
  185335. png_ptr->current_text[length] = '\0';
  185336. png_ptr->current_text_ptr = png_ptr->current_text;
  185337. png_ptr->current_text_size = (png_size_t)length;
  185338. png_ptr->current_text_left = (png_size_t)length;
  185339. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  185340. }
  185341. void /* PRIVATE */
  185342. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  185343. {
  185344. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185345. {
  185346. png_size_t text_size;
  185347. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185348. text_size = png_ptr->buffer_size;
  185349. else
  185350. text_size = png_ptr->current_text_left;
  185351. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185352. png_ptr->current_text_left -= text_size;
  185353. png_ptr->current_text_ptr += text_size;
  185354. }
  185355. if (!(png_ptr->current_text_left))
  185356. {
  185357. png_textp text_ptr;
  185358. png_charp key;
  185359. int comp_flag;
  185360. png_charp lang;
  185361. png_charp lang_key;
  185362. png_charp text;
  185363. int ret;
  185364. if (png_ptr->buffer_size < 4)
  185365. {
  185366. png_push_save_buffer(png_ptr);
  185367. return;
  185368. }
  185369. png_push_crc_finish(png_ptr);
  185370. #if defined(PNG_MAX_MALLOC_64K)
  185371. if (png_ptr->skip_length)
  185372. return;
  185373. #endif
  185374. key = png_ptr->current_text;
  185375. for (lang = key; *lang; lang++)
  185376. /* empty loop */ ;
  185377. if (lang < key + png_ptr->current_text_size - 3)
  185378. lang++;
  185379. comp_flag = *lang++;
  185380. lang++; /* skip comp_type, always zero */
  185381. for (lang_key = lang; *lang_key; lang_key++)
  185382. /* empty loop */ ;
  185383. lang_key++; /* skip NUL separator */
  185384. text=lang_key;
  185385. if (lang_key < key + png_ptr->current_text_size - 1)
  185386. {
  185387. for (; *text; text++)
  185388. /* empty loop */ ;
  185389. }
  185390. if (text < key + png_ptr->current_text_size)
  185391. text++;
  185392. text_ptr = (png_textp)png_malloc(png_ptr,
  185393. (png_uint_32)png_sizeof(png_text));
  185394. text_ptr->compression = comp_flag + 2;
  185395. text_ptr->key = key;
  185396. text_ptr->lang = lang;
  185397. text_ptr->lang_key = lang_key;
  185398. text_ptr->text = text;
  185399. text_ptr->text_length = 0;
  185400. text_ptr->itxt_length = png_strlen(text);
  185401. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185402. png_ptr->current_text = NULL;
  185403. png_free(png_ptr, text_ptr);
  185404. if (ret)
  185405. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  185406. }
  185407. }
  185408. #endif
  185409. /* This function is called when we haven't found a handler for this
  185410. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  185411. * name or a critical chunk), the chunk is (currently) silently ignored.
  185412. */
  185413. void /* PRIVATE */
  185414. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185415. length)
  185416. {
  185417. png_uint_32 skip=0;
  185418. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  185419. if (!(png_ptr->chunk_name[0] & 0x20))
  185420. {
  185421. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185422. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185423. PNG_HANDLE_CHUNK_ALWAYS
  185424. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185425. && png_ptr->read_user_chunk_fn == NULL
  185426. #endif
  185427. )
  185428. #endif
  185429. png_chunk_error(png_ptr, "unknown critical chunk");
  185430. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185431. }
  185432. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185433. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  185434. {
  185435. #ifdef PNG_MAX_MALLOC_64K
  185436. if (length > (png_uint_32)65535L)
  185437. {
  185438. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  185439. skip = length - (png_uint_32)65535L;
  185440. length = (png_uint_32)65535L;
  185441. }
  185442. #endif
  185443. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  185444. (png_charp)png_ptr->chunk_name, 5);
  185445. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  185446. png_ptr->unknown_chunk.size = (png_size_t)length;
  185447. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  185448. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185449. if(png_ptr->read_user_chunk_fn != NULL)
  185450. {
  185451. /* callback to user unknown chunk handler */
  185452. int ret;
  185453. ret = (*(png_ptr->read_user_chunk_fn))
  185454. (png_ptr, &png_ptr->unknown_chunk);
  185455. if (ret < 0)
  185456. png_chunk_error(png_ptr, "error in user chunk");
  185457. if (ret == 0)
  185458. {
  185459. if (!(png_ptr->chunk_name[0] & 0x20))
  185460. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185461. PNG_HANDLE_CHUNK_ALWAYS)
  185462. png_chunk_error(png_ptr, "unknown critical chunk");
  185463. png_set_unknown_chunks(png_ptr, info_ptr,
  185464. &png_ptr->unknown_chunk, 1);
  185465. }
  185466. }
  185467. #else
  185468. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  185469. #endif
  185470. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185471. png_ptr->unknown_chunk.data = NULL;
  185472. }
  185473. else
  185474. #endif
  185475. skip=length;
  185476. png_push_crc_skip(png_ptr, skip);
  185477. }
  185478. void /* PRIVATE */
  185479. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  185480. {
  185481. if (png_ptr->info_fn != NULL)
  185482. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  185483. }
  185484. void /* PRIVATE */
  185485. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  185486. {
  185487. if (png_ptr->end_fn != NULL)
  185488. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  185489. }
  185490. void /* PRIVATE */
  185491. png_push_have_row(png_structp png_ptr, png_bytep row)
  185492. {
  185493. if (png_ptr->row_fn != NULL)
  185494. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  185495. (int)png_ptr->pass);
  185496. }
  185497. void PNGAPI
  185498. png_progressive_combine_row (png_structp png_ptr,
  185499. png_bytep old_row, png_bytep new_row)
  185500. {
  185501. #ifdef PNG_USE_LOCAL_ARRAYS
  185502. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  185503. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  185504. #endif
  185505. if(png_ptr == NULL) return;
  185506. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  185507. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  185508. }
  185509. void PNGAPI
  185510. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  185511. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  185512. png_progressive_end_ptr end_fn)
  185513. {
  185514. if(png_ptr == NULL) return;
  185515. png_ptr->info_fn = info_fn;
  185516. png_ptr->row_fn = row_fn;
  185517. png_ptr->end_fn = end_fn;
  185518. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  185519. }
  185520. png_voidp PNGAPI
  185521. png_get_progressive_ptr(png_structp png_ptr)
  185522. {
  185523. if(png_ptr == NULL) return (NULL);
  185524. return png_ptr->io_ptr;
  185525. }
  185526. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  185527. /********* End of inlined file: pngpread.c *********/
  185528. /********* Start of inlined file: pngrio.c *********/
  185529. /* pngrio.c - functions for data input
  185530. *
  185531. * Last changed in libpng 1.2.13 November 13, 2006
  185532. * For conditions of distribution and use, see copyright notice in png.h
  185533. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185534. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185535. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185536. *
  185537. * This file provides a location for all input. Users who need
  185538. * special handling are expected to write a function that has the same
  185539. * arguments as this and performs a similar function, but that possibly
  185540. * has a different input method. Note that you shouldn't change this
  185541. * function, but rather write a replacement function and then make
  185542. * libpng use it at run time with png_set_read_fn(...).
  185543. */
  185544. #define PNG_INTERNAL
  185545. #if defined(PNG_READ_SUPPORTED)
  185546. /* Read the data from whatever input you are using. The default routine
  185547. reads from a file pointer. Note that this routine sometimes gets called
  185548. with very small lengths, so you should implement some kind of simple
  185549. buffering if you are using unbuffered reads. This should never be asked
  185550. to read more then 64K on a 16 bit machine. */
  185551. void /* PRIVATE */
  185552. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185553. {
  185554. png_debug1(4,"reading %d bytes\n", (int)length);
  185555. if (png_ptr->read_data_fn != NULL)
  185556. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  185557. else
  185558. png_error(png_ptr, "Call to NULL read function");
  185559. }
  185560. #if !defined(PNG_NO_STDIO)
  185561. /* This is the function that does the actual reading of data. If you are
  185562. not reading from a standard C stream, you should create a replacement
  185563. read_data function and use it at run time with png_set_read_fn(), rather
  185564. than changing the library. */
  185565. #ifndef USE_FAR_KEYWORD
  185566. void PNGAPI
  185567. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185568. {
  185569. png_size_t check;
  185570. if(png_ptr == NULL) return;
  185571. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  185572. * instead of an int, which is what fread() actually returns.
  185573. */
  185574. #if defined(_WIN32_WCE)
  185575. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185576. check = 0;
  185577. #else
  185578. check = (png_size_t)fread(data, (png_size_t)1, length,
  185579. (png_FILE_p)png_ptr->io_ptr);
  185580. #endif
  185581. if (check != length)
  185582. png_error(png_ptr, "Read Error");
  185583. }
  185584. #else
  185585. /* this is the model-independent version. Since the standard I/O library
  185586. can't handle far buffers in the medium and small models, we have to copy
  185587. the data.
  185588. */
  185589. #define NEAR_BUF_SIZE 1024
  185590. #define MIN(a,b) (a <= b ? a : b)
  185591. static void PNGAPI
  185592. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185593. {
  185594. int check;
  185595. png_byte *n_data;
  185596. png_FILE_p io_ptr;
  185597. if(png_ptr == NULL) return;
  185598. /* Check if data really is near. If so, use usual code. */
  185599. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  185600. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  185601. if ((png_bytep)n_data == data)
  185602. {
  185603. #if defined(_WIN32_WCE)
  185604. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185605. check = 0;
  185606. #else
  185607. check = fread(n_data, 1, length, io_ptr);
  185608. #endif
  185609. }
  185610. else
  185611. {
  185612. png_byte buf[NEAR_BUF_SIZE];
  185613. png_size_t read, remaining, err;
  185614. check = 0;
  185615. remaining = length;
  185616. do
  185617. {
  185618. read = MIN(NEAR_BUF_SIZE, remaining);
  185619. #if defined(_WIN32_WCE)
  185620. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  185621. err = 0;
  185622. #else
  185623. err = fread(buf, (png_size_t)1, read, io_ptr);
  185624. #endif
  185625. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  185626. if(err != read)
  185627. break;
  185628. else
  185629. check += err;
  185630. data += read;
  185631. remaining -= read;
  185632. }
  185633. while (remaining != 0);
  185634. }
  185635. if ((png_uint_32)check != (png_uint_32)length)
  185636. png_error(png_ptr, "read Error");
  185637. }
  185638. #endif
  185639. #endif
  185640. /* This function allows the application to supply a new input function
  185641. for libpng if standard C streams aren't being used.
  185642. This function takes as its arguments:
  185643. png_ptr - pointer to a png input data structure
  185644. io_ptr - pointer to user supplied structure containing info about
  185645. the input functions. May be NULL.
  185646. read_data_fn - pointer to a new input function that takes as its
  185647. arguments a pointer to a png_struct, a pointer to
  185648. a location where input data can be stored, and a 32-bit
  185649. unsigned int that is the number of bytes to be read.
  185650. To exit and output any fatal error messages the new write
  185651. function should call png_error(png_ptr, "Error msg"). */
  185652. void PNGAPI
  185653. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  185654. png_rw_ptr read_data_fn)
  185655. {
  185656. if(png_ptr == NULL) return;
  185657. png_ptr->io_ptr = io_ptr;
  185658. #if !defined(PNG_NO_STDIO)
  185659. if (read_data_fn != NULL)
  185660. png_ptr->read_data_fn = read_data_fn;
  185661. else
  185662. png_ptr->read_data_fn = png_default_read_data;
  185663. #else
  185664. png_ptr->read_data_fn = read_data_fn;
  185665. #endif
  185666. /* It is an error to write to a read device */
  185667. if (png_ptr->write_data_fn != NULL)
  185668. {
  185669. png_ptr->write_data_fn = NULL;
  185670. png_warning(png_ptr,
  185671. "It's an error to set both read_data_fn and write_data_fn in the ");
  185672. png_warning(png_ptr,
  185673. "same structure. Resetting write_data_fn to NULL.");
  185674. }
  185675. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  185676. png_ptr->output_flush_fn = NULL;
  185677. #endif
  185678. }
  185679. #endif /* PNG_READ_SUPPORTED */
  185680. /********* End of inlined file: pngrio.c *********/
  185681. /********* Start of inlined file: pngrtran.c *********/
  185682. /* pngrtran.c - transforms the data in a row for PNG readers
  185683. *
  185684. * Last changed in libpng 1.2.21 [October 4, 2007]
  185685. * For conditions of distribution and use, see copyright notice in png.h
  185686. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185687. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185688. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185689. *
  185690. * This file contains functions optionally called by an application
  185691. * in order to tell libpng how to handle data when reading a PNG.
  185692. * Transformations that are used in both reading and writing are
  185693. * in pngtrans.c.
  185694. */
  185695. #define PNG_INTERNAL
  185696. #if defined(PNG_READ_SUPPORTED)
  185697. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  185698. void PNGAPI
  185699. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  185700. {
  185701. png_debug(1, "in png_set_crc_action\n");
  185702. /* Tell libpng how we react to CRC errors in critical chunks */
  185703. if(png_ptr == NULL) return;
  185704. switch (crit_action)
  185705. {
  185706. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185707. break;
  185708. case PNG_CRC_WARN_USE: /* warn/use data */
  185709. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185710. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  185711. break;
  185712. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185713. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185714. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  185715. PNG_FLAG_CRC_CRITICAL_IGNORE;
  185716. break;
  185717. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  185718. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  185719. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185720. case PNG_CRC_DEFAULT:
  185721. default:
  185722. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185723. break;
  185724. }
  185725. switch (ancil_action)
  185726. {
  185727. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185728. break;
  185729. case PNG_CRC_WARN_USE: /* warn/use data */
  185730. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185731. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  185732. break;
  185733. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185734. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185735. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  185736. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185737. break;
  185738. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185739. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185740. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185741. break;
  185742. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  185743. case PNG_CRC_DEFAULT:
  185744. default:
  185745. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185746. break;
  185747. }
  185748. }
  185749. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  185750. defined(PNG_FLOATING_POINT_SUPPORTED)
  185751. /* handle alpha and tRNS via a background color */
  185752. void PNGAPI
  185753. png_set_background(png_structp png_ptr,
  185754. png_color_16p background_color, int background_gamma_code,
  185755. int need_expand, double background_gamma)
  185756. {
  185757. png_debug(1, "in png_set_background\n");
  185758. if(png_ptr == NULL) return;
  185759. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  185760. {
  185761. png_warning(png_ptr, "Application must supply a known background gamma");
  185762. return;
  185763. }
  185764. png_ptr->transformations |= PNG_BACKGROUND;
  185765. png_memcpy(&(png_ptr->background), background_color,
  185766. png_sizeof(png_color_16));
  185767. png_ptr->background_gamma = (float)background_gamma;
  185768. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  185769. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  185770. }
  185771. #endif
  185772. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185773. /* strip 16 bit depth files to 8 bit depth */
  185774. void PNGAPI
  185775. png_set_strip_16(png_structp png_ptr)
  185776. {
  185777. png_debug(1, "in png_set_strip_16\n");
  185778. if(png_ptr == NULL) return;
  185779. png_ptr->transformations |= PNG_16_TO_8;
  185780. }
  185781. #endif
  185782. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185783. void PNGAPI
  185784. png_set_strip_alpha(png_structp png_ptr)
  185785. {
  185786. png_debug(1, "in png_set_strip_alpha\n");
  185787. if(png_ptr == NULL) return;
  185788. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  185789. }
  185790. #endif
  185791. #if defined(PNG_READ_DITHER_SUPPORTED)
  185792. /* Dither file to 8 bit. Supply a palette, the current number
  185793. * of elements in the palette, the maximum number of elements
  185794. * allowed, and a histogram if possible. If the current number
  185795. * of colors is greater then the maximum number, the palette will be
  185796. * modified to fit in the maximum number. "full_dither" indicates
  185797. * whether we need a dithering cube set up for RGB images, or if we
  185798. * simply are reducing the number of colors in a paletted image.
  185799. */
  185800. typedef struct png_dsort_struct
  185801. {
  185802. struct png_dsort_struct FAR * next;
  185803. png_byte left;
  185804. png_byte right;
  185805. } png_dsort;
  185806. typedef png_dsort FAR * png_dsortp;
  185807. typedef png_dsort FAR * FAR * png_dsortpp;
  185808. void PNGAPI
  185809. png_set_dither(png_structp png_ptr, png_colorp palette,
  185810. int num_palette, int maximum_colors, png_uint_16p histogram,
  185811. int full_dither)
  185812. {
  185813. png_debug(1, "in png_set_dither\n");
  185814. if(png_ptr == NULL) return;
  185815. png_ptr->transformations |= PNG_DITHER;
  185816. if (!full_dither)
  185817. {
  185818. int i;
  185819. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  185820. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185821. for (i = 0; i < num_palette; i++)
  185822. png_ptr->dither_index[i] = (png_byte)i;
  185823. }
  185824. if (num_palette > maximum_colors)
  185825. {
  185826. if (histogram != NULL)
  185827. {
  185828. /* This is easy enough, just throw out the least used colors.
  185829. Perhaps not the best solution, but good enough. */
  185830. int i;
  185831. /* initialize an array to sort colors */
  185832. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  185833. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185834. /* initialize the dither_sort array */
  185835. for (i = 0; i < num_palette; i++)
  185836. png_ptr->dither_sort[i] = (png_byte)i;
  185837. /* Find the least used palette entries by starting a
  185838. bubble sort, and running it until we have sorted
  185839. out enough colors. Note that we don't care about
  185840. sorting all the colors, just finding which are
  185841. least used. */
  185842. for (i = num_palette - 1; i >= maximum_colors; i--)
  185843. {
  185844. int done; /* to stop early if the list is pre-sorted */
  185845. int j;
  185846. done = 1;
  185847. for (j = 0; j < i; j++)
  185848. {
  185849. if (histogram[png_ptr->dither_sort[j]]
  185850. < histogram[png_ptr->dither_sort[j + 1]])
  185851. {
  185852. png_byte t;
  185853. t = png_ptr->dither_sort[j];
  185854. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  185855. png_ptr->dither_sort[j + 1] = t;
  185856. done = 0;
  185857. }
  185858. }
  185859. if (done)
  185860. break;
  185861. }
  185862. /* swap the palette around, and set up a table, if necessary */
  185863. if (full_dither)
  185864. {
  185865. int j = num_palette;
  185866. /* put all the useful colors within the max, but don't
  185867. move the others */
  185868. for (i = 0; i < maximum_colors; i++)
  185869. {
  185870. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185871. {
  185872. do
  185873. j--;
  185874. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185875. palette[i] = palette[j];
  185876. }
  185877. }
  185878. }
  185879. else
  185880. {
  185881. int j = num_palette;
  185882. /* move all the used colors inside the max limit, and
  185883. develop a translation table */
  185884. for (i = 0; i < maximum_colors; i++)
  185885. {
  185886. /* only move the colors we need to */
  185887. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185888. {
  185889. png_color tmp_color;
  185890. do
  185891. j--;
  185892. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185893. tmp_color = palette[j];
  185894. palette[j] = palette[i];
  185895. palette[i] = tmp_color;
  185896. /* indicate where the color went */
  185897. png_ptr->dither_index[j] = (png_byte)i;
  185898. png_ptr->dither_index[i] = (png_byte)j;
  185899. }
  185900. }
  185901. /* find closest color for those colors we are not using */
  185902. for (i = 0; i < num_palette; i++)
  185903. {
  185904. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  185905. {
  185906. int min_d, k, min_k, d_index;
  185907. /* find the closest color to one we threw out */
  185908. d_index = png_ptr->dither_index[i];
  185909. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  185910. for (k = 1, min_k = 0; k < maximum_colors; k++)
  185911. {
  185912. int d;
  185913. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  185914. if (d < min_d)
  185915. {
  185916. min_d = d;
  185917. min_k = k;
  185918. }
  185919. }
  185920. /* point to closest color */
  185921. png_ptr->dither_index[i] = (png_byte)min_k;
  185922. }
  185923. }
  185924. }
  185925. png_free(png_ptr, png_ptr->dither_sort);
  185926. png_ptr->dither_sort=NULL;
  185927. }
  185928. else
  185929. {
  185930. /* This is much harder to do simply (and quickly). Perhaps
  185931. we need to go through a median cut routine, but those
  185932. don't always behave themselves with only a few colors
  185933. as input. So we will just find the closest two colors,
  185934. and throw out one of them (chosen somewhat randomly).
  185935. [We don't understand this at all, so if someone wants to
  185936. work on improving it, be our guest - AED, GRP]
  185937. */
  185938. int i;
  185939. int max_d;
  185940. int num_new_palette;
  185941. png_dsortp t;
  185942. png_dsortpp hash;
  185943. t=NULL;
  185944. /* initialize palette index arrays */
  185945. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  185946. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185947. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  185948. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185949. /* initialize the sort array */
  185950. for (i = 0; i < num_palette; i++)
  185951. {
  185952. png_ptr->index_to_palette[i] = (png_byte)i;
  185953. png_ptr->palette_to_index[i] = (png_byte)i;
  185954. }
  185955. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  185956. png_sizeof (png_dsortp)));
  185957. for (i = 0; i < 769; i++)
  185958. hash[i] = NULL;
  185959. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  185960. num_new_palette = num_palette;
  185961. /* initial wild guess at how far apart the farthest pixel
  185962. pair we will be eliminating will be. Larger
  185963. numbers mean more areas will be allocated, Smaller
  185964. numbers run the risk of not saving enough data, and
  185965. having to do this all over again.
  185966. I have not done extensive checking on this number.
  185967. */
  185968. max_d = 96;
  185969. while (num_new_palette > maximum_colors)
  185970. {
  185971. for (i = 0; i < num_new_palette - 1; i++)
  185972. {
  185973. int j;
  185974. for (j = i + 1; j < num_new_palette; j++)
  185975. {
  185976. int d;
  185977. d = PNG_COLOR_DIST(palette[i], palette[j]);
  185978. if (d <= max_d)
  185979. {
  185980. t = (png_dsortp)png_malloc_warn(png_ptr,
  185981. (png_uint_32)(png_sizeof(png_dsort)));
  185982. if (t == NULL)
  185983. break;
  185984. t->next = hash[d];
  185985. t->left = (png_byte)i;
  185986. t->right = (png_byte)j;
  185987. hash[d] = t;
  185988. }
  185989. }
  185990. if (t == NULL)
  185991. break;
  185992. }
  185993. if (t != NULL)
  185994. for (i = 0; i <= max_d; i++)
  185995. {
  185996. if (hash[i] != NULL)
  185997. {
  185998. png_dsortp p;
  185999. for (p = hash[i]; p; p = p->next)
  186000. {
  186001. if ((int)png_ptr->index_to_palette[p->left]
  186002. < num_new_palette &&
  186003. (int)png_ptr->index_to_palette[p->right]
  186004. < num_new_palette)
  186005. {
  186006. int j, next_j;
  186007. if (num_new_palette & 0x01)
  186008. {
  186009. j = p->left;
  186010. next_j = p->right;
  186011. }
  186012. else
  186013. {
  186014. j = p->right;
  186015. next_j = p->left;
  186016. }
  186017. num_new_palette--;
  186018. palette[png_ptr->index_to_palette[j]]
  186019. = palette[num_new_palette];
  186020. if (!full_dither)
  186021. {
  186022. int k;
  186023. for (k = 0; k < num_palette; k++)
  186024. {
  186025. if (png_ptr->dither_index[k] ==
  186026. png_ptr->index_to_palette[j])
  186027. png_ptr->dither_index[k] =
  186028. png_ptr->index_to_palette[next_j];
  186029. if ((int)png_ptr->dither_index[k] ==
  186030. num_new_palette)
  186031. png_ptr->dither_index[k] =
  186032. png_ptr->index_to_palette[j];
  186033. }
  186034. }
  186035. png_ptr->index_to_palette[png_ptr->palette_to_index
  186036. [num_new_palette]] = png_ptr->index_to_palette[j];
  186037. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  186038. = png_ptr->palette_to_index[num_new_palette];
  186039. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  186040. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  186041. }
  186042. if (num_new_palette <= maximum_colors)
  186043. break;
  186044. }
  186045. if (num_new_palette <= maximum_colors)
  186046. break;
  186047. }
  186048. }
  186049. for (i = 0; i < 769; i++)
  186050. {
  186051. if (hash[i] != NULL)
  186052. {
  186053. png_dsortp p = hash[i];
  186054. while (p)
  186055. {
  186056. t = p->next;
  186057. png_free(png_ptr, p);
  186058. p = t;
  186059. }
  186060. }
  186061. hash[i] = 0;
  186062. }
  186063. max_d += 96;
  186064. }
  186065. png_free(png_ptr, hash);
  186066. png_free(png_ptr, png_ptr->palette_to_index);
  186067. png_free(png_ptr, png_ptr->index_to_palette);
  186068. png_ptr->palette_to_index=NULL;
  186069. png_ptr->index_to_palette=NULL;
  186070. }
  186071. num_palette = maximum_colors;
  186072. }
  186073. if (png_ptr->palette == NULL)
  186074. {
  186075. png_ptr->palette = palette;
  186076. }
  186077. png_ptr->num_palette = (png_uint_16)num_palette;
  186078. if (full_dither)
  186079. {
  186080. int i;
  186081. png_bytep distance;
  186082. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  186083. PNG_DITHER_BLUE_BITS;
  186084. int num_red = (1 << PNG_DITHER_RED_BITS);
  186085. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  186086. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  186087. png_size_t num_entries = ((png_size_t)1 << total_bits);
  186088. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  186089. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  186090. png_memset(png_ptr->palette_lookup, 0, num_entries *
  186091. png_sizeof (png_byte));
  186092. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  186093. png_sizeof(png_byte)));
  186094. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  186095. for (i = 0; i < num_palette; i++)
  186096. {
  186097. int ir, ig, ib;
  186098. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  186099. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  186100. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  186101. for (ir = 0; ir < num_red; ir++)
  186102. {
  186103. /* int dr = abs(ir - r); */
  186104. int dr = ((ir > r) ? ir - r : r - ir);
  186105. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  186106. for (ig = 0; ig < num_green; ig++)
  186107. {
  186108. /* int dg = abs(ig - g); */
  186109. int dg = ((ig > g) ? ig - g : g - ig);
  186110. int dt = dr + dg;
  186111. int dm = ((dr > dg) ? dr : dg);
  186112. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  186113. for (ib = 0; ib < num_blue; ib++)
  186114. {
  186115. int d_index = index_g | ib;
  186116. /* int db = abs(ib - b); */
  186117. int db = ((ib > b) ? ib - b : b - ib);
  186118. int dmax = ((dm > db) ? dm : db);
  186119. int d = dmax + dt + db;
  186120. if (d < (int)distance[d_index])
  186121. {
  186122. distance[d_index] = (png_byte)d;
  186123. png_ptr->palette_lookup[d_index] = (png_byte)i;
  186124. }
  186125. }
  186126. }
  186127. }
  186128. }
  186129. png_free(png_ptr, distance);
  186130. }
  186131. }
  186132. #endif
  186133. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186134. /* Transform the image from the file_gamma to the screen_gamma. We
  186135. * only do transformations on images where the file_gamma and screen_gamma
  186136. * are not close reciprocals, otherwise it slows things down slightly, and
  186137. * also needlessly introduces small errors.
  186138. *
  186139. * We will turn off gamma transformation later if no semitransparent entries
  186140. * are present in the tRNS array for palette images. We can't do it here
  186141. * because we don't necessarily have the tRNS chunk yet.
  186142. */
  186143. void PNGAPI
  186144. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  186145. {
  186146. png_debug(1, "in png_set_gamma\n");
  186147. if(png_ptr == NULL) return;
  186148. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  186149. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  186150. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  186151. png_ptr->transformations |= PNG_GAMMA;
  186152. png_ptr->gamma = (float)file_gamma;
  186153. png_ptr->screen_gamma = (float)scrn_gamma;
  186154. }
  186155. #endif
  186156. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186157. /* Expand paletted images to RGB, expand grayscale images of
  186158. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  186159. * to alpha channels.
  186160. */
  186161. void PNGAPI
  186162. png_set_expand(png_structp png_ptr)
  186163. {
  186164. png_debug(1, "in png_set_expand\n");
  186165. if(png_ptr == NULL) return;
  186166. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186167. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186168. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186169. #endif
  186170. }
  186171. /* GRR 19990627: the following three functions currently are identical
  186172. * to png_set_expand(). However, it is entirely reasonable that someone
  186173. * might wish to expand an indexed image to RGB but *not* expand a single,
  186174. * fully transparent palette entry to a full alpha channel--perhaps instead
  186175. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  186176. * the transparent color with a particular RGB value, or drop tRNS entirely.
  186177. * IOW, a future version of the library may make the transformations flag
  186178. * a bit more fine-grained, with separate bits for each of these three
  186179. * functions.
  186180. *
  186181. * More to the point, these functions make it obvious what libpng will be
  186182. * doing, whereas "expand" can (and does) mean any number of things.
  186183. *
  186184. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  186185. * to expand only the sample depth but not to expand the tRNS to alpha.
  186186. */
  186187. /* Expand paletted images to RGB. */
  186188. void PNGAPI
  186189. png_set_palette_to_rgb(png_structp png_ptr)
  186190. {
  186191. png_debug(1, "in png_set_palette_to_rgb\n");
  186192. if(png_ptr == NULL) return;
  186193. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186194. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186195. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  186196. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186197. #endif
  186198. }
  186199. #if !defined(PNG_1_0_X)
  186200. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186201. void PNGAPI
  186202. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  186203. {
  186204. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  186205. if(png_ptr == NULL) return;
  186206. png_ptr->transformations |= PNG_EXPAND;
  186207. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186208. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186209. #endif
  186210. }
  186211. #endif
  186212. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186213. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186214. /* Deprecated as of libpng-1.2.9 */
  186215. void PNGAPI
  186216. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  186217. {
  186218. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  186219. if(png_ptr == NULL) return;
  186220. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186221. }
  186222. #endif
  186223. /* Expand tRNS chunks to alpha channels. */
  186224. void PNGAPI
  186225. png_set_tRNS_to_alpha(png_structp png_ptr)
  186226. {
  186227. png_debug(1, "in png_set_tRNS_to_alpha\n");
  186228. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186229. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186230. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186231. #endif
  186232. }
  186233. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  186234. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186235. void PNGAPI
  186236. png_set_gray_to_rgb(png_structp png_ptr)
  186237. {
  186238. png_debug(1, "in png_set_gray_to_rgb\n");
  186239. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  186240. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186241. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186242. #endif
  186243. }
  186244. #endif
  186245. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186246. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  186247. /* Convert a RGB image to a grayscale of the same width. This allows us,
  186248. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  186249. */
  186250. void PNGAPI
  186251. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  186252. double green)
  186253. {
  186254. int red_fixed = (int)((float)red*100000.0 + 0.5);
  186255. int green_fixed = (int)((float)green*100000.0 + 0.5);
  186256. if(png_ptr == NULL) return;
  186257. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  186258. }
  186259. #endif
  186260. void PNGAPI
  186261. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  186262. png_fixed_point red, png_fixed_point green)
  186263. {
  186264. png_debug(1, "in png_set_rgb_to_gray\n");
  186265. if(png_ptr == NULL) return;
  186266. switch(error_action)
  186267. {
  186268. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  186269. break;
  186270. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  186271. break;
  186272. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  186273. }
  186274. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186275. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186276. png_ptr->transformations |= PNG_EXPAND;
  186277. #else
  186278. {
  186279. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  186280. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  186281. }
  186282. #endif
  186283. {
  186284. png_uint_16 red_int, green_int;
  186285. if(red < 0 || green < 0)
  186286. {
  186287. red_int = 6968; /* .212671 * 32768 + .5 */
  186288. green_int = 23434; /* .715160 * 32768 + .5 */
  186289. }
  186290. else if(red + green < 100000L)
  186291. {
  186292. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  186293. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  186294. }
  186295. else
  186296. {
  186297. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  186298. red_int = 6968;
  186299. green_int = 23434;
  186300. }
  186301. png_ptr->rgb_to_gray_red_coeff = red_int;
  186302. png_ptr->rgb_to_gray_green_coeff = green_int;
  186303. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  186304. }
  186305. }
  186306. #endif
  186307. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  186308. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  186309. defined(PNG_LEGACY_SUPPORTED)
  186310. void PNGAPI
  186311. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  186312. read_user_transform_fn)
  186313. {
  186314. png_debug(1, "in png_set_read_user_transform_fn\n");
  186315. if(png_ptr == NULL) return;
  186316. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186317. png_ptr->transformations |= PNG_USER_TRANSFORM;
  186318. png_ptr->read_user_transform_fn = read_user_transform_fn;
  186319. #endif
  186320. #ifdef PNG_LEGACY_SUPPORTED
  186321. if(read_user_transform_fn)
  186322. png_warning(png_ptr,
  186323. "This version of libpng does not support user transforms");
  186324. #endif
  186325. }
  186326. #endif
  186327. /* Initialize everything needed for the read. This includes modifying
  186328. * the palette.
  186329. */
  186330. void /* PRIVATE */
  186331. png_init_read_transformations(png_structp png_ptr)
  186332. {
  186333. png_debug(1, "in png_init_read_transformations\n");
  186334. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186335. if(png_ptr != NULL)
  186336. #endif
  186337. {
  186338. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  186339. || defined(PNG_READ_GAMMA_SUPPORTED)
  186340. int color_type = png_ptr->color_type;
  186341. #endif
  186342. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  186343. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186344. /* Detect gray background and attempt to enable optimization
  186345. * for gray --> RGB case */
  186346. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  186347. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  186348. * background color might actually be gray yet not be flagged as such.
  186349. * This is not a problem for the current code, which uses
  186350. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  186351. * png_do_gray_to_rgb() transformation.
  186352. */
  186353. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186354. !(color_type & PNG_COLOR_MASK_COLOR))
  186355. {
  186356. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186357. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186358. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186359. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186360. png_ptr->background.red == png_ptr->background.green &&
  186361. png_ptr->background.red == png_ptr->background.blue)
  186362. {
  186363. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186364. png_ptr->background.gray = png_ptr->background.red;
  186365. }
  186366. #endif
  186367. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186368. (png_ptr->transformations & PNG_EXPAND))
  186369. {
  186370. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  186371. {
  186372. /* expand background and tRNS chunks */
  186373. switch (png_ptr->bit_depth)
  186374. {
  186375. case 1:
  186376. png_ptr->background.gray *= (png_uint_16)0xff;
  186377. png_ptr->background.red = png_ptr->background.green
  186378. = png_ptr->background.blue = png_ptr->background.gray;
  186379. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186380. {
  186381. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  186382. png_ptr->trans_values.red = png_ptr->trans_values.green
  186383. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186384. }
  186385. break;
  186386. case 2:
  186387. png_ptr->background.gray *= (png_uint_16)0x55;
  186388. png_ptr->background.red = png_ptr->background.green
  186389. = png_ptr->background.blue = png_ptr->background.gray;
  186390. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186391. {
  186392. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  186393. png_ptr->trans_values.red = png_ptr->trans_values.green
  186394. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186395. }
  186396. break;
  186397. case 4:
  186398. png_ptr->background.gray *= (png_uint_16)0x11;
  186399. png_ptr->background.red = png_ptr->background.green
  186400. = png_ptr->background.blue = png_ptr->background.gray;
  186401. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186402. {
  186403. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  186404. png_ptr->trans_values.red = png_ptr->trans_values.green
  186405. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186406. }
  186407. break;
  186408. case 8:
  186409. case 16:
  186410. png_ptr->background.red = png_ptr->background.green
  186411. = png_ptr->background.blue = png_ptr->background.gray;
  186412. break;
  186413. }
  186414. }
  186415. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  186416. {
  186417. png_ptr->background.red =
  186418. png_ptr->palette[png_ptr->background.index].red;
  186419. png_ptr->background.green =
  186420. png_ptr->palette[png_ptr->background.index].green;
  186421. png_ptr->background.blue =
  186422. png_ptr->palette[png_ptr->background.index].blue;
  186423. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186424. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186425. {
  186426. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186427. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186428. #endif
  186429. {
  186430. /* invert the alpha channel (in tRNS) unless the pixels are
  186431. going to be expanded, in which case leave it for later */
  186432. int i,istop;
  186433. istop=(int)png_ptr->num_trans;
  186434. for (i=0; i<istop; i++)
  186435. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  186436. }
  186437. }
  186438. #endif
  186439. }
  186440. }
  186441. #endif
  186442. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  186443. png_ptr->background_1 = png_ptr->background;
  186444. #endif
  186445. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186446. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  186447. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  186448. < PNG_GAMMA_THRESHOLD))
  186449. {
  186450. int i,k;
  186451. k=0;
  186452. for (i=0; i<png_ptr->num_trans; i++)
  186453. {
  186454. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  186455. k=1; /* partial transparency is present */
  186456. }
  186457. if (k == 0)
  186458. png_ptr->transformations &= (~PNG_GAMMA);
  186459. }
  186460. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  186461. png_ptr->gamma != 0.0)
  186462. {
  186463. png_build_gamma_table(png_ptr);
  186464. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186465. if (png_ptr->transformations & PNG_BACKGROUND)
  186466. {
  186467. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186468. {
  186469. /* could skip if no transparency and
  186470. */
  186471. png_color back, back_1;
  186472. png_colorp palette = png_ptr->palette;
  186473. int num_palette = png_ptr->num_palette;
  186474. int i;
  186475. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  186476. {
  186477. back.red = png_ptr->gamma_table[png_ptr->background.red];
  186478. back.green = png_ptr->gamma_table[png_ptr->background.green];
  186479. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  186480. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  186481. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  186482. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  186483. }
  186484. else
  186485. {
  186486. double g, gs;
  186487. switch (png_ptr->background_gamma_type)
  186488. {
  186489. case PNG_BACKGROUND_GAMMA_SCREEN:
  186490. g = (png_ptr->screen_gamma);
  186491. gs = 1.0;
  186492. break;
  186493. case PNG_BACKGROUND_GAMMA_FILE:
  186494. g = 1.0 / (png_ptr->gamma);
  186495. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186496. break;
  186497. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186498. g = 1.0 / (png_ptr->background_gamma);
  186499. gs = 1.0 / (png_ptr->background_gamma *
  186500. png_ptr->screen_gamma);
  186501. break;
  186502. default:
  186503. g = 1.0; /* back_1 */
  186504. gs = 1.0; /* back */
  186505. }
  186506. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  186507. {
  186508. back.red = (png_byte)png_ptr->background.red;
  186509. back.green = (png_byte)png_ptr->background.green;
  186510. back.blue = (png_byte)png_ptr->background.blue;
  186511. }
  186512. else
  186513. {
  186514. back.red = (png_byte)(pow(
  186515. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  186516. back.green = (png_byte)(pow(
  186517. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  186518. back.blue = (png_byte)(pow(
  186519. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  186520. }
  186521. back_1.red = (png_byte)(pow(
  186522. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  186523. back_1.green = (png_byte)(pow(
  186524. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  186525. back_1.blue = (png_byte)(pow(
  186526. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  186527. }
  186528. for (i = 0; i < num_palette; i++)
  186529. {
  186530. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  186531. {
  186532. if (png_ptr->trans[i] == 0)
  186533. {
  186534. palette[i] = back;
  186535. }
  186536. else /* if (png_ptr->trans[i] != 0xff) */
  186537. {
  186538. png_byte v, w;
  186539. v = png_ptr->gamma_to_1[palette[i].red];
  186540. png_composite(w, v, png_ptr->trans[i], back_1.red);
  186541. palette[i].red = png_ptr->gamma_from_1[w];
  186542. v = png_ptr->gamma_to_1[palette[i].green];
  186543. png_composite(w, v, png_ptr->trans[i], back_1.green);
  186544. palette[i].green = png_ptr->gamma_from_1[w];
  186545. v = png_ptr->gamma_to_1[palette[i].blue];
  186546. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  186547. palette[i].blue = png_ptr->gamma_from_1[w];
  186548. }
  186549. }
  186550. else
  186551. {
  186552. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186553. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186554. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186555. }
  186556. }
  186557. }
  186558. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  186559. else
  186560. /* color_type != PNG_COLOR_TYPE_PALETTE */
  186561. {
  186562. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  186563. double g = 1.0;
  186564. double gs = 1.0;
  186565. switch (png_ptr->background_gamma_type)
  186566. {
  186567. case PNG_BACKGROUND_GAMMA_SCREEN:
  186568. g = (png_ptr->screen_gamma);
  186569. gs = 1.0;
  186570. break;
  186571. case PNG_BACKGROUND_GAMMA_FILE:
  186572. g = 1.0 / (png_ptr->gamma);
  186573. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186574. break;
  186575. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186576. g = 1.0 / (png_ptr->background_gamma);
  186577. gs = 1.0 / (png_ptr->background_gamma *
  186578. png_ptr->screen_gamma);
  186579. break;
  186580. }
  186581. png_ptr->background_1.gray = (png_uint_16)(pow(
  186582. (double)png_ptr->background.gray / m, g) * m + .5);
  186583. png_ptr->background.gray = (png_uint_16)(pow(
  186584. (double)png_ptr->background.gray / m, gs) * m + .5);
  186585. if ((png_ptr->background.red != png_ptr->background.green) ||
  186586. (png_ptr->background.red != png_ptr->background.blue) ||
  186587. (png_ptr->background.red != png_ptr->background.gray))
  186588. {
  186589. /* RGB or RGBA with color background */
  186590. png_ptr->background_1.red = (png_uint_16)(pow(
  186591. (double)png_ptr->background.red / m, g) * m + .5);
  186592. png_ptr->background_1.green = (png_uint_16)(pow(
  186593. (double)png_ptr->background.green / m, g) * m + .5);
  186594. png_ptr->background_1.blue = (png_uint_16)(pow(
  186595. (double)png_ptr->background.blue / m, g) * m + .5);
  186596. png_ptr->background.red = (png_uint_16)(pow(
  186597. (double)png_ptr->background.red / m, gs) * m + .5);
  186598. png_ptr->background.green = (png_uint_16)(pow(
  186599. (double)png_ptr->background.green / m, gs) * m + .5);
  186600. png_ptr->background.blue = (png_uint_16)(pow(
  186601. (double)png_ptr->background.blue / m, gs) * m + .5);
  186602. }
  186603. else
  186604. {
  186605. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  186606. png_ptr->background_1.red = png_ptr->background_1.green
  186607. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  186608. png_ptr->background.red = png_ptr->background.green
  186609. = png_ptr->background.blue = png_ptr->background.gray;
  186610. }
  186611. }
  186612. }
  186613. else
  186614. /* transformation does not include PNG_BACKGROUND */
  186615. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186616. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186617. {
  186618. png_colorp palette = png_ptr->palette;
  186619. int num_palette = png_ptr->num_palette;
  186620. int i;
  186621. for (i = 0; i < num_palette; i++)
  186622. {
  186623. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186624. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186625. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186626. }
  186627. }
  186628. }
  186629. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186630. else
  186631. #endif
  186632. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  186633. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186634. /* No GAMMA transformation */
  186635. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186636. (color_type == PNG_COLOR_TYPE_PALETTE))
  186637. {
  186638. int i;
  186639. int istop = (int)png_ptr->num_trans;
  186640. png_color back;
  186641. png_colorp palette = png_ptr->palette;
  186642. back.red = (png_byte)png_ptr->background.red;
  186643. back.green = (png_byte)png_ptr->background.green;
  186644. back.blue = (png_byte)png_ptr->background.blue;
  186645. for (i = 0; i < istop; i++)
  186646. {
  186647. if (png_ptr->trans[i] == 0)
  186648. {
  186649. palette[i] = back;
  186650. }
  186651. else if (png_ptr->trans[i] != 0xff)
  186652. {
  186653. /* The png_composite() macro is defined in png.h */
  186654. png_composite(palette[i].red, palette[i].red,
  186655. png_ptr->trans[i], back.red);
  186656. png_composite(palette[i].green, palette[i].green,
  186657. png_ptr->trans[i], back.green);
  186658. png_composite(palette[i].blue, palette[i].blue,
  186659. png_ptr->trans[i], back.blue);
  186660. }
  186661. }
  186662. }
  186663. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186664. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186665. if ((png_ptr->transformations & PNG_SHIFT) &&
  186666. (color_type == PNG_COLOR_TYPE_PALETTE))
  186667. {
  186668. png_uint_16 i;
  186669. png_uint_16 istop = png_ptr->num_palette;
  186670. int sr = 8 - png_ptr->sig_bit.red;
  186671. int sg = 8 - png_ptr->sig_bit.green;
  186672. int sb = 8 - png_ptr->sig_bit.blue;
  186673. if (sr < 0 || sr > 8)
  186674. sr = 0;
  186675. if (sg < 0 || sg > 8)
  186676. sg = 0;
  186677. if (sb < 0 || sb > 8)
  186678. sb = 0;
  186679. for (i = 0; i < istop; i++)
  186680. {
  186681. png_ptr->palette[i].red >>= sr;
  186682. png_ptr->palette[i].green >>= sg;
  186683. png_ptr->palette[i].blue >>= sb;
  186684. }
  186685. }
  186686. #endif /* PNG_READ_SHIFT_SUPPORTED */
  186687. }
  186688. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  186689. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  186690. if(png_ptr)
  186691. return;
  186692. #endif
  186693. }
  186694. /* Modify the info structure to reflect the transformations. The
  186695. * info should be updated so a PNG file could be written with it,
  186696. * assuming the transformations result in valid PNG data.
  186697. */
  186698. void /* PRIVATE */
  186699. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  186700. {
  186701. png_debug(1, "in png_read_transform_info\n");
  186702. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186703. if (png_ptr->transformations & PNG_EXPAND)
  186704. {
  186705. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186706. {
  186707. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  186708. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  186709. else
  186710. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  186711. info_ptr->bit_depth = 8;
  186712. info_ptr->num_trans = 0;
  186713. }
  186714. else
  186715. {
  186716. if (png_ptr->num_trans)
  186717. {
  186718. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  186719. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186720. else
  186721. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186722. }
  186723. if (info_ptr->bit_depth < 8)
  186724. info_ptr->bit_depth = 8;
  186725. info_ptr->num_trans = 0;
  186726. }
  186727. }
  186728. #endif
  186729. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186730. if (png_ptr->transformations & PNG_BACKGROUND)
  186731. {
  186732. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186733. info_ptr->num_trans = 0;
  186734. info_ptr->background = png_ptr->background;
  186735. }
  186736. #endif
  186737. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186738. if (png_ptr->transformations & PNG_GAMMA)
  186739. {
  186740. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186741. info_ptr->gamma = png_ptr->gamma;
  186742. #endif
  186743. #ifdef PNG_FIXED_POINT_SUPPORTED
  186744. info_ptr->int_gamma = png_ptr->int_gamma;
  186745. #endif
  186746. }
  186747. #endif
  186748. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186749. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  186750. info_ptr->bit_depth = 8;
  186751. #endif
  186752. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186753. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  186754. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186755. #endif
  186756. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186757. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186758. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  186759. #endif
  186760. #if defined(PNG_READ_DITHER_SUPPORTED)
  186761. if (png_ptr->transformations & PNG_DITHER)
  186762. {
  186763. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186764. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  186765. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  186766. {
  186767. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  186768. }
  186769. }
  186770. #endif
  186771. #if defined(PNG_READ_PACK_SUPPORTED)
  186772. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  186773. info_ptr->bit_depth = 8;
  186774. #endif
  186775. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186776. info_ptr->channels = 1;
  186777. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  186778. info_ptr->channels = 3;
  186779. else
  186780. info_ptr->channels = 1;
  186781. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186782. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186783. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186784. #endif
  186785. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  186786. info_ptr->channels++;
  186787. #if defined(PNG_READ_FILLER_SUPPORTED)
  186788. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  186789. if ((png_ptr->transformations & PNG_FILLER) &&
  186790. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186791. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  186792. {
  186793. info_ptr->channels++;
  186794. /* if adding a true alpha channel not just filler */
  186795. #if !defined(PNG_1_0_X)
  186796. if (png_ptr->transformations & PNG_ADD_ALPHA)
  186797. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186798. #endif
  186799. }
  186800. #endif
  186801. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  186802. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186803. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  186804. {
  186805. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  186806. info_ptr->bit_depth = png_ptr->user_transform_depth;
  186807. if(info_ptr->channels < png_ptr->user_transform_channels)
  186808. info_ptr->channels = png_ptr->user_transform_channels;
  186809. }
  186810. #endif
  186811. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  186812. info_ptr->bit_depth);
  186813. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  186814. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  186815. if(png_ptr)
  186816. return;
  186817. #endif
  186818. }
  186819. /* Transform the row. The order of transformations is significant,
  186820. * and is very touchy. If you add a transformation, take care to
  186821. * decide how it fits in with the other transformations here.
  186822. */
  186823. void /* PRIVATE */
  186824. png_do_read_transformations(png_structp png_ptr)
  186825. {
  186826. png_debug(1, "in png_do_read_transformations\n");
  186827. if (png_ptr->row_buf == NULL)
  186828. {
  186829. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186830. char msg[50];
  186831. png_snprintf2(msg, 50,
  186832. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  186833. png_ptr->pass);
  186834. png_error(png_ptr, msg);
  186835. #else
  186836. png_error(png_ptr, "NULL row buffer");
  186837. #endif
  186838. }
  186839. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186840. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186841. /* Application has failed to call either png_read_start_image()
  186842. * or png_read_update_info() after setting transforms that expand
  186843. * pixels. This check added to libpng-1.2.19 */
  186844. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  186845. png_error(png_ptr, "Uninitialized row");
  186846. #else
  186847. png_warning(png_ptr, "Uninitialized row");
  186848. #endif
  186849. #endif
  186850. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186851. if (png_ptr->transformations & PNG_EXPAND)
  186852. {
  186853. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  186854. {
  186855. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186856. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  186857. }
  186858. else
  186859. {
  186860. if (png_ptr->num_trans &&
  186861. (png_ptr->transformations & PNG_EXPAND_tRNS))
  186862. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186863. &(png_ptr->trans_values));
  186864. else
  186865. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186866. NULL);
  186867. }
  186868. }
  186869. #endif
  186870. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186871. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186872. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186873. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  186874. #endif
  186875. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186876. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186877. {
  186878. int rgb_error =
  186879. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  186880. if(rgb_error)
  186881. {
  186882. png_ptr->rgb_to_gray_status=1;
  186883. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186884. PNG_RGB_TO_GRAY_WARN)
  186885. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186886. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186887. PNG_RGB_TO_GRAY_ERR)
  186888. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186889. }
  186890. }
  186891. #endif
  186892. /*
  186893. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  186894. In most cases, the "simple transparency" should be done prior to doing
  186895. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  186896. pixel is transparent. You would also need to make sure that the
  186897. transparency information is upgraded to RGB.
  186898. To summarize, the current flow is:
  186899. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  186900. with background "in place" if transparent,
  186901. convert to RGB if necessary
  186902. - Gray + alpha -> composite with gray background and remove alpha bytes,
  186903. convert to RGB if necessary
  186904. To support RGB backgrounds for gray images we need:
  186905. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  186906. 3 or 6 bytes and composite with background
  186907. "in place" if transparent (3x compare/pixel
  186908. compared to doing composite with gray bkgrnd)
  186909. - Gray + alpha -> convert to RGB + alpha, composite with background and
  186910. remove alpha bytes (3x float operations/pixel
  186911. compared with composite on gray background)
  186912. Greg's change will do this. The reason it wasn't done before is for
  186913. performance, as this increases the per-pixel operations. If we would check
  186914. in advance if the background was gray or RGB, and position the gray-to-RGB
  186915. transform appropriately, then it would save a lot of work/time.
  186916. */
  186917. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186918. /* if gray -> RGB, do so now only if background is non-gray; else do later
  186919. * for performance reasons */
  186920. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186921. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186922. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186923. #endif
  186924. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186925. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186926. ((png_ptr->num_trans != 0 ) ||
  186927. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  186928. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186929. &(png_ptr->trans_values), &(png_ptr->background)
  186930. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186931. , &(png_ptr->background_1),
  186932. png_ptr->gamma_table, png_ptr->gamma_from_1,
  186933. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  186934. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  186935. png_ptr->gamma_shift
  186936. #endif
  186937. );
  186938. #endif
  186939. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186940. if ((png_ptr->transformations & PNG_GAMMA) &&
  186941. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186942. !((png_ptr->transformations & PNG_BACKGROUND) &&
  186943. ((png_ptr->num_trans != 0) ||
  186944. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  186945. #endif
  186946. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  186947. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186948. png_ptr->gamma_table, png_ptr->gamma_16_table,
  186949. png_ptr->gamma_shift);
  186950. #endif
  186951. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186952. if (png_ptr->transformations & PNG_16_TO_8)
  186953. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186954. #endif
  186955. #if defined(PNG_READ_DITHER_SUPPORTED)
  186956. if (png_ptr->transformations & PNG_DITHER)
  186957. {
  186958. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  186959. png_ptr->palette_lookup, png_ptr->dither_index);
  186960. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  186961. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  186962. }
  186963. #endif
  186964. #if defined(PNG_READ_INVERT_SUPPORTED)
  186965. if (png_ptr->transformations & PNG_INVERT_MONO)
  186966. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186967. #endif
  186968. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186969. if (png_ptr->transformations & PNG_SHIFT)
  186970. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186971. &(png_ptr->shift));
  186972. #endif
  186973. #if defined(PNG_READ_PACK_SUPPORTED)
  186974. if (png_ptr->transformations & PNG_PACK)
  186975. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186976. #endif
  186977. #if defined(PNG_READ_BGR_SUPPORTED)
  186978. if (png_ptr->transformations & PNG_BGR)
  186979. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186980. #endif
  186981. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  186982. if (png_ptr->transformations & PNG_PACKSWAP)
  186983. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186984. #endif
  186985. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186986. /* if gray -> RGB, do so now only if we did not do so above */
  186987. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186988. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186989. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186990. #endif
  186991. #if defined(PNG_READ_FILLER_SUPPORTED)
  186992. if (png_ptr->transformations & PNG_FILLER)
  186993. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186994. (png_uint_32)png_ptr->filler, png_ptr->flags);
  186995. #endif
  186996. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186997. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186998. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186999. #endif
  187000. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187001. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  187002. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187003. #endif
  187004. #if defined(PNG_READ_SWAP_SUPPORTED)
  187005. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187006. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187007. #endif
  187008. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  187009. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  187010. {
  187011. if(png_ptr->read_user_transform_fn != NULL)
  187012. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  187013. (png_ptr, /* png_ptr */
  187014. &(png_ptr->row_info), /* row_info: */
  187015. /* png_uint_32 width; width of row */
  187016. /* png_uint_32 rowbytes; number of bytes in row */
  187017. /* png_byte color_type; color type of pixels */
  187018. /* png_byte bit_depth; bit depth of samples */
  187019. /* png_byte channels; number of channels (1-4) */
  187020. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  187021. png_ptr->row_buf + 1); /* start of pixel data for row */
  187022. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  187023. if(png_ptr->user_transform_depth)
  187024. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  187025. if(png_ptr->user_transform_channels)
  187026. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  187027. #endif
  187028. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  187029. png_ptr->row_info.channels);
  187030. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187031. png_ptr->row_info.width);
  187032. }
  187033. #endif
  187034. }
  187035. #if defined(PNG_READ_PACK_SUPPORTED)
  187036. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  187037. * without changing the actual values. Thus, if you had a row with
  187038. * a bit depth of 1, you would end up with bytes that only contained
  187039. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  187040. * png_do_shift() after this.
  187041. */
  187042. void /* PRIVATE */
  187043. png_do_unpack(png_row_infop row_info, png_bytep row)
  187044. {
  187045. png_debug(1, "in png_do_unpack\n");
  187046. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187047. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  187048. #else
  187049. if (row_info->bit_depth < 8)
  187050. #endif
  187051. {
  187052. png_uint_32 i;
  187053. png_uint_32 row_width=row_info->width;
  187054. switch (row_info->bit_depth)
  187055. {
  187056. case 1:
  187057. {
  187058. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  187059. png_bytep dp = row + (png_size_t)row_width - 1;
  187060. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  187061. for (i = 0; i < row_width; i++)
  187062. {
  187063. *dp = (png_byte)((*sp >> shift) & 0x01);
  187064. if (shift == 7)
  187065. {
  187066. shift = 0;
  187067. sp--;
  187068. }
  187069. else
  187070. shift++;
  187071. dp--;
  187072. }
  187073. break;
  187074. }
  187075. case 2:
  187076. {
  187077. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  187078. png_bytep dp = row + (png_size_t)row_width - 1;
  187079. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187080. for (i = 0; i < row_width; i++)
  187081. {
  187082. *dp = (png_byte)((*sp >> shift) & 0x03);
  187083. if (shift == 6)
  187084. {
  187085. shift = 0;
  187086. sp--;
  187087. }
  187088. else
  187089. shift += 2;
  187090. dp--;
  187091. }
  187092. break;
  187093. }
  187094. case 4:
  187095. {
  187096. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  187097. png_bytep dp = row + (png_size_t)row_width - 1;
  187098. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  187099. for (i = 0; i < row_width; i++)
  187100. {
  187101. *dp = (png_byte)((*sp >> shift) & 0x0f);
  187102. if (shift == 4)
  187103. {
  187104. shift = 0;
  187105. sp--;
  187106. }
  187107. else
  187108. shift = 4;
  187109. dp--;
  187110. }
  187111. break;
  187112. }
  187113. }
  187114. row_info->bit_depth = 8;
  187115. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187116. row_info->rowbytes = row_width * row_info->channels;
  187117. }
  187118. }
  187119. #endif
  187120. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187121. /* Reverse the effects of png_do_shift. This routine merely shifts the
  187122. * pixels back to their significant bits values. Thus, if you have
  187123. * a row of bit depth 8, but only 5 are significant, this will shift
  187124. * the values back to 0 through 31.
  187125. */
  187126. void /* PRIVATE */
  187127. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  187128. {
  187129. png_debug(1, "in png_do_unshift\n");
  187130. if (
  187131. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187132. row != NULL && row_info != NULL && sig_bits != NULL &&
  187133. #endif
  187134. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  187135. {
  187136. int shift[4];
  187137. int channels = 0;
  187138. int c;
  187139. png_uint_16 value = 0;
  187140. png_uint_32 row_width = row_info->width;
  187141. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  187142. {
  187143. shift[channels++] = row_info->bit_depth - sig_bits->red;
  187144. shift[channels++] = row_info->bit_depth - sig_bits->green;
  187145. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  187146. }
  187147. else
  187148. {
  187149. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  187150. }
  187151. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187152. {
  187153. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  187154. }
  187155. for (c = 0; c < channels; c++)
  187156. {
  187157. if (shift[c] <= 0)
  187158. shift[c] = 0;
  187159. else
  187160. value = 1;
  187161. }
  187162. if (!value)
  187163. return;
  187164. switch (row_info->bit_depth)
  187165. {
  187166. case 2:
  187167. {
  187168. png_bytep bp;
  187169. png_uint_32 i;
  187170. png_uint_32 istop = row_info->rowbytes;
  187171. for (bp = row, i = 0; i < istop; i++)
  187172. {
  187173. *bp >>= 1;
  187174. *bp++ &= 0x55;
  187175. }
  187176. break;
  187177. }
  187178. case 4:
  187179. {
  187180. png_bytep bp = row;
  187181. png_uint_32 i;
  187182. png_uint_32 istop = row_info->rowbytes;
  187183. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  187184. (png_byte)((int)0xf >> shift[0]));
  187185. for (i = 0; i < istop; i++)
  187186. {
  187187. *bp >>= shift[0];
  187188. *bp++ &= mask;
  187189. }
  187190. break;
  187191. }
  187192. case 8:
  187193. {
  187194. png_bytep bp = row;
  187195. png_uint_32 i;
  187196. png_uint_32 istop = row_width * channels;
  187197. for (i = 0; i < istop; i++)
  187198. {
  187199. *bp++ >>= shift[i%channels];
  187200. }
  187201. break;
  187202. }
  187203. case 16:
  187204. {
  187205. png_bytep bp = row;
  187206. png_uint_32 i;
  187207. png_uint_32 istop = channels * row_width;
  187208. for (i = 0; i < istop; i++)
  187209. {
  187210. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  187211. value >>= shift[i%channels];
  187212. *bp++ = (png_byte)(value >> 8);
  187213. *bp++ = (png_byte)(value & 0xff);
  187214. }
  187215. break;
  187216. }
  187217. }
  187218. }
  187219. }
  187220. #endif
  187221. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187222. /* chop rows of bit depth 16 down to 8 */
  187223. void /* PRIVATE */
  187224. png_do_chop(png_row_infop row_info, png_bytep row)
  187225. {
  187226. png_debug(1, "in png_do_chop\n");
  187227. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187228. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  187229. #else
  187230. if (row_info->bit_depth == 16)
  187231. #endif
  187232. {
  187233. png_bytep sp = row;
  187234. png_bytep dp = row;
  187235. png_uint_32 i;
  187236. png_uint_32 istop = row_info->width * row_info->channels;
  187237. for (i = 0; i<istop; i++, sp += 2, dp++)
  187238. {
  187239. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  187240. /* This does a more accurate scaling of the 16-bit color
  187241. * value, rather than a simple low-byte truncation.
  187242. *
  187243. * What the ideal calculation should be:
  187244. * *dp = (((((png_uint_32)(*sp) << 8) |
  187245. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  187246. *
  187247. * GRR: no, I think this is what it really should be:
  187248. * *dp = (((((png_uint_32)(*sp) << 8) |
  187249. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  187250. *
  187251. * GRR: here's the exact calculation with shifts:
  187252. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  187253. * *dp = (temp - (temp >> 8)) >> 8;
  187254. *
  187255. * Approximate calculation with shift/add instead of multiply/divide:
  187256. * *dp = ((((png_uint_32)(*sp) << 8) |
  187257. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  187258. *
  187259. * What we actually do to avoid extra shifting and conversion:
  187260. */
  187261. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  187262. #else
  187263. /* Simply discard the low order byte */
  187264. *dp = *sp;
  187265. #endif
  187266. }
  187267. row_info->bit_depth = 8;
  187268. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187269. row_info->rowbytes = row_info->width * row_info->channels;
  187270. }
  187271. }
  187272. #endif
  187273. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187274. void /* PRIVATE */
  187275. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  187276. {
  187277. png_debug(1, "in png_do_read_swap_alpha\n");
  187278. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187279. if (row != NULL && row_info != NULL)
  187280. #endif
  187281. {
  187282. png_uint_32 row_width = row_info->width;
  187283. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187284. {
  187285. /* This converts from RGBA to ARGB */
  187286. if (row_info->bit_depth == 8)
  187287. {
  187288. png_bytep sp = row + row_info->rowbytes;
  187289. png_bytep dp = sp;
  187290. png_byte save;
  187291. png_uint_32 i;
  187292. for (i = 0; i < row_width; i++)
  187293. {
  187294. save = *(--sp);
  187295. *(--dp) = *(--sp);
  187296. *(--dp) = *(--sp);
  187297. *(--dp) = *(--sp);
  187298. *(--dp) = save;
  187299. }
  187300. }
  187301. /* This converts from RRGGBBAA to AARRGGBB */
  187302. else
  187303. {
  187304. png_bytep sp = row + row_info->rowbytes;
  187305. png_bytep dp = sp;
  187306. png_byte save[2];
  187307. png_uint_32 i;
  187308. for (i = 0; i < row_width; i++)
  187309. {
  187310. save[0] = *(--sp);
  187311. save[1] = *(--sp);
  187312. *(--dp) = *(--sp);
  187313. *(--dp) = *(--sp);
  187314. *(--dp) = *(--sp);
  187315. *(--dp) = *(--sp);
  187316. *(--dp) = *(--sp);
  187317. *(--dp) = *(--sp);
  187318. *(--dp) = save[0];
  187319. *(--dp) = save[1];
  187320. }
  187321. }
  187322. }
  187323. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187324. {
  187325. /* This converts from GA to AG */
  187326. if (row_info->bit_depth == 8)
  187327. {
  187328. png_bytep sp = row + row_info->rowbytes;
  187329. png_bytep dp = sp;
  187330. png_byte save;
  187331. png_uint_32 i;
  187332. for (i = 0; i < row_width; i++)
  187333. {
  187334. save = *(--sp);
  187335. *(--dp) = *(--sp);
  187336. *(--dp) = save;
  187337. }
  187338. }
  187339. /* This converts from GGAA to AAGG */
  187340. else
  187341. {
  187342. png_bytep sp = row + row_info->rowbytes;
  187343. png_bytep dp = sp;
  187344. png_byte save[2];
  187345. png_uint_32 i;
  187346. for (i = 0; i < row_width; i++)
  187347. {
  187348. save[0] = *(--sp);
  187349. save[1] = *(--sp);
  187350. *(--dp) = *(--sp);
  187351. *(--dp) = *(--sp);
  187352. *(--dp) = save[0];
  187353. *(--dp) = save[1];
  187354. }
  187355. }
  187356. }
  187357. }
  187358. }
  187359. #endif
  187360. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187361. void /* PRIVATE */
  187362. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  187363. {
  187364. png_debug(1, "in png_do_read_invert_alpha\n");
  187365. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187366. if (row != NULL && row_info != NULL)
  187367. #endif
  187368. {
  187369. png_uint_32 row_width = row_info->width;
  187370. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187371. {
  187372. /* This inverts the alpha channel in RGBA */
  187373. if (row_info->bit_depth == 8)
  187374. {
  187375. png_bytep sp = row + row_info->rowbytes;
  187376. png_bytep dp = sp;
  187377. png_uint_32 i;
  187378. for (i = 0; i < row_width; i++)
  187379. {
  187380. *(--dp) = (png_byte)(255 - *(--sp));
  187381. /* This does nothing:
  187382. *(--dp) = *(--sp);
  187383. *(--dp) = *(--sp);
  187384. *(--dp) = *(--sp);
  187385. We can replace it with:
  187386. */
  187387. sp-=3;
  187388. dp=sp;
  187389. }
  187390. }
  187391. /* This inverts the alpha channel in RRGGBBAA */
  187392. else
  187393. {
  187394. png_bytep sp = row + row_info->rowbytes;
  187395. png_bytep dp = sp;
  187396. png_uint_32 i;
  187397. for (i = 0; i < row_width; i++)
  187398. {
  187399. *(--dp) = (png_byte)(255 - *(--sp));
  187400. *(--dp) = (png_byte)(255 - *(--sp));
  187401. /* This does nothing:
  187402. *(--dp) = *(--sp);
  187403. *(--dp) = *(--sp);
  187404. *(--dp) = *(--sp);
  187405. *(--dp) = *(--sp);
  187406. *(--dp) = *(--sp);
  187407. *(--dp) = *(--sp);
  187408. We can replace it with:
  187409. */
  187410. sp-=6;
  187411. dp=sp;
  187412. }
  187413. }
  187414. }
  187415. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187416. {
  187417. /* This inverts the alpha channel in GA */
  187418. if (row_info->bit_depth == 8)
  187419. {
  187420. png_bytep sp = row + row_info->rowbytes;
  187421. png_bytep dp = sp;
  187422. png_uint_32 i;
  187423. for (i = 0; i < row_width; i++)
  187424. {
  187425. *(--dp) = (png_byte)(255 - *(--sp));
  187426. *(--dp) = *(--sp);
  187427. }
  187428. }
  187429. /* This inverts the alpha channel in GGAA */
  187430. else
  187431. {
  187432. png_bytep sp = row + row_info->rowbytes;
  187433. png_bytep dp = sp;
  187434. png_uint_32 i;
  187435. for (i = 0; i < row_width; i++)
  187436. {
  187437. *(--dp) = (png_byte)(255 - *(--sp));
  187438. *(--dp) = (png_byte)(255 - *(--sp));
  187439. /*
  187440. *(--dp) = *(--sp);
  187441. *(--dp) = *(--sp);
  187442. */
  187443. sp-=2;
  187444. dp=sp;
  187445. }
  187446. }
  187447. }
  187448. }
  187449. }
  187450. #endif
  187451. #if defined(PNG_READ_FILLER_SUPPORTED)
  187452. /* Add filler channel if we have RGB color */
  187453. void /* PRIVATE */
  187454. png_do_read_filler(png_row_infop row_info, png_bytep row,
  187455. png_uint_32 filler, png_uint_32 flags)
  187456. {
  187457. png_uint_32 i;
  187458. png_uint_32 row_width = row_info->width;
  187459. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  187460. png_byte lo_filler = (png_byte)(filler & 0xff);
  187461. png_debug(1, "in png_do_read_filler\n");
  187462. if (
  187463. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187464. row != NULL && row_info != NULL &&
  187465. #endif
  187466. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187467. {
  187468. if(row_info->bit_depth == 8)
  187469. {
  187470. /* This changes the data from G to GX */
  187471. if (flags & PNG_FLAG_FILLER_AFTER)
  187472. {
  187473. png_bytep sp = row + (png_size_t)row_width;
  187474. png_bytep dp = sp + (png_size_t)row_width;
  187475. for (i = 1; i < row_width; i++)
  187476. {
  187477. *(--dp) = lo_filler;
  187478. *(--dp) = *(--sp);
  187479. }
  187480. *(--dp) = lo_filler;
  187481. row_info->channels = 2;
  187482. row_info->pixel_depth = 16;
  187483. row_info->rowbytes = row_width * 2;
  187484. }
  187485. /* This changes the data from G to XG */
  187486. else
  187487. {
  187488. png_bytep sp = row + (png_size_t)row_width;
  187489. png_bytep dp = sp + (png_size_t)row_width;
  187490. for (i = 0; i < row_width; i++)
  187491. {
  187492. *(--dp) = *(--sp);
  187493. *(--dp) = lo_filler;
  187494. }
  187495. row_info->channels = 2;
  187496. row_info->pixel_depth = 16;
  187497. row_info->rowbytes = row_width * 2;
  187498. }
  187499. }
  187500. else if(row_info->bit_depth == 16)
  187501. {
  187502. /* This changes the data from GG to GGXX */
  187503. if (flags & PNG_FLAG_FILLER_AFTER)
  187504. {
  187505. png_bytep sp = row + (png_size_t)row_width * 2;
  187506. png_bytep dp = sp + (png_size_t)row_width * 2;
  187507. for (i = 1; i < row_width; i++)
  187508. {
  187509. *(--dp) = hi_filler;
  187510. *(--dp) = lo_filler;
  187511. *(--dp) = *(--sp);
  187512. *(--dp) = *(--sp);
  187513. }
  187514. *(--dp) = hi_filler;
  187515. *(--dp) = lo_filler;
  187516. row_info->channels = 2;
  187517. row_info->pixel_depth = 32;
  187518. row_info->rowbytes = row_width * 4;
  187519. }
  187520. /* This changes the data from GG to XXGG */
  187521. else
  187522. {
  187523. png_bytep sp = row + (png_size_t)row_width * 2;
  187524. png_bytep dp = sp + (png_size_t)row_width * 2;
  187525. for (i = 0; i < row_width; i++)
  187526. {
  187527. *(--dp) = *(--sp);
  187528. *(--dp) = *(--sp);
  187529. *(--dp) = hi_filler;
  187530. *(--dp) = lo_filler;
  187531. }
  187532. row_info->channels = 2;
  187533. row_info->pixel_depth = 32;
  187534. row_info->rowbytes = row_width * 4;
  187535. }
  187536. }
  187537. } /* COLOR_TYPE == GRAY */
  187538. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187539. {
  187540. if(row_info->bit_depth == 8)
  187541. {
  187542. /* This changes the data from RGB to RGBX */
  187543. if (flags & PNG_FLAG_FILLER_AFTER)
  187544. {
  187545. png_bytep sp = row + (png_size_t)row_width * 3;
  187546. png_bytep dp = sp + (png_size_t)row_width;
  187547. for (i = 1; i < row_width; i++)
  187548. {
  187549. *(--dp) = lo_filler;
  187550. *(--dp) = *(--sp);
  187551. *(--dp) = *(--sp);
  187552. *(--dp) = *(--sp);
  187553. }
  187554. *(--dp) = lo_filler;
  187555. row_info->channels = 4;
  187556. row_info->pixel_depth = 32;
  187557. row_info->rowbytes = row_width * 4;
  187558. }
  187559. /* This changes the data from RGB to XRGB */
  187560. else
  187561. {
  187562. png_bytep sp = row + (png_size_t)row_width * 3;
  187563. png_bytep dp = sp + (png_size_t)row_width;
  187564. for (i = 0; i < row_width; i++)
  187565. {
  187566. *(--dp) = *(--sp);
  187567. *(--dp) = *(--sp);
  187568. *(--dp) = *(--sp);
  187569. *(--dp) = lo_filler;
  187570. }
  187571. row_info->channels = 4;
  187572. row_info->pixel_depth = 32;
  187573. row_info->rowbytes = row_width * 4;
  187574. }
  187575. }
  187576. else if(row_info->bit_depth == 16)
  187577. {
  187578. /* This changes the data from RRGGBB to RRGGBBXX */
  187579. if (flags & PNG_FLAG_FILLER_AFTER)
  187580. {
  187581. png_bytep sp = row + (png_size_t)row_width * 6;
  187582. png_bytep dp = sp + (png_size_t)row_width * 2;
  187583. for (i = 1; i < row_width; i++)
  187584. {
  187585. *(--dp) = hi_filler;
  187586. *(--dp) = lo_filler;
  187587. *(--dp) = *(--sp);
  187588. *(--dp) = *(--sp);
  187589. *(--dp) = *(--sp);
  187590. *(--dp) = *(--sp);
  187591. *(--dp) = *(--sp);
  187592. *(--dp) = *(--sp);
  187593. }
  187594. *(--dp) = hi_filler;
  187595. *(--dp) = lo_filler;
  187596. row_info->channels = 4;
  187597. row_info->pixel_depth = 64;
  187598. row_info->rowbytes = row_width * 8;
  187599. }
  187600. /* This changes the data from RRGGBB to XXRRGGBB */
  187601. else
  187602. {
  187603. png_bytep sp = row + (png_size_t)row_width * 6;
  187604. png_bytep dp = sp + (png_size_t)row_width * 2;
  187605. for (i = 0; i < row_width; i++)
  187606. {
  187607. *(--dp) = *(--sp);
  187608. *(--dp) = *(--sp);
  187609. *(--dp) = *(--sp);
  187610. *(--dp) = *(--sp);
  187611. *(--dp) = *(--sp);
  187612. *(--dp) = *(--sp);
  187613. *(--dp) = hi_filler;
  187614. *(--dp) = lo_filler;
  187615. }
  187616. row_info->channels = 4;
  187617. row_info->pixel_depth = 64;
  187618. row_info->rowbytes = row_width * 8;
  187619. }
  187620. }
  187621. } /* COLOR_TYPE == RGB */
  187622. }
  187623. #endif
  187624. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187625. /* expand grayscale files to RGB, with or without alpha */
  187626. void /* PRIVATE */
  187627. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  187628. {
  187629. png_uint_32 i;
  187630. png_uint_32 row_width = row_info->width;
  187631. png_debug(1, "in png_do_gray_to_rgb\n");
  187632. if (row_info->bit_depth >= 8 &&
  187633. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187634. row != NULL && row_info != NULL &&
  187635. #endif
  187636. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  187637. {
  187638. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187639. {
  187640. if (row_info->bit_depth == 8)
  187641. {
  187642. png_bytep sp = row + (png_size_t)row_width - 1;
  187643. png_bytep dp = sp + (png_size_t)row_width * 2;
  187644. for (i = 0; i < row_width; i++)
  187645. {
  187646. *(dp--) = *sp;
  187647. *(dp--) = *sp;
  187648. *(dp--) = *(sp--);
  187649. }
  187650. }
  187651. else
  187652. {
  187653. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187654. png_bytep dp = sp + (png_size_t)row_width * 4;
  187655. for (i = 0; i < row_width; i++)
  187656. {
  187657. *(dp--) = *sp;
  187658. *(dp--) = *(sp - 1);
  187659. *(dp--) = *sp;
  187660. *(dp--) = *(sp - 1);
  187661. *(dp--) = *(sp--);
  187662. *(dp--) = *(sp--);
  187663. }
  187664. }
  187665. }
  187666. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187667. {
  187668. if (row_info->bit_depth == 8)
  187669. {
  187670. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187671. png_bytep dp = sp + (png_size_t)row_width * 2;
  187672. for (i = 0; i < row_width; i++)
  187673. {
  187674. *(dp--) = *(sp--);
  187675. *(dp--) = *sp;
  187676. *(dp--) = *sp;
  187677. *(dp--) = *(sp--);
  187678. }
  187679. }
  187680. else
  187681. {
  187682. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  187683. png_bytep dp = sp + (png_size_t)row_width * 4;
  187684. for (i = 0; i < row_width; i++)
  187685. {
  187686. *(dp--) = *(sp--);
  187687. *(dp--) = *(sp--);
  187688. *(dp--) = *sp;
  187689. *(dp--) = *(sp - 1);
  187690. *(dp--) = *sp;
  187691. *(dp--) = *(sp - 1);
  187692. *(dp--) = *(sp--);
  187693. *(dp--) = *(sp--);
  187694. }
  187695. }
  187696. }
  187697. row_info->channels += (png_byte)2;
  187698. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  187699. row_info->pixel_depth = (png_byte)(row_info->channels *
  187700. row_info->bit_depth);
  187701. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187702. }
  187703. }
  187704. #endif
  187705. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187706. /* reduce RGB files to grayscale, with or without alpha
  187707. * using the equation given in Poynton's ColorFAQ at
  187708. * <http://www.inforamp.net/~poynton/>
  187709. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  187710. *
  187711. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  187712. *
  187713. * We approximate this with
  187714. *
  187715. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  187716. *
  187717. * which can be expressed with integers as
  187718. *
  187719. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  187720. *
  187721. * The calculation is to be done in a linear colorspace.
  187722. *
  187723. * Other integer coefficents can be used via png_set_rgb_to_gray().
  187724. */
  187725. int /* PRIVATE */
  187726. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  187727. {
  187728. png_uint_32 i;
  187729. png_uint_32 row_width = row_info->width;
  187730. int rgb_error = 0;
  187731. png_debug(1, "in png_do_rgb_to_gray\n");
  187732. if (
  187733. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187734. row != NULL && row_info != NULL &&
  187735. #endif
  187736. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187737. {
  187738. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  187739. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  187740. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  187741. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187742. {
  187743. if (row_info->bit_depth == 8)
  187744. {
  187745. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187746. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187747. {
  187748. png_bytep sp = row;
  187749. png_bytep dp = row;
  187750. for (i = 0; i < row_width; i++)
  187751. {
  187752. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187753. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187754. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187755. if(red != green || red != blue)
  187756. {
  187757. rgb_error |= 1;
  187758. *(dp++) = png_ptr->gamma_from_1[
  187759. (rc*red+gc*green+bc*blue)>>15];
  187760. }
  187761. else
  187762. *(dp++) = *(sp-1);
  187763. }
  187764. }
  187765. else
  187766. #endif
  187767. {
  187768. png_bytep sp = row;
  187769. png_bytep dp = row;
  187770. for (i = 0; i < row_width; i++)
  187771. {
  187772. png_byte red = *(sp++);
  187773. png_byte green = *(sp++);
  187774. png_byte blue = *(sp++);
  187775. if(red != green || red != blue)
  187776. {
  187777. rgb_error |= 1;
  187778. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  187779. }
  187780. else
  187781. *(dp++) = *(sp-1);
  187782. }
  187783. }
  187784. }
  187785. else /* RGB bit_depth == 16 */
  187786. {
  187787. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187788. if (png_ptr->gamma_16_to_1 != NULL &&
  187789. png_ptr->gamma_16_from_1 != NULL)
  187790. {
  187791. png_bytep sp = row;
  187792. png_bytep dp = row;
  187793. for (i = 0; i < row_width; i++)
  187794. {
  187795. png_uint_16 red, green, blue, w;
  187796. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187797. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187798. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187799. if(red == green && red == blue)
  187800. w = red;
  187801. else
  187802. {
  187803. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187804. png_ptr->gamma_shift][red>>8];
  187805. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187806. png_ptr->gamma_shift][green>>8];
  187807. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187808. png_ptr->gamma_shift][blue>>8];
  187809. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  187810. + bc*blue_1)>>15);
  187811. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187812. png_ptr->gamma_shift][gray16 >> 8];
  187813. rgb_error |= 1;
  187814. }
  187815. *(dp++) = (png_byte)((w>>8) & 0xff);
  187816. *(dp++) = (png_byte)(w & 0xff);
  187817. }
  187818. }
  187819. else
  187820. #endif
  187821. {
  187822. png_bytep sp = row;
  187823. png_bytep dp = row;
  187824. for (i = 0; i < row_width; i++)
  187825. {
  187826. png_uint_16 red, green, blue, gray16;
  187827. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187828. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187829. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187830. if(red != green || red != blue)
  187831. rgb_error |= 1;
  187832. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187833. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187834. *(dp++) = (png_byte)(gray16 & 0xff);
  187835. }
  187836. }
  187837. }
  187838. }
  187839. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187840. {
  187841. if (row_info->bit_depth == 8)
  187842. {
  187843. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187844. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187845. {
  187846. png_bytep sp = row;
  187847. png_bytep dp = row;
  187848. for (i = 0; i < row_width; i++)
  187849. {
  187850. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187851. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187852. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187853. if(red != green || red != blue)
  187854. rgb_error |= 1;
  187855. *(dp++) = png_ptr->gamma_from_1
  187856. [(rc*red + gc*green + bc*blue)>>15];
  187857. *(dp++) = *(sp++); /* alpha */
  187858. }
  187859. }
  187860. else
  187861. #endif
  187862. {
  187863. png_bytep sp = row;
  187864. png_bytep dp = row;
  187865. for (i = 0; i < row_width; i++)
  187866. {
  187867. png_byte red = *(sp++);
  187868. png_byte green = *(sp++);
  187869. png_byte blue = *(sp++);
  187870. if(red != green || red != blue)
  187871. rgb_error |= 1;
  187872. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  187873. *(dp++) = *(sp++); /* alpha */
  187874. }
  187875. }
  187876. }
  187877. else /* RGBA bit_depth == 16 */
  187878. {
  187879. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187880. if (png_ptr->gamma_16_to_1 != NULL &&
  187881. png_ptr->gamma_16_from_1 != NULL)
  187882. {
  187883. png_bytep sp = row;
  187884. png_bytep dp = row;
  187885. for (i = 0; i < row_width; i++)
  187886. {
  187887. png_uint_16 red, green, blue, w;
  187888. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187889. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187890. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187891. if(red == green && red == blue)
  187892. w = red;
  187893. else
  187894. {
  187895. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187896. png_ptr->gamma_shift][red>>8];
  187897. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187898. png_ptr->gamma_shift][green>>8];
  187899. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187900. png_ptr->gamma_shift][blue>>8];
  187901. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  187902. + gc * green_1 + bc * blue_1)>>15);
  187903. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187904. png_ptr->gamma_shift][gray16 >> 8];
  187905. rgb_error |= 1;
  187906. }
  187907. *(dp++) = (png_byte)((w>>8) & 0xff);
  187908. *(dp++) = (png_byte)(w & 0xff);
  187909. *(dp++) = *(sp++); /* alpha */
  187910. *(dp++) = *(sp++);
  187911. }
  187912. }
  187913. else
  187914. #endif
  187915. {
  187916. png_bytep sp = row;
  187917. png_bytep dp = row;
  187918. for (i = 0; i < row_width; i++)
  187919. {
  187920. png_uint_16 red, green, blue, gray16;
  187921. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187922. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187923. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187924. if(red != green || red != blue)
  187925. rgb_error |= 1;
  187926. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187927. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187928. *(dp++) = (png_byte)(gray16 & 0xff);
  187929. *(dp++) = *(sp++); /* alpha */
  187930. *(dp++) = *(sp++);
  187931. }
  187932. }
  187933. }
  187934. }
  187935. row_info->channels -= (png_byte)2;
  187936. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  187937. row_info->pixel_depth = (png_byte)(row_info->channels *
  187938. row_info->bit_depth);
  187939. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187940. }
  187941. return rgb_error;
  187942. }
  187943. #endif
  187944. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  187945. * large of png_color. This lets grayscale images be treated as
  187946. * paletted. Most useful for gamma correction and simplification
  187947. * of code.
  187948. */
  187949. void PNGAPI
  187950. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  187951. {
  187952. int num_palette;
  187953. int color_inc;
  187954. int i;
  187955. int v;
  187956. png_debug(1, "in png_do_build_grayscale_palette\n");
  187957. if (palette == NULL)
  187958. return;
  187959. switch (bit_depth)
  187960. {
  187961. case 1:
  187962. num_palette = 2;
  187963. color_inc = 0xff;
  187964. break;
  187965. case 2:
  187966. num_palette = 4;
  187967. color_inc = 0x55;
  187968. break;
  187969. case 4:
  187970. num_palette = 16;
  187971. color_inc = 0x11;
  187972. break;
  187973. case 8:
  187974. num_palette = 256;
  187975. color_inc = 1;
  187976. break;
  187977. default:
  187978. num_palette = 0;
  187979. color_inc = 0;
  187980. break;
  187981. }
  187982. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  187983. {
  187984. palette[i].red = (png_byte)v;
  187985. palette[i].green = (png_byte)v;
  187986. palette[i].blue = (png_byte)v;
  187987. }
  187988. }
  187989. /* This function is currently unused. Do we really need it? */
  187990. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  187991. void /* PRIVATE */
  187992. png_correct_palette(png_structp png_ptr, png_colorp palette,
  187993. int num_palette)
  187994. {
  187995. png_debug(1, "in png_correct_palette\n");
  187996. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187997. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187998. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  187999. {
  188000. png_color back, back_1;
  188001. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  188002. {
  188003. back.red = png_ptr->gamma_table[png_ptr->background.red];
  188004. back.green = png_ptr->gamma_table[png_ptr->background.green];
  188005. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  188006. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  188007. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  188008. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  188009. }
  188010. else
  188011. {
  188012. double g;
  188013. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  188014. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  188015. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  188016. {
  188017. back.red = png_ptr->background.red;
  188018. back.green = png_ptr->background.green;
  188019. back.blue = png_ptr->background.blue;
  188020. }
  188021. else
  188022. {
  188023. back.red =
  188024. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  188025. 255.0 + 0.5);
  188026. back.green =
  188027. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  188028. 255.0 + 0.5);
  188029. back.blue =
  188030. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  188031. 255.0 + 0.5);
  188032. }
  188033. g = 1.0 / png_ptr->background_gamma;
  188034. back_1.red =
  188035. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  188036. 255.0 + 0.5);
  188037. back_1.green =
  188038. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  188039. 255.0 + 0.5);
  188040. back_1.blue =
  188041. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  188042. 255.0 + 0.5);
  188043. }
  188044. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188045. {
  188046. png_uint_32 i;
  188047. for (i = 0; i < (png_uint_32)num_palette; i++)
  188048. {
  188049. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  188050. {
  188051. palette[i] = back;
  188052. }
  188053. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  188054. {
  188055. png_byte v, w;
  188056. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  188057. png_composite(w, v, png_ptr->trans[i], back_1.red);
  188058. palette[i].red = png_ptr->gamma_from_1[w];
  188059. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  188060. png_composite(w, v, png_ptr->trans[i], back_1.green);
  188061. palette[i].green = png_ptr->gamma_from_1[w];
  188062. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  188063. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  188064. palette[i].blue = png_ptr->gamma_from_1[w];
  188065. }
  188066. else
  188067. {
  188068. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188069. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188070. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188071. }
  188072. }
  188073. }
  188074. else
  188075. {
  188076. int i;
  188077. for (i = 0; i < num_palette; i++)
  188078. {
  188079. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  188080. {
  188081. palette[i] = back;
  188082. }
  188083. else
  188084. {
  188085. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188086. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188087. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188088. }
  188089. }
  188090. }
  188091. }
  188092. else
  188093. #endif
  188094. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188095. if (png_ptr->transformations & PNG_GAMMA)
  188096. {
  188097. int i;
  188098. for (i = 0; i < num_palette; i++)
  188099. {
  188100. palette[i].red = png_ptr->gamma_table[palette[i].red];
  188101. palette[i].green = png_ptr->gamma_table[palette[i].green];
  188102. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  188103. }
  188104. }
  188105. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188106. else
  188107. #endif
  188108. #endif
  188109. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188110. if (png_ptr->transformations & PNG_BACKGROUND)
  188111. {
  188112. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188113. {
  188114. png_color back;
  188115. back.red = (png_byte)png_ptr->background.red;
  188116. back.green = (png_byte)png_ptr->background.green;
  188117. back.blue = (png_byte)png_ptr->background.blue;
  188118. for (i = 0; i < (int)png_ptr->num_trans; i++)
  188119. {
  188120. if (png_ptr->trans[i] == 0)
  188121. {
  188122. palette[i].red = back.red;
  188123. palette[i].green = back.green;
  188124. palette[i].blue = back.blue;
  188125. }
  188126. else if (png_ptr->trans[i] != 0xff)
  188127. {
  188128. png_composite(palette[i].red, png_ptr->palette[i].red,
  188129. png_ptr->trans[i], back.red);
  188130. png_composite(palette[i].green, png_ptr->palette[i].green,
  188131. png_ptr->trans[i], back.green);
  188132. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  188133. png_ptr->trans[i], back.blue);
  188134. }
  188135. }
  188136. }
  188137. else /* assume grayscale palette (what else could it be?) */
  188138. {
  188139. int i;
  188140. for (i = 0; i < num_palette; i++)
  188141. {
  188142. if (i == (png_byte)png_ptr->trans_values.gray)
  188143. {
  188144. palette[i].red = (png_byte)png_ptr->background.red;
  188145. palette[i].green = (png_byte)png_ptr->background.green;
  188146. palette[i].blue = (png_byte)png_ptr->background.blue;
  188147. }
  188148. }
  188149. }
  188150. }
  188151. #endif
  188152. }
  188153. #endif
  188154. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188155. /* Replace any alpha or transparency with the supplied background color.
  188156. * "background" is already in the screen gamma, while "background_1" is
  188157. * at a gamma of 1.0. Paletted files have already been taken care of.
  188158. */
  188159. void /* PRIVATE */
  188160. png_do_background(png_row_infop row_info, png_bytep row,
  188161. png_color_16p trans_values, png_color_16p background
  188162. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188163. , png_color_16p background_1,
  188164. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  188165. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  188166. png_uint_16pp gamma_16_to_1, int gamma_shift
  188167. #endif
  188168. )
  188169. {
  188170. png_bytep sp, dp;
  188171. png_uint_32 i;
  188172. png_uint_32 row_width=row_info->width;
  188173. int shift;
  188174. png_debug(1, "in png_do_background\n");
  188175. if (background != NULL &&
  188176. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188177. row != NULL && row_info != NULL &&
  188178. #endif
  188179. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  188180. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  188181. {
  188182. switch (row_info->color_type)
  188183. {
  188184. case PNG_COLOR_TYPE_GRAY:
  188185. {
  188186. switch (row_info->bit_depth)
  188187. {
  188188. case 1:
  188189. {
  188190. sp = row;
  188191. shift = 7;
  188192. for (i = 0; i < row_width; i++)
  188193. {
  188194. if ((png_uint_16)((*sp >> shift) & 0x01)
  188195. == trans_values->gray)
  188196. {
  188197. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  188198. *sp |= (png_byte)(background->gray << shift);
  188199. }
  188200. if (!shift)
  188201. {
  188202. shift = 7;
  188203. sp++;
  188204. }
  188205. else
  188206. shift--;
  188207. }
  188208. break;
  188209. }
  188210. case 2:
  188211. {
  188212. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188213. if (gamma_table != NULL)
  188214. {
  188215. sp = row;
  188216. shift = 6;
  188217. for (i = 0; i < row_width; i++)
  188218. {
  188219. if ((png_uint_16)((*sp >> shift) & 0x03)
  188220. == trans_values->gray)
  188221. {
  188222. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188223. *sp |= (png_byte)(background->gray << shift);
  188224. }
  188225. else
  188226. {
  188227. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  188228. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  188229. (p << 4) | (p << 6)] >> 6) & 0x03);
  188230. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188231. *sp |= (png_byte)(g << shift);
  188232. }
  188233. if (!shift)
  188234. {
  188235. shift = 6;
  188236. sp++;
  188237. }
  188238. else
  188239. shift -= 2;
  188240. }
  188241. }
  188242. else
  188243. #endif
  188244. {
  188245. sp = row;
  188246. shift = 6;
  188247. for (i = 0; i < row_width; i++)
  188248. {
  188249. if ((png_uint_16)((*sp >> shift) & 0x03)
  188250. == trans_values->gray)
  188251. {
  188252. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188253. *sp |= (png_byte)(background->gray << shift);
  188254. }
  188255. if (!shift)
  188256. {
  188257. shift = 6;
  188258. sp++;
  188259. }
  188260. else
  188261. shift -= 2;
  188262. }
  188263. }
  188264. break;
  188265. }
  188266. case 4:
  188267. {
  188268. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188269. if (gamma_table != NULL)
  188270. {
  188271. sp = row;
  188272. shift = 4;
  188273. for (i = 0; i < row_width; i++)
  188274. {
  188275. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188276. == trans_values->gray)
  188277. {
  188278. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188279. *sp |= (png_byte)(background->gray << shift);
  188280. }
  188281. else
  188282. {
  188283. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  188284. png_byte g = (png_byte)((gamma_table[p |
  188285. (p << 4)] >> 4) & 0x0f);
  188286. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188287. *sp |= (png_byte)(g << shift);
  188288. }
  188289. if (!shift)
  188290. {
  188291. shift = 4;
  188292. sp++;
  188293. }
  188294. else
  188295. shift -= 4;
  188296. }
  188297. }
  188298. else
  188299. #endif
  188300. {
  188301. sp = row;
  188302. shift = 4;
  188303. for (i = 0; i < row_width; i++)
  188304. {
  188305. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188306. == trans_values->gray)
  188307. {
  188308. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188309. *sp |= (png_byte)(background->gray << shift);
  188310. }
  188311. if (!shift)
  188312. {
  188313. shift = 4;
  188314. sp++;
  188315. }
  188316. else
  188317. shift -= 4;
  188318. }
  188319. }
  188320. break;
  188321. }
  188322. case 8:
  188323. {
  188324. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188325. if (gamma_table != NULL)
  188326. {
  188327. sp = row;
  188328. for (i = 0; i < row_width; i++, sp++)
  188329. {
  188330. if (*sp == trans_values->gray)
  188331. {
  188332. *sp = (png_byte)background->gray;
  188333. }
  188334. else
  188335. {
  188336. *sp = gamma_table[*sp];
  188337. }
  188338. }
  188339. }
  188340. else
  188341. #endif
  188342. {
  188343. sp = row;
  188344. for (i = 0; i < row_width; i++, sp++)
  188345. {
  188346. if (*sp == trans_values->gray)
  188347. {
  188348. *sp = (png_byte)background->gray;
  188349. }
  188350. }
  188351. }
  188352. break;
  188353. }
  188354. case 16:
  188355. {
  188356. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188357. if (gamma_16 != NULL)
  188358. {
  188359. sp = row;
  188360. for (i = 0; i < row_width; i++, sp += 2)
  188361. {
  188362. png_uint_16 v;
  188363. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188364. if (v == trans_values->gray)
  188365. {
  188366. /* background is already in screen gamma */
  188367. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188368. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188369. }
  188370. else
  188371. {
  188372. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188373. *sp = (png_byte)((v >> 8) & 0xff);
  188374. *(sp + 1) = (png_byte)(v & 0xff);
  188375. }
  188376. }
  188377. }
  188378. else
  188379. #endif
  188380. {
  188381. sp = row;
  188382. for (i = 0; i < row_width; i++, sp += 2)
  188383. {
  188384. png_uint_16 v;
  188385. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188386. if (v == trans_values->gray)
  188387. {
  188388. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188389. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188390. }
  188391. }
  188392. }
  188393. break;
  188394. }
  188395. }
  188396. break;
  188397. }
  188398. case PNG_COLOR_TYPE_RGB:
  188399. {
  188400. if (row_info->bit_depth == 8)
  188401. {
  188402. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188403. if (gamma_table != NULL)
  188404. {
  188405. sp = row;
  188406. for (i = 0; i < row_width; i++, sp += 3)
  188407. {
  188408. if (*sp == trans_values->red &&
  188409. *(sp + 1) == trans_values->green &&
  188410. *(sp + 2) == trans_values->blue)
  188411. {
  188412. *sp = (png_byte)background->red;
  188413. *(sp + 1) = (png_byte)background->green;
  188414. *(sp + 2) = (png_byte)background->blue;
  188415. }
  188416. else
  188417. {
  188418. *sp = gamma_table[*sp];
  188419. *(sp + 1) = gamma_table[*(sp + 1)];
  188420. *(sp + 2) = gamma_table[*(sp + 2)];
  188421. }
  188422. }
  188423. }
  188424. else
  188425. #endif
  188426. {
  188427. sp = row;
  188428. for (i = 0; i < row_width; i++, sp += 3)
  188429. {
  188430. if (*sp == trans_values->red &&
  188431. *(sp + 1) == trans_values->green &&
  188432. *(sp + 2) == trans_values->blue)
  188433. {
  188434. *sp = (png_byte)background->red;
  188435. *(sp + 1) = (png_byte)background->green;
  188436. *(sp + 2) = (png_byte)background->blue;
  188437. }
  188438. }
  188439. }
  188440. }
  188441. else /* if (row_info->bit_depth == 16) */
  188442. {
  188443. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188444. if (gamma_16 != NULL)
  188445. {
  188446. sp = row;
  188447. for (i = 0; i < row_width; i++, sp += 6)
  188448. {
  188449. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188450. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188451. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188452. if (r == trans_values->red && g == trans_values->green &&
  188453. b == trans_values->blue)
  188454. {
  188455. /* background is already in screen gamma */
  188456. *sp = (png_byte)((background->red >> 8) & 0xff);
  188457. *(sp + 1) = (png_byte)(background->red & 0xff);
  188458. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188459. *(sp + 3) = (png_byte)(background->green & 0xff);
  188460. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188461. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188462. }
  188463. else
  188464. {
  188465. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188466. *sp = (png_byte)((v >> 8) & 0xff);
  188467. *(sp + 1) = (png_byte)(v & 0xff);
  188468. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188469. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  188470. *(sp + 3) = (png_byte)(v & 0xff);
  188471. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188472. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  188473. *(sp + 5) = (png_byte)(v & 0xff);
  188474. }
  188475. }
  188476. }
  188477. else
  188478. #endif
  188479. {
  188480. sp = row;
  188481. for (i = 0; i < row_width; i++, sp += 6)
  188482. {
  188483. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  188484. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188485. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188486. if (r == trans_values->red && g == trans_values->green &&
  188487. b == trans_values->blue)
  188488. {
  188489. *sp = (png_byte)((background->red >> 8) & 0xff);
  188490. *(sp + 1) = (png_byte)(background->red & 0xff);
  188491. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188492. *(sp + 3) = (png_byte)(background->green & 0xff);
  188493. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188494. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188495. }
  188496. }
  188497. }
  188498. }
  188499. break;
  188500. }
  188501. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188502. {
  188503. if (row_info->bit_depth == 8)
  188504. {
  188505. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188506. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188507. gamma_table != NULL)
  188508. {
  188509. sp = row;
  188510. dp = row;
  188511. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188512. {
  188513. png_uint_16 a = *(sp + 1);
  188514. if (a == 0xff)
  188515. {
  188516. *dp = gamma_table[*sp];
  188517. }
  188518. else if (a == 0)
  188519. {
  188520. /* background is already in screen gamma */
  188521. *dp = (png_byte)background->gray;
  188522. }
  188523. else
  188524. {
  188525. png_byte v, w;
  188526. v = gamma_to_1[*sp];
  188527. png_composite(w, v, a, background_1->gray);
  188528. *dp = gamma_from_1[w];
  188529. }
  188530. }
  188531. }
  188532. else
  188533. #endif
  188534. {
  188535. sp = row;
  188536. dp = row;
  188537. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188538. {
  188539. png_byte a = *(sp + 1);
  188540. if (a == 0xff)
  188541. {
  188542. *dp = *sp;
  188543. }
  188544. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188545. else if (a == 0)
  188546. {
  188547. *dp = (png_byte)background->gray;
  188548. }
  188549. else
  188550. {
  188551. png_composite(*dp, *sp, a, background_1->gray);
  188552. }
  188553. #else
  188554. *dp = (png_byte)background->gray;
  188555. #endif
  188556. }
  188557. }
  188558. }
  188559. else /* if (png_ptr->bit_depth == 16) */
  188560. {
  188561. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188562. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188563. gamma_16_to_1 != NULL)
  188564. {
  188565. sp = row;
  188566. dp = row;
  188567. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188568. {
  188569. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188570. if (a == (png_uint_16)0xffff)
  188571. {
  188572. png_uint_16 v;
  188573. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188574. *dp = (png_byte)((v >> 8) & 0xff);
  188575. *(dp + 1) = (png_byte)(v & 0xff);
  188576. }
  188577. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188578. else if (a == 0)
  188579. #else
  188580. else
  188581. #endif
  188582. {
  188583. /* background is already in screen gamma */
  188584. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188585. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188586. }
  188587. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188588. else
  188589. {
  188590. png_uint_16 g, v, w;
  188591. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188592. png_composite_16(v, g, a, background_1->gray);
  188593. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  188594. *dp = (png_byte)((w >> 8) & 0xff);
  188595. *(dp + 1) = (png_byte)(w & 0xff);
  188596. }
  188597. #endif
  188598. }
  188599. }
  188600. else
  188601. #endif
  188602. {
  188603. sp = row;
  188604. dp = row;
  188605. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188606. {
  188607. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188608. if (a == (png_uint_16)0xffff)
  188609. {
  188610. png_memcpy(dp, sp, 2);
  188611. }
  188612. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188613. else if (a == 0)
  188614. #else
  188615. else
  188616. #endif
  188617. {
  188618. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188619. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188620. }
  188621. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188622. else
  188623. {
  188624. png_uint_16 g, v;
  188625. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188626. png_composite_16(v, g, a, background_1->gray);
  188627. *dp = (png_byte)((v >> 8) & 0xff);
  188628. *(dp + 1) = (png_byte)(v & 0xff);
  188629. }
  188630. #endif
  188631. }
  188632. }
  188633. }
  188634. break;
  188635. }
  188636. case PNG_COLOR_TYPE_RGB_ALPHA:
  188637. {
  188638. if (row_info->bit_depth == 8)
  188639. {
  188640. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188641. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188642. gamma_table != NULL)
  188643. {
  188644. sp = row;
  188645. dp = row;
  188646. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188647. {
  188648. png_byte a = *(sp + 3);
  188649. if (a == 0xff)
  188650. {
  188651. *dp = gamma_table[*sp];
  188652. *(dp + 1) = gamma_table[*(sp + 1)];
  188653. *(dp + 2) = gamma_table[*(sp + 2)];
  188654. }
  188655. else if (a == 0)
  188656. {
  188657. /* background is already in screen gamma */
  188658. *dp = (png_byte)background->red;
  188659. *(dp + 1) = (png_byte)background->green;
  188660. *(dp + 2) = (png_byte)background->blue;
  188661. }
  188662. else
  188663. {
  188664. png_byte v, w;
  188665. v = gamma_to_1[*sp];
  188666. png_composite(w, v, a, background_1->red);
  188667. *dp = gamma_from_1[w];
  188668. v = gamma_to_1[*(sp + 1)];
  188669. png_composite(w, v, a, background_1->green);
  188670. *(dp + 1) = gamma_from_1[w];
  188671. v = gamma_to_1[*(sp + 2)];
  188672. png_composite(w, v, a, background_1->blue);
  188673. *(dp + 2) = gamma_from_1[w];
  188674. }
  188675. }
  188676. }
  188677. else
  188678. #endif
  188679. {
  188680. sp = row;
  188681. dp = row;
  188682. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188683. {
  188684. png_byte a = *(sp + 3);
  188685. if (a == 0xff)
  188686. {
  188687. *dp = *sp;
  188688. *(dp + 1) = *(sp + 1);
  188689. *(dp + 2) = *(sp + 2);
  188690. }
  188691. else if (a == 0)
  188692. {
  188693. *dp = (png_byte)background->red;
  188694. *(dp + 1) = (png_byte)background->green;
  188695. *(dp + 2) = (png_byte)background->blue;
  188696. }
  188697. else
  188698. {
  188699. png_composite(*dp, *sp, a, background->red);
  188700. png_composite(*(dp + 1), *(sp + 1), a,
  188701. background->green);
  188702. png_composite(*(dp + 2), *(sp + 2), a,
  188703. background->blue);
  188704. }
  188705. }
  188706. }
  188707. }
  188708. else /* if (row_info->bit_depth == 16) */
  188709. {
  188710. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188711. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188712. gamma_16_to_1 != NULL)
  188713. {
  188714. sp = row;
  188715. dp = row;
  188716. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188717. {
  188718. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188719. << 8) + (png_uint_16)(*(sp + 7)));
  188720. if (a == (png_uint_16)0xffff)
  188721. {
  188722. png_uint_16 v;
  188723. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188724. *dp = (png_byte)((v >> 8) & 0xff);
  188725. *(dp + 1) = (png_byte)(v & 0xff);
  188726. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188727. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188728. *(dp + 3) = (png_byte)(v & 0xff);
  188729. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188730. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188731. *(dp + 5) = (png_byte)(v & 0xff);
  188732. }
  188733. else if (a == 0)
  188734. {
  188735. /* background is already in screen gamma */
  188736. *dp = (png_byte)((background->red >> 8) & 0xff);
  188737. *(dp + 1) = (png_byte)(background->red & 0xff);
  188738. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188739. *(dp + 3) = (png_byte)(background->green & 0xff);
  188740. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188741. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188742. }
  188743. else
  188744. {
  188745. png_uint_16 v, w, x;
  188746. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188747. png_composite_16(w, v, a, background_1->red);
  188748. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188749. *dp = (png_byte)((x >> 8) & 0xff);
  188750. *(dp + 1) = (png_byte)(x & 0xff);
  188751. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188752. png_composite_16(w, v, a, background_1->green);
  188753. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188754. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  188755. *(dp + 3) = (png_byte)(x & 0xff);
  188756. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188757. png_composite_16(w, v, a, background_1->blue);
  188758. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  188759. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  188760. *(dp + 5) = (png_byte)(x & 0xff);
  188761. }
  188762. }
  188763. }
  188764. else
  188765. #endif
  188766. {
  188767. sp = row;
  188768. dp = row;
  188769. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188770. {
  188771. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188772. << 8) + (png_uint_16)(*(sp + 7)));
  188773. if (a == (png_uint_16)0xffff)
  188774. {
  188775. png_memcpy(dp, sp, 6);
  188776. }
  188777. else if (a == 0)
  188778. {
  188779. *dp = (png_byte)((background->red >> 8) & 0xff);
  188780. *(dp + 1) = (png_byte)(background->red & 0xff);
  188781. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188782. *(dp + 3) = (png_byte)(background->green & 0xff);
  188783. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188784. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188785. }
  188786. else
  188787. {
  188788. png_uint_16 v;
  188789. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188790. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  188791. + *(sp + 3));
  188792. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  188793. + *(sp + 5));
  188794. png_composite_16(v, r, a, background->red);
  188795. *dp = (png_byte)((v >> 8) & 0xff);
  188796. *(dp + 1) = (png_byte)(v & 0xff);
  188797. png_composite_16(v, g, a, background->green);
  188798. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188799. *(dp + 3) = (png_byte)(v & 0xff);
  188800. png_composite_16(v, b, a, background->blue);
  188801. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188802. *(dp + 5) = (png_byte)(v & 0xff);
  188803. }
  188804. }
  188805. }
  188806. }
  188807. break;
  188808. }
  188809. }
  188810. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  188811. {
  188812. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188813. row_info->channels--;
  188814. row_info->pixel_depth = (png_byte)(row_info->channels *
  188815. row_info->bit_depth);
  188816. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188817. }
  188818. }
  188819. }
  188820. #endif
  188821. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188822. /* Gamma correct the image, avoiding the alpha channel. Make sure
  188823. * you do this after you deal with the transparency issue on grayscale
  188824. * or RGB images. If your bit depth is 8, use gamma_table, if it
  188825. * is 16, use gamma_16_table and gamma_shift. Build these with
  188826. * build_gamma_table().
  188827. */
  188828. void /* PRIVATE */
  188829. png_do_gamma(png_row_infop row_info, png_bytep row,
  188830. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  188831. int gamma_shift)
  188832. {
  188833. png_bytep sp;
  188834. png_uint_32 i;
  188835. png_uint_32 row_width=row_info->width;
  188836. png_debug(1, "in png_do_gamma\n");
  188837. if (
  188838. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188839. row != NULL && row_info != NULL &&
  188840. #endif
  188841. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  188842. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  188843. {
  188844. switch (row_info->color_type)
  188845. {
  188846. case PNG_COLOR_TYPE_RGB:
  188847. {
  188848. if (row_info->bit_depth == 8)
  188849. {
  188850. sp = row;
  188851. for (i = 0; i < row_width; i++)
  188852. {
  188853. *sp = gamma_table[*sp];
  188854. sp++;
  188855. *sp = gamma_table[*sp];
  188856. sp++;
  188857. *sp = gamma_table[*sp];
  188858. sp++;
  188859. }
  188860. }
  188861. else /* if (row_info->bit_depth == 16) */
  188862. {
  188863. sp = row;
  188864. for (i = 0; i < row_width; i++)
  188865. {
  188866. png_uint_16 v;
  188867. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188868. *sp = (png_byte)((v >> 8) & 0xff);
  188869. *(sp + 1) = (png_byte)(v & 0xff);
  188870. sp += 2;
  188871. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188872. *sp = (png_byte)((v >> 8) & 0xff);
  188873. *(sp + 1) = (png_byte)(v & 0xff);
  188874. sp += 2;
  188875. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188876. *sp = (png_byte)((v >> 8) & 0xff);
  188877. *(sp + 1) = (png_byte)(v & 0xff);
  188878. sp += 2;
  188879. }
  188880. }
  188881. break;
  188882. }
  188883. case PNG_COLOR_TYPE_RGB_ALPHA:
  188884. {
  188885. if (row_info->bit_depth == 8)
  188886. {
  188887. sp = row;
  188888. for (i = 0; i < row_width; i++)
  188889. {
  188890. *sp = gamma_table[*sp];
  188891. sp++;
  188892. *sp = gamma_table[*sp];
  188893. sp++;
  188894. *sp = gamma_table[*sp];
  188895. sp++;
  188896. sp++;
  188897. }
  188898. }
  188899. else /* if (row_info->bit_depth == 16) */
  188900. {
  188901. sp = row;
  188902. for (i = 0; i < row_width; i++)
  188903. {
  188904. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188905. *sp = (png_byte)((v >> 8) & 0xff);
  188906. *(sp + 1) = (png_byte)(v & 0xff);
  188907. sp += 2;
  188908. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188909. *sp = (png_byte)((v >> 8) & 0xff);
  188910. *(sp + 1) = (png_byte)(v & 0xff);
  188911. sp += 2;
  188912. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188913. *sp = (png_byte)((v >> 8) & 0xff);
  188914. *(sp + 1) = (png_byte)(v & 0xff);
  188915. sp += 4;
  188916. }
  188917. }
  188918. break;
  188919. }
  188920. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188921. {
  188922. if (row_info->bit_depth == 8)
  188923. {
  188924. sp = row;
  188925. for (i = 0; i < row_width; i++)
  188926. {
  188927. *sp = gamma_table[*sp];
  188928. sp += 2;
  188929. }
  188930. }
  188931. else /* if (row_info->bit_depth == 16) */
  188932. {
  188933. sp = row;
  188934. for (i = 0; i < row_width; i++)
  188935. {
  188936. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188937. *sp = (png_byte)((v >> 8) & 0xff);
  188938. *(sp + 1) = (png_byte)(v & 0xff);
  188939. sp += 4;
  188940. }
  188941. }
  188942. break;
  188943. }
  188944. case PNG_COLOR_TYPE_GRAY:
  188945. {
  188946. if (row_info->bit_depth == 2)
  188947. {
  188948. sp = row;
  188949. for (i = 0; i < row_width; i += 4)
  188950. {
  188951. int a = *sp & 0xc0;
  188952. int b = *sp & 0x30;
  188953. int c = *sp & 0x0c;
  188954. int d = *sp & 0x03;
  188955. *sp = (png_byte)(
  188956. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  188957. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  188958. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  188959. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  188960. sp++;
  188961. }
  188962. }
  188963. if (row_info->bit_depth == 4)
  188964. {
  188965. sp = row;
  188966. for (i = 0; i < row_width; i += 2)
  188967. {
  188968. int msb = *sp & 0xf0;
  188969. int lsb = *sp & 0x0f;
  188970. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  188971. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  188972. sp++;
  188973. }
  188974. }
  188975. else if (row_info->bit_depth == 8)
  188976. {
  188977. sp = row;
  188978. for (i = 0; i < row_width; i++)
  188979. {
  188980. *sp = gamma_table[*sp];
  188981. sp++;
  188982. }
  188983. }
  188984. else if (row_info->bit_depth == 16)
  188985. {
  188986. sp = row;
  188987. for (i = 0; i < row_width; i++)
  188988. {
  188989. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188990. *sp = (png_byte)((v >> 8) & 0xff);
  188991. *(sp + 1) = (png_byte)(v & 0xff);
  188992. sp += 2;
  188993. }
  188994. }
  188995. break;
  188996. }
  188997. }
  188998. }
  188999. }
  189000. #endif
  189001. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189002. /* Expands a palette row to an RGB or RGBA row depending
  189003. * upon whether you supply trans and num_trans.
  189004. */
  189005. void /* PRIVATE */
  189006. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  189007. png_colorp palette, png_bytep trans, int num_trans)
  189008. {
  189009. int shift, value;
  189010. png_bytep sp, dp;
  189011. png_uint_32 i;
  189012. png_uint_32 row_width=row_info->width;
  189013. png_debug(1, "in png_do_expand_palette\n");
  189014. if (
  189015. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189016. row != NULL && row_info != NULL &&
  189017. #endif
  189018. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  189019. {
  189020. if (row_info->bit_depth < 8)
  189021. {
  189022. switch (row_info->bit_depth)
  189023. {
  189024. case 1:
  189025. {
  189026. sp = row + (png_size_t)((row_width - 1) >> 3);
  189027. dp = row + (png_size_t)row_width - 1;
  189028. shift = 7 - (int)((row_width + 7) & 0x07);
  189029. for (i = 0; i < row_width; i++)
  189030. {
  189031. if ((*sp >> shift) & 0x01)
  189032. *dp = 1;
  189033. else
  189034. *dp = 0;
  189035. if (shift == 7)
  189036. {
  189037. shift = 0;
  189038. sp--;
  189039. }
  189040. else
  189041. shift++;
  189042. dp--;
  189043. }
  189044. break;
  189045. }
  189046. case 2:
  189047. {
  189048. sp = row + (png_size_t)((row_width - 1) >> 2);
  189049. dp = row + (png_size_t)row_width - 1;
  189050. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189051. for (i = 0; i < row_width; i++)
  189052. {
  189053. value = (*sp >> shift) & 0x03;
  189054. *dp = (png_byte)value;
  189055. if (shift == 6)
  189056. {
  189057. shift = 0;
  189058. sp--;
  189059. }
  189060. else
  189061. shift += 2;
  189062. dp--;
  189063. }
  189064. break;
  189065. }
  189066. case 4:
  189067. {
  189068. sp = row + (png_size_t)((row_width - 1) >> 1);
  189069. dp = row + (png_size_t)row_width - 1;
  189070. shift = (int)((row_width & 0x01) << 2);
  189071. for (i = 0; i < row_width; i++)
  189072. {
  189073. value = (*sp >> shift) & 0x0f;
  189074. *dp = (png_byte)value;
  189075. if (shift == 4)
  189076. {
  189077. shift = 0;
  189078. sp--;
  189079. }
  189080. else
  189081. shift += 4;
  189082. dp--;
  189083. }
  189084. break;
  189085. }
  189086. }
  189087. row_info->bit_depth = 8;
  189088. row_info->pixel_depth = 8;
  189089. row_info->rowbytes = row_width;
  189090. }
  189091. switch (row_info->bit_depth)
  189092. {
  189093. case 8:
  189094. {
  189095. if (trans != NULL)
  189096. {
  189097. sp = row + (png_size_t)row_width - 1;
  189098. dp = row + (png_size_t)(row_width << 2) - 1;
  189099. for (i = 0; i < row_width; i++)
  189100. {
  189101. if ((int)(*sp) >= num_trans)
  189102. *dp-- = 0xff;
  189103. else
  189104. *dp-- = trans[*sp];
  189105. *dp-- = palette[*sp].blue;
  189106. *dp-- = palette[*sp].green;
  189107. *dp-- = palette[*sp].red;
  189108. sp--;
  189109. }
  189110. row_info->bit_depth = 8;
  189111. row_info->pixel_depth = 32;
  189112. row_info->rowbytes = row_width * 4;
  189113. row_info->color_type = 6;
  189114. row_info->channels = 4;
  189115. }
  189116. else
  189117. {
  189118. sp = row + (png_size_t)row_width - 1;
  189119. dp = row + (png_size_t)(row_width * 3) - 1;
  189120. for (i = 0; i < row_width; i++)
  189121. {
  189122. *dp-- = palette[*sp].blue;
  189123. *dp-- = palette[*sp].green;
  189124. *dp-- = palette[*sp].red;
  189125. sp--;
  189126. }
  189127. row_info->bit_depth = 8;
  189128. row_info->pixel_depth = 24;
  189129. row_info->rowbytes = row_width * 3;
  189130. row_info->color_type = 2;
  189131. row_info->channels = 3;
  189132. }
  189133. break;
  189134. }
  189135. }
  189136. }
  189137. }
  189138. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  189139. * expanded transparency value is supplied, an alpha channel is built.
  189140. */
  189141. void /* PRIVATE */
  189142. png_do_expand(png_row_infop row_info, png_bytep row,
  189143. png_color_16p trans_value)
  189144. {
  189145. int shift, value;
  189146. png_bytep sp, dp;
  189147. png_uint_32 i;
  189148. png_uint_32 row_width=row_info->width;
  189149. png_debug(1, "in png_do_expand\n");
  189150. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189151. if (row != NULL && row_info != NULL)
  189152. #endif
  189153. {
  189154. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  189155. {
  189156. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  189157. if (row_info->bit_depth < 8)
  189158. {
  189159. switch (row_info->bit_depth)
  189160. {
  189161. case 1:
  189162. {
  189163. gray = (png_uint_16)((gray&0x01)*0xff);
  189164. sp = row + (png_size_t)((row_width - 1) >> 3);
  189165. dp = row + (png_size_t)row_width - 1;
  189166. shift = 7 - (int)((row_width + 7) & 0x07);
  189167. for (i = 0; i < row_width; i++)
  189168. {
  189169. if ((*sp >> shift) & 0x01)
  189170. *dp = 0xff;
  189171. else
  189172. *dp = 0;
  189173. if (shift == 7)
  189174. {
  189175. shift = 0;
  189176. sp--;
  189177. }
  189178. else
  189179. shift++;
  189180. dp--;
  189181. }
  189182. break;
  189183. }
  189184. case 2:
  189185. {
  189186. gray = (png_uint_16)((gray&0x03)*0x55);
  189187. sp = row + (png_size_t)((row_width - 1) >> 2);
  189188. dp = row + (png_size_t)row_width - 1;
  189189. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189190. for (i = 0; i < row_width; i++)
  189191. {
  189192. value = (*sp >> shift) & 0x03;
  189193. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  189194. (value << 6));
  189195. if (shift == 6)
  189196. {
  189197. shift = 0;
  189198. sp--;
  189199. }
  189200. else
  189201. shift += 2;
  189202. dp--;
  189203. }
  189204. break;
  189205. }
  189206. case 4:
  189207. {
  189208. gray = (png_uint_16)((gray&0x0f)*0x11);
  189209. sp = row + (png_size_t)((row_width - 1) >> 1);
  189210. dp = row + (png_size_t)row_width - 1;
  189211. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  189212. for (i = 0; i < row_width; i++)
  189213. {
  189214. value = (*sp >> shift) & 0x0f;
  189215. *dp = (png_byte)(value | (value << 4));
  189216. if (shift == 4)
  189217. {
  189218. shift = 0;
  189219. sp--;
  189220. }
  189221. else
  189222. shift = 4;
  189223. dp--;
  189224. }
  189225. break;
  189226. }
  189227. }
  189228. row_info->bit_depth = 8;
  189229. row_info->pixel_depth = 8;
  189230. row_info->rowbytes = row_width;
  189231. }
  189232. if (trans_value != NULL)
  189233. {
  189234. if (row_info->bit_depth == 8)
  189235. {
  189236. gray = gray & 0xff;
  189237. sp = row + (png_size_t)row_width - 1;
  189238. dp = row + (png_size_t)(row_width << 1) - 1;
  189239. for (i = 0; i < row_width; i++)
  189240. {
  189241. if (*sp == gray)
  189242. *dp-- = 0;
  189243. else
  189244. *dp-- = 0xff;
  189245. *dp-- = *sp--;
  189246. }
  189247. }
  189248. else if (row_info->bit_depth == 16)
  189249. {
  189250. png_byte gray_high = (gray >> 8) & 0xff;
  189251. png_byte gray_low = gray & 0xff;
  189252. sp = row + row_info->rowbytes - 1;
  189253. dp = row + (row_info->rowbytes << 1) - 1;
  189254. for (i = 0; i < row_width; i++)
  189255. {
  189256. if (*(sp-1) == gray_high && *(sp) == gray_low)
  189257. {
  189258. *dp-- = 0;
  189259. *dp-- = 0;
  189260. }
  189261. else
  189262. {
  189263. *dp-- = 0xff;
  189264. *dp-- = 0xff;
  189265. }
  189266. *dp-- = *sp--;
  189267. *dp-- = *sp--;
  189268. }
  189269. }
  189270. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  189271. row_info->channels = 2;
  189272. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  189273. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  189274. row_width);
  189275. }
  189276. }
  189277. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  189278. {
  189279. if (row_info->bit_depth == 8)
  189280. {
  189281. png_byte red = trans_value->red & 0xff;
  189282. png_byte green = trans_value->green & 0xff;
  189283. png_byte blue = trans_value->blue & 0xff;
  189284. sp = row + (png_size_t)row_info->rowbytes - 1;
  189285. dp = row + (png_size_t)(row_width << 2) - 1;
  189286. for (i = 0; i < row_width; i++)
  189287. {
  189288. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  189289. *dp-- = 0;
  189290. else
  189291. *dp-- = 0xff;
  189292. *dp-- = *sp--;
  189293. *dp-- = *sp--;
  189294. *dp-- = *sp--;
  189295. }
  189296. }
  189297. else if (row_info->bit_depth == 16)
  189298. {
  189299. png_byte red_high = (trans_value->red >> 8) & 0xff;
  189300. png_byte green_high = (trans_value->green >> 8) & 0xff;
  189301. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  189302. png_byte red_low = trans_value->red & 0xff;
  189303. png_byte green_low = trans_value->green & 0xff;
  189304. png_byte blue_low = trans_value->blue & 0xff;
  189305. sp = row + row_info->rowbytes - 1;
  189306. dp = row + (png_size_t)(row_width << 3) - 1;
  189307. for (i = 0; i < row_width; i++)
  189308. {
  189309. if (*(sp - 5) == red_high &&
  189310. *(sp - 4) == red_low &&
  189311. *(sp - 3) == green_high &&
  189312. *(sp - 2) == green_low &&
  189313. *(sp - 1) == blue_high &&
  189314. *(sp ) == blue_low)
  189315. {
  189316. *dp-- = 0;
  189317. *dp-- = 0;
  189318. }
  189319. else
  189320. {
  189321. *dp-- = 0xff;
  189322. *dp-- = 0xff;
  189323. }
  189324. *dp-- = *sp--;
  189325. *dp-- = *sp--;
  189326. *dp-- = *sp--;
  189327. *dp-- = *sp--;
  189328. *dp-- = *sp--;
  189329. *dp-- = *sp--;
  189330. }
  189331. }
  189332. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  189333. row_info->channels = 4;
  189334. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  189335. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189336. }
  189337. }
  189338. }
  189339. #endif
  189340. #if defined(PNG_READ_DITHER_SUPPORTED)
  189341. void /* PRIVATE */
  189342. png_do_dither(png_row_infop row_info, png_bytep row,
  189343. png_bytep palette_lookup, png_bytep dither_lookup)
  189344. {
  189345. png_bytep sp, dp;
  189346. png_uint_32 i;
  189347. png_uint_32 row_width=row_info->width;
  189348. png_debug(1, "in png_do_dither\n");
  189349. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189350. if (row != NULL && row_info != NULL)
  189351. #endif
  189352. {
  189353. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  189354. palette_lookup && row_info->bit_depth == 8)
  189355. {
  189356. int r, g, b, p;
  189357. sp = row;
  189358. dp = row;
  189359. for (i = 0; i < row_width; i++)
  189360. {
  189361. r = *sp++;
  189362. g = *sp++;
  189363. b = *sp++;
  189364. /* this looks real messy, but the compiler will reduce
  189365. it down to a reasonable formula. For example, with
  189366. 5 bits per color, we get:
  189367. p = (((r >> 3) & 0x1f) << 10) |
  189368. (((g >> 3) & 0x1f) << 5) |
  189369. ((b >> 3) & 0x1f);
  189370. */
  189371. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189372. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189373. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189374. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189375. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189376. (PNG_DITHER_BLUE_BITS)) |
  189377. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189378. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189379. *dp++ = palette_lookup[p];
  189380. }
  189381. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189382. row_info->channels = 1;
  189383. row_info->pixel_depth = row_info->bit_depth;
  189384. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189385. }
  189386. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  189387. palette_lookup != NULL && row_info->bit_depth == 8)
  189388. {
  189389. int r, g, b, p;
  189390. sp = row;
  189391. dp = row;
  189392. for (i = 0; i < row_width; i++)
  189393. {
  189394. r = *sp++;
  189395. g = *sp++;
  189396. b = *sp++;
  189397. sp++;
  189398. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189399. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189400. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189401. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189402. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189403. (PNG_DITHER_BLUE_BITS)) |
  189404. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189405. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189406. *dp++ = palette_lookup[p];
  189407. }
  189408. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189409. row_info->channels = 1;
  189410. row_info->pixel_depth = row_info->bit_depth;
  189411. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189412. }
  189413. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  189414. dither_lookup && row_info->bit_depth == 8)
  189415. {
  189416. sp = row;
  189417. for (i = 0; i < row_width; i++, sp++)
  189418. {
  189419. *sp = dither_lookup[*sp];
  189420. }
  189421. }
  189422. }
  189423. }
  189424. #endif
  189425. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189426. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189427. static PNG_CONST int png_gamma_shift[] =
  189428. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  189429. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  189430. * tables, we don't make a full table if we are reducing to 8-bit in
  189431. * the future. Note also how the gamma_16 tables are segmented so that
  189432. * we don't need to allocate > 64K chunks for a full 16-bit table.
  189433. */
  189434. void /* PRIVATE */
  189435. png_build_gamma_table(png_structp png_ptr)
  189436. {
  189437. png_debug(1, "in png_build_gamma_table\n");
  189438. if (png_ptr->bit_depth <= 8)
  189439. {
  189440. int i;
  189441. double g;
  189442. if (png_ptr->screen_gamma > .000001)
  189443. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189444. else
  189445. g = 1.0;
  189446. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  189447. (png_uint_32)256);
  189448. for (i = 0; i < 256; i++)
  189449. {
  189450. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  189451. g) * 255.0 + .5);
  189452. }
  189453. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189454. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189455. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  189456. {
  189457. g = 1.0 / (png_ptr->gamma);
  189458. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  189459. (png_uint_32)256);
  189460. for (i = 0; i < 256; i++)
  189461. {
  189462. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  189463. g) * 255.0 + .5);
  189464. }
  189465. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  189466. (png_uint_32)256);
  189467. if(png_ptr->screen_gamma > 0.000001)
  189468. g = 1.0 / png_ptr->screen_gamma;
  189469. else
  189470. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189471. for (i = 0; i < 256; i++)
  189472. {
  189473. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  189474. g) * 255.0 + .5);
  189475. }
  189476. }
  189477. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189478. }
  189479. else
  189480. {
  189481. double g;
  189482. int i, j, shift, num;
  189483. int sig_bit;
  189484. png_uint_32 ig;
  189485. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189486. {
  189487. sig_bit = (int)png_ptr->sig_bit.red;
  189488. if ((int)png_ptr->sig_bit.green > sig_bit)
  189489. sig_bit = png_ptr->sig_bit.green;
  189490. if ((int)png_ptr->sig_bit.blue > sig_bit)
  189491. sig_bit = png_ptr->sig_bit.blue;
  189492. }
  189493. else
  189494. {
  189495. sig_bit = (int)png_ptr->sig_bit.gray;
  189496. }
  189497. if (sig_bit > 0)
  189498. shift = 16 - sig_bit;
  189499. else
  189500. shift = 0;
  189501. if (png_ptr->transformations & PNG_16_TO_8)
  189502. {
  189503. if (shift < (16 - PNG_MAX_GAMMA_8))
  189504. shift = (16 - PNG_MAX_GAMMA_8);
  189505. }
  189506. if (shift > 8)
  189507. shift = 8;
  189508. if (shift < 0)
  189509. shift = 0;
  189510. png_ptr->gamma_shift = (png_byte)shift;
  189511. num = (1 << (8 - shift));
  189512. if (png_ptr->screen_gamma > .000001)
  189513. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189514. else
  189515. g = 1.0;
  189516. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  189517. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189518. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  189519. {
  189520. double fin, fout;
  189521. png_uint_32 last, max;
  189522. for (i = 0; i < num; i++)
  189523. {
  189524. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189525. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189526. }
  189527. g = 1.0 / g;
  189528. last = 0;
  189529. for (i = 0; i < 256; i++)
  189530. {
  189531. fout = ((double)i + 0.5) / 256.0;
  189532. fin = pow(fout, g);
  189533. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  189534. while (last <= max)
  189535. {
  189536. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189537. [(int)(last >> (8 - shift))] = (png_uint_16)(
  189538. (png_uint_16)i | ((png_uint_16)i << 8));
  189539. last++;
  189540. }
  189541. }
  189542. while (last < ((png_uint_32)num << 8))
  189543. {
  189544. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189545. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  189546. last++;
  189547. }
  189548. }
  189549. else
  189550. {
  189551. for (i = 0; i < num; i++)
  189552. {
  189553. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189554. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189555. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  189556. for (j = 0; j < 256; j++)
  189557. {
  189558. png_ptr->gamma_16_table[i][j] =
  189559. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189560. 65535.0, g) * 65535.0 + .5);
  189561. }
  189562. }
  189563. }
  189564. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189565. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189566. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  189567. {
  189568. g = 1.0 / (png_ptr->gamma);
  189569. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  189570. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  189571. for (i = 0; i < num; i++)
  189572. {
  189573. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189574. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189575. ig = (((png_uint_32)i *
  189576. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189577. for (j = 0; j < 256; j++)
  189578. {
  189579. png_ptr->gamma_16_to_1[i][j] =
  189580. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189581. 65535.0, g) * 65535.0 + .5);
  189582. }
  189583. }
  189584. if(png_ptr->screen_gamma > 0.000001)
  189585. g = 1.0 / png_ptr->screen_gamma;
  189586. else
  189587. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189588. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  189589. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189590. for (i = 0; i < num; i++)
  189591. {
  189592. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189593. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189594. ig = (((png_uint_32)i *
  189595. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189596. for (j = 0; j < 256; j++)
  189597. {
  189598. png_ptr->gamma_16_from_1[i][j] =
  189599. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189600. 65535.0, g) * 65535.0 + .5);
  189601. }
  189602. }
  189603. }
  189604. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189605. }
  189606. }
  189607. #endif
  189608. /* To do: install integer version of png_build_gamma_table here */
  189609. #endif
  189610. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189611. /* undoes intrapixel differencing */
  189612. void /* PRIVATE */
  189613. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  189614. {
  189615. png_debug(1, "in png_do_read_intrapixel\n");
  189616. if (
  189617. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189618. row != NULL && row_info != NULL &&
  189619. #endif
  189620. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  189621. {
  189622. int bytes_per_pixel;
  189623. png_uint_32 row_width = row_info->width;
  189624. if (row_info->bit_depth == 8)
  189625. {
  189626. png_bytep rp;
  189627. png_uint_32 i;
  189628. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189629. bytes_per_pixel = 3;
  189630. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189631. bytes_per_pixel = 4;
  189632. else
  189633. return;
  189634. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189635. {
  189636. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  189637. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  189638. }
  189639. }
  189640. else if (row_info->bit_depth == 16)
  189641. {
  189642. png_bytep rp;
  189643. png_uint_32 i;
  189644. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189645. bytes_per_pixel = 6;
  189646. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189647. bytes_per_pixel = 8;
  189648. else
  189649. return;
  189650. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189651. {
  189652. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  189653. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  189654. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  189655. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  189656. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  189657. *(rp ) = (png_byte)((red >> 8) & 0xff);
  189658. *(rp+1) = (png_byte)(red & 0xff);
  189659. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  189660. *(rp+5) = (png_byte)(blue & 0xff);
  189661. }
  189662. }
  189663. }
  189664. }
  189665. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  189666. #endif /* PNG_READ_SUPPORTED */
  189667. /********* End of inlined file: pngrtran.c *********/
  189668. /********* Start of inlined file: pngrutil.c *********/
  189669. /* pngrutil.c - utilities to read a PNG file
  189670. *
  189671. * Last changed in libpng 1.2.21 [October 4, 2007]
  189672. * For conditions of distribution and use, see copyright notice in png.h
  189673. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189674. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189675. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189676. *
  189677. * This file contains routines that are only called from within
  189678. * libpng itself during the course of reading an image.
  189679. */
  189680. #define PNG_INTERNAL
  189681. #if defined(PNG_READ_SUPPORTED)
  189682. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  189683. # define WIN32_WCE_OLD
  189684. #endif
  189685. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189686. # if defined(WIN32_WCE_OLD)
  189687. /* strtod() function is not supported on WindowsCE */
  189688. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  189689. {
  189690. double result = 0;
  189691. int len;
  189692. wchar_t *str, *end;
  189693. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  189694. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  189695. if ( NULL != str )
  189696. {
  189697. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  189698. result = wcstod(str, &end);
  189699. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  189700. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  189701. png_free(png_ptr, str);
  189702. }
  189703. return result;
  189704. }
  189705. # else
  189706. # define png_strtod(p,a,b) strtod(a,b)
  189707. # endif
  189708. #endif
  189709. png_uint_32 PNGAPI
  189710. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  189711. {
  189712. png_uint_32 i = png_get_uint_32(buf);
  189713. if (i > PNG_UINT_31_MAX)
  189714. png_error(png_ptr, "PNG unsigned integer out of range.");
  189715. return (i);
  189716. }
  189717. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  189718. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  189719. png_uint_32 PNGAPI
  189720. png_get_uint_32(png_bytep buf)
  189721. {
  189722. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  189723. ((png_uint_32)(*(buf + 1)) << 16) +
  189724. ((png_uint_32)(*(buf + 2)) << 8) +
  189725. (png_uint_32)(*(buf + 3));
  189726. return (i);
  189727. }
  189728. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  189729. * data is stored in the PNG file in two's complement format, and it is
  189730. * assumed that the machine format for signed integers is the same. */
  189731. png_int_32 PNGAPI
  189732. png_get_int_32(png_bytep buf)
  189733. {
  189734. png_int_32 i = ((png_int_32)(*buf) << 24) +
  189735. ((png_int_32)(*(buf + 1)) << 16) +
  189736. ((png_int_32)(*(buf + 2)) << 8) +
  189737. (png_int_32)(*(buf + 3));
  189738. return (i);
  189739. }
  189740. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  189741. png_uint_16 PNGAPI
  189742. png_get_uint_16(png_bytep buf)
  189743. {
  189744. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  189745. (png_uint_16)(*(buf + 1)));
  189746. return (i);
  189747. }
  189748. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  189749. /* Read data, and (optionally) run it through the CRC. */
  189750. void /* PRIVATE */
  189751. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  189752. {
  189753. if(png_ptr == NULL) return;
  189754. png_read_data(png_ptr, buf, length);
  189755. png_calculate_crc(png_ptr, buf, length);
  189756. }
  189757. /* Optionally skip data and then check the CRC. Depending on whether we
  189758. are reading a ancillary or critical chunk, and how the program has set
  189759. things up, we may calculate the CRC on the data and print a message.
  189760. Returns '1' if there was a CRC error, '0' otherwise. */
  189761. int /* PRIVATE */
  189762. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  189763. {
  189764. png_size_t i;
  189765. png_size_t istop = png_ptr->zbuf_size;
  189766. for (i = (png_size_t)skip; i > istop; i -= istop)
  189767. {
  189768. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  189769. }
  189770. if (i)
  189771. {
  189772. png_crc_read(png_ptr, png_ptr->zbuf, i);
  189773. }
  189774. if (png_crc_error(png_ptr))
  189775. {
  189776. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  189777. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  189778. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  189779. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  189780. {
  189781. png_chunk_warning(png_ptr, "CRC error");
  189782. }
  189783. else
  189784. {
  189785. png_chunk_error(png_ptr, "CRC error");
  189786. }
  189787. return (1);
  189788. }
  189789. return (0);
  189790. }
  189791. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  189792. the data it has read thus far. */
  189793. int /* PRIVATE */
  189794. png_crc_error(png_structp png_ptr)
  189795. {
  189796. png_byte crc_bytes[4];
  189797. png_uint_32 crc;
  189798. int need_crc = 1;
  189799. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  189800. {
  189801. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  189802. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189803. need_crc = 0;
  189804. }
  189805. else /* critical */
  189806. {
  189807. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  189808. need_crc = 0;
  189809. }
  189810. png_read_data(png_ptr, crc_bytes, 4);
  189811. if (need_crc)
  189812. {
  189813. crc = png_get_uint_32(crc_bytes);
  189814. return ((int)(crc != png_ptr->crc));
  189815. }
  189816. else
  189817. return (0);
  189818. }
  189819. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  189820. defined(PNG_READ_iCCP_SUPPORTED)
  189821. /*
  189822. * Decompress trailing data in a chunk. The assumption is that chunkdata
  189823. * points at an allocated area holding the contents of a chunk with a
  189824. * trailing compressed part. What we get back is an allocated area
  189825. * holding the original prefix part and an uncompressed version of the
  189826. * trailing part (the malloc area passed in is freed).
  189827. */
  189828. png_charp /* PRIVATE */
  189829. png_decompress_chunk(png_structp png_ptr, int comp_type,
  189830. png_charp chunkdata, png_size_t chunklength,
  189831. png_size_t prefix_size, png_size_t *newlength)
  189832. {
  189833. static PNG_CONST char msg[] = "Error decoding compressed text";
  189834. png_charp text;
  189835. png_size_t text_size;
  189836. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  189837. {
  189838. int ret = Z_OK;
  189839. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  189840. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  189841. png_ptr->zstream.next_out = png_ptr->zbuf;
  189842. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189843. text_size = 0;
  189844. text = NULL;
  189845. while (png_ptr->zstream.avail_in)
  189846. {
  189847. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189848. if (ret != Z_OK && ret != Z_STREAM_END)
  189849. {
  189850. if (png_ptr->zstream.msg != NULL)
  189851. png_warning(png_ptr, png_ptr->zstream.msg);
  189852. else
  189853. png_warning(png_ptr, msg);
  189854. inflateReset(&png_ptr->zstream);
  189855. png_ptr->zstream.avail_in = 0;
  189856. if (text == NULL)
  189857. {
  189858. text_size = prefix_size + png_sizeof(msg) + 1;
  189859. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  189860. if (text == NULL)
  189861. {
  189862. png_free(png_ptr,chunkdata);
  189863. png_error(png_ptr,"Not enough memory to decompress chunk");
  189864. }
  189865. png_memcpy(text, chunkdata, prefix_size);
  189866. }
  189867. text[text_size - 1] = 0x00;
  189868. /* Copy what we can of the error message into the text chunk */
  189869. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  189870. text_size = png_sizeof(msg) > text_size ? text_size :
  189871. png_sizeof(msg);
  189872. png_memcpy(text + prefix_size, msg, text_size + 1);
  189873. break;
  189874. }
  189875. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  189876. {
  189877. if (text == NULL)
  189878. {
  189879. text_size = prefix_size +
  189880. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189881. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  189882. if (text == NULL)
  189883. {
  189884. png_free(png_ptr,chunkdata);
  189885. png_error(png_ptr,"Not enough memory to decompress chunk.");
  189886. }
  189887. png_memcpy(text + prefix_size, png_ptr->zbuf,
  189888. text_size - prefix_size);
  189889. png_memcpy(text, chunkdata, prefix_size);
  189890. *(text + text_size) = 0x00;
  189891. }
  189892. else
  189893. {
  189894. png_charp tmp;
  189895. tmp = text;
  189896. text = (png_charp)png_malloc_warn(png_ptr,
  189897. (png_uint_32)(text_size +
  189898. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  189899. if (text == NULL)
  189900. {
  189901. png_free(png_ptr, tmp);
  189902. png_free(png_ptr, chunkdata);
  189903. png_error(png_ptr,"Not enough memory to decompress chunk..");
  189904. }
  189905. png_memcpy(text, tmp, text_size);
  189906. png_free(png_ptr, tmp);
  189907. png_memcpy(text + text_size, png_ptr->zbuf,
  189908. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  189909. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189910. *(text + text_size) = 0x00;
  189911. }
  189912. if (ret == Z_STREAM_END)
  189913. break;
  189914. else
  189915. {
  189916. png_ptr->zstream.next_out = png_ptr->zbuf;
  189917. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189918. }
  189919. }
  189920. }
  189921. if (ret != Z_STREAM_END)
  189922. {
  189923. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189924. char umsg[52];
  189925. if (ret == Z_BUF_ERROR)
  189926. png_snprintf(umsg, 52,
  189927. "Buffer error in compressed datastream in %s chunk",
  189928. png_ptr->chunk_name);
  189929. else if (ret == Z_DATA_ERROR)
  189930. png_snprintf(umsg, 52,
  189931. "Data error in compressed datastream in %s chunk",
  189932. png_ptr->chunk_name);
  189933. else
  189934. png_snprintf(umsg, 52,
  189935. "Incomplete compressed datastream in %s chunk",
  189936. png_ptr->chunk_name);
  189937. png_warning(png_ptr, umsg);
  189938. #else
  189939. png_warning(png_ptr,
  189940. "Incomplete compressed datastream in chunk other than IDAT");
  189941. #endif
  189942. text_size=prefix_size;
  189943. if (text == NULL)
  189944. {
  189945. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  189946. if (text == NULL)
  189947. {
  189948. png_free(png_ptr, chunkdata);
  189949. png_error(png_ptr,"Not enough memory for text.");
  189950. }
  189951. png_memcpy(text, chunkdata, prefix_size);
  189952. }
  189953. *(text + text_size) = 0x00;
  189954. }
  189955. inflateReset(&png_ptr->zstream);
  189956. png_ptr->zstream.avail_in = 0;
  189957. png_free(png_ptr, chunkdata);
  189958. chunkdata = text;
  189959. *newlength=text_size;
  189960. }
  189961. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  189962. {
  189963. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189964. char umsg[50];
  189965. png_snprintf(umsg, 50,
  189966. "Unknown zTXt compression type %d", comp_type);
  189967. png_warning(png_ptr, umsg);
  189968. #else
  189969. png_warning(png_ptr, "Unknown zTXt compression type");
  189970. #endif
  189971. *(chunkdata + prefix_size) = 0x00;
  189972. *newlength=prefix_size;
  189973. }
  189974. return chunkdata;
  189975. }
  189976. #endif
  189977. /* read and check the IDHR chunk */
  189978. void /* PRIVATE */
  189979. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189980. {
  189981. png_byte buf[13];
  189982. png_uint_32 width, height;
  189983. int bit_depth, color_type, compression_type, filter_type;
  189984. int interlace_type;
  189985. png_debug(1, "in png_handle_IHDR\n");
  189986. if (png_ptr->mode & PNG_HAVE_IHDR)
  189987. png_error(png_ptr, "Out of place IHDR");
  189988. /* check the length */
  189989. if (length != 13)
  189990. png_error(png_ptr, "Invalid IHDR chunk");
  189991. png_ptr->mode |= PNG_HAVE_IHDR;
  189992. png_crc_read(png_ptr, buf, 13);
  189993. png_crc_finish(png_ptr, 0);
  189994. width = png_get_uint_31(png_ptr, buf);
  189995. height = png_get_uint_31(png_ptr, buf + 4);
  189996. bit_depth = buf[8];
  189997. color_type = buf[9];
  189998. compression_type = buf[10];
  189999. filter_type = buf[11];
  190000. interlace_type = buf[12];
  190001. /* set internal variables */
  190002. png_ptr->width = width;
  190003. png_ptr->height = height;
  190004. png_ptr->bit_depth = (png_byte)bit_depth;
  190005. png_ptr->interlaced = (png_byte)interlace_type;
  190006. png_ptr->color_type = (png_byte)color_type;
  190007. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190008. png_ptr->filter_type = (png_byte)filter_type;
  190009. #endif
  190010. png_ptr->compression_type = (png_byte)compression_type;
  190011. /* find number of channels */
  190012. switch (png_ptr->color_type)
  190013. {
  190014. case PNG_COLOR_TYPE_GRAY:
  190015. case PNG_COLOR_TYPE_PALETTE:
  190016. png_ptr->channels = 1;
  190017. break;
  190018. case PNG_COLOR_TYPE_RGB:
  190019. png_ptr->channels = 3;
  190020. break;
  190021. case PNG_COLOR_TYPE_GRAY_ALPHA:
  190022. png_ptr->channels = 2;
  190023. break;
  190024. case PNG_COLOR_TYPE_RGB_ALPHA:
  190025. png_ptr->channels = 4;
  190026. break;
  190027. }
  190028. /* set up other useful info */
  190029. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  190030. png_ptr->channels);
  190031. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  190032. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  190033. png_debug1(3,"channels = %d\n", png_ptr->channels);
  190034. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  190035. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  190036. color_type, interlace_type, compression_type, filter_type);
  190037. }
  190038. /* read and check the palette */
  190039. void /* PRIVATE */
  190040. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190041. {
  190042. png_color palette[PNG_MAX_PALETTE_LENGTH];
  190043. int num, i;
  190044. #ifndef PNG_NO_POINTER_INDEXING
  190045. png_colorp pal_ptr;
  190046. #endif
  190047. png_debug(1, "in png_handle_PLTE\n");
  190048. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190049. png_error(png_ptr, "Missing IHDR before PLTE");
  190050. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190051. {
  190052. png_warning(png_ptr, "Invalid PLTE after IDAT");
  190053. png_crc_finish(png_ptr, length);
  190054. return;
  190055. }
  190056. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190057. png_error(png_ptr, "Duplicate PLTE chunk");
  190058. png_ptr->mode |= PNG_HAVE_PLTE;
  190059. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  190060. {
  190061. png_warning(png_ptr,
  190062. "Ignoring PLTE chunk in grayscale PNG");
  190063. png_crc_finish(png_ptr, length);
  190064. return;
  190065. }
  190066. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190067. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190068. {
  190069. png_crc_finish(png_ptr, length);
  190070. return;
  190071. }
  190072. #endif
  190073. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  190074. {
  190075. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  190076. {
  190077. png_warning(png_ptr, "Invalid palette chunk");
  190078. png_crc_finish(png_ptr, length);
  190079. return;
  190080. }
  190081. else
  190082. {
  190083. png_error(png_ptr, "Invalid palette chunk");
  190084. }
  190085. }
  190086. num = (int)length / 3;
  190087. #ifndef PNG_NO_POINTER_INDEXING
  190088. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  190089. {
  190090. png_byte buf[3];
  190091. png_crc_read(png_ptr, buf, 3);
  190092. pal_ptr->red = buf[0];
  190093. pal_ptr->green = buf[1];
  190094. pal_ptr->blue = buf[2];
  190095. }
  190096. #else
  190097. for (i = 0; i < num; i++)
  190098. {
  190099. png_byte buf[3];
  190100. png_crc_read(png_ptr, buf, 3);
  190101. /* don't depend upon png_color being any order */
  190102. palette[i].red = buf[0];
  190103. palette[i].green = buf[1];
  190104. palette[i].blue = buf[2];
  190105. }
  190106. #endif
  190107. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  190108. whatever the normal CRC configuration tells us. However, if we
  190109. have an RGB image, the PLTE can be considered ancillary, so
  190110. we will act as though it is. */
  190111. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190112. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190113. #endif
  190114. {
  190115. png_crc_finish(png_ptr, 0);
  190116. }
  190117. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  190118. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  190119. {
  190120. /* If we don't want to use the data from an ancillary chunk,
  190121. we have two options: an error abort, or a warning and we
  190122. ignore the data in this chunk (which should be OK, since
  190123. it's considered ancillary for a RGB or RGBA image). */
  190124. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  190125. {
  190126. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  190127. {
  190128. png_chunk_error(png_ptr, "CRC error");
  190129. }
  190130. else
  190131. {
  190132. png_chunk_warning(png_ptr, "CRC error");
  190133. return;
  190134. }
  190135. }
  190136. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  190137. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  190138. {
  190139. png_chunk_warning(png_ptr, "CRC error");
  190140. }
  190141. }
  190142. #endif
  190143. png_set_PLTE(png_ptr, info_ptr, palette, num);
  190144. #if defined(PNG_READ_tRNS_SUPPORTED)
  190145. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190146. {
  190147. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190148. {
  190149. if (png_ptr->num_trans > (png_uint_16)num)
  190150. {
  190151. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  190152. png_ptr->num_trans = (png_uint_16)num;
  190153. }
  190154. if (info_ptr->num_trans > (png_uint_16)num)
  190155. {
  190156. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  190157. info_ptr->num_trans = (png_uint_16)num;
  190158. }
  190159. }
  190160. }
  190161. #endif
  190162. }
  190163. void /* PRIVATE */
  190164. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190165. {
  190166. png_debug(1, "in png_handle_IEND\n");
  190167. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  190168. {
  190169. png_error(png_ptr, "No image in file");
  190170. }
  190171. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  190172. if (length != 0)
  190173. {
  190174. png_warning(png_ptr, "Incorrect IEND chunk length");
  190175. }
  190176. png_crc_finish(png_ptr, length);
  190177. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  190178. }
  190179. #if defined(PNG_READ_gAMA_SUPPORTED)
  190180. void /* PRIVATE */
  190181. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190182. {
  190183. png_fixed_point igamma;
  190184. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190185. float file_gamma;
  190186. #endif
  190187. png_byte buf[4];
  190188. png_debug(1, "in png_handle_gAMA\n");
  190189. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190190. png_error(png_ptr, "Missing IHDR before gAMA");
  190191. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190192. {
  190193. png_warning(png_ptr, "Invalid gAMA after IDAT");
  190194. png_crc_finish(png_ptr, length);
  190195. return;
  190196. }
  190197. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190198. /* Should be an error, but we can cope with it */
  190199. png_warning(png_ptr, "Out of place gAMA chunk");
  190200. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  190201. #if defined(PNG_READ_sRGB_SUPPORTED)
  190202. && !(info_ptr->valid & PNG_INFO_sRGB)
  190203. #endif
  190204. )
  190205. {
  190206. png_warning(png_ptr, "Duplicate gAMA chunk");
  190207. png_crc_finish(png_ptr, length);
  190208. return;
  190209. }
  190210. if (length != 4)
  190211. {
  190212. png_warning(png_ptr, "Incorrect gAMA chunk length");
  190213. png_crc_finish(png_ptr, length);
  190214. return;
  190215. }
  190216. png_crc_read(png_ptr, buf, 4);
  190217. if (png_crc_finish(png_ptr, 0))
  190218. return;
  190219. igamma = (png_fixed_point)png_get_uint_32(buf);
  190220. /* check for zero gamma */
  190221. if (igamma == 0)
  190222. {
  190223. png_warning(png_ptr,
  190224. "Ignoring gAMA chunk with gamma=0");
  190225. return;
  190226. }
  190227. #if defined(PNG_READ_sRGB_SUPPORTED)
  190228. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190229. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190230. {
  190231. png_warning(png_ptr,
  190232. "Ignoring incorrect gAMA value when sRGB is also present");
  190233. #ifndef PNG_NO_CONSOLE_IO
  190234. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  190235. #endif
  190236. return;
  190237. }
  190238. #endif /* PNG_READ_sRGB_SUPPORTED */
  190239. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190240. file_gamma = (float)igamma / (float)100000.0;
  190241. # ifdef PNG_READ_GAMMA_SUPPORTED
  190242. png_ptr->gamma = file_gamma;
  190243. # endif
  190244. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  190245. #endif
  190246. #ifdef PNG_FIXED_POINT_SUPPORTED
  190247. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  190248. #endif
  190249. }
  190250. #endif
  190251. #if defined(PNG_READ_sBIT_SUPPORTED)
  190252. void /* PRIVATE */
  190253. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190254. {
  190255. png_size_t truelen;
  190256. png_byte buf[4];
  190257. png_debug(1, "in png_handle_sBIT\n");
  190258. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  190259. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190260. png_error(png_ptr, "Missing IHDR before sBIT");
  190261. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190262. {
  190263. png_warning(png_ptr, "Invalid sBIT after IDAT");
  190264. png_crc_finish(png_ptr, length);
  190265. return;
  190266. }
  190267. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190268. {
  190269. /* Should be an error, but we can cope with it */
  190270. png_warning(png_ptr, "Out of place sBIT chunk");
  190271. }
  190272. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  190273. {
  190274. png_warning(png_ptr, "Duplicate sBIT chunk");
  190275. png_crc_finish(png_ptr, length);
  190276. return;
  190277. }
  190278. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190279. truelen = 3;
  190280. else
  190281. truelen = (png_size_t)png_ptr->channels;
  190282. if (length != truelen || length > 4)
  190283. {
  190284. png_warning(png_ptr, "Incorrect sBIT chunk length");
  190285. png_crc_finish(png_ptr, length);
  190286. return;
  190287. }
  190288. png_crc_read(png_ptr, buf, truelen);
  190289. if (png_crc_finish(png_ptr, 0))
  190290. return;
  190291. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190292. {
  190293. png_ptr->sig_bit.red = buf[0];
  190294. png_ptr->sig_bit.green = buf[1];
  190295. png_ptr->sig_bit.blue = buf[2];
  190296. png_ptr->sig_bit.alpha = buf[3];
  190297. }
  190298. else
  190299. {
  190300. png_ptr->sig_bit.gray = buf[0];
  190301. png_ptr->sig_bit.red = buf[0];
  190302. png_ptr->sig_bit.green = buf[0];
  190303. png_ptr->sig_bit.blue = buf[0];
  190304. png_ptr->sig_bit.alpha = buf[1];
  190305. }
  190306. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  190307. }
  190308. #endif
  190309. #if defined(PNG_READ_cHRM_SUPPORTED)
  190310. void /* PRIVATE */
  190311. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190312. {
  190313. png_byte buf[4];
  190314. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190315. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  190316. #endif
  190317. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190318. int_y_green, int_x_blue, int_y_blue;
  190319. png_uint_32 uint_x, uint_y;
  190320. png_debug(1, "in png_handle_cHRM\n");
  190321. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190322. png_error(png_ptr, "Missing IHDR before cHRM");
  190323. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190324. {
  190325. png_warning(png_ptr, "Invalid cHRM after IDAT");
  190326. png_crc_finish(png_ptr, length);
  190327. return;
  190328. }
  190329. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190330. /* Should be an error, but we can cope with it */
  190331. png_warning(png_ptr, "Missing PLTE before cHRM");
  190332. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  190333. #if defined(PNG_READ_sRGB_SUPPORTED)
  190334. && !(info_ptr->valid & PNG_INFO_sRGB)
  190335. #endif
  190336. )
  190337. {
  190338. png_warning(png_ptr, "Duplicate cHRM chunk");
  190339. png_crc_finish(png_ptr, length);
  190340. return;
  190341. }
  190342. if (length != 32)
  190343. {
  190344. png_warning(png_ptr, "Incorrect cHRM chunk length");
  190345. png_crc_finish(png_ptr, length);
  190346. return;
  190347. }
  190348. png_crc_read(png_ptr, buf, 4);
  190349. uint_x = png_get_uint_32(buf);
  190350. png_crc_read(png_ptr, buf, 4);
  190351. uint_y = png_get_uint_32(buf);
  190352. if (uint_x > 80000L || uint_y > 80000L ||
  190353. uint_x + uint_y > 100000L)
  190354. {
  190355. png_warning(png_ptr, "Invalid cHRM white point");
  190356. png_crc_finish(png_ptr, 24);
  190357. return;
  190358. }
  190359. int_x_white = (png_fixed_point)uint_x;
  190360. int_y_white = (png_fixed_point)uint_y;
  190361. png_crc_read(png_ptr, buf, 4);
  190362. uint_x = png_get_uint_32(buf);
  190363. png_crc_read(png_ptr, buf, 4);
  190364. uint_y = png_get_uint_32(buf);
  190365. if (uint_x + uint_y > 100000L)
  190366. {
  190367. png_warning(png_ptr, "Invalid cHRM red point");
  190368. png_crc_finish(png_ptr, 16);
  190369. return;
  190370. }
  190371. int_x_red = (png_fixed_point)uint_x;
  190372. int_y_red = (png_fixed_point)uint_y;
  190373. png_crc_read(png_ptr, buf, 4);
  190374. uint_x = png_get_uint_32(buf);
  190375. png_crc_read(png_ptr, buf, 4);
  190376. uint_y = png_get_uint_32(buf);
  190377. if (uint_x + uint_y > 100000L)
  190378. {
  190379. png_warning(png_ptr, "Invalid cHRM green point");
  190380. png_crc_finish(png_ptr, 8);
  190381. return;
  190382. }
  190383. int_x_green = (png_fixed_point)uint_x;
  190384. int_y_green = (png_fixed_point)uint_y;
  190385. png_crc_read(png_ptr, buf, 4);
  190386. uint_x = png_get_uint_32(buf);
  190387. png_crc_read(png_ptr, buf, 4);
  190388. uint_y = png_get_uint_32(buf);
  190389. if (uint_x + uint_y > 100000L)
  190390. {
  190391. png_warning(png_ptr, "Invalid cHRM blue point");
  190392. png_crc_finish(png_ptr, 0);
  190393. return;
  190394. }
  190395. int_x_blue = (png_fixed_point)uint_x;
  190396. int_y_blue = (png_fixed_point)uint_y;
  190397. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190398. white_x = (float)int_x_white / (float)100000.0;
  190399. white_y = (float)int_y_white / (float)100000.0;
  190400. red_x = (float)int_x_red / (float)100000.0;
  190401. red_y = (float)int_y_red / (float)100000.0;
  190402. green_x = (float)int_x_green / (float)100000.0;
  190403. green_y = (float)int_y_green / (float)100000.0;
  190404. blue_x = (float)int_x_blue / (float)100000.0;
  190405. blue_y = (float)int_y_blue / (float)100000.0;
  190406. #endif
  190407. #if defined(PNG_READ_sRGB_SUPPORTED)
  190408. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  190409. {
  190410. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  190411. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  190412. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  190413. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  190414. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  190415. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  190416. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  190417. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  190418. {
  190419. png_warning(png_ptr,
  190420. "Ignoring incorrect cHRM value when sRGB is also present");
  190421. #ifndef PNG_NO_CONSOLE_IO
  190422. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190423. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  190424. white_x, white_y, red_x, red_y);
  190425. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  190426. green_x, green_y, blue_x, blue_y);
  190427. #else
  190428. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  190429. int_x_white, int_y_white, int_x_red, int_y_red);
  190430. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  190431. int_x_green, int_y_green, int_x_blue, int_y_blue);
  190432. #endif
  190433. #endif /* PNG_NO_CONSOLE_IO */
  190434. }
  190435. png_crc_finish(png_ptr, 0);
  190436. return;
  190437. }
  190438. #endif /* PNG_READ_sRGB_SUPPORTED */
  190439. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190440. png_set_cHRM(png_ptr, info_ptr,
  190441. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  190442. #endif
  190443. #ifdef PNG_FIXED_POINT_SUPPORTED
  190444. png_set_cHRM_fixed(png_ptr, info_ptr,
  190445. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190446. int_y_green, int_x_blue, int_y_blue);
  190447. #endif
  190448. if (png_crc_finish(png_ptr, 0))
  190449. return;
  190450. }
  190451. #endif
  190452. #if defined(PNG_READ_sRGB_SUPPORTED)
  190453. void /* PRIVATE */
  190454. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190455. {
  190456. int intent;
  190457. png_byte buf[1];
  190458. png_debug(1, "in png_handle_sRGB\n");
  190459. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190460. png_error(png_ptr, "Missing IHDR before sRGB");
  190461. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190462. {
  190463. png_warning(png_ptr, "Invalid sRGB after IDAT");
  190464. png_crc_finish(png_ptr, length);
  190465. return;
  190466. }
  190467. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190468. /* Should be an error, but we can cope with it */
  190469. png_warning(png_ptr, "Out of place sRGB chunk");
  190470. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190471. {
  190472. png_warning(png_ptr, "Duplicate sRGB chunk");
  190473. png_crc_finish(png_ptr, length);
  190474. return;
  190475. }
  190476. if (length != 1)
  190477. {
  190478. png_warning(png_ptr, "Incorrect sRGB chunk length");
  190479. png_crc_finish(png_ptr, length);
  190480. return;
  190481. }
  190482. png_crc_read(png_ptr, buf, 1);
  190483. if (png_crc_finish(png_ptr, 0))
  190484. return;
  190485. intent = buf[0];
  190486. /* check for bad intent */
  190487. if (intent >= PNG_sRGB_INTENT_LAST)
  190488. {
  190489. png_warning(png_ptr, "Unknown sRGB intent");
  190490. return;
  190491. }
  190492. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190493. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  190494. {
  190495. png_fixed_point igamma;
  190496. #ifdef PNG_FIXED_POINT_SUPPORTED
  190497. igamma=info_ptr->int_gamma;
  190498. #else
  190499. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190500. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  190501. # endif
  190502. #endif
  190503. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190504. {
  190505. png_warning(png_ptr,
  190506. "Ignoring incorrect gAMA value when sRGB is also present");
  190507. #ifndef PNG_NO_CONSOLE_IO
  190508. # ifdef PNG_FIXED_POINT_SUPPORTED
  190509. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  190510. # else
  190511. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190512. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  190513. # endif
  190514. # endif
  190515. #endif
  190516. }
  190517. }
  190518. #endif /* PNG_READ_gAMA_SUPPORTED */
  190519. #ifdef PNG_READ_cHRM_SUPPORTED
  190520. #ifdef PNG_FIXED_POINT_SUPPORTED
  190521. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  190522. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  190523. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  190524. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  190525. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  190526. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  190527. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  190528. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  190529. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  190530. {
  190531. png_warning(png_ptr,
  190532. "Ignoring incorrect cHRM value when sRGB is also present");
  190533. }
  190534. #endif /* PNG_FIXED_POINT_SUPPORTED */
  190535. #endif /* PNG_READ_cHRM_SUPPORTED */
  190536. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  190537. }
  190538. #endif /* PNG_READ_sRGB_SUPPORTED */
  190539. #if defined(PNG_READ_iCCP_SUPPORTED)
  190540. void /* PRIVATE */
  190541. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190542. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190543. {
  190544. png_charp chunkdata;
  190545. png_byte compression_type;
  190546. png_bytep pC;
  190547. png_charp profile;
  190548. png_uint_32 skip = 0;
  190549. png_uint_32 profile_size, profile_length;
  190550. png_size_t slength, prefix_length, data_length;
  190551. png_debug(1, "in png_handle_iCCP\n");
  190552. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190553. png_error(png_ptr, "Missing IHDR before iCCP");
  190554. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190555. {
  190556. png_warning(png_ptr, "Invalid iCCP after IDAT");
  190557. png_crc_finish(png_ptr, length);
  190558. return;
  190559. }
  190560. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190561. /* Should be an error, but we can cope with it */
  190562. png_warning(png_ptr, "Out of place iCCP chunk");
  190563. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  190564. {
  190565. png_warning(png_ptr, "Duplicate iCCP chunk");
  190566. png_crc_finish(png_ptr, length);
  190567. return;
  190568. }
  190569. #ifdef PNG_MAX_MALLOC_64K
  190570. if (length > (png_uint_32)65535L)
  190571. {
  190572. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  190573. skip = length - (png_uint_32)65535L;
  190574. length = (png_uint_32)65535L;
  190575. }
  190576. #endif
  190577. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  190578. slength = (png_size_t)length;
  190579. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190580. if (png_crc_finish(png_ptr, skip))
  190581. {
  190582. png_free(png_ptr, chunkdata);
  190583. return;
  190584. }
  190585. chunkdata[slength] = 0x00;
  190586. for (profile = chunkdata; *profile; profile++)
  190587. /* empty loop to find end of name */ ;
  190588. ++profile;
  190589. /* there should be at least one zero (the compression type byte)
  190590. following the separator, and we should be on it */
  190591. if ( profile >= chunkdata + slength - 1)
  190592. {
  190593. png_free(png_ptr, chunkdata);
  190594. png_warning(png_ptr, "Malformed iCCP chunk");
  190595. return;
  190596. }
  190597. /* compression_type should always be zero */
  190598. compression_type = *profile++;
  190599. if (compression_type)
  190600. {
  190601. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  190602. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  190603. wrote nonzero) */
  190604. }
  190605. prefix_length = profile - chunkdata;
  190606. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  190607. slength, prefix_length, &data_length);
  190608. profile_length = data_length - prefix_length;
  190609. if ( prefix_length > data_length || profile_length < 4)
  190610. {
  190611. png_free(png_ptr, chunkdata);
  190612. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  190613. return;
  190614. }
  190615. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  190616. pC = (png_bytep)(chunkdata+prefix_length);
  190617. profile_size = ((*(pC ))<<24) |
  190618. ((*(pC+1))<<16) |
  190619. ((*(pC+2))<< 8) |
  190620. ((*(pC+3)) );
  190621. if(profile_size < profile_length)
  190622. profile_length = profile_size;
  190623. if(profile_size > profile_length)
  190624. {
  190625. png_free(png_ptr, chunkdata);
  190626. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  190627. return;
  190628. }
  190629. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  190630. chunkdata + prefix_length, profile_length);
  190631. png_free(png_ptr, chunkdata);
  190632. }
  190633. #endif /* PNG_READ_iCCP_SUPPORTED */
  190634. #if defined(PNG_READ_sPLT_SUPPORTED)
  190635. void /* PRIVATE */
  190636. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190637. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190638. {
  190639. png_bytep chunkdata;
  190640. png_bytep entry_start;
  190641. png_sPLT_t new_palette;
  190642. #ifdef PNG_NO_POINTER_INDEXING
  190643. png_sPLT_entryp pp;
  190644. #endif
  190645. int data_length, entry_size, i;
  190646. png_uint_32 skip = 0;
  190647. png_size_t slength;
  190648. png_debug(1, "in png_handle_sPLT\n");
  190649. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190650. png_error(png_ptr, "Missing IHDR before sPLT");
  190651. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190652. {
  190653. png_warning(png_ptr, "Invalid sPLT after IDAT");
  190654. png_crc_finish(png_ptr, length);
  190655. return;
  190656. }
  190657. #ifdef PNG_MAX_MALLOC_64K
  190658. if (length > (png_uint_32)65535L)
  190659. {
  190660. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  190661. skip = length - (png_uint_32)65535L;
  190662. length = (png_uint_32)65535L;
  190663. }
  190664. #endif
  190665. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  190666. slength = (png_size_t)length;
  190667. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190668. if (png_crc_finish(png_ptr, skip))
  190669. {
  190670. png_free(png_ptr, chunkdata);
  190671. return;
  190672. }
  190673. chunkdata[slength] = 0x00;
  190674. for (entry_start = chunkdata; *entry_start; entry_start++)
  190675. /* empty loop to find end of name */ ;
  190676. ++entry_start;
  190677. /* a sample depth should follow the separator, and we should be on it */
  190678. if (entry_start > chunkdata + slength - 2)
  190679. {
  190680. png_free(png_ptr, chunkdata);
  190681. png_warning(png_ptr, "malformed sPLT chunk");
  190682. return;
  190683. }
  190684. new_palette.depth = *entry_start++;
  190685. entry_size = (new_palette.depth == 8 ? 6 : 10);
  190686. data_length = (slength - (entry_start - chunkdata));
  190687. /* integrity-check the data length */
  190688. if (data_length % entry_size)
  190689. {
  190690. png_free(png_ptr, chunkdata);
  190691. png_warning(png_ptr, "sPLT chunk has bad length");
  190692. return;
  190693. }
  190694. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  190695. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  190696. png_sizeof(png_sPLT_entry)))
  190697. {
  190698. png_warning(png_ptr, "sPLT chunk too long");
  190699. return;
  190700. }
  190701. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  190702. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  190703. if (new_palette.entries == NULL)
  190704. {
  190705. png_warning(png_ptr, "sPLT chunk requires too much memory");
  190706. return;
  190707. }
  190708. #ifndef PNG_NO_POINTER_INDEXING
  190709. for (i = 0; i < new_palette.nentries; i++)
  190710. {
  190711. png_sPLT_entryp pp = new_palette.entries + i;
  190712. if (new_palette.depth == 8)
  190713. {
  190714. pp->red = *entry_start++;
  190715. pp->green = *entry_start++;
  190716. pp->blue = *entry_start++;
  190717. pp->alpha = *entry_start++;
  190718. }
  190719. else
  190720. {
  190721. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  190722. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  190723. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  190724. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  190725. }
  190726. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190727. }
  190728. #else
  190729. pp = new_palette.entries;
  190730. for (i = 0; i < new_palette.nentries; i++)
  190731. {
  190732. if (new_palette.depth == 8)
  190733. {
  190734. pp[i].red = *entry_start++;
  190735. pp[i].green = *entry_start++;
  190736. pp[i].blue = *entry_start++;
  190737. pp[i].alpha = *entry_start++;
  190738. }
  190739. else
  190740. {
  190741. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  190742. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  190743. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  190744. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  190745. }
  190746. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190747. }
  190748. #endif
  190749. /* discard all chunk data except the name and stash that */
  190750. new_palette.name = (png_charp)chunkdata;
  190751. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  190752. png_free(png_ptr, chunkdata);
  190753. png_free(png_ptr, new_palette.entries);
  190754. }
  190755. #endif /* PNG_READ_sPLT_SUPPORTED */
  190756. #if defined(PNG_READ_tRNS_SUPPORTED)
  190757. void /* PRIVATE */
  190758. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190759. {
  190760. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  190761. int bit_mask;
  190762. png_debug(1, "in png_handle_tRNS\n");
  190763. /* For non-indexed color, mask off any bits in the tRNS value that
  190764. * exceed the bit depth. Some creators were writing extra bits there.
  190765. * This is not needed for indexed color. */
  190766. bit_mask = (1 << png_ptr->bit_depth) - 1;
  190767. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190768. png_error(png_ptr, "Missing IHDR before tRNS");
  190769. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190770. {
  190771. png_warning(png_ptr, "Invalid tRNS after IDAT");
  190772. png_crc_finish(png_ptr, length);
  190773. return;
  190774. }
  190775. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190776. {
  190777. png_warning(png_ptr, "Duplicate tRNS chunk");
  190778. png_crc_finish(png_ptr, length);
  190779. return;
  190780. }
  190781. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190782. {
  190783. png_byte buf[2];
  190784. if (length != 2)
  190785. {
  190786. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190787. png_crc_finish(png_ptr, length);
  190788. return;
  190789. }
  190790. png_crc_read(png_ptr, buf, 2);
  190791. png_ptr->num_trans = 1;
  190792. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  190793. }
  190794. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190795. {
  190796. png_byte buf[6];
  190797. if (length != 6)
  190798. {
  190799. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190800. png_crc_finish(png_ptr, length);
  190801. return;
  190802. }
  190803. png_crc_read(png_ptr, buf, (png_size_t)length);
  190804. png_ptr->num_trans = 1;
  190805. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  190806. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  190807. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  190808. }
  190809. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190810. {
  190811. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190812. {
  190813. /* Should be an error, but we can cope with it. */
  190814. png_warning(png_ptr, "Missing PLTE before tRNS");
  190815. }
  190816. if (length > (png_uint_32)png_ptr->num_palette ||
  190817. length > PNG_MAX_PALETTE_LENGTH)
  190818. {
  190819. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190820. png_crc_finish(png_ptr, length);
  190821. return;
  190822. }
  190823. if (length == 0)
  190824. {
  190825. png_warning(png_ptr, "Zero length tRNS chunk");
  190826. png_crc_finish(png_ptr, length);
  190827. return;
  190828. }
  190829. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  190830. png_ptr->num_trans = (png_uint_16)length;
  190831. }
  190832. else
  190833. {
  190834. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  190835. png_crc_finish(png_ptr, length);
  190836. return;
  190837. }
  190838. if (png_crc_finish(png_ptr, 0))
  190839. {
  190840. png_ptr->num_trans = 0;
  190841. return;
  190842. }
  190843. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  190844. &(png_ptr->trans_values));
  190845. }
  190846. #endif
  190847. #if defined(PNG_READ_bKGD_SUPPORTED)
  190848. void /* PRIVATE */
  190849. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190850. {
  190851. png_size_t truelen;
  190852. png_byte buf[6];
  190853. png_debug(1, "in png_handle_bKGD\n");
  190854. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190855. png_error(png_ptr, "Missing IHDR before bKGD");
  190856. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190857. {
  190858. png_warning(png_ptr, "Invalid bKGD after IDAT");
  190859. png_crc_finish(png_ptr, length);
  190860. return;
  190861. }
  190862. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  190863. !(png_ptr->mode & PNG_HAVE_PLTE))
  190864. {
  190865. png_warning(png_ptr, "Missing PLTE before bKGD");
  190866. png_crc_finish(png_ptr, length);
  190867. return;
  190868. }
  190869. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  190870. {
  190871. png_warning(png_ptr, "Duplicate bKGD chunk");
  190872. png_crc_finish(png_ptr, length);
  190873. return;
  190874. }
  190875. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190876. truelen = 1;
  190877. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190878. truelen = 6;
  190879. else
  190880. truelen = 2;
  190881. if (length != truelen)
  190882. {
  190883. png_warning(png_ptr, "Incorrect bKGD chunk length");
  190884. png_crc_finish(png_ptr, length);
  190885. return;
  190886. }
  190887. png_crc_read(png_ptr, buf, truelen);
  190888. if (png_crc_finish(png_ptr, 0))
  190889. return;
  190890. /* We convert the index value into RGB components so that we can allow
  190891. * arbitrary RGB values for background when we have transparency, and
  190892. * so it is easy to determine the RGB values of the background color
  190893. * from the info_ptr struct. */
  190894. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190895. {
  190896. png_ptr->background.index = buf[0];
  190897. if(info_ptr->num_palette)
  190898. {
  190899. if(buf[0] > info_ptr->num_palette)
  190900. {
  190901. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  190902. return;
  190903. }
  190904. png_ptr->background.red =
  190905. (png_uint_16)png_ptr->palette[buf[0]].red;
  190906. png_ptr->background.green =
  190907. (png_uint_16)png_ptr->palette[buf[0]].green;
  190908. png_ptr->background.blue =
  190909. (png_uint_16)png_ptr->palette[buf[0]].blue;
  190910. }
  190911. }
  190912. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  190913. {
  190914. png_ptr->background.red =
  190915. png_ptr->background.green =
  190916. png_ptr->background.blue =
  190917. png_ptr->background.gray = png_get_uint_16(buf);
  190918. }
  190919. else
  190920. {
  190921. png_ptr->background.red = png_get_uint_16(buf);
  190922. png_ptr->background.green = png_get_uint_16(buf + 2);
  190923. png_ptr->background.blue = png_get_uint_16(buf + 4);
  190924. }
  190925. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  190926. }
  190927. #endif
  190928. #if defined(PNG_READ_hIST_SUPPORTED)
  190929. void /* PRIVATE */
  190930. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190931. {
  190932. unsigned int num, i;
  190933. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  190934. png_debug(1, "in png_handle_hIST\n");
  190935. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190936. png_error(png_ptr, "Missing IHDR before hIST");
  190937. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190938. {
  190939. png_warning(png_ptr, "Invalid hIST after IDAT");
  190940. png_crc_finish(png_ptr, length);
  190941. return;
  190942. }
  190943. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190944. {
  190945. png_warning(png_ptr, "Missing PLTE before hIST");
  190946. png_crc_finish(png_ptr, length);
  190947. return;
  190948. }
  190949. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  190950. {
  190951. png_warning(png_ptr, "Duplicate hIST chunk");
  190952. png_crc_finish(png_ptr, length);
  190953. return;
  190954. }
  190955. num = length / 2 ;
  190956. if (num != (unsigned int) png_ptr->num_palette || num >
  190957. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  190958. {
  190959. png_warning(png_ptr, "Incorrect hIST chunk length");
  190960. png_crc_finish(png_ptr, length);
  190961. return;
  190962. }
  190963. for (i = 0; i < num; i++)
  190964. {
  190965. png_byte buf[2];
  190966. png_crc_read(png_ptr, buf, 2);
  190967. readbuf[i] = png_get_uint_16(buf);
  190968. }
  190969. if (png_crc_finish(png_ptr, 0))
  190970. return;
  190971. png_set_hIST(png_ptr, info_ptr, readbuf);
  190972. }
  190973. #endif
  190974. #if defined(PNG_READ_pHYs_SUPPORTED)
  190975. void /* PRIVATE */
  190976. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190977. {
  190978. png_byte buf[9];
  190979. png_uint_32 res_x, res_y;
  190980. int unit_type;
  190981. png_debug(1, "in png_handle_pHYs\n");
  190982. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190983. png_error(png_ptr, "Missing IHDR before pHYs");
  190984. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190985. {
  190986. png_warning(png_ptr, "Invalid pHYs after IDAT");
  190987. png_crc_finish(png_ptr, length);
  190988. return;
  190989. }
  190990. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  190991. {
  190992. png_warning(png_ptr, "Duplicate pHYs chunk");
  190993. png_crc_finish(png_ptr, length);
  190994. return;
  190995. }
  190996. if (length != 9)
  190997. {
  190998. png_warning(png_ptr, "Incorrect pHYs chunk length");
  190999. png_crc_finish(png_ptr, length);
  191000. return;
  191001. }
  191002. png_crc_read(png_ptr, buf, 9);
  191003. if (png_crc_finish(png_ptr, 0))
  191004. return;
  191005. res_x = png_get_uint_32(buf);
  191006. res_y = png_get_uint_32(buf + 4);
  191007. unit_type = buf[8];
  191008. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  191009. }
  191010. #endif
  191011. #if defined(PNG_READ_oFFs_SUPPORTED)
  191012. void /* PRIVATE */
  191013. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191014. {
  191015. png_byte buf[9];
  191016. png_int_32 offset_x, offset_y;
  191017. int unit_type;
  191018. png_debug(1, "in png_handle_oFFs\n");
  191019. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191020. png_error(png_ptr, "Missing IHDR before oFFs");
  191021. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191022. {
  191023. png_warning(png_ptr, "Invalid oFFs after IDAT");
  191024. png_crc_finish(png_ptr, length);
  191025. return;
  191026. }
  191027. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  191028. {
  191029. png_warning(png_ptr, "Duplicate oFFs chunk");
  191030. png_crc_finish(png_ptr, length);
  191031. return;
  191032. }
  191033. if (length != 9)
  191034. {
  191035. png_warning(png_ptr, "Incorrect oFFs chunk length");
  191036. png_crc_finish(png_ptr, length);
  191037. return;
  191038. }
  191039. png_crc_read(png_ptr, buf, 9);
  191040. if (png_crc_finish(png_ptr, 0))
  191041. return;
  191042. offset_x = png_get_int_32(buf);
  191043. offset_y = png_get_int_32(buf + 4);
  191044. unit_type = buf[8];
  191045. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  191046. }
  191047. #endif
  191048. #if defined(PNG_READ_pCAL_SUPPORTED)
  191049. /* read the pCAL chunk (described in the PNG Extensions document) */
  191050. void /* PRIVATE */
  191051. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191052. {
  191053. png_charp purpose;
  191054. png_int_32 X0, X1;
  191055. png_byte type, nparams;
  191056. png_charp buf, units, endptr;
  191057. png_charpp params;
  191058. png_size_t slength;
  191059. int i;
  191060. png_debug(1, "in png_handle_pCAL\n");
  191061. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191062. png_error(png_ptr, "Missing IHDR before pCAL");
  191063. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191064. {
  191065. png_warning(png_ptr, "Invalid pCAL after IDAT");
  191066. png_crc_finish(png_ptr, length);
  191067. return;
  191068. }
  191069. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  191070. {
  191071. png_warning(png_ptr, "Duplicate pCAL chunk");
  191072. png_crc_finish(png_ptr, length);
  191073. return;
  191074. }
  191075. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  191076. length + 1);
  191077. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191078. if (purpose == NULL)
  191079. {
  191080. png_warning(png_ptr, "No memory for pCAL purpose.");
  191081. return;
  191082. }
  191083. slength = (png_size_t)length;
  191084. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  191085. if (png_crc_finish(png_ptr, 0))
  191086. {
  191087. png_free(png_ptr, purpose);
  191088. return;
  191089. }
  191090. purpose[slength] = 0x00; /* null terminate the last string */
  191091. png_debug(3, "Finding end of pCAL purpose string\n");
  191092. for (buf = purpose; *buf; buf++)
  191093. /* empty loop */ ;
  191094. endptr = purpose + slength;
  191095. /* We need to have at least 12 bytes after the purpose string
  191096. in order to get the parameter information. */
  191097. if (endptr <= buf + 12)
  191098. {
  191099. png_warning(png_ptr, "Invalid pCAL data");
  191100. png_free(png_ptr, purpose);
  191101. return;
  191102. }
  191103. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  191104. X0 = png_get_int_32((png_bytep)buf+1);
  191105. X1 = png_get_int_32((png_bytep)buf+5);
  191106. type = buf[9];
  191107. nparams = buf[10];
  191108. units = buf + 11;
  191109. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  191110. /* Check that we have the right number of parameters for known
  191111. equation types. */
  191112. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  191113. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  191114. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  191115. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  191116. {
  191117. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  191118. png_free(png_ptr, purpose);
  191119. return;
  191120. }
  191121. else if (type >= PNG_EQUATION_LAST)
  191122. {
  191123. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  191124. }
  191125. for (buf = units; *buf; buf++)
  191126. /* Empty loop to move past the units string. */ ;
  191127. png_debug(3, "Allocating pCAL parameters array\n");
  191128. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  191129. *png_sizeof(png_charp))) ;
  191130. if (params == NULL)
  191131. {
  191132. png_free(png_ptr, purpose);
  191133. png_warning(png_ptr, "No memory for pCAL params.");
  191134. return;
  191135. }
  191136. /* Get pointers to the start of each parameter string. */
  191137. for (i = 0; i < (int)nparams; i++)
  191138. {
  191139. buf++; /* Skip the null string terminator from previous parameter. */
  191140. png_debug1(3, "Reading pCAL parameter %d\n", i);
  191141. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  191142. /* Empty loop to move past each parameter string */ ;
  191143. /* Make sure we haven't run out of data yet */
  191144. if (buf > endptr)
  191145. {
  191146. png_warning(png_ptr, "Invalid pCAL data");
  191147. png_free(png_ptr, purpose);
  191148. png_free(png_ptr, params);
  191149. return;
  191150. }
  191151. }
  191152. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  191153. units, params);
  191154. png_free(png_ptr, purpose);
  191155. png_free(png_ptr, params);
  191156. }
  191157. #endif
  191158. #if defined(PNG_READ_sCAL_SUPPORTED)
  191159. /* read the sCAL chunk */
  191160. void /* PRIVATE */
  191161. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191162. {
  191163. png_charp buffer, ep;
  191164. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191165. double width, height;
  191166. png_charp vp;
  191167. #else
  191168. #ifdef PNG_FIXED_POINT_SUPPORTED
  191169. png_charp swidth, sheight;
  191170. #endif
  191171. #endif
  191172. png_size_t slength;
  191173. png_debug(1, "in png_handle_sCAL\n");
  191174. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191175. png_error(png_ptr, "Missing IHDR before sCAL");
  191176. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191177. {
  191178. png_warning(png_ptr, "Invalid sCAL after IDAT");
  191179. png_crc_finish(png_ptr, length);
  191180. return;
  191181. }
  191182. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  191183. {
  191184. png_warning(png_ptr, "Duplicate sCAL chunk");
  191185. png_crc_finish(png_ptr, length);
  191186. return;
  191187. }
  191188. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  191189. length + 1);
  191190. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191191. if (buffer == NULL)
  191192. {
  191193. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  191194. return;
  191195. }
  191196. slength = (png_size_t)length;
  191197. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  191198. if (png_crc_finish(png_ptr, 0))
  191199. {
  191200. png_free(png_ptr, buffer);
  191201. return;
  191202. }
  191203. buffer[slength] = 0x00; /* null terminate the last string */
  191204. ep = buffer + 1; /* skip unit byte */
  191205. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191206. width = png_strtod(png_ptr, ep, &vp);
  191207. if (*vp)
  191208. {
  191209. png_warning(png_ptr, "malformed width string in sCAL chunk");
  191210. return;
  191211. }
  191212. #else
  191213. #ifdef PNG_FIXED_POINT_SUPPORTED
  191214. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191215. if (swidth == NULL)
  191216. {
  191217. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  191218. return;
  191219. }
  191220. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  191221. #endif
  191222. #endif
  191223. for (ep = buffer; *ep; ep++)
  191224. /* empty loop */ ;
  191225. ep++;
  191226. if (buffer + slength < ep)
  191227. {
  191228. png_warning(png_ptr, "Truncated sCAL chunk");
  191229. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  191230. !defined(PNG_FLOATING_POINT_SUPPORTED)
  191231. png_free(png_ptr, swidth);
  191232. #endif
  191233. png_free(png_ptr, buffer);
  191234. return;
  191235. }
  191236. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191237. height = png_strtod(png_ptr, ep, &vp);
  191238. if (*vp)
  191239. {
  191240. png_warning(png_ptr, "malformed height string in sCAL chunk");
  191241. return;
  191242. }
  191243. #else
  191244. #ifdef PNG_FIXED_POINT_SUPPORTED
  191245. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191246. if (swidth == NULL)
  191247. {
  191248. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  191249. return;
  191250. }
  191251. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  191252. #endif
  191253. #endif
  191254. if (buffer + slength < ep
  191255. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191256. || width <= 0. || height <= 0.
  191257. #endif
  191258. )
  191259. {
  191260. png_warning(png_ptr, "Invalid sCAL data");
  191261. png_free(png_ptr, buffer);
  191262. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191263. png_free(png_ptr, swidth);
  191264. png_free(png_ptr, sheight);
  191265. #endif
  191266. return;
  191267. }
  191268. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191269. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  191270. #else
  191271. #ifdef PNG_FIXED_POINT_SUPPORTED
  191272. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  191273. #endif
  191274. #endif
  191275. png_free(png_ptr, buffer);
  191276. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191277. png_free(png_ptr, swidth);
  191278. png_free(png_ptr, sheight);
  191279. #endif
  191280. }
  191281. #endif
  191282. #if defined(PNG_READ_tIME_SUPPORTED)
  191283. void /* PRIVATE */
  191284. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191285. {
  191286. png_byte buf[7];
  191287. png_time mod_time;
  191288. png_debug(1, "in png_handle_tIME\n");
  191289. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191290. png_error(png_ptr, "Out of place tIME chunk");
  191291. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  191292. {
  191293. png_warning(png_ptr, "Duplicate tIME chunk");
  191294. png_crc_finish(png_ptr, length);
  191295. return;
  191296. }
  191297. if (png_ptr->mode & PNG_HAVE_IDAT)
  191298. png_ptr->mode |= PNG_AFTER_IDAT;
  191299. if (length != 7)
  191300. {
  191301. png_warning(png_ptr, "Incorrect tIME chunk length");
  191302. png_crc_finish(png_ptr, length);
  191303. return;
  191304. }
  191305. png_crc_read(png_ptr, buf, 7);
  191306. if (png_crc_finish(png_ptr, 0))
  191307. return;
  191308. mod_time.second = buf[6];
  191309. mod_time.minute = buf[5];
  191310. mod_time.hour = buf[4];
  191311. mod_time.day = buf[3];
  191312. mod_time.month = buf[2];
  191313. mod_time.year = png_get_uint_16(buf);
  191314. png_set_tIME(png_ptr, info_ptr, &mod_time);
  191315. }
  191316. #endif
  191317. #if defined(PNG_READ_tEXt_SUPPORTED)
  191318. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191319. void /* PRIVATE */
  191320. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191321. {
  191322. png_textp text_ptr;
  191323. png_charp key;
  191324. png_charp text;
  191325. png_uint_32 skip = 0;
  191326. png_size_t slength;
  191327. int ret;
  191328. png_debug(1, "in png_handle_tEXt\n");
  191329. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191330. png_error(png_ptr, "Missing IHDR before tEXt");
  191331. if (png_ptr->mode & PNG_HAVE_IDAT)
  191332. png_ptr->mode |= PNG_AFTER_IDAT;
  191333. #ifdef PNG_MAX_MALLOC_64K
  191334. if (length > (png_uint_32)65535L)
  191335. {
  191336. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  191337. skip = length - (png_uint_32)65535L;
  191338. length = (png_uint_32)65535L;
  191339. }
  191340. #endif
  191341. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191342. if (key == NULL)
  191343. {
  191344. png_warning(png_ptr, "No memory to process text chunk.");
  191345. return;
  191346. }
  191347. slength = (png_size_t)length;
  191348. png_crc_read(png_ptr, (png_bytep)key, slength);
  191349. if (png_crc_finish(png_ptr, skip))
  191350. {
  191351. png_free(png_ptr, key);
  191352. return;
  191353. }
  191354. key[slength] = 0x00;
  191355. for (text = key; *text; text++)
  191356. /* empty loop to find end of key */ ;
  191357. if (text != key + slength)
  191358. text++;
  191359. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191360. (png_uint_32)png_sizeof(png_text));
  191361. if (text_ptr == NULL)
  191362. {
  191363. png_warning(png_ptr, "Not enough memory to process text chunk.");
  191364. png_free(png_ptr, key);
  191365. return;
  191366. }
  191367. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  191368. text_ptr->key = key;
  191369. #ifdef PNG_iTXt_SUPPORTED
  191370. text_ptr->lang = NULL;
  191371. text_ptr->lang_key = NULL;
  191372. text_ptr->itxt_length = 0;
  191373. #endif
  191374. text_ptr->text = text;
  191375. text_ptr->text_length = png_strlen(text);
  191376. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191377. png_free(png_ptr, key);
  191378. png_free(png_ptr, text_ptr);
  191379. if (ret)
  191380. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  191381. }
  191382. #endif
  191383. #if defined(PNG_READ_zTXt_SUPPORTED)
  191384. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191385. void /* PRIVATE */
  191386. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191387. {
  191388. png_textp text_ptr;
  191389. png_charp chunkdata;
  191390. png_charp text;
  191391. int comp_type;
  191392. int ret;
  191393. png_size_t slength, prefix_len, data_len;
  191394. png_debug(1, "in png_handle_zTXt\n");
  191395. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191396. png_error(png_ptr, "Missing IHDR before zTXt");
  191397. if (png_ptr->mode & PNG_HAVE_IDAT)
  191398. png_ptr->mode |= PNG_AFTER_IDAT;
  191399. #ifdef PNG_MAX_MALLOC_64K
  191400. /* We will no doubt have problems with chunks even half this size, but
  191401. there is no hard and fast rule to tell us where to stop. */
  191402. if (length > (png_uint_32)65535L)
  191403. {
  191404. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  191405. png_crc_finish(png_ptr, length);
  191406. return;
  191407. }
  191408. #endif
  191409. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191410. if (chunkdata == NULL)
  191411. {
  191412. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  191413. return;
  191414. }
  191415. slength = (png_size_t)length;
  191416. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191417. if (png_crc_finish(png_ptr, 0))
  191418. {
  191419. png_free(png_ptr, chunkdata);
  191420. return;
  191421. }
  191422. chunkdata[slength] = 0x00;
  191423. for (text = chunkdata; *text; text++)
  191424. /* empty loop */ ;
  191425. /* zTXt must have some text after the chunkdataword */
  191426. if (text >= chunkdata + slength - 2)
  191427. {
  191428. png_warning(png_ptr, "Truncated zTXt chunk");
  191429. png_free(png_ptr, chunkdata);
  191430. return;
  191431. }
  191432. else
  191433. {
  191434. comp_type = *(++text);
  191435. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  191436. {
  191437. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  191438. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  191439. }
  191440. text++; /* skip the compression_method byte */
  191441. }
  191442. prefix_len = text - chunkdata;
  191443. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191444. (png_size_t)length, prefix_len, &data_len);
  191445. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191446. (png_uint_32)png_sizeof(png_text));
  191447. if (text_ptr == NULL)
  191448. {
  191449. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  191450. png_free(png_ptr, chunkdata);
  191451. return;
  191452. }
  191453. text_ptr->compression = comp_type;
  191454. text_ptr->key = chunkdata;
  191455. #ifdef PNG_iTXt_SUPPORTED
  191456. text_ptr->lang = NULL;
  191457. text_ptr->lang_key = NULL;
  191458. text_ptr->itxt_length = 0;
  191459. #endif
  191460. text_ptr->text = chunkdata + prefix_len;
  191461. text_ptr->text_length = data_len;
  191462. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191463. png_free(png_ptr, text_ptr);
  191464. png_free(png_ptr, chunkdata);
  191465. if (ret)
  191466. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  191467. }
  191468. #endif
  191469. #if defined(PNG_READ_iTXt_SUPPORTED)
  191470. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191471. void /* PRIVATE */
  191472. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191473. {
  191474. png_textp text_ptr;
  191475. png_charp chunkdata;
  191476. png_charp key, lang, text, lang_key;
  191477. int comp_flag;
  191478. int comp_type = 0;
  191479. int ret;
  191480. png_size_t slength, prefix_len, data_len;
  191481. png_debug(1, "in png_handle_iTXt\n");
  191482. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191483. png_error(png_ptr, "Missing IHDR before iTXt");
  191484. if (png_ptr->mode & PNG_HAVE_IDAT)
  191485. png_ptr->mode |= PNG_AFTER_IDAT;
  191486. #ifdef PNG_MAX_MALLOC_64K
  191487. /* We will no doubt have problems with chunks even half this size, but
  191488. there is no hard and fast rule to tell us where to stop. */
  191489. if (length > (png_uint_32)65535L)
  191490. {
  191491. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  191492. png_crc_finish(png_ptr, length);
  191493. return;
  191494. }
  191495. #endif
  191496. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191497. if (chunkdata == NULL)
  191498. {
  191499. png_warning(png_ptr, "No memory to process iTXt chunk.");
  191500. return;
  191501. }
  191502. slength = (png_size_t)length;
  191503. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191504. if (png_crc_finish(png_ptr, 0))
  191505. {
  191506. png_free(png_ptr, chunkdata);
  191507. return;
  191508. }
  191509. chunkdata[slength] = 0x00;
  191510. for (lang = chunkdata; *lang; lang++)
  191511. /* empty loop */ ;
  191512. lang++; /* skip NUL separator */
  191513. /* iTXt must have a language tag (possibly empty), two compression bytes,
  191514. translated keyword (possibly empty), and possibly some text after the
  191515. keyword */
  191516. if (lang >= chunkdata + slength - 3)
  191517. {
  191518. png_warning(png_ptr, "Truncated iTXt chunk");
  191519. png_free(png_ptr, chunkdata);
  191520. return;
  191521. }
  191522. else
  191523. {
  191524. comp_flag = *lang++;
  191525. comp_type = *lang++;
  191526. }
  191527. for (lang_key = lang; *lang_key; lang_key++)
  191528. /* empty loop */ ;
  191529. lang_key++; /* skip NUL separator */
  191530. if (lang_key >= chunkdata + slength)
  191531. {
  191532. png_warning(png_ptr, "Truncated iTXt chunk");
  191533. png_free(png_ptr, chunkdata);
  191534. return;
  191535. }
  191536. for (text = lang_key; *text; text++)
  191537. /* empty loop */ ;
  191538. text++; /* skip NUL separator */
  191539. if (text >= chunkdata + slength)
  191540. {
  191541. png_warning(png_ptr, "Malformed iTXt chunk");
  191542. png_free(png_ptr, chunkdata);
  191543. return;
  191544. }
  191545. prefix_len = text - chunkdata;
  191546. key=chunkdata;
  191547. if (comp_flag)
  191548. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191549. (size_t)length, prefix_len, &data_len);
  191550. else
  191551. data_len=png_strlen(chunkdata + prefix_len);
  191552. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191553. (png_uint_32)png_sizeof(png_text));
  191554. if (text_ptr == NULL)
  191555. {
  191556. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  191557. png_free(png_ptr, chunkdata);
  191558. return;
  191559. }
  191560. text_ptr->compression = (int)comp_flag + 1;
  191561. text_ptr->lang_key = chunkdata+(lang_key-key);
  191562. text_ptr->lang = chunkdata+(lang-key);
  191563. text_ptr->itxt_length = data_len;
  191564. text_ptr->text_length = 0;
  191565. text_ptr->key = chunkdata;
  191566. text_ptr->text = chunkdata + prefix_len;
  191567. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191568. png_free(png_ptr, text_ptr);
  191569. png_free(png_ptr, chunkdata);
  191570. if (ret)
  191571. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  191572. }
  191573. #endif
  191574. /* This function is called when we haven't found a handler for a
  191575. chunk. If there isn't a problem with the chunk itself (ie bad
  191576. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  191577. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  191578. case it will be saved away to be written out later. */
  191579. void /* PRIVATE */
  191580. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191581. {
  191582. png_uint_32 skip = 0;
  191583. png_debug(1, "in png_handle_unknown\n");
  191584. if (png_ptr->mode & PNG_HAVE_IDAT)
  191585. {
  191586. #ifdef PNG_USE_LOCAL_ARRAYS
  191587. PNG_CONST PNG_IDAT;
  191588. #endif
  191589. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  191590. png_ptr->mode |= PNG_AFTER_IDAT;
  191591. }
  191592. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  191593. if (!(png_ptr->chunk_name[0] & 0x20))
  191594. {
  191595. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191596. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191597. PNG_HANDLE_CHUNK_ALWAYS
  191598. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191599. && png_ptr->read_user_chunk_fn == NULL
  191600. #endif
  191601. )
  191602. #endif
  191603. png_chunk_error(png_ptr, "unknown critical chunk");
  191604. }
  191605. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191606. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  191607. (png_ptr->read_user_chunk_fn != NULL))
  191608. {
  191609. #ifdef PNG_MAX_MALLOC_64K
  191610. if (length > (png_uint_32)65535L)
  191611. {
  191612. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  191613. skip = length - (png_uint_32)65535L;
  191614. length = (png_uint_32)65535L;
  191615. }
  191616. #endif
  191617. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  191618. (png_charp)png_ptr->chunk_name, 5);
  191619. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  191620. png_ptr->unknown_chunk.size = (png_size_t)length;
  191621. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  191622. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191623. if(png_ptr->read_user_chunk_fn != NULL)
  191624. {
  191625. /* callback to user unknown chunk handler */
  191626. int ret;
  191627. ret = (*(png_ptr->read_user_chunk_fn))
  191628. (png_ptr, &png_ptr->unknown_chunk);
  191629. if (ret < 0)
  191630. png_chunk_error(png_ptr, "error in user chunk");
  191631. if (ret == 0)
  191632. {
  191633. if (!(png_ptr->chunk_name[0] & 0x20))
  191634. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191635. PNG_HANDLE_CHUNK_ALWAYS)
  191636. png_chunk_error(png_ptr, "unknown critical chunk");
  191637. png_set_unknown_chunks(png_ptr, info_ptr,
  191638. &png_ptr->unknown_chunk, 1);
  191639. }
  191640. }
  191641. #else
  191642. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  191643. #endif
  191644. png_free(png_ptr, png_ptr->unknown_chunk.data);
  191645. png_ptr->unknown_chunk.data = NULL;
  191646. }
  191647. else
  191648. #endif
  191649. skip = length;
  191650. png_crc_finish(png_ptr, skip);
  191651. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191652. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  191653. #endif
  191654. }
  191655. /* This function is called to verify that a chunk name is valid.
  191656. This function can't have the "critical chunk check" incorporated
  191657. into it, since in the future we will need to be able to call user
  191658. functions to handle unknown critical chunks after we check that
  191659. the chunk name itself is valid. */
  191660. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  191661. void /* PRIVATE */
  191662. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  191663. {
  191664. png_debug(1, "in png_check_chunk_name\n");
  191665. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  191666. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  191667. {
  191668. png_chunk_error(png_ptr, "invalid chunk type");
  191669. }
  191670. }
  191671. /* Combines the row recently read in with the existing pixels in the
  191672. row. This routine takes care of alpha and transparency if requested.
  191673. This routine also handles the two methods of progressive display
  191674. of interlaced images, depending on the mask value.
  191675. The mask value describes which pixels are to be combined with
  191676. the row. The pattern always repeats every 8 pixels, so just 8
  191677. bits are needed. A one indicates the pixel is to be combined,
  191678. a zero indicates the pixel is to be skipped. This is in addition
  191679. to any alpha or transparency value associated with the pixel. If
  191680. you want all pixels to be combined, pass 0xff (255) in mask. */
  191681. void /* PRIVATE */
  191682. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  191683. {
  191684. png_debug(1,"in png_combine_row\n");
  191685. if (mask == 0xff)
  191686. {
  191687. png_memcpy(row, png_ptr->row_buf + 1,
  191688. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  191689. }
  191690. else
  191691. {
  191692. switch (png_ptr->row_info.pixel_depth)
  191693. {
  191694. case 1:
  191695. {
  191696. png_bytep sp = png_ptr->row_buf + 1;
  191697. png_bytep dp = row;
  191698. int s_inc, s_start, s_end;
  191699. int m = 0x80;
  191700. int shift;
  191701. png_uint_32 i;
  191702. png_uint_32 row_width = png_ptr->width;
  191703. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191704. if (png_ptr->transformations & PNG_PACKSWAP)
  191705. {
  191706. s_start = 0;
  191707. s_end = 7;
  191708. s_inc = 1;
  191709. }
  191710. else
  191711. #endif
  191712. {
  191713. s_start = 7;
  191714. s_end = 0;
  191715. s_inc = -1;
  191716. }
  191717. shift = s_start;
  191718. for (i = 0; i < row_width; i++)
  191719. {
  191720. if (m & mask)
  191721. {
  191722. int value;
  191723. value = (*sp >> shift) & 0x01;
  191724. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191725. *dp |= (png_byte)(value << shift);
  191726. }
  191727. if (shift == s_end)
  191728. {
  191729. shift = s_start;
  191730. sp++;
  191731. dp++;
  191732. }
  191733. else
  191734. shift += s_inc;
  191735. if (m == 1)
  191736. m = 0x80;
  191737. else
  191738. m >>= 1;
  191739. }
  191740. break;
  191741. }
  191742. case 2:
  191743. {
  191744. png_bytep sp = png_ptr->row_buf + 1;
  191745. png_bytep dp = row;
  191746. int s_start, s_end, s_inc;
  191747. int m = 0x80;
  191748. int shift;
  191749. png_uint_32 i;
  191750. png_uint_32 row_width = png_ptr->width;
  191751. int value;
  191752. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191753. if (png_ptr->transformations & PNG_PACKSWAP)
  191754. {
  191755. s_start = 0;
  191756. s_end = 6;
  191757. s_inc = 2;
  191758. }
  191759. else
  191760. #endif
  191761. {
  191762. s_start = 6;
  191763. s_end = 0;
  191764. s_inc = -2;
  191765. }
  191766. shift = s_start;
  191767. for (i = 0; i < row_width; i++)
  191768. {
  191769. if (m & mask)
  191770. {
  191771. value = (*sp >> shift) & 0x03;
  191772. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191773. *dp |= (png_byte)(value << shift);
  191774. }
  191775. if (shift == s_end)
  191776. {
  191777. shift = s_start;
  191778. sp++;
  191779. dp++;
  191780. }
  191781. else
  191782. shift += s_inc;
  191783. if (m == 1)
  191784. m = 0x80;
  191785. else
  191786. m >>= 1;
  191787. }
  191788. break;
  191789. }
  191790. case 4:
  191791. {
  191792. png_bytep sp = png_ptr->row_buf + 1;
  191793. png_bytep dp = row;
  191794. int s_start, s_end, s_inc;
  191795. int m = 0x80;
  191796. int shift;
  191797. png_uint_32 i;
  191798. png_uint_32 row_width = png_ptr->width;
  191799. int value;
  191800. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191801. if (png_ptr->transformations & PNG_PACKSWAP)
  191802. {
  191803. s_start = 0;
  191804. s_end = 4;
  191805. s_inc = 4;
  191806. }
  191807. else
  191808. #endif
  191809. {
  191810. s_start = 4;
  191811. s_end = 0;
  191812. s_inc = -4;
  191813. }
  191814. shift = s_start;
  191815. for (i = 0; i < row_width; i++)
  191816. {
  191817. if (m & mask)
  191818. {
  191819. value = (*sp >> shift) & 0xf;
  191820. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191821. *dp |= (png_byte)(value << shift);
  191822. }
  191823. if (shift == s_end)
  191824. {
  191825. shift = s_start;
  191826. sp++;
  191827. dp++;
  191828. }
  191829. else
  191830. shift += s_inc;
  191831. if (m == 1)
  191832. m = 0x80;
  191833. else
  191834. m >>= 1;
  191835. }
  191836. break;
  191837. }
  191838. default:
  191839. {
  191840. png_bytep sp = png_ptr->row_buf + 1;
  191841. png_bytep dp = row;
  191842. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  191843. png_uint_32 i;
  191844. png_uint_32 row_width = png_ptr->width;
  191845. png_byte m = 0x80;
  191846. for (i = 0; i < row_width; i++)
  191847. {
  191848. if (m & mask)
  191849. {
  191850. png_memcpy(dp, sp, pixel_bytes);
  191851. }
  191852. sp += pixel_bytes;
  191853. dp += pixel_bytes;
  191854. if (m == 1)
  191855. m = 0x80;
  191856. else
  191857. m >>= 1;
  191858. }
  191859. break;
  191860. }
  191861. }
  191862. }
  191863. }
  191864. #ifdef PNG_READ_INTERLACING_SUPPORTED
  191865. /* OLD pre-1.0.9 interface:
  191866. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  191867. png_uint_32 transformations)
  191868. */
  191869. void /* PRIVATE */
  191870. png_do_read_interlace(png_structp png_ptr)
  191871. {
  191872. png_row_infop row_info = &(png_ptr->row_info);
  191873. png_bytep row = png_ptr->row_buf + 1;
  191874. int pass = png_ptr->pass;
  191875. png_uint_32 transformations = png_ptr->transformations;
  191876. #ifdef PNG_USE_LOCAL_ARRAYS
  191877. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191878. /* offset to next interlace block */
  191879. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191880. #endif
  191881. png_debug(1,"in png_do_read_interlace\n");
  191882. if (row != NULL && row_info != NULL)
  191883. {
  191884. png_uint_32 final_width;
  191885. final_width = row_info->width * png_pass_inc[pass];
  191886. switch (row_info->pixel_depth)
  191887. {
  191888. case 1:
  191889. {
  191890. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  191891. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  191892. int sshift, dshift;
  191893. int s_start, s_end, s_inc;
  191894. int jstop = png_pass_inc[pass];
  191895. png_byte v;
  191896. png_uint_32 i;
  191897. int j;
  191898. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191899. if (transformations & PNG_PACKSWAP)
  191900. {
  191901. sshift = (int)((row_info->width + 7) & 0x07);
  191902. dshift = (int)((final_width + 7) & 0x07);
  191903. s_start = 7;
  191904. s_end = 0;
  191905. s_inc = -1;
  191906. }
  191907. else
  191908. #endif
  191909. {
  191910. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  191911. dshift = 7 - (int)((final_width + 7) & 0x07);
  191912. s_start = 0;
  191913. s_end = 7;
  191914. s_inc = 1;
  191915. }
  191916. for (i = 0; i < row_info->width; i++)
  191917. {
  191918. v = (png_byte)((*sp >> sshift) & 0x01);
  191919. for (j = 0; j < jstop; j++)
  191920. {
  191921. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  191922. *dp |= (png_byte)(v << dshift);
  191923. if (dshift == s_end)
  191924. {
  191925. dshift = s_start;
  191926. dp--;
  191927. }
  191928. else
  191929. dshift += s_inc;
  191930. }
  191931. if (sshift == s_end)
  191932. {
  191933. sshift = s_start;
  191934. sp--;
  191935. }
  191936. else
  191937. sshift += s_inc;
  191938. }
  191939. break;
  191940. }
  191941. case 2:
  191942. {
  191943. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  191944. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  191945. int sshift, dshift;
  191946. int s_start, s_end, s_inc;
  191947. int jstop = png_pass_inc[pass];
  191948. png_uint_32 i;
  191949. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191950. if (transformations & PNG_PACKSWAP)
  191951. {
  191952. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  191953. dshift = (int)(((final_width + 3) & 0x03) << 1);
  191954. s_start = 6;
  191955. s_end = 0;
  191956. s_inc = -2;
  191957. }
  191958. else
  191959. #endif
  191960. {
  191961. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  191962. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  191963. s_start = 0;
  191964. s_end = 6;
  191965. s_inc = 2;
  191966. }
  191967. for (i = 0; i < row_info->width; i++)
  191968. {
  191969. png_byte v;
  191970. int j;
  191971. v = (png_byte)((*sp >> sshift) & 0x03);
  191972. for (j = 0; j < jstop; j++)
  191973. {
  191974. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  191975. *dp |= (png_byte)(v << dshift);
  191976. if (dshift == s_end)
  191977. {
  191978. dshift = s_start;
  191979. dp--;
  191980. }
  191981. else
  191982. dshift += s_inc;
  191983. }
  191984. if (sshift == s_end)
  191985. {
  191986. sshift = s_start;
  191987. sp--;
  191988. }
  191989. else
  191990. sshift += s_inc;
  191991. }
  191992. break;
  191993. }
  191994. case 4:
  191995. {
  191996. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  191997. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  191998. int sshift, dshift;
  191999. int s_start, s_end, s_inc;
  192000. png_uint_32 i;
  192001. int jstop = png_pass_inc[pass];
  192002. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192003. if (transformations & PNG_PACKSWAP)
  192004. {
  192005. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  192006. dshift = (int)(((final_width + 1) & 0x01) << 2);
  192007. s_start = 4;
  192008. s_end = 0;
  192009. s_inc = -4;
  192010. }
  192011. else
  192012. #endif
  192013. {
  192014. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  192015. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  192016. s_start = 0;
  192017. s_end = 4;
  192018. s_inc = 4;
  192019. }
  192020. for (i = 0; i < row_info->width; i++)
  192021. {
  192022. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  192023. int j;
  192024. for (j = 0; j < jstop; j++)
  192025. {
  192026. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  192027. *dp |= (png_byte)(v << dshift);
  192028. if (dshift == s_end)
  192029. {
  192030. dshift = s_start;
  192031. dp--;
  192032. }
  192033. else
  192034. dshift += s_inc;
  192035. }
  192036. if (sshift == s_end)
  192037. {
  192038. sshift = s_start;
  192039. sp--;
  192040. }
  192041. else
  192042. sshift += s_inc;
  192043. }
  192044. break;
  192045. }
  192046. default:
  192047. {
  192048. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  192049. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  192050. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  192051. int jstop = png_pass_inc[pass];
  192052. png_uint_32 i;
  192053. for (i = 0; i < row_info->width; i++)
  192054. {
  192055. png_byte v[8];
  192056. int j;
  192057. png_memcpy(v, sp, pixel_bytes);
  192058. for (j = 0; j < jstop; j++)
  192059. {
  192060. png_memcpy(dp, v, pixel_bytes);
  192061. dp -= pixel_bytes;
  192062. }
  192063. sp -= pixel_bytes;
  192064. }
  192065. break;
  192066. }
  192067. }
  192068. row_info->width = final_width;
  192069. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  192070. }
  192071. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  192072. transformations = transformations; /* silence compiler warning */
  192073. #endif
  192074. }
  192075. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  192076. void /* PRIVATE */
  192077. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  192078. png_bytep prev_row, int filter)
  192079. {
  192080. png_debug(1, "in png_read_filter_row\n");
  192081. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  192082. switch (filter)
  192083. {
  192084. case PNG_FILTER_VALUE_NONE:
  192085. break;
  192086. case PNG_FILTER_VALUE_SUB:
  192087. {
  192088. png_uint_32 i;
  192089. png_uint_32 istop = row_info->rowbytes;
  192090. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192091. png_bytep rp = row + bpp;
  192092. png_bytep lp = row;
  192093. for (i = bpp; i < istop; i++)
  192094. {
  192095. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  192096. rp++;
  192097. }
  192098. break;
  192099. }
  192100. case PNG_FILTER_VALUE_UP:
  192101. {
  192102. png_uint_32 i;
  192103. png_uint_32 istop = row_info->rowbytes;
  192104. png_bytep rp = row;
  192105. png_bytep pp = prev_row;
  192106. for (i = 0; i < istop; i++)
  192107. {
  192108. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192109. rp++;
  192110. }
  192111. break;
  192112. }
  192113. case PNG_FILTER_VALUE_AVG:
  192114. {
  192115. png_uint_32 i;
  192116. png_bytep rp = row;
  192117. png_bytep pp = prev_row;
  192118. png_bytep lp = row;
  192119. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192120. png_uint_32 istop = row_info->rowbytes - bpp;
  192121. for (i = 0; i < bpp; i++)
  192122. {
  192123. *rp = (png_byte)(((int)(*rp) +
  192124. ((int)(*pp++) / 2 )) & 0xff);
  192125. rp++;
  192126. }
  192127. for (i = 0; i < istop; i++)
  192128. {
  192129. *rp = (png_byte)(((int)(*rp) +
  192130. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  192131. rp++;
  192132. }
  192133. break;
  192134. }
  192135. case PNG_FILTER_VALUE_PAETH:
  192136. {
  192137. png_uint_32 i;
  192138. png_bytep rp = row;
  192139. png_bytep pp = prev_row;
  192140. png_bytep lp = row;
  192141. png_bytep cp = prev_row;
  192142. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  192143. png_uint_32 istop=row_info->rowbytes - bpp;
  192144. for (i = 0; i < bpp; i++)
  192145. {
  192146. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  192147. rp++;
  192148. }
  192149. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  192150. {
  192151. int a, b, c, pa, pb, pc, p;
  192152. a = *lp++;
  192153. b = *pp++;
  192154. c = *cp++;
  192155. p = b - c;
  192156. pc = a - c;
  192157. #ifdef PNG_USE_ABS
  192158. pa = abs(p);
  192159. pb = abs(pc);
  192160. pc = abs(p + pc);
  192161. #else
  192162. pa = p < 0 ? -p : p;
  192163. pb = pc < 0 ? -pc : pc;
  192164. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  192165. #endif
  192166. /*
  192167. if (pa <= pb && pa <= pc)
  192168. p = a;
  192169. else if (pb <= pc)
  192170. p = b;
  192171. else
  192172. p = c;
  192173. */
  192174. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  192175. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  192176. rp++;
  192177. }
  192178. break;
  192179. }
  192180. default:
  192181. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  192182. *row=0;
  192183. break;
  192184. }
  192185. }
  192186. void /* PRIVATE */
  192187. png_read_finish_row(png_structp png_ptr)
  192188. {
  192189. #ifdef PNG_USE_LOCAL_ARRAYS
  192190. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192191. /* start of interlace block */
  192192. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192193. /* offset to next interlace block */
  192194. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192195. /* start of interlace block in the y direction */
  192196. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192197. /* offset to next interlace block in the y direction */
  192198. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192199. #endif
  192200. png_debug(1, "in png_read_finish_row\n");
  192201. png_ptr->row_number++;
  192202. if (png_ptr->row_number < png_ptr->num_rows)
  192203. return;
  192204. if (png_ptr->interlaced)
  192205. {
  192206. png_ptr->row_number = 0;
  192207. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  192208. png_ptr->rowbytes + 1);
  192209. do
  192210. {
  192211. png_ptr->pass++;
  192212. if (png_ptr->pass >= 7)
  192213. break;
  192214. png_ptr->iwidth = (png_ptr->width +
  192215. png_pass_inc[png_ptr->pass] - 1 -
  192216. png_pass_start[png_ptr->pass]) /
  192217. png_pass_inc[png_ptr->pass];
  192218. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  192219. png_ptr->iwidth) + 1;
  192220. if (!(png_ptr->transformations & PNG_INTERLACE))
  192221. {
  192222. png_ptr->num_rows = (png_ptr->height +
  192223. png_pass_yinc[png_ptr->pass] - 1 -
  192224. png_pass_ystart[png_ptr->pass]) /
  192225. png_pass_yinc[png_ptr->pass];
  192226. if (!(png_ptr->num_rows))
  192227. continue;
  192228. }
  192229. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  192230. break;
  192231. } while (png_ptr->iwidth == 0);
  192232. if (png_ptr->pass < 7)
  192233. return;
  192234. }
  192235. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  192236. {
  192237. #ifdef PNG_USE_LOCAL_ARRAYS
  192238. PNG_CONST PNG_IDAT;
  192239. #endif
  192240. char extra;
  192241. int ret;
  192242. png_ptr->zstream.next_out = (Bytef *)&extra;
  192243. png_ptr->zstream.avail_out = (uInt)1;
  192244. for(;;)
  192245. {
  192246. if (!(png_ptr->zstream.avail_in))
  192247. {
  192248. while (!png_ptr->idat_size)
  192249. {
  192250. png_byte chunk_length[4];
  192251. png_crc_finish(png_ptr, 0);
  192252. png_read_data(png_ptr, chunk_length, 4);
  192253. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  192254. png_reset_crc(png_ptr);
  192255. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  192256. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  192257. png_error(png_ptr, "Not enough image data");
  192258. }
  192259. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  192260. png_ptr->zstream.next_in = png_ptr->zbuf;
  192261. if (png_ptr->zbuf_size > png_ptr->idat_size)
  192262. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  192263. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  192264. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  192265. }
  192266. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  192267. if (ret == Z_STREAM_END)
  192268. {
  192269. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  192270. png_ptr->idat_size)
  192271. png_warning(png_ptr, "Extra compressed data");
  192272. png_ptr->mode |= PNG_AFTER_IDAT;
  192273. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192274. break;
  192275. }
  192276. if (ret != Z_OK)
  192277. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  192278. "Decompression Error");
  192279. if (!(png_ptr->zstream.avail_out))
  192280. {
  192281. png_warning(png_ptr, "Extra compressed data.");
  192282. png_ptr->mode |= PNG_AFTER_IDAT;
  192283. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192284. break;
  192285. }
  192286. }
  192287. png_ptr->zstream.avail_out = 0;
  192288. }
  192289. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  192290. png_warning(png_ptr, "Extra compression data");
  192291. inflateReset(&png_ptr->zstream);
  192292. png_ptr->mode |= PNG_AFTER_IDAT;
  192293. }
  192294. void /* PRIVATE */
  192295. png_read_start_row(png_structp png_ptr)
  192296. {
  192297. #ifdef PNG_USE_LOCAL_ARRAYS
  192298. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192299. /* start of interlace block */
  192300. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192301. /* offset to next interlace block */
  192302. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192303. /* start of interlace block in the y direction */
  192304. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192305. /* offset to next interlace block in the y direction */
  192306. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192307. #endif
  192308. int max_pixel_depth;
  192309. png_uint_32 row_bytes;
  192310. png_debug(1, "in png_read_start_row\n");
  192311. png_ptr->zstream.avail_in = 0;
  192312. png_init_read_transformations(png_ptr);
  192313. if (png_ptr->interlaced)
  192314. {
  192315. if (!(png_ptr->transformations & PNG_INTERLACE))
  192316. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  192317. png_pass_ystart[0]) / png_pass_yinc[0];
  192318. else
  192319. png_ptr->num_rows = png_ptr->height;
  192320. png_ptr->iwidth = (png_ptr->width +
  192321. png_pass_inc[png_ptr->pass] - 1 -
  192322. png_pass_start[png_ptr->pass]) /
  192323. png_pass_inc[png_ptr->pass];
  192324. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  192325. png_ptr->irowbytes = (png_size_t)row_bytes;
  192326. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  192327. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  192328. }
  192329. else
  192330. {
  192331. png_ptr->num_rows = png_ptr->height;
  192332. png_ptr->iwidth = png_ptr->width;
  192333. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  192334. }
  192335. max_pixel_depth = png_ptr->pixel_depth;
  192336. #if defined(PNG_READ_PACK_SUPPORTED)
  192337. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  192338. max_pixel_depth = 8;
  192339. #endif
  192340. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192341. if (png_ptr->transformations & PNG_EXPAND)
  192342. {
  192343. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192344. {
  192345. if (png_ptr->num_trans)
  192346. max_pixel_depth = 32;
  192347. else
  192348. max_pixel_depth = 24;
  192349. }
  192350. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192351. {
  192352. if (max_pixel_depth < 8)
  192353. max_pixel_depth = 8;
  192354. if (png_ptr->num_trans)
  192355. max_pixel_depth *= 2;
  192356. }
  192357. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192358. {
  192359. if (png_ptr->num_trans)
  192360. {
  192361. max_pixel_depth *= 4;
  192362. max_pixel_depth /= 3;
  192363. }
  192364. }
  192365. }
  192366. #endif
  192367. #if defined(PNG_READ_FILLER_SUPPORTED)
  192368. if (png_ptr->transformations & (PNG_FILLER))
  192369. {
  192370. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192371. max_pixel_depth = 32;
  192372. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192373. {
  192374. if (max_pixel_depth <= 8)
  192375. max_pixel_depth = 16;
  192376. else
  192377. max_pixel_depth = 32;
  192378. }
  192379. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192380. {
  192381. if (max_pixel_depth <= 32)
  192382. max_pixel_depth = 32;
  192383. else
  192384. max_pixel_depth = 64;
  192385. }
  192386. }
  192387. #endif
  192388. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192389. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  192390. {
  192391. if (
  192392. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192393. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  192394. #endif
  192395. #if defined(PNG_READ_FILLER_SUPPORTED)
  192396. (png_ptr->transformations & (PNG_FILLER)) ||
  192397. #endif
  192398. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192399. {
  192400. if (max_pixel_depth <= 16)
  192401. max_pixel_depth = 32;
  192402. else
  192403. max_pixel_depth = 64;
  192404. }
  192405. else
  192406. {
  192407. if (max_pixel_depth <= 8)
  192408. {
  192409. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192410. max_pixel_depth = 32;
  192411. else
  192412. max_pixel_depth = 24;
  192413. }
  192414. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192415. max_pixel_depth = 64;
  192416. else
  192417. max_pixel_depth = 48;
  192418. }
  192419. }
  192420. #endif
  192421. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  192422. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192423. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  192424. {
  192425. int user_pixel_depth=png_ptr->user_transform_depth*
  192426. png_ptr->user_transform_channels;
  192427. if(user_pixel_depth > max_pixel_depth)
  192428. max_pixel_depth=user_pixel_depth;
  192429. }
  192430. #endif
  192431. /* align the width on the next larger 8 pixels. Mainly used
  192432. for interlacing */
  192433. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  192434. /* calculate the maximum bytes needed, adding a byte and a pixel
  192435. for safety's sake */
  192436. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  192437. 1 + ((max_pixel_depth + 7) >> 3);
  192438. #ifdef PNG_MAX_MALLOC_64K
  192439. if (row_bytes > (png_uint_32)65536L)
  192440. png_error(png_ptr, "This image requires a row greater than 64KB");
  192441. #endif
  192442. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  192443. png_ptr->row_buf = png_ptr->big_row_buf+32;
  192444. #ifdef PNG_MAX_MALLOC_64K
  192445. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  192446. png_error(png_ptr, "This image requires a row greater than 64KB");
  192447. #endif
  192448. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  192449. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  192450. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  192451. png_ptr->rowbytes + 1));
  192452. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  192453. png_debug1(3, "width = %lu,\n", png_ptr->width);
  192454. png_debug1(3, "height = %lu,\n", png_ptr->height);
  192455. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  192456. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  192457. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  192458. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  192459. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  192460. }
  192461. #endif /* PNG_READ_SUPPORTED */
  192462. /********* End of inlined file: pngrutil.c *********/
  192463. /********* Start of inlined file: pngset.c *********/
  192464. /* pngset.c - storage of image information into info struct
  192465. *
  192466. * Last changed in libpng 1.2.21 [October 4, 2007]
  192467. * For conditions of distribution and use, see copyright notice in png.h
  192468. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192469. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192470. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192471. *
  192472. * The functions here are used during reads to store data from the file
  192473. * into the info struct, and during writes to store application data
  192474. * into the info struct for writing into the file. This abstracts the
  192475. * info struct and allows us to change the structure in the future.
  192476. */
  192477. #define PNG_INTERNAL
  192478. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  192479. #if defined(PNG_bKGD_SUPPORTED)
  192480. void PNGAPI
  192481. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  192482. {
  192483. png_debug1(1, "in %s storage function\n", "bKGD");
  192484. if (png_ptr == NULL || info_ptr == NULL)
  192485. return;
  192486. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  192487. info_ptr->valid |= PNG_INFO_bKGD;
  192488. }
  192489. #endif
  192490. #if defined(PNG_cHRM_SUPPORTED)
  192491. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192492. void PNGAPI
  192493. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  192494. double white_x, double white_y, double red_x, double red_y,
  192495. double green_x, double green_y, double blue_x, double blue_y)
  192496. {
  192497. png_debug1(1, "in %s storage function\n", "cHRM");
  192498. if (png_ptr == NULL || info_ptr == NULL)
  192499. return;
  192500. if (white_x < 0.0 || white_y < 0.0 ||
  192501. red_x < 0.0 || red_y < 0.0 ||
  192502. green_x < 0.0 || green_y < 0.0 ||
  192503. blue_x < 0.0 || blue_y < 0.0)
  192504. {
  192505. png_warning(png_ptr,
  192506. "Ignoring attempt to set negative chromaticity value");
  192507. return;
  192508. }
  192509. if (white_x > 21474.83 || white_y > 21474.83 ||
  192510. red_x > 21474.83 || red_y > 21474.83 ||
  192511. green_x > 21474.83 || green_y > 21474.83 ||
  192512. blue_x > 21474.83 || blue_y > 21474.83)
  192513. {
  192514. png_warning(png_ptr,
  192515. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192516. return;
  192517. }
  192518. info_ptr->x_white = (float)white_x;
  192519. info_ptr->y_white = (float)white_y;
  192520. info_ptr->x_red = (float)red_x;
  192521. info_ptr->y_red = (float)red_y;
  192522. info_ptr->x_green = (float)green_x;
  192523. info_ptr->y_green = (float)green_y;
  192524. info_ptr->x_blue = (float)blue_x;
  192525. info_ptr->y_blue = (float)blue_y;
  192526. #ifdef PNG_FIXED_POINT_SUPPORTED
  192527. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  192528. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  192529. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  192530. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  192531. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  192532. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  192533. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  192534. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  192535. #endif
  192536. info_ptr->valid |= PNG_INFO_cHRM;
  192537. }
  192538. #endif
  192539. #ifdef PNG_FIXED_POINT_SUPPORTED
  192540. void PNGAPI
  192541. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  192542. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  192543. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  192544. png_fixed_point blue_x, png_fixed_point blue_y)
  192545. {
  192546. png_debug1(1, "in %s storage function\n", "cHRM");
  192547. if (png_ptr == NULL || info_ptr == NULL)
  192548. return;
  192549. if (white_x < 0 || white_y < 0 ||
  192550. red_x < 0 || red_y < 0 ||
  192551. green_x < 0 || green_y < 0 ||
  192552. blue_x < 0 || blue_y < 0)
  192553. {
  192554. png_warning(png_ptr,
  192555. "Ignoring attempt to set negative chromaticity value");
  192556. return;
  192557. }
  192558. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192559. if (white_x > (double) PNG_UINT_31_MAX ||
  192560. white_y > (double) PNG_UINT_31_MAX ||
  192561. red_x > (double) PNG_UINT_31_MAX ||
  192562. red_y > (double) PNG_UINT_31_MAX ||
  192563. green_x > (double) PNG_UINT_31_MAX ||
  192564. green_y > (double) PNG_UINT_31_MAX ||
  192565. blue_x > (double) PNG_UINT_31_MAX ||
  192566. blue_y > (double) PNG_UINT_31_MAX)
  192567. #else
  192568. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192569. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192570. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192571. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192572. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192573. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192574. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192575. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  192576. #endif
  192577. {
  192578. png_warning(png_ptr,
  192579. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192580. return;
  192581. }
  192582. info_ptr->int_x_white = white_x;
  192583. info_ptr->int_y_white = white_y;
  192584. info_ptr->int_x_red = red_x;
  192585. info_ptr->int_y_red = red_y;
  192586. info_ptr->int_x_green = green_x;
  192587. info_ptr->int_y_green = green_y;
  192588. info_ptr->int_x_blue = blue_x;
  192589. info_ptr->int_y_blue = blue_y;
  192590. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192591. info_ptr->x_white = (float)(white_x/100000.);
  192592. info_ptr->y_white = (float)(white_y/100000.);
  192593. info_ptr->x_red = (float)( red_x/100000.);
  192594. info_ptr->y_red = (float)( red_y/100000.);
  192595. info_ptr->x_green = (float)(green_x/100000.);
  192596. info_ptr->y_green = (float)(green_y/100000.);
  192597. info_ptr->x_blue = (float)( blue_x/100000.);
  192598. info_ptr->y_blue = (float)( blue_y/100000.);
  192599. #endif
  192600. info_ptr->valid |= PNG_INFO_cHRM;
  192601. }
  192602. #endif
  192603. #endif
  192604. #if defined(PNG_gAMA_SUPPORTED)
  192605. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192606. void PNGAPI
  192607. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  192608. {
  192609. double gamma;
  192610. png_debug1(1, "in %s storage function\n", "gAMA");
  192611. if (png_ptr == NULL || info_ptr == NULL)
  192612. return;
  192613. /* Check for overflow */
  192614. if (file_gamma > 21474.83)
  192615. {
  192616. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192617. gamma=21474.83;
  192618. }
  192619. else
  192620. gamma=file_gamma;
  192621. info_ptr->gamma = (float)gamma;
  192622. #ifdef PNG_FIXED_POINT_SUPPORTED
  192623. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  192624. #endif
  192625. info_ptr->valid |= PNG_INFO_gAMA;
  192626. if(gamma == 0.0)
  192627. png_warning(png_ptr, "Setting gamma=0");
  192628. }
  192629. #endif
  192630. void PNGAPI
  192631. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  192632. int_gamma)
  192633. {
  192634. png_fixed_point gamma;
  192635. png_debug1(1, "in %s storage function\n", "gAMA");
  192636. if (png_ptr == NULL || info_ptr == NULL)
  192637. return;
  192638. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  192639. {
  192640. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192641. gamma=PNG_UINT_31_MAX;
  192642. }
  192643. else
  192644. {
  192645. if (int_gamma < 0)
  192646. {
  192647. png_warning(png_ptr, "Setting negative gamma to zero");
  192648. gamma=0;
  192649. }
  192650. else
  192651. gamma=int_gamma;
  192652. }
  192653. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192654. info_ptr->gamma = (float)(gamma/100000.);
  192655. #endif
  192656. #ifdef PNG_FIXED_POINT_SUPPORTED
  192657. info_ptr->int_gamma = gamma;
  192658. #endif
  192659. info_ptr->valid |= PNG_INFO_gAMA;
  192660. if(gamma == 0)
  192661. png_warning(png_ptr, "Setting gamma=0");
  192662. }
  192663. #endif
  192664. #if defined(PNG_hIST_SUPPORTED)
  192665. void PNGAPI
  192666. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  192667. {
  192668. int i;
  192669. png_debug1(1, "in %s storage function\n", "hIST");
  192670. if (png_ptr == NULL || info_ptr == NULL)
  192671. return;
  192672. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  192673. > PNG_MAX_PALETTE_LENGTH)
  192674. {
  192675. png_warning(png_ptr,
  192676. "Invalid palette size, hIST allocation skipped.");
  192677. return;
  192678. }
  192679. #ifdef PNG_FREE_ME_SUPPORTED
  192680. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  192681. #endif
  192682. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  192683. 1.2.1 */
  192684. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  192685. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  192686. if (png_ptr->hist == NULL)
  192687. {
  192688. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  192689. return;
  192690. }
  192691. for (i = 0; i < info_ptr->num_palette; i++)
  192692. png_ptr->hist[i] = hist[i];
  192693. info_ptr->hist = png_ptr->hist;
  192694. info_ptr->valid |= PNG_INFO_hIST;
  192695. #ifdef PNG_FREE_ME_SUPPORTED
  192696. info_ptr->free_me |= PNG_FREE_HIST;
  192697. #else
  192698. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  192699. #endif
  192700. }
  192701. #endif
  192702. void PNGAPI
  192703. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  192704. png_uint_32 width, png_uint_32 height, int bit_depth,
  192705. int color_type, int interlace_type, int compression_type,
  192706. int filter_type)
  192707. {
  192708. png_debug1(1, "in %s storage function\n", "IHDR");
  192709. if (png_ptr == NULL || info_ptr == NULL)
  192710. return;
  192711. /* check for width and height valid values */
  192712. if (width == 0 || height == 0)
  192713. png_error(png_ptr, "Image width or height is zero in IHDR");
  192714. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192715. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  192716. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192717. #else
  192718. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  192719. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192720. #endif
  192721. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  192722. png_error(png_ptr, "Invalid image size in IHDR");
  192723. if ( width > (PNG_UINT_32_MAX
  192724. >> 3) /* 8-byte RGBA pixels */
  192725. - 64 /* bigrowbuf hack */
  192726. - 1 /* filter byte */
  192727. - 7*8 /* rounding of width to multiple of 8 pixels */
  192728. - 8) /* extra max_pixel_depth pad */
  192729. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  192730. /* check other values */
  192731. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  192732. bit_depth != 8 && bit_depth != 16)
  192733. png_error(png_ptr, "Invalid bit depth in IHDR");
  192734. if (color_type < 0 || color_type == 1 ||
  192735. color_type == 5 || color_type > 6)
  192736. png_error(png_ptr, "Invalid color type in IHDR");
  192737. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  192738. ((color_type == PNG_COLOR_TYPE_RGB ||
  192739. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  192740. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  192741. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  192742. if (interlace_type >= PNG_INTERLACE_LAST)
  192743. png_error(png_ptr, "Unknown interlace method in IHDR");
  192744. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  192745. png_error(png_ptr, "Unknown compression method in IHDR");
  192746. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192747. /* Accept filter_method 64 (intrapixel differencing) only if
  192748. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  192749. * 2. Libpng did not read a PNG signature (this filter_method is only
  192750. * used in PNG datastreams that are embedded in MNG datastreams) and
  192751. * 3. The application called png_permit_mng_features with a mask that
  192752. * included PNG_FLAG_MNG_FILTER_64 and
  192753. * 4. The filter_method is 64 and
  192754. * 5. The color_type is RGB or RGBA
  192755. */
  192756. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  192757. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192758. if(filter_type != PNG_FILTER_TYPE_BASE)
  192759. {
  192760. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192761. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  192762. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  192763. (color_type == PNG_COLOR_TYPE_RGB ||
  192764. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  192765. png_error(png_ptr, "Unknown filter method in IHDR");
  192766. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  192767. png_warning(png_ptr, "Invalid filter method in IHDR");
  192768. }
  192769. #else
  192770. if(filter_type != PNG_FILTER_TYPE_BASE)
  192771. png_error(png_ptr, "Unknown filter method in IHDR");
  192772. #endif
  192773. info_ptr->width = width;
  192774. info_ptr->height = height;
  192775. info_ptr->bit_depth = (png_byte)bit_depth;
  192776. info_ptr->color_type =(png_byte) color_type;
  192777. info_ptr->compression_type = (png_byte)compression_type;
  192778. info_ptr->filter_type = (png_byte)filter_type;
  192779. info_ptr->interlace_type = (png_byte)interlace_type;
  192780. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192781. info_ptr->channels = 1;
  192782. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192783. info_ptr->channels = 3;
  192784. else
  192785. info_ptr->channels = 1;
  192786. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  192787. info_ptr->channels++;
  192788. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  192789. /* check for potential overflow */
  192790. if (width > (PNG_UINT_32_MAX
  192791. >> 3) /* 8-byte RGBA pixels */
  192792. - 64 /* bigrowbuf hack */
  192793. - 1 /* filter byte */
  192794. - 7*8 /* rounding of width to multiple of 8 pixels */
  192795. - 8) /* extra max_pixel_depth pad */
  192796. info_ptr->rowbytes = (png_size_t)0;
  192797. else
  192798. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  192799. }
  192800. #if defined(PNG_oFFs_SUPPORTED)
  192801. void PNGAPI
  192802. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  192803. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  192804. {
  192805. png_debug1(1, "in %s storage function\n", "oFFs");
  192806. if (png_ptr == NULL || info_ptr == NULL)
  192807. return;
  192808. info_ptr->x_offset = offset_x;
  192809. info_ptr->y_offset = offset_y;
  192810. info_ptr->offset_unit_type = (png_byte)unit_type;
  192811. info_ptr->valid |= PNG_INFO_oFFs;
  192812. }
  192813. #endif
  192814. #if defined(PNG_pCAL_SUPPORTED)
  192815. void PNGAPI
  192816. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  192817. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  192818. png_charp units, png_charpp params)
  192819. {
  192820. png_uint_32 length;
  192821. int i;
  192822. png_debug1(1, "in %s storage function\n", "pCAL");
  192823. if (png_ptr == NULL || info_ptr == NULL)
  192824. return;
  192825. length = png_strlen(purpose) + 1;
  192826. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  192827. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  192828. if (info_ptr->pcal_purpose == NULL)
  192829. {
  192830. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  192831. return;
  192832. }
  192833. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  192834. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  192835. info_ptr->pcal_X0 = X0;
  192836. info_ptr->pcal_X1 = X1;
  192837. info_ptr->pcal_type = (png_byte)type;
  192838. info_ptr->pcal_nparams = (png_byte)nparams;
  192839. length = png_strlen(units) + 1;
  192840. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  192841. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  192842. if (info_ptr->pcal_units == NULL)
  192843. {
  192844. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  192845. return;
  192846. }
  192847. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  192848. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  192849. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  192850. if (info_ptr->pcal_params == NULL)
  192851. {
  192852. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  192853. return;
  192854. }
  192855. info_ptr->pcal_params[nparams] = NULL;
  192856. for (i = 0; i < nparams; i++)
  192857. {
  192858. length = png_strlen(params[i]) + 1;
  192859. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  192860. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  192861. if (info_ptr->pcal_params[i] == NULL)
  192862. {
  192863. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  192864. return;
  192865. }
  192866. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  192867. }
  192868. info_ptr->valid |= PNG_INFO_pCAL;
  192869. #ifdef PNG_FREE_ME_SUPPORTED
  192870. info_ptr->free_me |= PNG_FREE_PCAL;
  192871. #endif
  192872. }
  192873. #endif
  192874. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  192875. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192876. void PNGAPI
  192877. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  192878. int unit, double width, double height)
  192879. {
  192880. png_debug1(1, "in %s storage function\n", "sCAL");
  192881. if (png_ptr == NULL || info_ptr == NULL)
  192882. return;
  192883. info_ptr->scal_unit = (png_byte)unit;
  192884. info_ptr->scal_pixel_width = width;
  192885. info_ptr->scal_pixel_height = height;
  192886. info_ptr->valid |= PNG_INFO_sCAL;
  192887. }
  192888. #else
  192889. #ifdef PNG_FIXED_POINT_SUPPORTED
  192890. void PNGAPI
  192891. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  192892. int unit, png_charp swidth, png_charp sheight)
  192893. {
  192894. png_uint_32 length;
  192895. png_debug1(1, "in %s storage function\n", "sCAL");
  192896. if (png_ptr == NULL || info_ptr == NULL)
  192897. return;
  192898. info_ptr->scal_unit = (png_byte)unit;
  192899. length = png_strlen(swidth) + 1;
  192900. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192901. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  192902. if (info_ptr->scal_s_width == NULL)
  192903. {
  192904. png_warning(png_ptr,
  192905. "Memory allocation failed while processing sCAL.");
  192906. }
  192907. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  192908. length = png_strlen(sheight) + 1;
  192909. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192910. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  192911. if (info_ptr->scal_s_height == NULL)
  192912. {
  192913. png_free (png_ptr, info_ptr->scal_s_width);
  192914. png_warning(png_ptr,
  192915. "Memory allocation failed while processing sCAL.");
  192916. }
  192917. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  192918. info_ptr->valid |= PNG_INFO_sCAL;
  192919. #ifdef PNG_FREE_ME_SUPPORTED
  192920. info_ptr->free_me |= PNG_FREE_SCAL;
  192921. #endif
  192922. }
  192923. #endif
  192924. #endif
  192925. #endif
  192926. #if defined(PNG_pHYs_SUPPORTED)
  192927. void PNGAPI
  192928. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  192929. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  192930. {
  192931. png_debug1(1, "in %s storage function\n", "pHYs");
  192932. if (png_ptr == NULL || info_ptr == NULL)
  192933. return;
  192934. info_ptr->x_pixels_per_unit = res_x;
  192935. info_ptr->y_pixels_per_unit = res_y;
  192936. info_ptr->phys_unit_type = (png_byte)unit_type;
  192937. info_ptr->valid |= PNG_INFO_pHYs;
  192938. }
  192939. #endif
  192940. void PNGAPI
  192941. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  192942. png_colorp palette, int num_palette)
  192943. {
  192944. png_debug1(1, "in %s storage function\n", "PLTE");
  192945. if (png_ptr == NULL || info_ptr == NULL)
  192946. return;
  192947. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  192948. {
  192949. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192950. png_error(png_ptr, "Invalid palette length");
  192951. else
  192952. {
  192953. png_warning(png_ptr, "Invalid palette length");
  192954. return;
  192955. }
  192956. }
  192957. /*
  192958. * It may not actually be necessary to set png_ptr->palette here;
  192959. * we do it for backward compatibility with the way the png_handle_tRNS
  192960. * function used to do the allocation.
  192961. */
  192962. #ifdef PNG_FREE_ME_SUPPORTED
  192963. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  192964. #endif
  192965. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  192966. of num_palette entries,
  192967. in case of an invalid PNG file that has too-large sample values. */
  192968. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  192969. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  192970. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  192971. png_sizeof(png_color));
  192972. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  192973. info_ptr->palette = png_ptr->palette;
  192974. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  192975. #ifdef PNG_FREE_ME_SUPPORTED
  192976. info_ptr->free_me |= PNG_FREE_PLTE;
  192977. #else
  192978. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  192979. #endif
  192980. info_ptr->valid |= PNG_INFO_PLTE;
  192981. }
  192982. #if defined(PNG_sBIT_SUPPORTED)
  192983. void PNGAPI
  192984. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  192985. png_color_8p sig_bit)
  192986. {
  192987. png_debug1(1, "in %s storage function\n", "sBIT");
  192988. if (png_ptr == NULL || info_ptr == NULL)
  192989. return;
  192990. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  192991. info_ptr->valid |= PNG_INFO_sBIT;
  192992. }
  192993. #endif
  192994. #if defined(PNG_sRGB_SUPPORTED)
  192995. void PNGAPI
  192996. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  192997. {
  192998. png_debug1(1, "in %s storage function\n", "sRGB");
  192999. if (png_ptr == NULL || info_ptr == NULL)
  193000. return;
  193001. info_ptr->srgb_intent = (png_byte)intent;
  193002. info_ptr->valid |= PNG_INFO_sRGB;
  193003. }
  193004. void PNGAPI
  193005. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  193006. int intent)
  193007. {
  193008. #if defined(PNG_gAMA_SUPPORTED)
  193009. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193010. float file_gamma;
  193011. #endif
  193012. #ifdef PNG_FIXED_POINT_SUPPORTED
  193013. png_fixed_point int_file_gamma;
  193014. #endif
  193015. #endif
  193016. #if defined(PNG_cHRM_SUPPORTED)
  193017. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193018. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193019. #endif
  193020. #ifdef PNG_FIXED_POINT_SUPPORTED
  193021. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  193022. int_green_y, int_blue_x, int_blue_y;
  193023. #endif
  193024. #endif
  193025. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  193026. if (png_ptr == NULL || info_ptr == NULL)
  193027. return;
  193028. png_set_sRGB(png_ptr, info_ptr, intent);
  193029. #if defined(PNG_gAMA_SUPPORTED)
  193030. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193031. file_gamma = (float).45455;
  193032. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193033. #endif
  193034. #ifdef PNG_FIXED_POINT_SUPPORTED
  193035. int_file_gamma = 45455L;
  193036. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  193037. #endif
  193038. #endif
  193039. #if defined(PNG_cHRM_SUPPORTED)
  193040. #ifdef PNG_FIXED_POINT_SUPPORTED
  193041. int_white_x = 31270L;
  193042. int_white_y = 32900L;
  193043. int_red_x = 64000L;
  193044. int_red_y = 33000L;
  193045. int_green_x = 30000L;
  193046. int_green_y = 60000L;
  193047. int_blue_x = 15000L;
  193048. int_blue_y = 6000L;
  193049. png_set_cHRM_fixed(png_ptr, info_ptr,
  193050. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  193051. int_blue_x, int_blue_y);
  193052. #endif
  193053. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193054. white_x = (float).3127;
  193055. white_y = (float).3290;
  193056. red_x = (float).64;
  193057. red_y = (float).33;
  193058. green_x = (float).30;
  193059. green_y = (float).60;
  193060. blue_x = (float).15;
  193061. blue_y = (float).06;
  193062. png_set_cHRM(png_ptr, info_ptr,
  193063. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193064. #endif
  193065. #endif
  193066. }
  193067. #endif
  193068. #if defined(PNG_iCCP_SUPPORTED)
  193069. void PNGAPI
  193070. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  193071. png_charp name, int compression_type,
  193072. png_charp profile, png_uint_32 proflen)
  193073. {
  193074. png_charp new_iccp_name;
  193075. png_charp new_iccp_profile;
  193076. png_debug1(1, "in %s storage function\n", "iCCP");
  193077. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  193078. return;
  193079. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  193080. if (new_iccp_name == NULL)
  193081. {
  193082. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  193083. return;
  193084. }
  193085. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  193086. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  193087. if (new_iccp_profile == NULL)
  193088. {
  193089. png_free (png_ptr, new_iccp_name);
  193090. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  193091. return;
  193092. }
  193093. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  193094. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  193095. info_ptr->iccp_proflen = proflen;
  193096. info_ptr->iccp_name = new_iccp_name;
  193097. info_ptr->iccp_profile = new_iccp_profile;
  193098. /* Compression is always zero but is here so the API and info structure
  193099. * does not have to change if we introduce multiple compression types */
  193100. info_ptr->iccp_compression = (png_byte)compression_type;
  193101. #ifdef PNG_FREE_ME_SUPPORTED
  193102. info_ptr->free_me |= PNG_FREE_ICCP;
  193103. #endif
  193104. info_ptr->valid |= PNG_INFO_iCCP;
  193105. }
  193106. #endif
  193107. #if defined(PNG_TEXT_SUPPORTED)
  193108. void PNGAPI
  193109. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193110. int num_text)
  193111. {
  193112. int ret;
  193113. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  193114. if (ret)
  193115. png_error(png_ptr, "Insufficient memory to store text");
  193116. }
  193117. int /* PRIVATE */
  193118. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  193119. int num_text)
  193120. {
  193121. int i;
  193122. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  193123. "text" : (png_const_charp)png_ptr->chunk_name));
  193124. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  193125. return(0);
  193126. /* Make sure we have enough space in the "text" array in info_struct
  193127. * to hold all of the incoming text_ptr objects.
  193128. */
  193129. if (info_ptr->num_text + num_text > info_ptr->max_text)
  193130. {
  193131. if (info_ptr->text != NULL)
  193132. {
  193133. png_textp old_text;
  193134. int old_max;
  193135. old_max = info_ptr->max_text;
  193136. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  193137. old_text = info_ptr->text;
  193138. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193139. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193140. if (info_ptr->text == NULL)
  193141. {
  193142. png_free(png_ptr, old_text);
  193143. return(1);
  193144. }
  193145. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  193146. png_sizeof(png_text)));
  193147. png_free(png_ptr, old_text);
  193148. }
  193149. else
  193150. {
  193151. info_ptr->max_text = num_text + 8;
  193152. info_ptr->num_text = 0;
  193153. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  193154. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  193155. if (info_ptr->text == NULL)
  193156. return(1);
  193157. #ifdef PNG_FREE_ME_SUPPORTED
  193158. info_ptr->free_me |= PNG_FREE_TEXT;
  193159. #endif
  193160. }
  193161. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  193162. info_ptr->max_text);
  193163. }
  193164. for (i = 0; i < num_text; i++)
  193165. {
  193166. png_size_t text_length,key_len;
  193167. png_size_t lang_len,lang_key_len;
  193168. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  193169. if (text_ptr[i].key == NULL)
  193170. continue;
  193171. key_len = png_strlen(text_ptr[i].key);
  193172. if(text_ptr[i].compression <= 0)
  193173. {
  193174. lang_len = 0;
  193175. lang_key_len = 0;
  193176. }
  193177. else
  193178. #ifdef PNG_iTXt_SUPPORTED
  193179. {
  193180. /* set iTXt data */
  193181. if (text_ptr[i].lang != NULL)
  193182. lang_len = png_strlen(text_ptr[i].lang);
  193183. else
  193184. lang_len = 0;
  193185. if (text_ptr[i].lang_key != NULL)
  193186. lang_key_len = png_strlen(text_ptr[i].lang_key);
  193187. else
  193188. lang_key_len = 0;
  193189. }
  193190. #else
  193191. {
  193192. png_warning(png_ptr, "iTXt chunk not supported.");
  193193. continue;
  193194. }
  193195. #endif
  193196. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  193197. {
  193198. text_length = 0;
  193199. #ifdef PNG_iTXt_SUPPORTED
  193200. if(text_ptr[i].compression > 0)
  193201. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  193202. else
  193203. #endif
  193204. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  193205. }
  193206. else
  193207. {
  193208. text_length = png_strlen(text_ptr[i].text);
  193209. textp->compression = text_ptr[i].compression;
  193210. }
  193211. textp->key = (png_charp)png_malloc_warn(png_ptr,
  193212. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  193213. if (textp->key == NULL)
  193214. return(1);
  193215. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  193216. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  193217. (int)textp->key);
  193218. png_memcpy(textp->key, text_ptr[i].key,
  193219. (png_size_t)(key_len));
  193220. *(textp->key+key_len) = '\0';
  193221. #ifdef PNG_iTXt_SUPPORTED
  193222. if (text_ptr[i].compression > 0)
  193223. {
  193224. textp->lang=textp->key + key_len + 1;
  193225. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  193226. *(textp->lang+lang_len) = '\0';
  193227. textp->lang_key=textp->lang + lang_len + 1;
  193228. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  193229. *(textp->lang_key+lang_key_len) = '\0';
  193230. textp->text=textp->lang_key + lang_key_len + 1;
  193231. }
  193232. else
  193233. #endif
  193234. {
  193235. #ifdef PNG_iTXt_SUPPORTED
  193236. textp->lang=NULL;
  193237. textp->lang_key=NULL;
  193238. #endif
  193239. textp->text=textp->key + key_len + 1;
  193240. }
  193241. if(text_length)
  193242. png_memcpy(textp->text, text_ptr[i].text,
  193243. (png_size_t)(text_length));
  193244. *(textp->text+text_length) = '\0';
  193245. #ifdef PNG_iTXt_SUPPORTED
  193246. if(textp->compression > 0)
  193247. {
  193248. textp->text_length = 0;
  193249. textp->itxt_length = text_length;
  193250. }
  193251. else
  193252. #endif
  193253. {
  193254. textp->text_length = text_length;
  193255. #ifdef PNG_iTXt_SUPPORTED
  193256. textp->itxt_length = 0;
  193257. #endif
  193258. }
  193259. info_ptr->num_text++;
  193260. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  193261. }
  193262. return(0);
  193263. }
  193264. #endif
  193265. #if defined(PNG_tIME_SUPPORTED)
  193266. void PNGAPI
  193267. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  193268. {
  193269. png_debug1(1, "in %s storage function\n", "tIME");
  193270. if (png_ptr == NULL || info_ptr == NULL ||
  193271. (png_ptr->mode & PNG_WROTE_tIME))
  193272. return;
  193273. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  193274. info_ptr->valid |= PNG_INFO_tIME;
  193275. }
  193276. #endif
  193277. #if defined(PNG_tRNS_SUPPORTED)
  193278. void PNGAPI
  193279. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  193280. png_bytep trans, int num_trans, png_color_16p trans_values)
  193281. {
  193282. png_debug1(1, "in %s storage function\n", "tRNS");
  193283. if (png_ptr == NULL || info_ptr == NULL)
  193284. return;
  193285. if (trans != NULL)
  193286. {
  193287. /*
  193288. * It may not actually be necessary to set png_ptr->trans here;
  193289. * we do it for backward compatibility with the way the png_handle_tRNS
  193290. * function used to do the allocation.
  193291. */
  193292. #ifdef PNG_FREE_ME_SUPPORTED
  193293. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  193294. #endif
  193295. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  193296. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  193297. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  193298. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  193299. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  193300. #ifdef PNG_FREE_ME_SUPPORTED
  193301. info_ptr->free_me |= PNG_FREE_TRNS;
  193302. #else
  193303. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  193304. #endif
  193305. }
  193306. if (trans_values != NULL)
  193307. {
  193308. png_memcpy(&(info_ptr->trans_values), trans_values,
  193309. png_sizeof(png_color_16));
  193310. if (num_trans == 0)
  193311. num_trans = 1;
  193312. }
  193313. info_ptr->num_trans = (png_uint_16)num_trans;
  193314. info_ptr->valid |= PNG_INFO_tRNS;
  193315. }
  193316. #endif
  193317. #if defined(PNG_sPLT_SUPPORTED)
  193318. void PNGAPI
  193319. png_set_sPLT(png_structp png_ptr,
  193320. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  193321. {
  193322. png_sPLT_tp np;
  193323. int i;
  193324. if (png_ptr == NULL || info_ptr == NULL)
  193325. return;
  193326. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  193327. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  193328. if (np == NULL)
  193329. {
  193330. png_warning(png_ptr, "No memory for sPLT palettes.");
  193331. return;
  193332. }
  193333. png_memcpy(np, info_ptr->splt_palettes,
  193334. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  193335. png_free(png_ptr, info_ptr->splt_palettes);
  193336. info_ptr->splt_palettes=NULL;
  193337. for (i = 0; i < nentries; i++)
  193338. {
  193339. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  193340. png_sPLT_tp from = entries + i;
  193341. to->name = (png_charp)png_malloc_warn(png_ptr,
  193342. png_strlen(from->name) + 1);
  193343. if (to->name == NULL)
  193344. {
  193345. png_warning(png_ptr,
  193346. "Out of memory while processing sPLT chunk");
  193347. }
  193348. /* TODO: use png_malloc_warn */
  193349. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  193350. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  193351. from->nentries * png_sizeof(png_sPLT_entry));
  193352. /* TODO: use png_malloc_warn */
  193353. png_memcpy(to->entries, from->entries,
  193354. from->nentries * png_sizeof(png_sPLT_entry));
  193355. if (to->entries == NULL)
  193356. {
  193357. png_warning(png_ptr,
  193358. "Out of memory while processing sPLT chunk");
  193359. png_free(png_ptr,to->name);
  193360. to->name = NULL;
  193361. }
  193362. to->nentries = from->nentries;
  193363. to->depth = from->depth;
  193364. }
  193365. info_ptr->splt_palettes = np;
  193366. info_ptr->splt_palettes_num += nentries;
  193367. info_ptr->valid |= PNG_INFO_sPLT;
  193368. #ifdef PNG_FREE_ME_SUPPORTED
  193369. info_ptr->free_me |= PNG_FREE_SPLT;
  193370. #endif
  193371. }
  193372. #endif /* PNG_sPLT_SUPPORTED */
  193373. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193374. void PNGAPI
  193375. png_set_unknown_chunks(png_structp png_ptr,
  193376. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  193377. {
  193378. png_unknown_chunkp np;
  193379. int i;
  193380. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  193381. return;
  193382. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  193383. (info_ptr->unknown_chunks_num + num_unknowns) *
  193384. png_sizeof(png_unknown_chunk));
  193385. if (np == NULL)
  193386. {
  193387. png_warning(png_ptr,
  193388. "Out of memory while processing unknown chunk.");
  193389. return;
  193390. }
  193391. png_memcpy(np, info_ptr->unknown_chunks,
  193392. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  193393. png_free(png_ptr, info_ptr->unknown_chunks);
  193394. info_ptr->unknown_chunks=NULL;
  193395. for (i = 0; i < num_unknowns; i++)
  193396. {
  193397. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  193398. png_unknown_chunkp from = unknowns + i;
  193399. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  193400. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  193401. if (to->data == NULL)
  193402. {
  193403. png_warning(png_ptr,
  193404. "Out of memory while processing unknown chunk.");
  193405. }
  193406. else
  193407. {
  193408. png_memcpy(to->data, from->data, from->size);
  193409. to->size = from->size;
  193410. /* note our location in the read or write sequence */
  193411. to->location = (png_byte)(png_ptr->mode & 0xff);
  193412. }
  193413. }
  193414. info_ptr->unknown_chunks = np;
  193415. info_ptr->unknown_chunks_num += num_unknowns;
  193416. #ifdef PNG_FREE_ME_SUPPORTED
  193417. info_ptr->free_me |= PNG_FREE_UNKN;
  193418. #endif
  193419. }
  193420. void PNGAPI
  193421. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  193422. int chunk, int location)
  193423. {
  193424. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  193425. (int)info_ptr->unknown_chunks_num)
  193426. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  193427. }
  193428. #endif
  193429. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  193430. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  193431. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  193432. void PNGAPI
  193433. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  193434. {
  193435. /* This function is deprecated in favor of png_permit_mng_features()
  193436. and will be removed from libpng-1.3.0 */
  193437. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  193438. if (png_ptr == NULL)
  193439. return;
  193440. png_ptr->mng_features_permitted = (png_byte)
  193441. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  193442. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  193443. }
  193444. #endif
  193445. #endif
  193446. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193447. png_uint_32 PNGAPI
  193448. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  193449. {
  193450. png_debug(1, "in png_permit_mng_features\n");
  193451. if (png_ptr == NULL)
  193452. return (png_uint_32)0;
  193453. png_ptr->mng_features_permitted =
  193454. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  193455. return (png_uint_32)png_ptr->mng_features_permitted;
  193456. }
  193457. #endif
  193458. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193459. void PNGAPI
  193460. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  193461. chunk_list, int num_chunks)
  193462. {
  193463. png_bytep new_list, p;
  193464. int i, old_num_chunks;
  193465. if (png_ptr == NULL)
  193466. return;
  193467. if (num_chunks == 0)
  193468. {
  193469. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  193470. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193471. else
  193472. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193473. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  193474. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193475. else
  193476. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193477. return;
  193478. }
  193479. if (chunk_list == NULL)
  193480. return;
  193481. old_num_chunks=png_ptr->num_chunk_list;
  193482. new_list=(png_bytep)png_malloc(png_ptr,
  193483. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  193484. if(png_ptr->chunk_list != NULL)
  193485. {
  193486. png_memcpy(new_list, png_ptr->chunk_list,
  193487. (png_size_t)(5*old_num_chunks));
  193488. png_free(png_ptr, png_ptr->chunk_list);
  193489. png_ptr->chunk_list=NULL;
  193490. }
  193491. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  193492. (png_size_t)(5*num_chunks));
  193493. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  193494. *p=(png_byte)keep;
  193495. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  193496. png_ptr->chunk_list=new_list;
  193497. #ifdef PNG_FREE_ME_SUPPORTED
  193498. png_ptr->free_me |= PNG_FREE_LIST;
  193499. #endif
  193500. }
  193501. #endif
  193502. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  193503. void PNGAPI
  193504. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  193505. png_user_chunk_ptr read_user_chunk_fn)
  193506. {
  193507. png_debug(1, "in png_set_read_user_chunk_fn\n");
  193508. if (png_ptr == NULL)
  193509. return;
  193510. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  193511. png_ptr->user_chunk_ptr = user_chunk_ptr;
  193512. }
  193513. #endif
  193514. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  193515. void PNGAPI
  193516. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  193517. {
  193518. png_debug1(1, "in %s storage function\n", "rows");
  193519. if (png_ptr == NULL || info_ptr == NULL)
  193520. return;
  193521. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  193522. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  193523. info_ptr->row_pointers = row_pointers;
  193524. if(row_pointers)
  193525. info_ptr->valid |= PNG_INFO_IDAT;
  193526. }
  193527. #endif
  193528. #ifdef PNG_WRITE_SUPPORTED
  193529. void PNGAPI
  193530. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  193531. {
  193532. if (png_ptr == NULL)
  193533. return;
  193534. if(png_ptr->zbuf)
  193535. png_free(png_ptr, png_ptr->zbuf);
  193536. png_ptr->zbuf_size = (png_size_t)size;
  193537. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  193538. png_ptr->zstream.next_out = png_ptr->zbuf;
  193539. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193540. }
  193541. #endif
  193542. void PNGAPI
  193543. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  193544. {
  193545. if (png_ptr && info_ptr)
  193546. info_ptr->valid &= ~(mask);
  193547. }
  193548. #ifndef PNG_1_0_X
  193549. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  193550. /* function was added to libpng 1.2.0 and should always exist by default */
  193551. void PNGAPI
  193552. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  193553. {
  193554. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193555. if (png_ptr != NULL)
  193556. png_ptr->asm_flags = 0;
  193557. }
  193558. /* this function was added to libpng 1.2.0 */
  193559. void PNGAPI
  193560. png_set_mmx_thresholds (png_structp png_ptr,
  193561. png_byte mmx_bitdepth_threshold,
  193562. png_uint_32 mmx_rowbytes_threshold)
  193563. {
  193564. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193565. if (png_ptr == NULL)
  193566. return;
  193567. }
  193568. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  193569. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193570. /* this function was added to libpng 1.2.6 */
  193571. void PNGAPI
  193572. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  193573. png_uint_32 user_height_max)
  193574. {
  193575. /* Images with dimensions larger than these limits will be
  193576. * rejected by png_set_IHDR(). To accept any PNG datastream
  193577. * regardless of dimensions, set both limits to 0x7ffffffL.
  193578. */
  193579. if(png_ptr == NULL) return;
  193580. png_ptr->user_width_max = user_width_max;
  193581. png_ptr->user_height_max = user_height_max;
  193582. }
  193583. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  193584. #endif /* ?PNG_1_0_X */
  193585. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  193586. /********* End of inlined file: pngset.c *********/
  193587. /********* Start of inlined file: pngtrans.c *********/
  193588. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  193589. *
  193590. * Last changed in libpng 1.2.17 May 15, 2007
  193591. * For conditions of distribution and use, see copyright notice in png.h
  193592. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193593. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193594. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193595. */
  193596. #define PNG_INTERNAL
  193597. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193598. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193599. /* turn on BGR-to-RGB mapping */
  193600. void PNGAPI
  193601. png_set_bgr(png_structp png_ptr)
  193602. {
  193603. png_debug(1, "in png_set_bgr\n");
  193604. if(png_ptr == NULL) return;
  193605. png_ptr->transformations |= PNG_BGR;
  193606. }
  193607. #endif
  193608. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193609. /* turn on 16 bit byte swapping */
  193610. void PNGAPI
  193611. png_set_swap(png_structp png_ptr)
  193612. {
  193613. png_debug(1, "in png_set_swap\n");
  193614. if(png_ptr == NULL) return;
  193615. if (png_ptr->bit_depth == 16)
  193616. png_ptr->transformations |= PNG_SWAP_BYTES;
  193617. }
  193618. #endif
  193619. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  193620. /* turn on pixel packing */
  193621. void PNGAPI
  193622. png_set_packing(png_structp png_ptr)
  193623. {
  193624. png_debug(1, "in png_set_packing\n");
  193625. if(png_ptr == NULL) return;
  193626. if (png_ptr->bit_depth < 8)
  193627. {
  193628. png_ptr->transformations |= PNG_PACK;
  193629. png_ptr->usr_bit_depth = 8;
  193630. }
  193631. }
  193632. #endif
  193633. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193634. /* turn on packed pixel swapping */
  193635. void PNGAPI
  193636. png_set_packswap(png_structp png_ptr)
  193637. {
  193638. png_debug(1, "in png_set_packswap\n");
  193639. if(png_ptr == NULL) return;
  193640. if (png_ptr->bit_depth < 8)
  193641. png_ptr->transformations |= PNG_PACKSWAP;
  193642. }
  193643. #endif
  193644. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  193645. void PNGAPI
  193646. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  193647. {
  193648. png_debug(1, "in png_set_shift\n");
  193649. if(png_ptr == NULL) return;
  193650. png_ptr->transformations |= PNG_SHIFT;
  193651. png_ptr->shift = *true_bits;
  193652. }
  193653. #endif
  193654. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  193655. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193656. int PNGAPI
  193657. png_set_interlace_handling(png_structp png_ptr)
  193658. {
  193659. png_debug(1, "in png_set_interlace handling\n");
  193660. if (png_ptr && png_ptr->interlaced)
  193661. {
  193662. png_ptr->transformations |= PNG_INTERLACE;
  193663. return (7);
  193664. }
  193665. return (1);
  193666. }
  193667. #endif
  193668. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  193669. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  193670. * The filler type has changed in v0.95 to allow future 2-byte fillers
  193671. * for 48-bit input data, as well as to avoid problems with some compilers
  193672. * that don't like bytes as parameters.
  193673. */
  193674. void PNGAPI
  193675. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193676. {
  193677. png_debug(1, "in png_set_filler\n");
  193678. if(png_ptr == NULL) return;
  193679. png_ptr->transformations |= PNG_FILLER;
  193680. png_ptr->filler = (png_byte)filler;
  193681. if (filler_loc == PNG_FILLER_AFTER)
  193682. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  193683. else
  193684. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  193685. /* This should probably go in the "do_read_filler" routine.
  193686. * I attempted to do that in libpng-1.0.1a but that caused problems
  193687. * so I restored it in libpng-1.0.2a
  193688. */
  193689. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193690. {
  193691. png_ptr->usr_channels = 4;
  193692. }
  193693. /* Also I added this in libpng-1.0.2a (what happens when we expand
  193694. * a less-than-8-bit grayscale to GA? */
  193695. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  193696. {
  193697. png_ptr->usr_channels = 2;
  193698. }
  193699. }
  193700. #if !defined(PNG_1_0_X)
  193701. /* Added to libpng-1.2.7 */
  193702. void PNGAPI
  193703. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193704. {
  193705. png_debug(1, "in png_set_add_alpha\n");
  193706. if(png_ptr == NULL) return;
  193707. png_set_filler(png_ptr, filler, filler_loc);
  193708. png_ptr->transformations |= PNG_ADD_ALPHA;
  193709. }
  193710. #endif
  193711. #endif
  193712. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  193713. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193714. void PNGAPI
  193715. png_set_swap_alpha(png_structp png_ptr)
  193716. {
  193717. png_debug(1, "in png_set_swap_alpha\n");
  193718. if(png_ptr == NULL) return;
  193719. png_ptr->transformations |= PNG_SWAP_ALPHA;
  193720. }
  193721. #endif
  193722. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  193723. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193724. void PNGAPI
  193725. png_set_invert_alpha(png_structp png_ptr)
  193726. {
  193727. png_debug(1, "in png_set_invert_alpha\n");
  193728. if(png_ptr == NULL) return;
  193729. png_ptr->transformations |= PNG_INVERT_ALPHA;
  193730. }
  193731. #endif
  193732. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  193733. void PNGAPI
  193734. png_set_invert_mono(png_structp png_ptr)
  193735. {
  193736. png_debug(1, "in png_set_invert_mono\n");
  193737. if(png_ptr == NULL) return;
  193738. png_ptr->transformations |= PNG_INVERT_MONO;
  193739. }
  193740. /* invert monochrome grayscale data */
  193741. void /* PRIVATE */
  193742. png_do_invert(png_row_infop row_info, png_bytep row)
  193743. {
  193744. png_debug(1, "in png_do_invert\n");
  193745. /* This test removed from libpng version 1.0.13 and 1.2.0:
  193746. * if (row_info->bit_depth == 1 &&
  193747. */
  193748. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193749. if (row == NULL || row_info == NULL)
  193750. return;
  193751. #endif
  193752. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193753. {
  193754. png_bytep rp = row;
  193755. png_uint_32 i;
  193756. png_uint_32 istop = row_info->rowbytes;
  193757. for (i = 0; i < istop; i++)
  193758. {
  193759. *rp = (png_byte)(~(*rp));
  193760. rp++;
  193761. }
  193762. }
  193763. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193764. row_info->bit_depth == 8)
  193765. {
  193766. png_bytep rp = row;
  193767. png_uint_32 i;
  193768. png_uint_32 istop = row_info->rowbytes;
  193769. for (i = 0; i < istop; i+=2)
  193770. {
  193771. *rp = (png_byte)(~(*rp));
  193772. rp+=2;
  193773. }
  193774. }
  193775. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193776. row_info->bit_depth == 16)
  193777. {
  193778. png_bytep rp = row;
  193779. png_uint_32 i;
  193780. png_uint_32 istop = row_info->rowbytes;
  193781. for (i = 0; i < istop; i+=4)
  193782. {
  193783. *rp = (png_byte)(~(*rp));
  193784. *(rp+1) = (png_byte)(~(*(rp+1)));
  193785. rp+=4;
  193786. }
  193787. }
  193788. }
  193789. #endif
  193790. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193791. /* swaps byte order on 16 bit depth images */
  193792. void /* PRIVATE */
  193793. png_do_swap(png_row_infop row_info, png_bytep row)
  193794. {
  193795. png_debug(1, "in png_do_swap\n");
  193796. if (
  193797. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193798. row != NULL && row_info != NULL &&
  193799. #endif
  193800. row_info->bit_depth == 16)
  193801. {
  193802. png_bytep rp = row;
  193803. png_uint_32 i;
  193804. png_uint_32 istop= row_info->width * row_info->channels;
  193805. for (i = 0; i < istop; i++, rp += 2)
  193806. {
  193807. png_byte t = *rp;
  193808. *rp = *(rp + 1);
  193809. *(rp + 1) = t;
  193810. }
  193811. }
  193812. }
  193813. #endif
  193814. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193815. static PNG_CONST png_byte onebppswaptable[256] = {
  193816. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  193817. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  193818. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  193819. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  193820. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  193821. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  193822. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  193823. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  193824. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  193825. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  193826. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  193827. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  193828. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  193829. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  193830. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  193831. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  193832. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  193833. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  193834. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  193835. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  193836. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  193837. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  193838. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  193839. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  193840. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  193841. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  193842. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  193843. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  193844. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  193845. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  193846. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  193847. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  193848. };
  193849. static PNG_CONST png_byte twobppswaptable[256] = {
  193850. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  193851. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  193852. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  193853. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  193854. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  193855. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  193856. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  193857. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  193858. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  193859. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  193860. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  193861. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  193862. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  193863. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  193864. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  193865. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  193866. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  193867. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  193868. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  193869. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  193870. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  193871. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  193872. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  193873. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  193874. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  193875. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  193876. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  193877. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  193878. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  193879. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  193880. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  193881. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  193882. };
  193883. static PNG_CONST png_byte fourbppswaptable[256] = {
  193884. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  193885. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  193886. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  193887. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  193888. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  193889. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  193890. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  193891. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  193892. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  193893. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  193894. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  193895. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  193896. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  193897. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  193898. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  193899. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  193900. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  193901. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  193902. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  193903. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  193904. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  193905. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  193906. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  193907. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  193908. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  193909. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  193910. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  193911. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  193912. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  193913. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  193914. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  193915. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  193916. };
  193917. /* swaps pixel packing order within bytes */
  193918. void /* PRIVATE */
  193919. png_do_packswap(png_row_infop row_info, png_bytep row)
  193920. {
  193921. png_debug(1, "in png_do_packswap\n");
  193922. if (
  193923. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193924. row != NULL && row_info != NULL &&
  193925. #endif
  193926. row_info->bit_depth < 8)
  193927. {
  193928. png_bytep rp, end, table;
  193929. end = row + row_info->rowbytes;
  193930. if (row_info->bit_depth == 1)
  193931. table = (png_bytep)onebppswaptable;
  193932. else if (row_info->bit_depth == 2)
  193933. table = (png_bytep)twobppswaptable;
  193934. else if (row_info->bit_depth == 4)
  193935. table = (png_bytep)fourbppswaptable;
  193936. else
  193937. return;
  193938. for (rp = row; rp < end; rp++)
  193939. *rp = table[*rp];
  193940. }
  193941. }
  193942. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  193943. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  193944. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  193945. /* remove filler or alpha byte(s) */
  193946. void /* PRIVATE */
  193947. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  193948. {
  193949. png_debug(1, "in png_do_strip_filler\n");
  193950. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193951. if (row != NULL && row_info != NULL)
  193952. #endif
  193953. {
  193954. png_bytep sp=row;
  193955. png_bytep dp=row;
  193956. png_uint_32 row_width=row_info->width;
  193957. png_uint_32 i;
  193958. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  193959. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193960. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193961. row_info->channels == 4)
  193962. {
  193963. if (row_info->bit_depth == 8)
  193964. {
  193965. /* This converts from RGBX or RGBA to RGB */
  193966. if (flags & PNG_FLAG_FILLER_AFTER)
  193967. {
  193968. dp+=3; sp+=4;
  193969. for (i = 1; i < row_width; i++)
  193970. {
  193971. *dp++ = *sp++;
  193972. *dp++ = *sp++;
  193973. *dp++ = *sp++;
  193974. sp++;
  193975. }
  193976. }
  193977. /* This converts from XRGB or ARGB to RGB */
  193978. else
  193979. {
  193980. for (i = 0; i < row_width; i++)
  193981. {
  193982. sp++;
  193983. *dp++ = *sp++;
  193984. *dp++ = *sp++;
  193985. *dp++ = *sp++;
  193986. }
  193987. }
  193988. row_info->pixel_depth = 24;
  193989. row_info->rowbytes = row_width * 3;
  193990. }
  193991. else /* if (row_info->bit_depth == 16) */
  193992. {
  193993. if (flags & PNG_FLAG_FILLER_AFTER)
  193994. {
  193995. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  193996. sp += 8; dp += 6;
  193997. for (i = 1; i < row_width; i++)
  193998. {
  193999. /* This could be (although png_memcpy is probably slower):
  194000. png_memcpy(dp, sp, 6);
  194001. sp += 8;
  194002. dp += 6;
  194003. */
  194004. *dp++ = *sp++;
  194005. *dp++ = *sp++;
  194006. *dp++ = *sp++;
  194007. *dp++ = *sp++;
  194008. *dp++ = *sp++;
  194009. *dp++ = *sp++;
  194010. sp += 2;
  194011. }
  194012. }
  194013. else
  194014. {
  194015. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  194016. for (i = 0; i < row_width; i++)
  194017. {
  194018. /* This could be (although png_memcpy is probably slower):
  194019. png_memcpy(dp, sp, 6);
  194020. sp += 8;
  194021. dp += 6;
  194022. */
  194023. sp+=2;
  194024. *dp++ = *sp++;
  194025. *dp++ = *sp++;
  194026. *dp++ = *sp++;
  194027. *dp++ = *sp++;
  194028. *dp++ = *sp++;
  194029. *dp++ = *sp++;
  194030. }
  194031. }
  194032. row_info->pixel_depth = 48;
  194033. row_info->rowbytes = row_width * 6;
  194034. }
  194035. row_info->channels = 3;
  194036. }
  194037. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  194038. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  194039. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  194040. row_info->channels == 2)
  194041. {
  194042. if (row_info->bit_depth == 8)
  194043. {
  194044. /* This converts from GX or GA to G */
  194045. if (flags & PNG_FLAG_FILLER_AFTER)
  194046. {
  194047. for (i = 0; i < row_width; i++)
  194048. {
  194049. *dp++ = *sp++;
  194050. sp++;
  194051. }
  194052. }
  194053. /* This converts from XG or AG to G */
  194054. else
  194055. {
  194056. for (i = 0; i < row_width; i++)
  194057. {
  194058. sp++;
  194059. *dp++ = *sp++;
  194060. }
  194061. }
  194062. row_info->pixel_depth = 8;
  194063. row_info->rowbytes = row_width;
  194064. }
  194065. else /* if (row_info->bit_depth == 16) */
  194066. {
  194067. if (flags & PNG_FLAG_FILLER_AFTER)
  194068. {
  194069. /* This converts from GGXX or GGAA to GG */
  194070. sp += 4; dp += 2;
  194071. for (i = 1; i < row_width; i++)
  194072. {
  194073. *dp++ = *sp++;
  194074. *dp++ = *sp++;
  194075. sp += 2;
  194076. }
  194077. }
  194078. else
  194079. {
  194080. /* This converts from XXGG or AAGG to GG */
  194081. for (i = 0; i < row_width; i++)
  194082. {
  194083. sp += 2;
  194084. *dp++ = *sp++;
  194085. *dp++ = *sp++;
  194086. }
  194087. }
  194088. row_info->pixel_depth = 16;
  194089. row_info->rowbytes = row_width * 2;
  194090. }
  194091. row_info->channels = 1;
  194092. }
  194093. if (flags & PNG_FLAG_STRIP_ALPHA)
  194094. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  194095. }
  194096. }
  194097. #endif
  194098. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  194099. /* swaps red and blue bytes within a pixel */
  194100. void /* PRIVATE */
  194101. png_do_bgr(png_row_infop row_info, png_bytep row)
  194102. {
  194103. png_debug(1, "in png_do_bgr\n");
  194104. if (
  194105. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194106. row != NULL && row_info != NULL &&
  194107. #endif
  194108. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194109. {
  194110. png_uint_32 row_width = row_info->width;
  194111. if (row_info->bit_depth == 8)
  194112. {
  194113. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194114. {
  194115. png_bytep rp;
  194116. png_uint_32 i;
  194117. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  194118. {
  194119. png_byte save = *rp;
  194120. *rp = *(rp + 2);
  194121. *(rp + 2) = save;
  194122. }
  194123. }
  194124. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194125. {
  194126. png_bytep rp;
  194127. png_uint_32 i;
  194128. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  194129. {
  194130. png_byte save = *rp;
  194131. *rp = *(rp + 2);
  194132. *(rp + 2) = save;
  194133. }
  194134. }
  194135. }
  194136. else if (row_info->bit_depth == 16)
  194137. {
  194138. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194139. {
  194140. png_bytep rp;
  194141. png_uint_32 i;
  194142. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  194143. {
  194144. png_byte save = *rp;
  194145. *rp = *(rp + 4);
  194146. *(rp + 4) = save;
  194147. save = *(rp + 1);
  194148. *(rp + 1) = *(rp + 5);
  194149. *(rp + 5) = save;
  194150. }
  194151. }
  194152. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194153. {
  194154. png_bytep rp;
  194155. png_uint_32 i;
  194156. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  194157. {
  194158. png_byte save = *rp;
  194159. *rp = *(rp + 4);
  194160. *(rp + 4) = save;
  194161. save = *(rp + 1);
  194162. *(rp + 1) = *(rp + 5);
  194163. *(rp + 5) = save;
  194164. }
  194165. }
  194166. }
  194167. }
  194168. }
  194169. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  194170. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  194171. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  194172. defined(PNG_LEGACY_SUPPORTED)
  194173. void PNGAPI
  194174. png_set_user_transform_info(png_structp png_ptr, png_voidp
  194175. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  194176. {
  194177. png_debug(1, "in png_set_user_transform_info\n");
  194178. if(png_ptr == NULL) return;
  194179. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194180. png_ptr->user_transform_ptr = user_transform_ptr;
  194181. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  194182. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  194183. #else
  194184. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  194185. png_warning(png_ptr,
  194186. "This version of libpng does not support user transform info");
  194187. #endif
  194188. }
  194189. #endif
  194190. /* This function returns a pointer to the user_transform_ptr associated with
  194191. * the user transform functions. The application should free any memory
  194192. * associated with this pointer before png_write_destroy and png_read_destroy
  194193. * are called.
  194194. */
  194195. png_voidp PNGAPI
  194196. png_get_user_transform_ptr(png_structp png_ptr)
  194197. {
  194198. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194199. if (png_ptr == NULL) return (NULL);
  194200. return ((png_voidp)png_ptr->user_transform_ptr);
  194201. #else
  194202. return (NULL);
  194203. #endif
  194204. }
  194205. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194206. /********* End of inlined file: pngtrans.c *********/
  194207. /********* Start of inlined file: pngwio.c *********/
  194208. /* pngwio.c - functions for data output
  194209. *
  194210. * Last changed in libpng 1.2.13 November 13, 2006
  194211. * For conditions of distribution and use, see copyright notice in png.h
  194212. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194213. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194214. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194215. *
  194216. * This file provides a location for all output. Users who need
  194217. * special handling are expected to write functions that have the same
  194218. * arguments as these and perform similar functions, but that possibly
  194219. * use different output methods. Note that you shouldn't change these
  194220. * functions, but rather write replacement functions and then change
  194221. * them at run time with png_set_write_fn(...).
  194222. */
  194223. #define PNG_INTERNAL
  194224. #ifdef PNG_WRITE_SUPPORTED
  194225. /* Write the data to whatever output you are using. The default routine
  194226. writes to a file pointer. Note that this routine sometimes gets called
  194227. with very small lengths, so you should implement some kind of simple
  194228. buffering if you are using unbuffered writes. This should never be asked
  194229. to write more than 64K on a 16 bit machine. */
  194230. void /* PRIVATE */
  194231. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194232. {
  194233. if (png_ptr->write_data_fn != NULL )
  194234. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  194235. else
  194236. png_error(png_ptr, "Call to NULL write function");
  194237. }
  194238. #if !defined(PNG_NO_STDIO)
  194239. /* This is the function that does the actual writing of data. If you are
  194240. not writing to a standard C stream, you should create a replacement
  194241. write_data function and use it at run time with png_set_write_fn(), rather
  194242. than changing the library. */
  194243. #ifndef USE_FAR_KEYWORD
  194244. void PNGAPI
  194245. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194246. {
  194247. png_uint_32 check;
  194248. if(png_ptr == NULL) return;
  194249. #if defined(_WIN32_WCE)
  194250. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  194251. check = 0;
  194252. #else
  194253. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  194254. #endif
  194255. if (check != length)
  194256. png_error(png_ptr, "Write Error");
  194257. }
  194258. #else
  194259. /* this is the model-independent version. Since the standard I/O library
  194260. can't handle far buffers in the medium and small models, we have to copy
  194261. the data.
  194262. */
  194263. #define NEAR_BUF_SIZE 1024
  194264. #define MIN(a,b) (a <= b ? a : b)
  194265. void PNGAPI
  194266. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194267. {
  194268. png_uint_32 check;
  194269. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  194270. png_FILE_p io_ptr;
  194271. if(png_ptr == NULL) return;
  194272. /* Check if data really is near. If so, use usual code. */
  194273. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  194274. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  194275. if ((png_bytep)near_data == data)
  194276. {
  194277. #if defined(_WIN32_WCE)
  194278. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  194279. check = 0;
  194280. #else
  194281. check = fwrite(near_data, 1, length, io_ptr);
  194282. #endif
  194283. }
  194284. else
  194285. {
  194286. png_byte buf[NEAR_BUF_SIZE];
  194287. png_size_t written, remaining, err;
  194288. check = 0;
  194289. remaining = length;
  194290. do
  194291. {
  194292. written = MIN(NEAR_BUF_SIZE, remaining);
  194293. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  194294. #if defined(_WIN32_WCE)
  194295. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  194296. err = 0;
  194297. #else
  194298. err = fwrite(buf, 1, written, io_ptr);
  194299. #endif
  194300. if (err != written)
  194301. break;
  194302. else
  194303. check += err;
  194304. data += written;
  194305. remaining -= written;
  194306. }
  194307. while (remaining != 0);
  194308. }
  194309. if (check != length)
  194310. png_error(png_ptr, "Write Error");
  194311. }
  194312. #endif
  194313. #endif
  194314. /* This function is called to output any data pending writing (normally
  194315. to disk). After png_flush is called, there should be no data pending
  194316. writing in any buffers. */
  194317. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194318. void /* PRIVATE */
  194319. png_flush(png_structp png_ptr)
  194320. {
  194321. if (png_ptr->output_flush_fn != NULL)
  194322. (*(png_ptr->output_flush_fn))(png_ptr);
  194323. }
  194324. #if !defined(PNG_NO_STDIO)
  194325. void PNGAPI
  194326. png_default_flush(png_structp png_ptr)
  194327. {
  194328. #if !defined(_WIN32_WCE)
  194329. png_FILE_p io_ptr;
  194330. #endif
  194331. if(png_ptr == NULL) return;
  194332. #if !defined(_WIN32_WCE)
  194333. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  194334. if (io_ptr != NULL)
  194335. fflush(io_ptr);
  194336. #endif
  194337. }
  194338. #endif
  194339. #endif
  194340. /* This function allows the application to supply new output functions for
  194341. libpng if standard C streams aren't being used.
  194342. This function takes as its arguments:
  194343. png_ptr - pointer to a png output data structure
  194344. io_ptr - pointer to user supplied structure containing info about
  194345. the output functions. May be NULL.
  194346. write_data_fn - pointer to a new output function that takes as its
  194347. arguments a pointer to a png_struct, a pointer to
  194348. data to be written, and a 32-bit unsigned int that is
  194349. the number of bytes to be written. The new write
  194350. function should call png_error(png_ptr, "Error msg")
  194351. to exit and output any fatal error messages.
  194352. flush_data_fn - pointer to a new flush function that takes as its
  194353. arguments a pointer to a png_struct. After a call to
  194354. the flush function, there should be no data in any buffers
  194355. or pending transmission. If the output method doesn't do
  194356. any buffering of ouput, a function prototype must still be
  194357. supplied although it doesn't have to do anything. If
  194358. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  194359. time, output_flush_fn will be ignored, although it must be
  194360. supplied for compatibility. */
  194361. void PNGAPI
  194362. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  194363. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  194364. {
  194365. if(png_ptr == NULL) return;
  194366. png_ptr->io_ptr = io_ptr;
  194367. #if !defined(PNG_NO_STDIO)
  194368. if (write_data_fn != NULL)
  194369. png_ptr->write_data_fn = write_data_fn;
  194370. else
  194371. png_ptr->write_data_fn = png_default_write_data;
  194372. #else
  194373. png_ptr->write_data_fn = write_data_fn;
  194374. #endif
  194375. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194376. #if !defined(PNG_NO_STDIO)
  194377. if (output_flush_fn != NULL)
  194378. png_ptr->output_flush_fn = output_flush_fn;
  194379. else
  194380. png_ptr->output_flush_fn = png_default_flush;
  194381. #else
  194382. png_ptr->output_flush_fn = output_flush_fn;
  194383. #endif
  194384. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  194385. /* It is an error to read while writing a png file */
  194386. if (png_ptr->read_data_fn != NULL)
  194387. {
  194388. png_ptr->read_data_fn = NULL;
  194389. png_warning(png_ptr,
  194390. "Attempted to set both read_data_fn and write_data_fn in");
  194391. png_warning(png_ptr,
  194392. "the same structure. Resetting read_data_fn to NULL.");
  194393. }
  194394. }
  194395. #if defined(USE_FAR_KEYWORD)
  194396. #if defined(_MSC_VER)
  194397. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194398. {
  194399. void *near_ptr;
  194400. void FAR *far_ptr;
  194401. FP_OFF(near_ptr) = FP_OFF(ptr);
  194402. far_ptr = (void FAR *)near_ptr;
  194403. if(check != 0)
  194404. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  194405. png_error(png_ptr,"segment lost in conversion");
  194406. return(near_ptr);
  194407. }
  194408. # else
  194409. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194410. {
  194411. void *near_ptr;
  194412. void FAR *far_ptr;
  194413. near_ptr = (void FAR *)ptr;
  194414. far_ptr = (void FAR *)near_ptr;
  194415. if(check != 0)
  194416. if(far_ptr != ptr)
  194417. png_error(png_ptr,"segment lost in conversion");
  194418. return(near_ptr);
  194419. }
  194420. # endif
  194421. # endif
  194422. #endif /* PNG_WRITE_SUPPORTED */
  194423. /********* End of inlined file: pngwio.c *********/
  194424. /********* Start of inlined file: pngwrite.c *********/
  194425. /* pngwrite.c - general routines to write a PNG file
  194426. *
  194427. * Last changed in libpng 1.2.15 January 5, 2007
  194428. * For conditions of distribution and use, see copyright notice in png.h
  194429. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194430. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194431. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194432. */
  194433. /* get internal access to png.h */
  194434. #define PNG_INTERNAL
  194435. #ifdef PNG_WRITE_SUPPORTED
  194436. /* Writes all the PNG information. This is the suggested way to use the
  194437. * library. If you have a new chunk to add, make a function to write it,
  194438. * and put it in the correct location here. If you want the chunk written
  194439. * after the image data, put it in png_write_end(). I strongly encourage
  194440. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  194441. * the chunk, as that will keep the code from breaking if you want to just
  194442. * write a plain PNG file. If you have long comments, I suggest writing
  194443. * them in png_write_end(), and compressing them.
  194444. */
  194445. void PNGAPI
  194446. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  194447. {
  194448. png_debug(1, "in png_write_info_before_PLTE\n");
  194449. if (png_ptr == NULL || info_ptr == NULL)
  194450. return;
  194451. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194452. {
  194453. png_write_sig(png_ptr); /* write PNG signature */
  194454. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194455. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  194456. {
  194457. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  194458. png_ptr->mng_features_permitted=0;
  194459. }
  194460. #endif
  194461. /* write IHDR information. */
  194462. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  194463. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  194464. info_ptr->filter_type,
  194465. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194466. info_ptr->interlace_type);
  194467. #else
  194468. 0);
  194469. #endif
  194470. /* the rest of these check to see if the valid field has the appropriate
  194471. flag set, and if it does, writes the chunk. */
  194472. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  194473. if (info_ptr->valid & PNG_INFO_gAMA)
  194474. {
  194475. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194476. png_write_gAMA(png_ptr, info_ptr->gamma);
  194477. #else
  194478. #ifdef PNG_FIXED_POINT_SUPPORTED
  194479. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  194480. # endif
  194481. #endif
  194482. }
  194483. #endif
  194484. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  194485. if (info_ptr->valid & PNG_INFO_sRGB)
  194486. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  194487. #endif
  194488. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  194489. if (info_ptr->valid & PNG_INFO_iCCP)
  194490. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  194491. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  194492. #endif
  194493. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  194494. if (info_ptr->valid & PNG_INFO_sBIT)
  194495. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  194496. #endif
  194497. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  194498. if (info_ptr->valid & PNG_INFO_cHRM)
  194499. {
  194500. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194501. png_write_cHRM(png_ptr,
  194502. info_ptr->x_white, info_ptr->y_white,
  194503. info_ptr->x_red, info_ptr->y_red,
  194504. info_ptr->x_green, info_ptr->y_green,
  194505. info_ptr->x_blue, info_ptr->y_blue);
  194506. #else
  194507. # ifdef PNG_FIXED_POINT_SUPPORTED
  194508. png_write_cHRM_fixed(png_ptr,
  194509. info_ptr->int_x_white, info_ptr->int_y_white,
  194510. info_ptr->int_x_red, info_ptr->int_y_red,
  194511. info_ptr->int_x_green, info_ptr->int_y_green,
  194512. info_ptr->int_x_blue, info_ptr->int_y_blue);
  194513. # endif
  194514. #endif
  194515. }
  194516. #endif
  194517. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194518. if (info_ptr->unknown_chunks_num)
  194519. {
  194520. png_unknown_chunk *up;
  194521. png_debug(5, "writing extra chunks\n");
  194522. for (up = info_ptr->unknown_chunks;
  194523. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194524. up++)
  194525. {
  194526. int keep=png_handle_as_unknown(png_ptr, up->name);
  194527. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194528. up->location && !(up->location & PNG_HAVE_PLTE) &&
  194529. !(up->location & PNG_HAVE_IDAT) &&
  194530. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194531. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194532. {
  194533. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194534. }
  194535. }
  194536. }
  194537. #endif
  194538. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  194539. }
  194540. }
  194541. void PNGAPI
  194542. png_write_info(png_structp png_ptr, png_infop info_ptr)
  194543. {
  194544. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  194545. int i;
  194546. #endif
  194547. png_debug(1, "in png_write_info\n");
  194548. if (png_ptr == NULL || info_ptr == NULL)
  194549. return;
  194550. png_write_info_before_PLTE(png_ptr, info_ptr);
  194551. if (info_ptr->valid & PNG_INFO_PLTE)
  194552. png_write_PLTE(png_ptr, info_ptr->palette,
  194553. (png_uint_32)info_ptr->num_palette);
  194554. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194555. png_error(png_ptr, "Valid palette required for paletted images");
  194556. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  194557. if (info_ptr->valid & PNG_INFO_tRNS)
  194558. {
  194559. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194560. /* invert the alpha channel (in tRNS) */
  194561. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  194562. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194563. {
  194564. int j;
  194565. for (j=0; j<(int)info_ptr->num_trans; j++)
  194566. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  194567. }
  194568. #endif
  194569. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  194570. info_ptr->num_trans, info_ptr->color_type);
  194571. }
  194572. #endif
  194573. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  194574. if (info_ptr->valid & PNG_INFO_bKGD)
  194575. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  194576. #endif
  194577. #if defined(PNG_WRITE_hIST_SUPPORTED)
  194578. if (info_ptr->valid & PNG_INFO_hIST)
  194579. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  194580. #endif
  194581. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  194582. if (info_ptr->valid & PNG_INFO_oFFs)
  194583. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  194584. info_ptr->offset_unit_type);
  194585. #endif
  194586. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  194587. if (info_ptr->valid & PNG_INFO_pCAL)
  194588. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  194589. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  194590. info_ptr->pcal_units, info_ptr->pcal_params);
  194591. #endif
  194592. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  194593. if (info_ptr->valid & PNG_INFO_sCAL)
  194594. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  194595. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  194596. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  194597. #else
  194598. #ifdef PNG_FIXED_POINT_SUPPORTED
  194599. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  194600. info_ptr->scal_s_width, info_ptr->scal_s_height);
  194601. #else
  194602. png_warning(png_ptr,
  194603. "png_write_sCAL not supported; sCAL chunk not written.");
  194604. #endif
  194605. #endif
  194606. #endif
  194607. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  194608. if (info_ptr->valid & PNG_INFO_pHYs)
  194609. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  194610. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  194611. #endif
  194612. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194613. if (info_ptr->valid & PNG_INFO_tIME)
  194614. {
  194615. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194616. png_ptr->mode |= PNG_WROTE_tIME;
  194617. }
  194618. #endif
  194619. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  194620. if (info_ptr->valid & PNG_INFO_sPLT)
  194621. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  194622. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  194623. #endif
  194624. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194625. /* Check to see if we need to write text chunks */
  194626. for (i = 0; i < info_ptr->num_text; i++)
  194627. {
  194628. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  194629. info_ptr->text[i].compression);
  194630. /* an internationalized chunk? */
  194631. if (info_ptr->text[i].compression > 0)
  194632. {
  194633. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194634. /* write international chunk */
  194635. png_write_iTXt(png_ptr,
  194636. info_ptr->text[i].compression,
  194637. info_ptr->text[i].key,
  194638. info_ptr->text[i].lang,
  194639. info_ptr->text[i].lang_key,
  194640. info_ptr->text[i].text);
  194641. #else
  194642. png_warning(png_ptr, "Unable to write international text");
  194643. #endif
  194644. /* Mark this chunk as written */
  194645. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194646. }
  194647. /* If we want a compressed text chunk */
  194648. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  194649. {
  194650. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194651. /* write compressed chunk */
  194652. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194653. info_ptr->text[i].text, 0,
  194654. info_ptr->text[i].compression);
  194655. #else
  194656. png_warning(png_ptr, "Unable to write compressed text");
  194657. #endif
  194658. /* Mark this chunk as written */
  194659. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194660. }
  194661. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194662. {
  194663. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194664. /* write uncompressed chunk */
  194665. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194666. info_ptr->text[i].text,
  194667. 0);
  194668. #else
  194669. png_warning(png_ptr, "Unable to write uncompressed text");
  194670. #endif
  194671. /* Mark this chunk as written */
  194672. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194673. }
  194674. }
  194675. #endif
  194676. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194677. if (info_ptr->unknown_chunks_num)
  194678. {
  194679. png_unknown_chunk *up;
  194680. png_debug(5, "writing extra chunks\n");
  194681. for (up = info_ptr->unknown_chunks;
  194682. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194683. up++)
  194684. {
  194685. int keep=png_handle_as_unknown(png_ptr, up->name);
  194686. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194687. up->location && (up->location & PNG_HAVE_PLTE) &&
  194688. !(up->location & PNG_HAVE_IDAT) &&
  194689. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194690. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194691. {
  194692. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194693. }
  194694. }
  194695. }
  194696. #endif
  194697. }
  194698. /* Writes the end of the PNG file. If you don't want to write comments or
  194699. * time information, you can pass NULL for info. If you already wrote these
  194700. * in png_write_info(), do not write them again here. If you have long
  194701. * comments, I suggest writing them here, and compressing them.
  194702. */
  194703. void PNGAPI
  194704. png_write_end(png_structp png_ptr, png_infop info_ptr)
  194705. {
  194706. png_debug(1, "in png_write_end\n");
  194707. if (png_ptr == NULL)
  194708. return;
  194709. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  194710. png_error(png_ptr, "No IDATs written into file");
  194711. /* see if user wants us to write information chunks */
  194712. if (info_ptr != NULL)
  194713. {
  194714. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194715. int i; /* local index variable */
  194716. #endif
  194717. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194718. /* check to see if user has supplied a time chunk */
  194719. if ((info_ptr->valid & PNG_INFO_tIME) &&
  194720. !(png_ptr->mode & PNG_WROTE_tIME))
  194721. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194722. #endif
  194723. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194724. /* loop through comment chunks */
  194725. for (i = 0; i < info_ptr->num_text; i++)
  194726. {
  194727. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  194728. info_ptr->text[i].compression);
  194729. /* an internationalized chunk? */
  194730. if (info_ptr->text[i].compression > 0)
  194731. {
  194732. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194733. /* write international chunk */
  194734. png_write_iTXt(png_ptr,
  194735. info_ptr->text[i].compression,
  194736. info_ptr->text[i].key,
  194737. info_ptr->text[i].lang,
  194738. info_ptr->text[i].lang_key,
  194739. info_ptr->text[i].text);
  194740. #else
  194741. png_warning(png_ptr, "Unable to write international text");
  194742. #endif
  194743. /* Mark this chunk as written */
  194744. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194745. }
  194746. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  194747. {
  194748. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194749. /* write compressed chunk */
  194750. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194751. info_ptr->text[i].text, 0,
  194752. info_ptr->text[i].compression);
  194753. #else
  194754. png_warning(png_ptr, "Unable to write compressed text");
  194755. #endif
  194756. /* Mark this chunk as written */
  194757. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194758. }
  194759. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194760. {
  194761. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194762. /* write uncompressed chunk */
  194763. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194764. info_ptr->text[i].text, 0);
  194765. #else
  194766. png_warning(png_ptr, "Unable to write uncompressed text");
  194767. #endif
  194768. /* Mark this chunk as written */
  194769. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194770. }
  194771. }
  194772. #endif
  194773. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194774. if (info_ptr->unknown_chunks_num)
  194775. {
  194776. png_unknown_chunk *up;
  194777. png_debug(5, "writing extra chunks\n");
  194778. for (up = info_ptr->unknown_chunks;
  194779. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194780. up++)
  194781. {
  194782. int keep=png_handle_as_unknown(png_ptr, up->name);
  194783. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194784. up->location && (up->location & PNG_AFTER_IDAT) &&
  194785. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194786. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194787. {
  194788. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194789. }
  194790. }
  194791. }
  194792. #endif
  194793. }
  194794. png_ptr->mode |= PNG_AFTER_IDAT;
  194795. /* write end of PNG file */
  194796. png_write_IEND(png_ptr);
  194797. }
  194798. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194799. #if !defined(_WIN32_WCE)
  194800. /* "time.h" functions are not supported on WindowsCE */
  194801. void PNGAPI
  194802. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  194803. {
  194804. png_debug(1, "in png_convert_from_struct_tm\n");
  194805. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  194806. ptime->month = (png_byte)(ttime->tm_mon + 1);
  194807. ptime->day = (png_byte)ttime->tm_mday;
  194808. ptime->hour = (png_byte)ttime->tm_hour;
  194809. ptime->minute = (png_byte)ttime->tm_min;
  194810. ptime->second = (png_byte)ttime->tm_sec;
  194811. }
  194812. void PNGAPI
  194813. png_convert_from_time_t(png_timep ptime, time_t ttime)
  194814. {
  194815. struct tm *tbuf;
  194816. png_debug(1, "in png_convert_from_time_t\n");
  194817. tbuf = gmtime(&ttime);
  194818. png_convert_from_struct_tm(ptime, tbuf);
  194819. }
  194820. #endif
  194821. #endif
  194822. /* Initialize png_ptr structure, and allocate any memory needed */
  194823. png_structp PNGAPI
  194824. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  194825. png_error_ptr error_fn, png_error_ptr warn_fn)
  194826. {
  194827. #ifdef PNG_USER_MEM_SUPPORTED
  194828. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  194829. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  194830. }
  194831. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  194832. png_structp PNGAPI
  194833. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  194834. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  194835. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  194836. {
  194837. #endif /* PNG_USER_MEM_SUPPORTED */
  194838. png_structp png_ptr;
  194839. #ifdef PNG_SETJMP_SUPPORTED
  194840. #ifdef USE_FAR_KEYWORD
  194841. jmp_buf jmpbuf;
  194842. #endif
  194843. #endif
  194844. int i;
  194845. png_debug(1, "in png_create_write_struct\n");
  194846. #ifdef PNG_USER_MEM_SUPPORTED
  194847. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  194848. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  194849. #else
  194850. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194851. #endif /* PNG_USER_MEM_SUPPORTED */
  194852. if (png_ptr == NULL)
  194853. return (NULL);
  194854. /* added at libpng-1.2.6 */
  194855. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194856. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194857. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194858. #endif
  194859. #ifdef PNG_SETJMP_SUPPORTED
  194860. #ifdef USE_FAR_KEYWORD
  194861. if (setjmp(jmpbuf))
  194862. #else
  194863. if (setjmp(png_ptr->jmpbuf))
  194864. #endif
  194865. {
  194866. png_free(png_ptr, png_ptr->zbuf);
  194867. png_ptr->zbuf=NULL;
  194868. png_destroy_struct(png_ptr);
  194869. return (NULL);
  194870. }
  194871. #ifdef USE_FAR_KEYWORD
  194872. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194873. #endif
  194874. #endif
  194875. #ifdef PNG_USER_MEM_SUPPORTED
  194876. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  194877. #endif /* PNG_USER_MEM_SUPPORTED */
  194878. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  194879. i=0;
  194880. do
  194881. {
  194882. if(user_png_ver[i] != png_libpng_ver[i])
  194883. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194884. } while (png_libpng_ver[i++]);
  194885. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  194886. {
  194887. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  194888. * we must recompile any applications that use any older library version.
  194889. * For versions after libpng 1.0, we will be compatible, so we need
  194890. * only check the first digit.
  194891. */
  194892. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  194893. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  194894. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  194895. {
  194896. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194897. char msg[80];
  194898. if (user_png_ver)
  194899. {
  194900. png_snprintf(msg, 80,
  194901. "Application was compiled with png.h from libpng-%.20s",
  194902. user_png_ver);
  194903. png_warning(png_ptr, msg);
  194904. }
  194905. png_snprintf(msg, 80,
  194906. "Application is running with png.c from libpng-%.20s",
  194907. png_libpng_ver);
  194908. png_warning(png_ptr, msg);
  194909. #endif
  194910. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194911. png_ptr->flags=0;
  194912. #endif
  194913. png_error(png_ptr,
  194914. "Incompatible libpng version in application and library");
  194915. }
  194916. }
  194917. /* initialize zbuf - compression buffer */
  194918. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194919. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194920. (png_uint_32)png_ptr->zbuf_size);
  194921. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194922. png_flush_ptr_NULL);
  194923. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194924. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194925. 1, png_doublep_NULL, png_doublep_NULL);
  194926. #endif
  194927. #ifdef PNG_SETJMP_SUPPORTED
  194928. /* Applications that neglect to set up their own setjmp() and then encounter
  194929. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  194930. abort instead of returning. */
  194931. #ifdef USE_FAR_KEYWORD
  194932. if (setjmp(jmpbuf))
  194933. PNG_ABORT();
  194934. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194935. #else
  194936. if (setjmp(png_ptr->jmpbuf))
  194937. PNG_ABORT();
  194938. #endif
  194939. #endif
  194940. return (png_ptr);
  194941. }
  194942. /* Initialize png_ptr structure, and allocate any memory needed */
  194943. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194944. /* Deprecated. */
  194945. #undef png_write_init
  194946. void PNGAPI
  194947. png_write_init(png_structp png_ptr)
  194948. {
  194949. /* We only come here via pre-1.0.7-compiled applications */
  194950. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  194951. }
  194952. void PNGAPI
  194953. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  194954. png_size_t png_struct_size, png_size_t png_info_size)
  194955. {
  194956. /* We only come here via pre-1.0.12-compiled applications */
  194957. if(png_ptr == NULL) return;
  194958. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194959. if(png_sizeof(png_struct) > png_struct_size ||
  194960. png_sizeof(png_info) > png_info_size)
  194961. {
  194962. char msg[80];
  194963. png_ptr->warning_fn=NULL;
  194964. if (user_png_ver)
  194965. {
  194966. png_snprintf(msg, 80,
  194967. "Application was compiled with png.h from libpng-%.20s",
  194968. user_png_ver);
  194969. png_warning(png_ptr, msg);
  194970. }
  194971. png_snprintf(msg, 80,
  194972. "Application is running with png.c from libpng-%.20s",
  194973. png_libpng_ver);
  194974. png_warning(png_ptr, msg);
  194975. }
  194976. #endif
  194977. if(png_sizeof(png_struct) > png_struct_size)
  194978. {
  194979. png_ptr->error_fn=NULL;
  194980. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194981. png_ptr->flags=0;
  194982. #endif
  194983. png_error(png_ptr,
  194984. "The png struct allocated by the application for writing is too small.");
  194985. }
  194986. if(png_sizeof(png_info) > png_info_size)
  194987. {
  194988. png_ptr->error_fn=NULL;
  194989. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194990. png_ptr->flags=0;
  194991. #endif
  194992. png_error(png_ptr,
  194993. "The info struct allocated by the application for writing is too small.");
  194994. }
  194995. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  194996. }
  194997. #endif /* PNG_1_0_X || PNG_1_2_X */
  194998. void PNGAPI
  194999. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  195000. png_size_t png_struct_size)
  195001. {
  195002. png_structp png_ptr=*ptr_ptr;
  195003. #ifdef PNG_SETJMP_SUPPORTED
  195004. jmp_buf tmp_jmp; /* to save current jump buffer */
  195005. #endif
  195006. int i = 0;
  195007. if (png_ptr == NULL)
  195008. return;
  195009. do
  195010. {
  195011. if (user_png_ver[i] != png_libpng_ver[i])
  195012. {
  195013. #ifdef PNG_LEGACY_SUPPORTED
  195014. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  195015. #else
  195016. png_ptr->warning_fn=NULL;
  195017. png_warning(png_ptr,
  195018. "Application uses deprecated png_write_init() and should be recompiled.");
  195019. break;
  195020. #endif
  195021. }
  195022. } while (png_libpng_ver[i++]);
  195023. png_debug(1, "in png_write_init_3\n");
  195024. #ifdef PNG_SETJMP_SUPPORTED
  195025. /* save jump buffer and error functions */
  195026. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  195027. #endif
  195028. if (png_sizeof(png_struct) > png_struct_size)
  195029. {
  195030. png_destroy_struct(png_ptr);
  195031. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  195032. *ptr_ptr = png_ptr;
  195033. }
  195034. /* reset all variables to 0 */
  195035. png_memset(png_ptr, 0, png_sizeof (png_struct));
  195036. /* added at libpng-1.2.6 */
  195037. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  195038. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  195039. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  195040. #endif
  195041. #ifdef PNG_SETJMP_SUPPORTED
  195042. /* restore jump buffer */
  195043. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195044. #endif
  195045. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  195046. png_flush_ptr_NULL);
  195047. /* initialize zbuf - compression buffer */
  195048. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  195049. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  195050. (png_uint_32)png_ptr->zbuf_size);
  195051. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195052. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  195053. 1, png_doublep_NULL, png_doublep_NULL);
  195054. #endif
  195055. }
  195056. /* Write a few rows of image data. If the image is interlaced,
  195057. * either you will have to write the 7 sub images, or, if you
  195058. * have called png_set_interlace_handling(), you will have to
  195059. * "write" the image seven times.
  195060. */
  195061. void PNGAPI
  195062. png_write_rows(png_structp png_ptr, png_bytepp row,
  195063. png_uint_32 num_rows)
  195064. {
  195065. png_uint_32 i; /* row counter */
  195066. png_bytepp rp; /* row pointer */
  195067. png_debug(1, "in png_write_rows\n");
  195068. if (png_ptr == NULL)
  195069. return;
  195070. /* loop through the rows */
  195071. for (i = 0, rp = row; i < num_rows; i++, rp++)
  195072. {
  195073. png_write_row(png_ptr, *rp);
  195074. }
  195075. }
  195076. /* Write the image. You only need to call this function once, even
  195077. * if you are writing an interlaced image.
  195078. */
  195079. void PNGAPI
  195080. png_write_image(png_structp png_ptr, png_bytepp image)
  195081. {
  195082. png_uint_32 i; /* row index */
  195083. int pass, num_pass; /* pass variables */
  195084. png_bytepp rp; /* points to current row */
  195085. if (png_ptr == NULL)
  195086. return;
  195087. png_debug(1, "in png_write_image\n");
  195088. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195089. /* intialize interlace handling. If image is not interlaced,
  195090. this will set pass to 1 */
  195091. num_pass = png_set_interlace_handling(png_ptr);
  195092. #else
  195093. num_pass = 1;
  195094. #endif
  195095. /* loop through passes */
  195096. for (pass = 0; pass < num_pass; pass++)
  195097. {
  195098. /* loop through image */
  195099. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  195100. {
  195101. png_write_row(png_ptr, *rp);
  195102. }
  195103. }
  195104. }
  195105. /* called by user to write a row of image data */
  195106. void PNGAPI
  195107. png_write_row(png_structp png_ptr, png_bytep row)
  195108. {
  195109. if (png_ptr == NULL)
  195110. return;
  195111. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  195112. png_ptr->row_number, png_ptr->pass);
  195113. /* initialize transformations and other stuff if first time */
  195114. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  195115. {
  195116. /* make sure we wrote the header info */
  195117. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  195118. png_error(png_ptr,
  195119. "png_write_info was never called before png_write_row.");
  195120. /* check for transforms that have been set but were defined out */
  195121. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  195122. if (png_ptr->transformations & PNG_INVERT_MONO)
  195123. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  195124. #endif
  195125. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  195126. if (png_ptr->transformations & PNG_FILLER)
  195127. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  195128. #endif
  195129. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  195130. if (png_ptr->transformations & PNG_PACKSWAP)
  195131. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  195132. #endif
  195133. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  195134. if (png_ptr->transformations & PNG_PACK)
  195135. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  195136. #endif
  195137. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  195138. if (png_ptr->transformations & PNG_SHIFT)
  195139. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  195140. #endif
  195141. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  195142. if (png_ptr->transformations & PNG_BGR)
  195143. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  195144. #endif
  195145. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  195146. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195147. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  195148. #endif
  195149. png_write_start_row(png_ptr);
  195150. }
  195151. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195152. /* if interlaced and not interested in row, return */
  195153. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  195154. {
  195155. switch (png_ptr->pass)
  195156. {
  195157. case 0:
  195158. if (png_ptr->row_number & 0x07)
  195159. {
  195160. png_write_finish_row(png_ptr);
  195161. return;
  195162. }
  195163. break;
  195164. case 1:
  195165. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  195166. {
  195167. png_write_finish_row(png_ptr);
  195168. return;
  195169. }
  195170. break;
  195171. case 2:
  195172. if ((png_ptr->row_number & 0x07) != 4)
  195173. {
  195174. png_write_finish_row(png_ptr);
  195175. return;
  195176. }
  195177. break;
  195178. case 3:
  195179. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  195180. {
  195181. png_write_finish_row(png_ptr);
  195182. return;
  195183. }
  195184. break;
  195185. case 4:
  195186. if ((png_ptr->row_number & 0x03) != 2)
  195187. {
  195188. png_write_finish_row(png_ptr);
  195189. return;
  195190. }
  195191. break;
  195192. case 5:
  195193. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  195194. {
  195195. png_write_finish_row(png_ptr);
  195196. return;
  195197. }
  195198. break;
  195199. case 6:
  195200. if (!(png_ptr->row_number & 0x01))
  195201. {
  195202. png_write_finish_row(png_ptr);
  195203. return;
  195204. }
  195205. break;
  195206. }
  195207. }
  195208. #endif
  195209. /* set up row info for transformations */
  195210. png_ptr->row_info.color_type = png_ptr->color_type;
  195211. png_ptr->row_info.width = png_ptr->usr_width;
  195212. png_ptr->row_info.channels = png_ptr->usr_channels;
  195213. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  195214. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  195215. png_ptr->row_info.channels);
  195216. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  195217. png_ptr->row_info.width);
  195218. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  195219. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  195220. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  195221. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  195222. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  195223. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  195224. /* Copy user's row into buffer, leaving room for filter byte. */
  195225. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  195226. png_ptr->row_info.rowbytes);
  195227. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195228. /* handle interlacing */
  195229. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  195230. (png_ptr->transformations & PNG_INTERLACE))
  195231. {
  195232. png_do_write_interlace(&(png_ptr->row_info),
  195233. png_ptr->row_buf + 1, png_ptr->pass);
  195234. /* this should always get caught above, but still ... */
  195235. if (!(png_ptr->row_info.width))
  195236. {
  195237. png_write_finish_row(png_ptr);
  195238. return;
  195239. }
  195240. }
  195241. #endif
  195242. /* handle other transformations */
  195243. if (png_ptr->transformations)
  195244. png_do_write_transformations(png_ptr);
  195245. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195246. /* Write filter_method 64 (intrapixel differencing) only if
  195247. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195248. * 2. Libpng did not write a PNG signature (this filter_method is only
  195249. * used in PNG datastreams that are embedded in MNG datastreams) and
  195250. * 3. The application called png_permit_mng_features with a mask that
  195251. * included PNG_FLAG_MNG_FILTER_64 and
  195252. * 4. The filter_method is 64 and
  195253. * 5. The color_type is RGB or RGBA
  195254. */
  195255. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195256. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  195257. {
  195258. /* Intrapixel differencing */
  195259. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195260. }
  195261. #endif
  195262. /* Find a filter if necessary, filter the row and write it out. */
  195263. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  195264. if (png_ptr->write_row_fn != NULL)
  195265. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  195266. }
  195267. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195268. /* Set the automatic flush interval or 0 to turn flushing off */
  195269. void PNGAPI
  195270. png_set_flush(png_structp png_ptr, int nrows)
  195271. {
  195272. png_debug(1, "in png_set_flush\n");
  195273. if (png_ptr == NULL)
  195274. return;
  195275. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  195276. }
  195277. /* flush the current output buffers now */
  195278. void PNGAPI
  195279. png_write_flush(png_structp png_ptr)
  195280. {
  195281. int wrote_IDAT;
  195282. png_debug(1, "in png_write_flush\n");
  195283. if (png_ptr == NULL)
  195284. return;
  195285. /* We have already written out all of the data */
  195286. if (png_ptr->row_number >= png_ptr->num_rows)
  195287. return;
  195288. do
  195289. {
  195290. int ret;
  195291. /* compress the data */
  195292. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  195293. wrote_IDAT = 0;
  195294. /* check for compression errors */
  195295. if (ret != Z_OK)
  195296. {
  195297. if (png_ptr->zstream.msg != NULL)
  195298. png_error(png_ptr, png_ptr->zstream.msg);
  195299. else
  195300. png_error(png_ptr, "zlib error");
  195301. }
  195302. if (!(png_ptr->zstream.avail_out))
  195303. {
  195304. /* write the IDAT and reset the zlib output buffer */
  195305. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195306. png_ptr->zbuf_size);
  195307. png_ptr->zstream.next_out = png_ptr->zbuf;
  195308. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195309. wrote_IDAT = 1;
  195310. }
  195311. } while(wrote_IDAT == 1);
  195312. /* If there is any data left to be output, write it into a new IDAT */
  195313. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  195314. {
  195315. /* write the IDAT and reset the zlib output buffer */
  195316. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195317. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  195318. png_ptr->zstream.next_out = png_ptr->zbuf;
  195319. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195320. }
  195321. png_ptr->flush_rows = 0;
  195322. png_flush(png_ptr);
  195323. }
  195324. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195325. /* free all memory used by the write */
  195326. void PNGAPI
  195327. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  195328. {
  195329. png_structp png_ptr = NULL;
  195330. png_infop info_ptr = NULL;
  195331. #ifdef PNG_USER_MEM_SUPPORTED
  195332. png_free_ptr free_fn = NULL;
  195333. png_voidp mem_ptr = NULL;
  195334. #endif
  195335. png_debug(1, "in png_destroy_write_struct\n");
  195336. if (png_ptr_ptr != NULL)
  195337. {
  195338. png_ptr = *png_ptr_ptr;
  195339. #ifdef PNG_USER_MEM_SUPPORTED
  195340. free_fn = png_ptr->free_fn;
  195341. mem_ptr = png_ptr->mem_ptr;
  195342. #endif
  195343. }
  195344. if (info_ptr_ptr != NULL)
  195345. info_ptr = *info_ptr_ptr;
  195346. if (info_ptr != NULL)
  195347. {
  195348. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  195349. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  195350. if (png_ptr->num_chunk_list)
  195351. {
  195352. png_free(png_ptr, png_ptr->chunk_list);
  195353. png_ptr->chunk_list=NULL;
  195354. png_ptr->num_chunk_list=0;
  195355. }
  195356. #endif
  195357. #ifdef PNG_USER_MEM_SUPPORTED
  195358. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  195359. (png_voidp)mem_ptr);
  195360. #else
  195361. png_destroy_struct((png_voidp)info_ptr);
  195362. #endif
  195363. *info_ptr_ptr = NULL;
  195364. }
  195365. if (png_ptr != NULL)
  195366. {
  195367. png_write_destroy(png_ptr);
  195368. #ifdef PNG_USER_MEM_SUPPORTED
  195369. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  195370. (png_voidp)mem_ptr);
  195371. #else
  195372. png_destroy_struct((png_voidp)png_ptr);
  195373. #endif
  195374. *png_ptr_ptr = NULL;
  195375. }
  195376. }
  195377. /* Free any memory used in png_ptr struct (old method) */
  195378. void /* PRIVATE */
  195379. png_write_destroy(png_structp png_ptr)
  195380. {
  195381. #ifdef PNG_SETJMP_SUPPORTED
  195382. jmp_buf tmp_jmp; /* save jump buffer */
  195383. #endif
  195384. png_error_ptr error_fn;
  195385. png_error_ptr warning_fn;
  195386. png_voidp error_ptr;
  195387. #ifdef PNG_USER_MEM_SUPPORTED
  195388. png_free_ptr free_fn;
  195389. #endif
  195390. png_debug(1, "in png_write_destroy\n");
  195391. /* free any memory zlib uses */
  195392. deflateEnd(&png_ptr->zstream);
  195393. /* free our memory. png_free checks NULL for us. */
  195394. png_free(png_ptr, png_ptr->zbuf);
  195395. png_free(png_ptr, png_ptr->row_buf);
  195396. png_free(png_ptr, png_ptr->prev_row);
  195397. png_free(png_ptr, png_ptr->sub_row);
  195398. png_free(png_ptr, png_ptr->up_row);
  195399. png_free(png_ptr, png_ptr->avg_row);
  195400. png_free(png_ptr, png_ptr->paeth_row);
  195401. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  195402. png_free(png_ptr, png_ptr->time_buffer);
  195403. #endif
  195404. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195405. png_free(png_ptr, png_ptr->prev_filters);
  195406. png_free(png_ptr, png_ptr->filter_weights);
  195407. png_free(png_ptr, png_ptr->inv_filter_weights);
  195408. png_free(png_ptr, png_ptr->filter_costs);
  195409. png_free(png_ptr, png_ptr->inv_filter_costs);
  195410. #endif
  195411. #ifdef PNG_SETJMP_SUPPORTED
  195412. /* reset structure */
  195413. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  195414. #endif
  195415. error_fn = png_ptr->error_fn;
  195416. warning_fn = png_ptr->warning_fn;
  195417. error_ptr = png_ptr->error_ptr;
  195418. #ifdef PNG_USER_MEM_SUPPORTED
  195419. free_fn = png_ptr->free_fn;
  195420. #endif
  195421. png_memset(png_ptr, 0, png_sizeof (png_struct));
  195422. png_ptr->error_fn = error_fn;
  195423. png_ptr->warning_fn = warning_fn;
  195424. png_ptr->error_ptr = error_ptr;
  195425. #ifdef PNG_USER_MEM_SUPPORTED
  195426. png_ptr->free_fn = free_fn;
  195427. #endif
  195428. #ifdef PNG_SETJMP_SUPPORTED
  195429. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195430. #endif
  195431. }
  195432. /* Allow the application to select one or more row filters to use. */
  195433. void PNGAPI
  195434. png_set_filter(png_structp png_ptr, int method, int filters)
  195435. {
  195436. png_debug(1, "in png_set_filter\n");
  195437. if (png_ptr == NULL)
  195438. return;
  195439. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195440. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195441. (method == PNG_INTRAPIXEL_DIFFERENCING))
  195442. method = PNG_FILTER_TYPE_BASE;
  195443. #endif
  195444. if (method == PNG_FILTER_TYPE_BASE)
  195445. {
  195446. switch (filters & (PNG_ALL_FILTERS | 0x07))
  195447. {
  195448. #ifndef PNG_NO_WRITE_FILTER
  195449. case 5:
  195450. case 6:
  195451. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  195452. #endif /* PNG_NO_WRITE_FILTER */
  195453. case PNG_FILTER_VALUE_NONE:
  195454. png_ptr->do_filter=PNG_FILTER_NONE; break;
  195455. #ifndef PNG_NO_WRITE_FILTER
  195456. case PNG_FILTER_VALUE_SUB:
  195457. png_ptr->do_filter=PNG_FILTER_SUB; break;
  195458. case PNG_FILTER_VALUE_UP:
  195459. png_ptr->do_filter=PNG_FILTER_UP; break;
  195460. case PNG_FILTER_VALUE_AVG:
  195461. png_ptr->do_filter=PNG_FILTER_AVG; break;
  195462. case PNG_FILTER_VALUE_PAETH:
  195463. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  195464. default: png_ptr->do_filter = (png_byte)filters; break;
  195465. #else
  195466. default: png_warning(png_ptr, "Unknown row filter for method 0");
  195467. #endif /* PNG_NO_WRITE_FILTER */
  195468. }
  195469. /* If we have allocated the row_buf, this means we have already started
  195470. * with the image and we should have allocated all of the filter buffers
  195471. * that have been selected. If prev_row isn't already allocated, then
  195472. * it is too late to start using the filters that need it, since we
  195473. * will be missing the data in the previous row. If an application
  195474. * wants to start and stop using particular filters during compression,
  195475. * it should start out with all of the filters, and then add and
  195476. * remove them after the start of compression.
  195477. */
  195478. if (png_ptr->row_buf != NULL)
  195479. {
  195480. #ifndef PNG_NO_WRITE_FILTER
  195481. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  195482. {
  195483. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  195484. (png_ptr->rowbytes + 1));
  195485. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  195486. }
  195487. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  195488. {
  195489. if (png_ptr->prev_row == NULL)
  195490. {
  195491. png_warning(png_ptr, "Can't add Up filter after starting");
  195492. png_ptr->do_filter &= ~PNG_FILTER_UP;
  195493. }
  195494. else
  195495. {
  195496. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  195497. (png_ptr->rowbytes + 1));
  195498. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  195499. }
  195500. }
  195501. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  195502. {
  195503. if (png_ptr->prev_row == NULL)
  195504. {
  195505. png_warning(png_ptr, "Can't add Average filter after starting");
  195506. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  195507. }
  195508. else
  195509. {
  195510. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  195511. (png_ptr->rowbytes + 1));
  195512. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  195513. }
  195514. }
  195515. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  195516. png_ptr->paeth_row == NULL)
  195517. {
  195518. if (png_ptr->prev_row == NULL)
  195519. {
  195520. png_warning(png_ptr, "Can't add Paeth filter after starting");
  195521. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  195522. }
  195523. else
  195524. {
  195525. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  195526. (png_ptr->rowbytes + 1));
  195527. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  195528. }
  195529. }
  195530. if (png_ptr->do_filter == PNG_NO_FILTERS)
  195531. #endif /* PNG_NO_WRITE_FILTER */
  195532. png_ptr->do_filter = PNG_FILTER_NONE;
  195533. }
  195534. }
  195535. else
  195536. png_error(png_ptr, "Unknown custom filter method");
  195537. }
  195538. /* This allows us to influence the way in which libpng chooses the "best"
  195539. * filter for the current scanline. While the "minimum-sum-of-absolute-
  195540. * differences metric is relatively fast and effective, there is some
  195541. * question as to whether it can be improved upon by trying to keep the
  195542. * filtered data going to zlib more consistent, hopefully resulting in
  195543. * better compression.
  195544. */
  195545. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  195546. void PNGAPI
  195547. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  195548. int num_weights, png_doublep filter_weights,
  195549. png_doublep filter_costs)
  195550. {
  195551. int i;
  195552. png_debug(1, "in png_set_filter_heuristics\n");
  195553. if (png_ptr == NULL)
  195554. return;
  195555. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  195556. {
  195557. png_warning(png_ptr, "Unknown filter heuristic method");
  195558. return;
  195559. }
  195560. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  195561. {
  195562. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  195563. }
  195564. if (num_weights < 0 || filter_weights == NULL ||
  195565. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  195566. {
  195567. num_weights = 0;
  195568. }
  195569. png_ptr->num_prev_filters = (png_byte)num_weights;
  195570. png_ptr->heuristic_method = (png_byte)heuristic_method;
  195571. if (num_weights > 0)
  195572. {
  195573. if (png_ptr->prev_filters == NULL)
  195574. {
  195575. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  195576. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  195577. /* To make sure that the weighting starts out fairly */
  195578. for (i = 0; i < num_weights; i++)
  195579. {
  195580. png_ptr->prev_filters[i] = 255;
  195581. }
  195582. }
  195583. if (png_ptr->filter_weights == NULL)
  195584. {
  195585. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195586. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195587. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195588. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195589. for (i = 0; i < num_weights; i++)
  195590. {
  195591. png_ptr->inv_filter_weights[i] =
  195592. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195593. }
  195594. }
  195595. for (i = 0; i < num_weights; i++)
  195596. {
  195597. if (filter_weights[i] < 0.0)
  195598. {
  195599. png_ptr->inv_filter_weights[i] =
  195600. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195601. }
  195602. else
  195603. {
  195604. png_ptr->inv_filter_weights[i] =
  195605. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  195606. png_ptr->filter_weights[i] =
  195607. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  195608. }
  195609. }
  195610. }
  195611. /* If, in the future, there are other filter methods, this would
  195612. * need to be based on png_ptr->filter.
  195613. */
  195614. if (png_ptr->filter_costs == NULL)
  195615. {
  195616. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195617. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195618. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195619. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195620. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195621. {
  195622. png_ptr->inv_filter_costs[i] =
  195623. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195624. }
  195625. }
  195626. /* Here is where we set the relative costs of the different filters. We
  195627. * should take the desired compression level into account when setting
  195628. * the costs, so that Paeth, for instance, has a high relative cost at low
  195629. * compression levels, while it has a lower relative cost at higher
  195630. * compression settings. The filter types are in order of increasing
  195631. * relative cost, so it would be possible to do this with an algorithm.
  195632. */
  195633. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195634. {
  195635. if (filter_costs == NULL || filter_costs[i] < 0.0)
  195636. {
  195637. png_ptr->inv_filter_costs[i] =
  195638. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195639. }
  195640. else if (filter_costs[i] >= 1.0)
  195641. {
  195642. png_ptr->inv_filter_costs[i] =
  195643. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  195644. png_ptr->filter_costs[i] =
  195645. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  195646. }
  195647. }
  195648. }
  195649. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  195650. void PNGAPI
  195651. png_set_compression_level(png_structp png_ptr, int level)
  195652. {
  195653. png_debug(1, "in png_set_compression_level\n");
  195654. if (png_ptr == NULL)
  195655. return;
  195656. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  195657. png_ptr->zlib_level = level;
  195658. }
  195659. void PNGAPI
  195660. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  195661. {
  195662. png_debug(1, "in png_set_compression_mem_level\n");
  195663. if (png_ptr == NULL)
  195664. return;
  195665. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  195666. png_ptr->zlib_mem_level = mem_level;
  195667. }
  195668. void PNGAPI
  195669. png_set_compression_strategy(png_structp png_ptr, int strategy)
  195670. {
  195671. png_debug(1, "in png_set_compression_strategy\n");
  195672. if (png_ptr == NULL)
  195673. return;
  195674. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  195675. png_ptr->zlib_strategy = strategy;
  195676. }
  195677. void PNGAPI
  195678. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  195679. {
  195680. if (png_ptr == NULL)
  195681. return;
  195682. if (window_bits > 15)
  195683. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  195684. else if (window_bits < 8)
  195685. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  195686. #ifndef WBITS_8_OK
  195687. /* avoid libpng bug with 256-byte windows */
  195688. if (window_bits == 8)
  195689. {
  195690. png_warning(png_ptr, "Compression window is being reset to 512");
  195691. window_bits=9;
  195692. }
  195693. #endif
  195694. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  195695. png_ptr->zlib_window_bits = window_bits;
  195696. }
  195697. void PNGAPI
  195698. png_set_compression_method(png_structp png_ptr, int method)
  195699. {
  195700. png_debug(1, "in png_set_compression_method\n");
  195701. if (png_ptr == NULL)
  195702. return;
  195703. if (method != 8)
  195704. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  195705. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  195706. png_ptr->zlib_method = method;
  195707. }
  195708. void PNGAPI
  195709. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  195710. {
  195711. if (png_ptr == NULL)
  195712. return;
  195713. png_ptr->write_row_fn = write_row_fn;
  195714. }
  195715. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195716. void PNGAPI
  195717. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  195718. write_user_transform_fn)
  195719. {
  195720. png_debug(1, "in png_set_write_user_transform_fn\n");
  195721. if (png_ptr == NULL)
  195722. return;
  195723. png_ptr->transformations |= PNG_USER_TRANSFORM;
  195724. png_ptr->write_user_transform_fn = write_user_transform_fn;
  195725. }
  195726. #endif
  195727. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  195728. void PNGAPI
  195729. png_write_png(png_structp png_ptr, png_infop info_ptr,
  195730. int transforms, voidp params)
  195731. {
  195732. if (png_ptr == NULL || info_ptr == NULL)
  195733. return;
  195734. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195735. /* invert the alpha channel from opacity to transparency */
  195736. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  195737. png_set_invert_alpha(png_ptr);
  195738. #endif
  195739. /* Write the file header information. */
  195740. png_write_info(png_ptr, info_ptr);
  195741. /* ------ these transformations don't touch the info structure ------- */
  195742. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195743. /* invert monochrome pixels */
  195744. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  195745. png_set_invert_mono(png_ptr);
  195746. #endif
  195747. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195748. /* Shift the pixels up to a legal bit depth and fill in
  195749. * as appropriate to correctly scale the image.
  195750. */
  195751. if ((transforms & PNG_TRANSFORM_SHIFT)
  195752. && (info_ptr->valid & PNG_INFO_sBIT))
  195753. png_set_shift(png_ptr, &info_ptr->sig_bit);
  195754. #endif
  195755. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195756. /* pack pixels into bytes */
  195757. if (transforms & PNG_TRANSFORM_PACKING)
  195758. png_set_packing(png_ptr);
  195759. #endif
  195760. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195761. /* swap location of alpha bytes from ARGB to RGBA */
  195762. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  195763. png_set_swap_alpha(png_ptr);
  195764. #endif
  195765. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195766. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  195767. * RGB (4 channels -> 3 channels). The second parameter is not used.
  195768. */
  195769. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  195770. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  195771. #endif
  195772. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195773. /* flip BGR pixels to RGB */
  195774. if (transforms & PNG_TRANSFORM_BGR)
  195775. png_set_bgr(png_ptr);
  195776. #endif
  195777. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195778. /* swap bytes of 16-bit files to most significant byte first */
  195779. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  195780. png_set_swap(png_ptr);
  195781. #endif
  195782. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195783. /* swap bits of 1, 2, 4 bit packed pixel formats */
  195784. if (transforms & PNG_TRANSFORM_PACKSWAP)
  195785. png_set_packswap(png_ptr);
  195786. #endif
  195787. /* ----------------------- end of transformations ------------------- */
  195788. /* write the bits */
  195789. if (info_ptr->valid & PNG_INFO_IDAT)
  195790. png_write_image(png_ptr, info_ptr->row_pointers);
  195791. /* It is REQUIRED to call this to finish writing the rest of the file */
  195792. png_write_end(png_ptr, info_ptr);
  195793. transforms = transforms; /* quiet compiler warnings */
  195794. params = params;
  195795. }
  195796. #endif
  195797. #endif /* PNG_WRITE_SUPPORTED */
  195798. /********* End of inlined file: pngwrite.c *********/
  195799. /********* Start of inlined file: pngwtran.c *********/
  195800. /* pngwtran.c - transforms the data in a row for PNG writers
  195801. *
  195802. * Last changed in libpng 1.2.9 April 14, 2006
  195803. * For conditions of distribution and use, see copyright notice in png.h
  195804. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  195805. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195806. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195807. */
  195808. #define PNG_INTERNAL
  195809. #ifdef PNG_WRITE_SUPPORTED
  195810. /* Transform the data according to the user's wishes. The order of
  195811. * transformations is significant.
  195812. */
  195813. void /* PRIVATE */
  195814. png_do_write_transformations(png_structp png_ptr)
  195815. {
  195816. png_debug(1, "in png_do_write_transformations\n");
  195817. if (png_ptr == NULL)
  195818. return;
  195819. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195820. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  195821. if(png_ptr->write_user_transform_fn != NULL)
  195822. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  195823. (png_ptr, /* png_ptr */
  195824. &(png_ptr->row_info), /* row_info: */
  195825. /* png_uint_32 width; width of row */
  195826. /* png_uint_32 rowbytes; number of bytes in row */
  195827. /* png_byte color_type; color type of pixels */
  195828. /* png_byte bit_depth; bit depth of samples */
  195829. /* png_byte channels; number of channels (1-4) */
  195830. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  195831. png_ptr->row_buf + 1); /* start of pixel data for row */
  195832. #endif
  195833. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195834. if (png_ptr->transformations & PNG_FILLER)
  195835. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195836. png_ptr->flags);
  195837. #endif
  195838. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195839. if (png_ptr->transformations & PNG_PACKSWAP)
  195840. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195841. #endif
  195842. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195843. if (png_ptr->transformations & PNG_PACK)
  195844. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195845. (png_uint_32)png_ptr->bit_depth);
  195846. #endif
  195847. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195848. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195849. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195850. #endif
  195851. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195852. if (png_ptr->transformations & PNG_SHIFT)
  195853. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195854. &(png_ptr->shift));
  195855. #endif
  195856. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195857. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  195858. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195859. #endif
  195860. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195861. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  195862. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195863. #endif
  195864. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195865. if (png_ptr->transformations & PNG_BGR)
  195866. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195867. #endif
  195868. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195869. if (png_ptr->transformations & PNG_INVERT_MONO)
  195870. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195871. #endif
  195872. }
  195873. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195874. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  195875. * row_info bit depth should be 8 (one pixel per byte). The channels
  195876. * should be 1 (this only happens on grayscale and paletted images).
  195877. */
  195878. void /* PRIVATE */
  195879. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  195880. {
  195881. png_debug(1, "in png_do_pack\n");
  195882. if (row_info->bit_depth == 8 &&
  195883. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195884. row != NULL && row_info != NULL &&
  195885. #endif
  195886. row_info->channels == 1)
  195887. {
  195888. switch ((int)bit_depth)
  195889. {
  195890. case 1:
  195891. {
  195892. png_bytep sp, dp;
  195893. int mask, v;
  195894. png_uint_32 i;
  195895. png_uint_32 row_width = row_info->width;
  195896. sp = row;
  195897. dp = row;
  195898. mask = 0x80;
  195899. v = 0;
  195900. for (i = 0; i < row_width; i++)
  195901. {
  195902. if (*sp != 0)
  195903. v |= mask;
  195904. sp++;
  195905. if (mask > 1)
  195906. mask >>= 1;
  195907. else
  195908. {
  195909. mask = 0x80;
  195910. *dp = (png_byte)v;
  195911. dp++;
  195912. v = 0;
  195913. }
  195914. }
  195915. if (mask != 0x80)
  195916. *dp = (png_byte)v;
  195917. break;
  195918. }
  195919. case 2:
  195920. {
  195921. png_bytep sp, dp;
  195922. int shift, v;
  195923. png_uint_32 i;
  195924. png_uint_32 row_width = row_info->width;
  195925. sp = row;
  195926. dp = row;
  195927. shift = 6;
  195928. v = 0;
  195929. for (i = 0; i < row_width; i++)
  195930. {
  195931. png_byte value;
  195932. value = (png_byte)(*sp & 0x03);
  195933. v |= (value << shift);
  195934. if (shift == 0)
  195935. {
  195936. shift = 6;
  195937. *dp = (png_byte)v;
  195938. dp++;
  195939. v = 0;
  195940. }
  195941. else
  195942. shift -= 2;
  195943. sp++;
  195944. }
  195945. if (shift != 6)
  195946. *dp = (png_byte)v;
  195947. break;
  195948. }
  195949. case 4:
  195950. {
  195951. png_bytep sp, dp;
  195952. int shift, v;
  195953. png_uint_32 i;
  195954. png_uint_32 row_width = row_info->width;
  195955. sp = row;
  195956. dp = row;
  195957. shift = 4;
  195958. v = 0;
  195959. for (i = 0; i < row_width; i++)
  195960. {
  195961. png_byte value;
  195962. value = (png_byte)(*sp & 0x0f);
  195963. v |= (value << shift);
  195964. if (shift == 0)
  195965. {
  195966. shift = 4;
  195967. *dp = (png_byte)v;
  195968. dp++;
  195969. v = 0;
  195970. }
  195971. else
  195972. shift -= 4;
  195973. sp++;
  195974. }
  195975. if (shift != 4)
  195976. *dp = (png_byte)v;
  195977. break;
  195978. }
  195979. }
  195980. row_info->bit_depth = (png_byte)bit_depth;
  195981. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  195982. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195983. row_info->width);
  195984. }
  195985. }
  195986. #endif
  195987. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195988. /* Shift pixel values to take advantage of whole range. Pass the
  195989. * true number of bits in bit_depth. The row should be packed
  195990. * according to row_info->bit_depth. Thus, if you had a row of
  195991. * bit depth 4, but the pixels only had values from 0 to 7, you
  195992. * would pass 3 as bit_depth, and this routine would translate the
  195993. * data to 0 to 15.
  195994. */
  195995. void /* PRIVATE */
  195996. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  195997. {
  195998. png_debug(1, "in png_do_shift\n");
  195999. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196000. if (row != NULL && row_info != NULL &&
  196001. #else
  196002. if (
  196003. #endif
  196004. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  196005. {
  196006. int shift_start[4], shift_dec[4];
  196007. int channels = 0;
  196008. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  196009. {
  196010. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  196011. shift_dec[channels] = bit_depth->red;
  196012. channels++;
  196013. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  196014. shift_dec[channels] = bit_depth->green;
  196015. channels++;
  196016. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  196017. shift_dec[channels] = bit_depth->blue;
  196018. channels++;
  196019. }
  196020. else
  196021. {
  196022. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  196023. shift_dec[channels] = bit_depth->gray;
  196024. channels++;
  196025. }
  196026. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  196027. {
  196028. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  196029. shift_dec[channels] = bit_depth->alpha;
  196030. channels++;
  196031. }
  196032. /* with low row depths, could only be grayscale, so one channel */
  196033. if (row_info->bit_depth < 8)
  196034. {
  196035. png_bytep bp = row;
  196036. png_uint_32 i;
  196037. png_byte mask;
  196038. png_uint_32 row_bytes = row_info->rowbytes;
  196039. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  196040. mask = 0x55;
  196041. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  196042. mask = 0x11;
  196043. else
  196044. mask = 0xff;
  196045. for (i = 0; i < row_bytes; i++, bp++)
  196046. {
  196047. png_uint_16 v;
  196048. int j;
  196049. v = *bp;
  196050. *bp = 0;
  196051. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  196052. {
  196053. if (j > 0)
  196054. *bp |= (png_byte)((v << j) & 0xff);
  196055. else
  196056. *bp |= (png_byte)((v >> (-j)) & mask);
  196057. }
  196058. }
  196059. }
  196060. else if (row_info->bit_depth == 8)
  196061. {
  196062. png_bytep bp = row;
  196063. png_uint_32 i;
  196064. png_uint_32 istop = channels * row_info->width;
  196065. for (i = 0; i < istop; i++, bp++)
  196066. {
  196067. png_uint_16 v;
  196068. int j;
  196069. int c = (int)(i%channels);
  196070. v = *bp;
  196071. *bp = 0;
  196072. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196073. {
  196074. if (j > 0)
  196075. *bp |= (png_byte)((v << j) & 0xff);
  196076. else
  196077. *bp |= (png_byte)((v >> (-j)) & 0xff);
  196078. }
  196079. }
  196080. }
  196081. else
  196082. {
  196083. png_bytep bp;
  196084. png_uint_32 i;
  196085. png_uint_32 istop = channels * row_info->width;
  196086. for (bp = row, i = 0; i < istop; i++)
  196087. {
  196088. int c = (int)(i%channels);
  196089. png_uint_16 value, v;
  196090. int j;
  196091. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  196092. value = 0;
  196093. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  196094. {
  196095. if (j > 0)
  196096. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  196097. else
  196098. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  196099. }
  196100. *bp++ = (png_byte)(value >> 8);
  196101. *bp++ = (png_byte)(value & 0xff);
  196102. }
  196103. }
  196104. }
  196105. }
  196106. #endif
  196107. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196108. void /* PRIVATE */
  196109. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  196110. {
  196111. png_debug(1, "in png_do_write_swap_alpha\n");
  196112. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196113. if (row != NULL && row_info != NULL)
  196114. #endif
  196115. {
  196116. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196117. {
  196118. /* This converts from ARGB to RGBA */
  196119. if (row_info->bit_depth == 8)
  196120. {
  196121. png_bytep sp, dp;
  196122. png_uint_32 i;
  196123. png_uint_32 row_width = row_info->width;
  196124. for (i = 0, sp = dp = row; i < row_width; i++)
  196125. {
  196126. png_byte save = *(sp++);
  196127. *(dp++) = *(sp++);
  196128. *(dp++) = *(sp++);
  196129. *(dp++) = *(sp++);
  196130. *(dp++) = save;
  196131. }
  196132. }
  196133. /* This converts from AARRGGBB to RRGGBBAA */
  196134. else
  196135. {
  196136. png_bytep sp, dp;
  196137. png_uint_32 i;
  196138. png_uint_32 row_width = row_info->width;
  196139. for (i = 0, sp = dp = row; i < row_width; i++)
  196140. {
  196141. png_byte save[2];
  196142. save[0] = *(sp++);
  196143. save[1] = *(sp++);
  196144. *(dp++) = *(sp++);
  196145. *(dp++) = *(sp++);
  196146. *(dp++) = *(sp++);
  196147. *(dp++) = *(sp++);
  196148. *(dp++) = *(sp++);
  196149. *(dp++) = *(sp++);
  196150. *(dp++) = save[0];
  196151. *(dp++) = save[1];
  196152. }
  196153. }
  196154. }
  196155. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196156. {
  196157. /* This converts from AG to GA */
  196158. if (row_info->bit_depth == 8)
  196159. {
  196160. png_bytep sp, dp;
  196161. png_uint_32 i;
  196162. png_uint_32 row_width = row_info->width;
  196163. for (i = 0, sp = dp = row; i < row_width; i++)
  196164. {
  196165. png_byte save = *(sp++);
  196166. *(dp++) = *(sp++);
  196167. *(dp++) = save;
  196168. }
  196169. }
  196170. /* This converts from AAGG to GGAA */
  196171. else
  196172. {
  196173. png_bytep sp, dp;
  196174. png_uint_32 i;
  196175. png_uint_32 row_width = row_info->width;
  196176. for (i = 0, sp = dp = row; i < row_width; i++)
  196177. {
  196178. png_byte save[2];
  196179. save[0] = *(sp++);
  196180. save[1] = *(sp++);
  196181. *(dp++) = *(sp++);
  196182. *(dp++) = *(sp++);
  196183. *(dp++) = save[0];
  196184. *(dp++) = save[1];
  196185. }
  196186. }
  196187. }
  196188. }
  196189. }
  196190. #endif
  196191. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196192. void /* PRIVATE */
  196193. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  196194. {
  196195. png_debug(1, "in png_do_write_invert_alpha\n");
  196196. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196197. if (row != NULL && row_info != NULL)
  196198. #endif
  196199. {
  196200. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196201. {
  196202. /* This inverts the alpha channel in RGBA */
  196203. if (row_info->bit_depth == 8)
  196204. {
  196205. png_bytep sp, dp;
  196206. png_uint_32 i;
  196207. png_uint_32 row_width = row_info->width;
  196208. for (i = 0, sp = dp = row; i < row_width; i++)
  196209. {
  196210. /* does nothing
  196211. *(dp++) = *(sp++);
  196212. *(dp++) = *(sp++);
  196213. *(dp++) = *(sp++);
  196214. */
  196215. sp+=3; dp = sp;
  196216. *(dp++) = (png_byte)(255 - *(sp++));
  196217. }
  196218. }
  196219. /* This inverts the alpha channel in RRGGBBAA */
  196220. else
  196221. {
  196222. png_bytep sp, dp;
  196223. png_uint_32 i;
  196224. png_uint_32 row_width = row_info->width;
  196225. for (i = 0, sp = dp = row; i < row_width; i++)
  196226. {
  196227. /* does nothing
  196228. *(dp++) = *(sp++);
  196229. *(dp++) = *(sp++);
  196230. *(dp++) = *(sp++);
  196231. *(dp++) = *(sp++);
  196232. *(dp++) = *(sp++);
  196233. *(dp++) = *(sp++);
  196234. */
  196235. sp+=6; dp = sp;
  196236. *(dp++) = (png_byte)(255 - *(sp++));
  196237. *(dp++) = (png_byte)(255 - *(sp++));
  196238. }
  196239. }
  196240. }
  196241. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196242. {
  196243. /* This inverts the alpha channel in GA */
  196244. if (row_info->bit_depth == 8)
  196245. {
  196246. png_bytep sp, dp;
  196247. png_uint_32 i;
  196248. png_uint_32 row_width = row_info->width;
  196249. for (i = 0, sp = dp = row; i < row_width; i++)
  196250. {
  196251. *(dp++) = *(sp++);
  196252. *(dp++) = (png_byte)(255 - *(sp++));
  196253. }
  196254. }
  196255. /* This inverts the alpha channel in GGAA */
  196256. else
  196257. {
  196258. png_bytep sp, dp;
  196259. png_uint_32 i;
  196260. png_uint_32 row_width = row_info->width;
  196261. for (i = 0, sp = dp = row; i < row_width; i++)
  196262. {
  196263. /* does nothing
  196264. *(dp++) = *(sp++);
  196265. *(dp++) = *(sp++);
  196266. */
  196267. sp+=2; dp = sp;
  196268. *(dp++) = (png_byte)(255 - *(sp++));
  196269. *(dp++) = (png_byte)(255 - *(sp++));
  196270. }
  196271. }
  196272. }
  196273. }
  196274. }
  196275. #endif
  196276. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196277. /* undoes intrapixel differencing */
  196278. void /* PRIVATE */
  196279. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  196280. {
  196281. png_debug(1, "in png_do_write_intrapixel\n");
  196282. if (
  196283. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196284. row != NULL && row_info != NULL &&
  196285. #endif
  196286. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  196287. {
  196288. int bytes_per_pixel;
  196289. png_uint_32 row_width = row_info->width;
  196290. if (row_info->bit_depth == 8)
  196291. {
  196292. png_bytep rp;
  196293. png_uint_32 i;
  196294. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196295. bytes_per_pixel = 3;
  196296. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196297. bytes_per_pixel = 4;
  196298. else
  196299. return;
  196300. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196301. {
  196302. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  196303. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  196304. }
  196305. }
  196306. else if (row_info->bit_depth == 16)
  196307. {
  196308. png_bytep rp;
  196309. png_uint_32 i;
  196310. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196311. bytes_per_pixel = 6;
  196312. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196313. bytes_per_pixel = 8;
  196314. else
  196315. return;
  196316. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196317. {
  196318. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  196319. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  196320. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  196321. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  196322. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  196323. *(rp ) = (png_byte)((red >> 8) & 0xff);
  196324. *(rp+1) = (png_byte)(red & 0xff);
  196325. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  196326. *(rp+5) = (png_byte)(blue & 0xff);
  196327. }
  196328. }
  196329. }
  196330. }
  196331. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  196332. #endif /* PNG_WRITE_SUPPORTED */
  196333. /********* End of inlined file: pngwtran.c *********/
  196334. /********* Start of inlined file: pngwutil.c *********/
  196335. /* pngwutil.c - utilities to write a PNG file
  196336. *
  196337. * Last changed in libpng 1.2.20 Septhember 3, 2007
  196338. * For conditions of distribution and use, see copyright notice in png.h
  196339. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196340. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196341. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196342. */
  196343. #define PNG_INTERNAL
  196344. #ifdef PNG_WRITE_SUPPORTED
  196345. /* Place a 32-bit number into a buffer in PNG byte order. We work
  196346. * with unsigned numbers for convenience, although one supported
  196347. * ancillary chunk uses signed (two's complement) numbers.
  196348. */
  196349. void PNGAPI
  196350. png_save_uint_32(png_bytep buf, png_uint_32 i)
  196351. {
  196352. buf[0] = (png_byte)((i >> 24) & 0xff);
  196353. buf[1] = (png_byte)((i >> 16) & 0xff);
  196354. buf[2] = (png_byte)((i >> 8) & 0xff);
  196355. buf[3] = (png_byte)(i & 0xff);
  196356. }
  196357. /* The png_save_int_32 function assumes integers are stored in two's
  196358. * complement format. If this isn't the case, then this routine needs to
  196359. * be modified to write data in two's complement format.
  196360. */
  196361. void PNGAPI
  196362. png_save_int_32(png_bytep buf, png_int_32 i)
  196363. {
  196364. buf[0] = (png_byte)((i >> 24) & 0xff);
  196365. buf[1] = (png_byte)((i >> 16) & 0xff);
  196366. buf[2] = (png_byte)((i >> 8) & 0xff);
  196367. buf[3] = (png_byte)(i & 0xff);
  196368. }
  196369. /* Place a 16-bit number into a buffer in PNG byte order.
  196370. * The parameter is declared unsigned int, not png_uint_16,
  196371. * just to avoid potential problems on pre-ANSI C compilers.
  196372. */
  196373. void PNGAPI
  196374. png_save_uint_16(png_bytep buf, unsigned int i)
  196375. {
  196376. buf[0] = (png_byte)((i >> 8) & 0xff);
  196377. buf[1] = (png_byte)(i & 0xff);
  196378. }
  196379. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  196380. * representing the chunk name. The array must be at least 4 bytes in
  196381. * length, and does not need to be null terminated. To be safe, pass the
  196382. * pre-defined chunk names here, and if you need a new one, define it
  196383. * where the others are defined. The length is the length of the data.
  196384. * All the data must be present. If that is not possible, use the
  196385. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  196386. * functions instead.
  196387. */
  196388. void PNGAPI
  196389. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  196390. png_bytep data, png_size_t length)
  196391. {
  196392. if(png_ptr == NULL) return;
  196393. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  196394. png_write_chunk_data(png_ptr, data, length);
  196395. png_write_chunk_end(png_ptr);
  196396. }
  196397. /* Write the start of a PNG chunk. The type is the chunk type.
  196398. * The total_length is the sum of the lengths of all the data you will be
  196399. * passing in png_write_chunk_data().
  196400. */
  196401. void PNGAPI
  196402. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  196403. png_uint_32 length)
  196404. {
  196405. png_byte buf[4];
  196406. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  196407. if(png_ptr == NULL) return;
  196408. /* write the length */
  196409. png_save_uint_32(buf, length);
  196410. png_write_data(png_ptr, buf, (png_size_t)4);
  196411. /* write the chunk name */
  196412. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  196413. /* reset the crc and run it over the chunk name */
  196414. png_reset_crc(png_ptr);
  196415. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  196416. }
  196417. /* Write the data of a PNG chunk started with png_write_chunk_start().
  196418. * Note that multiple calls to this function are allowed, and that the
  196419. * sum of the lengths from these calls *must* add up to the total_length
  196420. * given to png_write_chunk_start().
  196421. */
  196422. void PNGAPI
  196423. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  196424. {
  196425. /* write the data, and run the CRC over it */
  196426. if(png_ptr == NULL) return;
  196427. if (data != NULL && length > 0)
  196428. {
  196429. png_calculate_crc(png_ptr, data, length);
  196430. png_write_data(png_ptr, data, length);
  196431. }
  196432. }
  196433. /* Finish a chunk started with png_write_chunk_start(). */
  196434. void PNGAPI
  196435. png_write_chunk_end(png_structp png_ptr)
  196436. {
  196437. png_byte buf[4];
  196438. if(png_ptr == NULL) return;
  196439. /* write the crc */
  196440. png_save_uint_32(buf, png_ptr->crc);
  196441. png_write_data(png_ptr, buf, (png_size_t)4);
  196442. }
  196443. /* Simple function to write the signature. If we have already written
  196444. * the magic bytes of the signature, or more likely, the PNG stream is
  196445. * being embedded into another stream and doesn't need its own signature,
  196446. * we should call png_set_sig_bytes() to tell libpng how many of the
  196447. * bytes have already been written.
  196448. */
  196449. void /* PRIVATE */
  196450. png_write_sig(png_structp png_ptr)
  196451. {
  196452. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  196453. /* write the rest of the 8 byte signature */
  196454. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  196455. (png_size_t)8 - png_ptr->sig_bytes);
  196456. if(png_ptr->sig_bytes < 3)
  196457. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  196458. }
  196459. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  196460. /*
  196461. * This pair of functions encapsulates the operation of (a) compressing a
  196462. * text string, and (b) issuing it later as a series of chunk data writes.
  196463. * The compression_state structure is shared context for these functions
  196464. * set up by the caller in order to make the whole mess thread-safe.
  196465. */
  196466. typedef struct
  196467. {
  196468. char *input; /* the uncompressed input data */
  196469. int input_len; /* its length */
  196470. int num_output_ptr; /* number of output pointers used */
  196471. int max_output_ptr; /* size of output_ptr */
  196472. png_charpp output_ptr; /* array of pointers to output */
  196473. } compression_state;
  196474. /* compress given text into storage in the png_ptr structure */
  196475. static int /* PRIVATE */
  196476. png_text_compress(png_structp png_ptr,
  196477. png_charp text, png_size_t text_len, int compression,
  196478. compression_state *comp)
  196479. {
  196480. int ret;
  196481. comp->num_output_ptr = 0;
  196482. comp->max_output_ptr = 0;
  196483. comp->output_ptr = NULL;
  196484. comp->input = NULL;
  196485. comp->input_len = 0;
  196486. /* we may just want to pass the text right through */
  196487. if (compression == PNG_TEXT_COMPRESSION_NONE)
  196488. {
  196489. comp->input = text;
  196490. comp->input_len = text_len;
  196491. return((int)text_len);
  196492. }
  196493. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  196494. {
  196495. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196496. char msg[50];
  196497. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  196498. png_warning(png_ptr, msg);
  196499. #else
  196500. png_warning(png_ptr, "Unknown compression type");
  196501. #endif
  196502. }
  196503. /* We can't write the chunk until we find out how much data we have,
  196504. * which means we need to run the compressor first and save the
  196505. * output. This shouldn't be a problem, as the vast majority of
  196506. * comments should be reasonable, but we will set up an array of
  196507. * malloc'd pointers to be sure.
  196508. *
  196509. * If we knew the application was well behaved, we could simplify this
  196510. * greatly by assuming we can always malloc an output buffer large
  196511. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  196512. * and malloc this directly. The only time this would be a bad idea is
  196513. * if we can't malloc more than 64K and we have 64K of random input
  196514. * data, or if the input string is incredibly large (although this
  196515. * wouldn't cause a failure, just a slowdown due to swapping).
  196516. */
  196517. /* set up the compression buffers */
  196518. png_ptr->zstream.avail_in = (uInt)text_len;
  196519. png_ptr->zstream.next_in = (Bytef *)text;
  196520. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196521. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  196522. /* this is the same compression loop as in png_write_row() */
  196523. do
  196524. {
  196525. /* compress the data */
  196526. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  196527. if (ret != Z_OK)
  196528. {
  196529. /* error */
  196530. if (png_ptr->zstream.msg != NULL)
  196531. png_error(png_ptr, png_ptr->zstream.msg);
  196532. else
  196533. png_error(png_ptr, "zlib error");
  196534. }
  196535. /* check to see if we need more room */
  196536. if (!(png_ptr->zstream.avail_out))
  196537. {
  196538. /* make sure the output array has room */
  196539. if (comp->num_output_ptr >= comp->max_output_ptr)
  196540. {
  196541. int old_max;
  196542. old_max = comp->max_output_ptr;
  196543. comp->max_output_ptr = comp->num_output_ptr + 4;
  196544. if (comp->output_ptr != NULL)
  196545. {
  196546. png_charpp old_ptr;
  196547. old_ptr = comp->output_ptr;
  196548. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196549. (png_uint_32)(comp->max_output_ptr *
  196550. png_sizeof (png_charpp)));
  196551. png_memcpy(comp->output_ptr, old_ptr, old_max
  196552. * png_sizeof (png_charp));
  196553. png_free(png_ptr, old_ptr);
  196554. }
  196555. else
  196556. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196557. (png_uint_32)(comp->max_output_ptr *
  196558. png_sizeof (png_charp)));
  196559. }
  196560. /* save the data */
  196561. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  196562. (png_uint_32)png_ptr->zbuf_size);
  196563. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196564. png_ptr->zbuf_size);
  196565. comp->num_output_ptr++;
  196566. /* and reset the buffer */
  196567. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196568. png_ptr->zstream.next_out = png_ptr->zbuf;
  196569. }
  196570. /* continue until we don't have any more to compress */
  196571. } while (png_ptr->zstream.avail_in);
  196572. /* finish the compression */
  196573. do
  196574. {
  196575. /* tell zlib we are finished */
  196576. ret = deflate(&png_ptr->zstream, Z_FINISH);
  196577. if (ret == Z_OK)
  196578. {
  196579. /* check to see if we need more room */
  196580. if (!(png_ptr->zstream.avail_out))
  196581. {
  196582. /* check to make sure our output array has room */
  196583. if (comp->num_output_ptr >= comp->max_output_ptr)
  196584. {
  196585. int old_max;
  196586. old_max = comp->max_output_ptr;
  196587. comp->max_output_ptr = comp->num_output_ptr + 4;
  196588. if (comp->output_ptr != NULL)
  196589. {
  196590. png_charpp old_ptr;
  196591. old_ptr = comp->output_ptr;
  196592. /* This could be optimized to realloc() */
  196593. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196594. (png_uint_32)(comp->max_output_ptr *
  196595. png_sizeof (png_charpp)));
  196596. png_memcpy(comp->output_ptr, old_ptr,
  196597. old_max * png_sizeof (png_charp));
  196598. png_free(png_ptr, old_ptr);
  196599. }
  196600. else
  196601. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196602. (png_uint_32)(comp->max_output_ptr *
  196603. png_sizeof (png_charp)));
  196604. }
  196605. /* save off the data */
  196606. comp->output_ptr[comp->num_output_ptr] =
  196607. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  196608. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196609. png_ptr->zbuf_size);
  196610. comp->num_output_ptr++;
  196611. /* and reset the buffer pointers */
  196612. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196613. png_ptr->zstream.next_out = png_ptr->zbuf;
  196614. }
  196615. }
  196616. else if (ret != Z_STREAM_END)
  196617. {
  196618. /* we got an error */
  196619. if (png_ptr->zstream.msg != NULL)
  196620. png_error(png_ptr, png_ptr->zstream.msg);
  196621. else
  196622. png_error(png_ptr, "zlib error");
  196623. }
  196624. } while (ret != Z_STREAM_END);
  196625. /* text length is number of buffers plus last buffer */
  196626. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  196627. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  196628. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  196629. return((int)text_len);
  196630. }
  196631. /* ship the compressed text out via chunk writes */
  196632. static void /* PRIVATE */
  196633. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  196634. {
  196635. int i;
  196636. /* handle the no-compression case */
  196637. if (comp->input)
  196638. {
  196639. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  196640. (png_size_t)comp->input_len);
  196641. return;
  196642. }
  196643. /* write saved output buffers, if any */
  196644. for (i = 0; i < comp->num_output_ptr; i++)
  196645. {
  196646. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  196647. png_ptr->zbuf_size);
  196648. png_free(png_ptr, comp->output_ptr[i]);
  196649. comp->output_ptr[i]=NULL;
  196650. }
  196651. if (comp->max_output_ptr != 0)
  196652. png_free(png_ptr, comp->output_ptr);
  196653. comp->output_ptr=NULL;
  196654. /* write anything left in zbuf */
  196655. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  196656. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  196657. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196658. /* reset zlib for another zTXt/iTXt or image data */
  196659. deflateReset(&png_ptr->zstream);
  196660. png_ptr->zstream.data_type = Z_BINARY;
  196661. }
  196662. #endif
  196663. /* Write the IHDR chunk, and update the png_struct with the necessary
  196664. * information. Note that the rest of this code depends upon this
  196665. * information being correct.
  196666. */
  196667. void /* PRIVATE */
  196668. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  196669. int bit_depth, int color_type, int compression_type, int filter_type,
  196670. int interlace_type)
  196671. {
  196672. #ifdef PNG_USE_LOCAL_ARRAYS
  196673. PNG_IHDR;
  196674. #endif
  196675. png_byte buf[13]; /* buffer to store the IHDR info */
  196676. png_debug(1, "in png_write_IHDR\n");
  196677. /* Check that we have valid input data from the application info */
  196678. switch (color_type)
  196679. {
  196680. case PNG_COLOR_TYPE_GRAY:
  196681. switch (bit_depth)
  196682. {
  196683. case 1:
  196684. case 2:
  196685. case 4:
  196686. case 8:
  196687. case 16: png_ptr->channels = 1; break;
  196688. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  196689. }
  196690. break;
  196691. case PNG_COLOR_TYPE_RGB:
  196692. if (bit_depth != 8 && bit_depth != 16)
  196693. png_error(png_ptr, "Invalid bit depth for RGB image");
  196694. png_ptr->channels = 3;
  196695. break;
  196696. case PNG_COLOR_TYPE_PALETTE:
  196697. switch (bit_depth)
  196698. {
  196699. case 1:
  196700. case 2:
  196701. case 4:
  196702. case 8: png_ptr->channels = 1; break;
  196703. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  196704. }
  196705. break;
  196706. case PNG_COLOR_TYPE_GRAY_ALPHA:
  196707. if (bit_depth != 8 && bit_depth != 16)
  196708. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  196709. png_ptr->channels = 2;
  196710. break;
  196711. case PNG_COLOR_TYPE_RGB_ALPHA:
  196712. if (bit_depth != 8 && bit_depth != 16)
  196713. png_error(png_ptr, "Invalid bit depth for RGBA image");
  196714. png_ptr->channels = 4;
  196715. break;
  196716. default:
  196717. png_error(png_ptr, "Invalid image color type specified");
  196718. }
  196719. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196720. {
  196721. png_warning(png_ptr, "Invalid compression type specified");
  196722. compression_type = PNG_COMPRESSION_TYPE_BASE;
  196723. }
  196724. /* Write filter_method 64 (intrapixel differencing) only if
  196725. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196726. * 2. Libpng did not write a PNG signature (this filter_method is only
  196727. * used in PNG datastreams that are embedded in MNG datastreams) and
  196728. * 3. The application called png_permit_mng_features with a mask that
  196729. * included PNG_FLAG_MNG_FILTER_64 and
  196730. * 4. The filter_method is 64 and
  196731. * 5. The color_type is RGB or RGBA
  196732. */
  196733. if (
  196734. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196735. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196736. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196737. (color_type == PNG_COLOR_TYPE_RGB ||
  196738. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  196739. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  196740. #endif
  196741. filter_type != PNG_FILTER_TYPE_BASE)
  196742. {
  196743. png_warning(png_ptr, "Invalid filter type specified");
  196744. filter_type = PNG_FILTER_TYPE_BASE;
  196745. }
  196746. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196747. if (interlace_type != PNG_INTERLACE_NONE &&
  196748. interlace_type != PNG_INTERLACE_ADAM7)
  196749. {
  196750. png_warning(png_ptr, "Invalid interlace type specified");
  196751. interlace_type = PNG_INTERLACE_ADAM7;
  196752. }
  196753. #else
  196754. interlace_type=PNG_INTERLACE_NONE;
  196755. #endif
  196756. /* save off the relevent information */
  196757. png_ptr->bit_depth = (png_byte)bit_depth;
  196758. png_ptr->color_type = (png_byte)color_type;
  196759. png_ptr->interlaced = (png_byte)interlace_type;
  196760. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196761. png_ptr->filter_type = (png_byte)filter_type;
  196762. #endif
  196763. png_ptr->compression_type = (png_byte)compression_type;
  196764. png_ptr->width = width;
  196765. png_ptr->height = height;
  196766. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  196767. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  196768. /* set the usr info, so any transformations can modify it */
  196769. png_ptr->usr_width = png_ptr->width;
  196770. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  196771. png_ptr->usr_channels = png_ptr->channels;
  196772. /* pack the header information into the buffer */
  196773. png_save_uint_32(buf, width);
  196774. png_save_uint_32(buf + 4, height);
  196775. buf[8] = (png_byte)bit_depth;
  196776. buf[9] = (png_byte)color_type;
  196777. buf[10] = (png_byte)compression_type;
  196778. buf[11] = (png_byte)filter_type;
  196779. buf[12] = (png_byte)interlace_type;
  196780. /* write the chunk */
  196781. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  196782. /* initialize zlib with PNG info */
  196783. png_ptr->zstream.zalloc = png_zalloc;
  196784. png_ptr->zstream.zfree = png_zfree;
  196785. png_ptr->zstream.opaque = (voidpf)png_ptr;
  196786. if (!(png_ptr->do_filter))
  196787. {
  196788. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  196789. png_ptr->bit_depth < 8)
  196790. png_ptr->do_filter = PNG_FILTER_NONE;
  196791. else
  196792. png_ptr->do_filter = PNG_ALL_FILTERS;
  196793. }
  196794. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  196795. {
  196796. if (png_ptr->do_filter != PNG_FILTER_NONE)
  196797. png_ptr->zlib_strategy = Z_FILTERED;
  196798. else
  196799. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  196800. }
  196801. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  196802. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  196803. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  196804. png_ptr->zlib_mem_level = 8;
  196805. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  196806. png_ptr->zlib_window_bits = 15;
  196807. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  196808. png_ptr->zlib_method = 8;
  196809. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  196810. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  196811. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  196812. png_error(png_ptr, "zlib failed to initialize compressor");
  196813. png_ptr->zstream.next_out = png_ptr->zbuf;
  196814. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196815. /* libpng is not interested in zstream.data_type */
  196816. /* set it to a predefined value, to avoid its evaluation inside zlib */
  196817. png_ptr->zstream.data_type = Z_BINARY;
  196818. png_ptr->mode = PNG_HAVE_IHDR;
  196819. }
  196820. /* write the palette. We are careful not to trust png_color to be in the
  196821. * correct order for PNG, so people can redefine it to any convenient
  196822. * structure.
  196823. */
  196824. void /* PRIVATE */
  196825. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  196826. {
  196827. #ifdef PNG_USE_LOCAL_ARRAYS
  196828. PNG_PLTE;
  196829. #endif
  196830. png_uint_32 i;
  196831. png_colorp pal_ptr;
  196832. png_byte buf[3];
  196833. png_debug(1, "in png_write_PLTE\n");
  196834. if ((
  196835. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196836. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  196837. #endif
  196838. num_pal == 0) || num_pal > 256)
  196839. {
  196840. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196841. {
  196842. png_error(png_ptr, "Invalid number of colors in palette");
  196843. }
  196844. else
  196845. {
  196846. png_warning(png_ptr, "Invalid number of colors in palette");
  196847. return;
  196848. }
  196849. }
  196850. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  196851. {
  196852. png_warning(png_ptr,
  196853. "Ignoring request to write a PLTE chunk in grayscale PNG");
  196854. return;
  196855. }
  196856. png_ptr->num_palette = (png_uint_16)num_pal;
  196857. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  196858. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  196859. #ifndef PNG_NO_POINTER_INDEXING
  196860. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  196861. {
  196862. buf[0] = pal_ptr->red;
  196863. buf[1] = pal_ptr->green;
  196864. buf[2] = pal_ptr->blue;
  196865. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196866. }
  196867. #else
  196868. /* This is a little slower but some buggy compilers need to do this instead */
  196869. pal_ptr=palette;
  196870. for (i = 0; i < num_pal; i++)
  196871. {
  196872. buf[0] = pal_ptr[i].red;
  196873. buf[1] = pal_ptr[i].green;
  196874. buf[2] = pal_ptr[i].blue;
  196875. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196876. }
  196877. #endif
  196878. png_write_chunk_end(png_ptr);
  196879. png_ptr->mode |= PNG_HAVE_PLTE;
  196880. }
  196881. /* write an IDAT chunk */
  196882. void /* PRIVATE */
  196883. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  196884. {
  196885. #ifdef PNG_USE_LOCAL_ARRAYS
  196886. PNG_IDAT;
  196887. #endif
  196888. png_debug(1, "in png_write_IDAT\n");
  196889. /* Optimize the CMF field in the zlib stream. */
  196890. /* This hack of the zlib stream is compliant to the stream specification. */
  196891. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  196892. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  196893. {
  196894. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  196895. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  196896. {
  196897. /* Avoid memory underflows and multiplication overflows. */
  196898. /* The conditions below are practically always satisfied;
  196899. however, they still must be checked. */
  196900. if (length >= 2 &&
  196901. png_ptr->height < 16384 && png_ptr->width < 16384)
  196902. {
  196903. png_uint_32 uncompressed_idat_size = png_ptr->height *
  196904. ((png_ptr->width *
  196905. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  196906. unsigned int z_cinfo = z_cmf >> 4;
  196907. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  196908. while (uncompressed_idat_size <= half_z_window_size &&
  196909. half_z_window_size >= 256)
  196910. {
  196911. z_cinfo--;
  196912. half_z_window_size >>= 1;
  196913. }
  196914. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  196915. if (data[0] != (png_byte)z_cmf)
  196916. {
  196917. data[0] = (png_byte)z_cmf;
  196918. data[1] &= 0xe0;
  196919. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  196920. }
  196921. }
  196922. }
  196923. else
  196924. png_error(png_ptr,
  196925. "Invalid zlib compression method or flags in IDAT");
  196926. }
  196927. png_write_chunk(png_ptr, png_IDAT, data, length);
  196928. png_ptr->mode |= PNG_HAVE_IDAT;
  196929. }
  196930. /* write an IEND chunk */
  196931. void /* PRIVATE */
  196932. png_write_IEND(png_structp png_ptr)
  196933. {
  196934. #ifdef PNG_USE_LOCAL_ARRAYS
  196935. PNG_IEND;
  196936. #endif
  196937. png_debug(1, "in png_write_IEND\n");
  196938. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  196939. (png_size_t)0);
  196940. png_ptr->mode |= PNG_HAVE_IEND;
  196941. }
  196942. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  196943. /* write a gAMA chunk */
  196944. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196945. void /* PRIVATE */
  196946. png_write_gAMA(png_structp png_ptr, double file_gamma)
  196947. {
  196948. #ifdef PNG_USE_LOCAL_ARRAYS
  196949. PNG_gAMA;
  196950. #endif
  196951. png_uint_32 igamma;
  196952. png_byte buf[4];
  196953. png_debug(1, "in png_write_gAMA\n");
  196954. /* file_gamma is saved in 1/100,000ths */
  196955. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  196956. png_save_uint_32(buf, igamma);
  196957. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196958. }
  196959. #endif
  196960. #ifdef PNG_FIXED_POINT_SUPPORTED
  196961. void /* PRIVATE */
  196962. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  196963. {
  196964. #ifdef PNG_USE_LOCAL_ARRAYS
  196965. PNG_gAMA;
  196966. #endif
  196967. png_byte buf[4];
  196968. png_debug(1, "in png_write_gAMA\n");
  196969. /* file_gamma is saved in 1/100,000ths */
  196970. png_save_uint_32(buf, (png_uint_32)file_gamma);
  196971. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196972. }
  196973. #endif
  196974. #endif
  196975. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  196976. /* write a sRGB chunk */
  196977. void /* PRIVATE */
  196978. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  196979. {
  196980. #ifdef PNG_USE_LOCAL_ARRAYS
  196981. PNG_sRGB;
  196982. #endif
  196983. png_byte buf[1];
  196984. png_debug(1, "in png_write_sRGB\n");
  196985. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  196986. png_warning(png_ptr,
  196987. "Invalid sRGB rendering intent specified");
  196988. buf[0]=(png_byte)srgb_intent;
  196989. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  196990. }
  196991. #endif
  196992. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  196993. /* write an iCCP chunk */
  196994. void /* PRIVATE */
  196995. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  196996. png_charp profile, int profile_len)
  196997. {
  196998. #ifdef PNG_USE_LOCAL_ARRAYS
  196999. PNG_iCCP;
  197000. #endif
  197001. png_size_t name_len;
  197002. png_charp new_name;
  197003. compression_state comp;
  197004. int embedded_profile_len = 0;
  197005. png_debug(1, "in png_write_iCCP\n");
  197006. comp.num_output_ptr = 0;
  197007. comp.max_output_ptr = 0;
  197008. comp.output_ptr = NULL;
  197009. comp.input = NULL;
  197010. comp.input_len = 0;
  197011. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  197012. &new_name)) == 0)
  197013. {
  197014. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  197015. return;
  197016. }
  197017. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197018. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  197019. if (profile == NULL)
  197020. profile_len = 0;
  197021. if (profile_len > 3)
  197022. embedded_profile_len =
  197023. ((*( (png_bytep)profile ))<<24) |
  197024. ((*( (png_bytep)profile+1))<<16) |
  197025. ((*( (png_bytep)profile+2))<< 8) |
  197026. ((*( (png_bytep)profile+3)) );
  197027. if (profile_len < embedded_profile_len)
  197028. {
  197029. png_warning(png_ptr,
  197030. "Embedded profile length too large in iCCP chunk");
  197031. return;
  197032. }
  197033. if (profile_len > embedded_profile_len)
  197034. {
  197035. png_warning(png_ptr,
  197036. "Truncating profile to actual length in iCCP chunk");
  197037. profile_len = embedded_profile_len;
  197038. }
  197039. if (profile_len)
  197040. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  197041. PNG_COMPRESSION_TYPE_BASE, &comp);
  197042. /* make sure we include the NULL after the name and the compression type */
  197043. png_write_chunk_start(png_ptr, png_iCCP,
  197044. (png_uint_32)name_len+profile_len+2);
  197045. new_name[name_len+1]=0x00;
  197046. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  197047. if (profile_len)
  197048. png_write_compressed_data_out(png_ptr, &comp);
  197049. png_write_chunk_end(png_ptr);
  197050. png_free(png_ptr, new_name);
  197051. }
  197052. #endif
  197053. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  197054. /* write a sPLT chunk */
  197055. void /* PRIVATE */
  197056. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  197057. {
  197058. #ifdef PNG_USE_LOCAL_ARRAYS
  197059. PNG_sPLT;
  197060. #endif
  197061. png_size_t name_len;
  197062. png_charp new_name;
  197063. png_byte entrybuf[10];
  197064. int entry_size = (spalette->depth == 8 ? 6 : 10);
  197065. int palette_size = entry_size * spalette->nentries;
  197066. png_sPLT_entryp ep;
  197067. #ifdef PNG_NO_POINTER_INDEXING
  197068. int i;
  197069. #endif
  197070. png_debug(1, "in png_write_sPLT\n");
  197071. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  197072. spalette->name, &new_name))==0)
  197073. {
  197074. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  197075. return;
  197076. }
  197077. /* make sure we include the NULL after the name */
  197078. png_write_chunk_start(png_ptr, png_sPLT,
  197079. (png_uint_32)(name_len + 2 + palette_size));
  197080. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  197081. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  197082. /* loop through each palette entry, writing appropriately */
  197083. #ifndef PNG_NO_POINTER_INDEXING
  197084. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  197085. {
  197086. if (spalette->depth == 8)
  197087. {
  197088. entrybuf[0] = (png_byte)ep->red;
  197089. entrybuf[1] = (png_byte)ep->green;
  197090. entrybuf[2] = (png_byte)ep->blue;
  197091. entrybuf[3] = (png_byte)ep->alpha;
  197092. png_save_uint_16(entrybuf + 4, ep->frequency);
  197093. }
  197094. else
  197095. {
  197096. png_save_uint_16(entrybuf + 0, ep->red);
  197097. png_save_uint_16(entrybuf + 2, ep->green);
  197098. png_save_uint_16(entrybuf + 4, ep->blue);
  197099. png_save_uint_16(entrybuf + 6, ep->alpha);
  197100. png_save_uint_16(entrybuf + 8, ep->frequency);
  197101. }
  197102. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  197103. }
  197104. #else
  197105. ep=spalette->entries;
  197106. for (i=0; i>spalette->nentries; i++)
  197107. {
  197108. if (spalette->depth == 8)
  197109. {
  197110. entrybuf[0] = (png_byte)ep[i].red;
  197111. entrybuf[1] = (png_byte)ep[i].green;
  197112. entrybuf[2] = (png_byte)ep[i].blue;
  197113. entrybuf[3] = (png_byte)ep[i].alpha;
  197114. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  197115. }
  197116. else
  197117. {
  197118. png_save_uint_16(entrybuf + 0, ep[i].red);
  197119. png_save_uint_16(entrybuf + 2, ep[i].green);
  197120. png_save_uint_16(entrybuf + 4, ep[i].blue);
  197121. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  197122. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  197123. }
  197124. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  197125. }
  197126. #endif
  197127. png_write_chunk_end(png_ptr);
  197128. png_free(png_ptr, new_name);
  197129. }
  197130. #endif
  197131. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197132. /* write the sBIT chunk */
  197133. void /* PRIVATE */
  197134. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  197135. {
  197136. #ifdef PNG_USE_LOCAL_ARRAYS
  197137. PNG_sBIT;
  197138. #endif
  197139. png_byte buf[4];
  197140. png_size_t size;
  197141. png_debug(1, "in png_write_sBIT\n");
  197142. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  197143. if (color_type & PNG_COLOR_MASK_COLOR)
  197144. {
  197145. png_byte maxbits;
  197146. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  197147. png_ptr->usr_bit_depth);
  197148. if (sbit->red == 0 || sbit->red > maxbits ||
  197149. sbit->green == 0 || sbit->green > maxbits ||
  197150. sbit->blue == 0 || sbit->blue > maxbits)
  197151. {
  197152. png_warning(png_ptr, "Invalid sBIT depth specified");
  197153. return;
  197154. }
  197155. buf[0] = sbit->red;
  197156. buf[1] = sbit->green;
  197157. buf[2] = sbit->blue;
  197158. size = 3;
  197159. }
  197160. else
  197161. {
  197162. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  197163. {
  197164. png_warning(png_ptr, "Invalid sBIT depth specified");
  197165. return;
  197166. }
  197167. buf[0] = sbit->gray;
  197168. size = 1;
  197169. }
  197170. if (color_type & PNG_COLOR_MASK_ALPHA)
  197171. {
  197172. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  197173. {
  197174. png_warning(png_ptr, "Invalid sBIT depth specified");
  197175. return;
  197176. }
  197177. buf[size++] = sbit->alpha;
  197178. }
  197179. png_write_chunk(png_ptr, png_sBIT, buf, size);
  197180. }
  197181. #endif
  197182. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197183. /* write the cHRM chunk */
  197184. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197185. void /* PRIVATE */
  197186. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  197187. double red_x, double red_y, double green_x, double green_y,
  197188. double blue_x, double blue_y)
  197189. {
  197190. #ifdef PNG_USE_LOCAL_ARRAYS
  197191. PNG_cHRM;
  197192. #endif
  197193. png_byte buf[32];
  197194. png_uint_32 itemp;
  197195. png_debug(1, "in png_write_cHRM\n");
  197196. /* each value is saved in 1/100,000ths */
  197197. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  197198. white_x + white_y > 1.0)
  197199. {
  197200. png_warning(png_ptr, "Invalid cHRM white point specified");
  197201. #if !defined(PNG_NO_CONSOLE_IO)
  197202. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  197203. #endif
  197204. return;
  197205. }
  197206. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  197207. png_save_uint_32(buf, itemp);
  197208. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  197209. png_save_uint_32(buf + 4, itemp);
  197210. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  197211. {
  197212. png_warning(png_ptr, "Invalid cHRM red point specified");
  197213. return;
  197214. }
  197215. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  197216. png_save_uint_32(buf + 8, itemp);
  197217. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  197218. png_save_uint_32(buf + 12, itemp);
  197219. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  197220. {
  197221. png_warning(png_ptr, "Invalid cHRM green point specified");
  197222. return;
  197223. }
  197224. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  197225. png_save_uint_32(buf + 16, itemp);
  197226. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  197227. png_save_uint_32(buf + 20, itemp);
  197228. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  197229. {
  197230. png_warning(png_ptr, "Invalid cHRM blue point specified");
  197231. return;
  197232. }
  197233. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  197234. png_save_uint_32(buf + 24, itemp);
  197235. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  197236. png_save_uint_32(buf + 28, itemp);
  197237. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197238. }
  197239. #endif
  197240. #ifdef PNG_FIXED_POINT_SUPPORTED
  197241. void /* PRIVATE */
  197242. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  197243. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  197244. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  197245. png_fixed_point blue_y)
  197246. {
  197247. #ifdef PNG_USE_LOCAL_ARRAYS
  197248. PNG_cHRM;
  197249. #endif
  197250. png_byte buf[32];
  197251. png_debug(1, "in png_write_cHRM\n");
  197252. /* each value is saved in 1/100,000ths */
  197253. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  197254. {
  197255. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  197256. #if !defined(PNG_NO_CONSOLE_IO)
  197257. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  197258. #endif
  197259. return;
  197260. }
  197261. png_save_uint_32(buf, (png_uint_32)white_x);
  197262. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  197263. if (red_x + red_y > 100000L)
  197264. {
  197265. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  197266. return;
  197267. }
  197268. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  197269. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  197270. if (green_x + green_y > 100000L)
  197271. {
  197272. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  197273. return;
  197274. }
  197275. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  197276. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  197277. if (blue_x + blue_y > 100000L)
  197278. {
  197279. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  197280. return;
  197281. }
  197282. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  197283. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  197284. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197285. }
  197286. #endif
  197287. #endif
  197288. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197289. /* write the tRNS chunk */
  197290. void /* PRIVATE */
  197291. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  197292. int num_trans, int color_type)
  197293. {
  197294. #ifdef PNG_USE_LOCAL_ARRAYS
  197295. PNG_tRNS;
  197296. #endif
  197297. png_byte buf[6];
  197298. png_debug(1, "in png_write_tRNS\n");
  197299. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197300. {
  197301. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  197302. {
  197303. png_warning(png_ptr,"Invalid number of transparent colors specified");
  197304. return;
  197305. }
  197306. /* write the chunk out as it is */
  197307. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  197308. }
  197309. else if (color_type == PNG_COLOR_TYPE_GRAY)
  197310. {
  197311. /* one 16 bit value */
  197312. if(tran->gray >= (1 << png_ptr->bit_depth))
  197313. {
  197314. png_warning(png_ptr,
  197315. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  197316. return;
  197317. }
  197318. png_save_uint_16(buf, tran->gray);
  197319. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  197320. }
  197321. else if (color_type == PNG_COLOR_TYPE_RGB)
  197322. {
  197323. /* three 16 bit values */
  197324. png_save_uint_16(buf, tran->red);
  197325. png_save_uint_16(buf + 2, tran->green);
  197326. png_save_uint_16(buf + 4, tran->blue);
  197327. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197328. {
  197329. png_warning(png_ptr,
  197330. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  197331. return;
  197332. }
  197333. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  197334. }
  197335. else
  197336. {
  197337. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  197338. }
  197339. }
  197340. #endif
  197341. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197342. /* write the background chunk */
  197343. void /* PRIVATE */
  197344. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  197345. {
  197346. #ifdef PNG_USE_LOCAL_ARRAYS
  197347. PNG_bKGD;
  197348. #endif
  197349. png_byte buf[6];
  197350. png_debug(1, "in png_write_bKGD\n");
  197351. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197352. {
  197353. if (
  197354. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197355. (png_ptr->num_palette ||
  197356. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  197357. #endif
  197358. back->index > png_ptr->num_palette)
  197359. {
  197360. png_warning(png_ptr, "Invalid background palette index");
  197361. return;
  197362. }
  197363. buf[0] = back->index;
  197364. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  197365. }
  197366. else if (color_type & PNG_COLOR_MASK_COLOR)
  197367. {
  197368. png_save_uint_16(buf, back->red);
  197369. png_save_uint_16(buf + 2, back->green);
  197370. png_save_uint_16(buf + 4, back->blue);
  197371. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197372. {
  197373. png_warning(png_ptr,
  197374. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  197375. return;
  197376. }
  197377. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  197378. }
  197379. else
  197380. {
  197381. if(back->gray >= (1 << png_ptr->bit_depth))
  197382. {
  197383. png_warning(png_ptr,
  197384. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  197385. return;
  197386. }
  197387. png_save_uint_16(buf, back->gray);
  197388. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  197389. }
  197390. }
  197391. #endif
  197392. #if defined(PNG_WRITE_hIST_SUPPORTED)
  197393. /* write the histogram */
  197394. void /* PRIVATE */
  197395. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  197396. {
  197397. #ifdef PNG_USE_LOCAL_ARRAYS
  197398. PNG_hIST;
  197399. #endif
  197400. int i;
  197401. png_byte buf[3];
  197402. png_debug(1, "in png_write_hIST\n");
  197403. if (num_hist > (int)png_ptr->num_palette)
  197404. {
  197405. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  197406. png_ptr->num_palette);
  197407. png_warning(png_ptr, "Invalid number of histogram entries specified");
  197408. return;
  197409. }
  197410. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  197411. for (i = 0; i < num_hist; i++)
  197412. {
  197413. png_save_uint_16(buf, hist[i]);
  197414. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  197415. }
  197416. png_write_chunk_end(png_ptr);
  197417. }
  197418. #endif
  197419. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  197420. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197421. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  197422. * and if invalid, correct the keyword rather than discarding the entire
  197423. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  197424. * length, forbids leading or trailing whitespace, multiple internal spaces,
  197425. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  197426. *
  197427. * The new_key is allocated to hold the corrected keyword and must be freed
  197428. * by the calling routine. This avoids problems with trying to write to
  197429. * static keywords without having to have duplicate copies of the strings.
  197430. */
  197431. png_size_t /* PRIVATE */
  197432. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  197433. {
  197434. png_size_t key_len;
  197435. png_charp kp, dp;
  197436. int kflag;
  197437. int kwarn=0;
  197438. png_debug(1, "in png_check_keyword\n");
  197439. *new_key = NULL;
  197440. if (key == NULL || (key_len = png_strlen(key)) == 0)
  197441. {
  197442. png_warning(png_ptr, "zero length keyword");
  197443. return ((png_size_t)0);
  197444. }
  197445. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  197446. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  197447. if (*new_key == NULL)
  197448. {
  197449. png_warning(png_ptr, "Out of memory while procesing keyword");
  197450. return ((png_size_t)0);
  197451. }
  197452. /* Replace non-printing characters with a blank and print a warning */
  197453. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  197454. {
  197455. if ((png_byte)*kp < 0x20 ||
  197456. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  197457. {
  197458. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197459. char msg[40];
  197460. png_snprintf(msg, 40,
  197461. "invalid keyword character 0x%02X", (png_byte)*kp);
  197462. png_warning(png_ptr, msg);
  197463. #else
  197464. png_warning(png_ptr, "invalid character in keyword");
  197465. #endif
  197466. *dp = ' ';
  197467. }
  197468. else
  197469. {
  197470. *dp = *kp;
  197471. }
  197472. }
  197473. *dp = '\0';
  197474. /* Remove any trailing white space. */
  197475. kp = *new_key + key_len - 1;
  197476. if (*kp == ' ')
  197477. {
  197478. png_warning(png_ptr, "trailing spaces removed from keyword");
  197479. while (*kp == ' ')
  197480. {
  197481. *(kp--) = '\0';
  197482. key_len--;
  197483. }
  197484. }
  197485. /* Remove any leading white space. */
  197486. kp = *new_key;
  197487. if (*kp == ' ')
  197488. {
  197489. png_warning(png_ptr, "leading spaces removed from keyword");
  197490. while (*kp == ' ')
  197491. {
  197492. kp++;
  197493. key_len--;
  197494. }
  197495. }
  197496. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  197497. /* Remove multiple internal spaces. */
  197498. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  197499. {
  197500. if (*kp == ' ' && kflag == 0)
  197501. {
  197502. *(dp++) = *kp;
  197503. kflag = 1;
  197504. }
  197505. else if (*kp == ' ')
  197506. {
  197507. key_len--;
  197508. kwarn=1;
  197509. }
  197510. else
  197511. {
  197512. *(dp++) = *kp;
  197513. kflag = 0;
  197514. }
  197515. }
  197516. *dp = '\0';
  197517. if(kwarn)
  197518. png_warning(png_ptr, "extra interior spaces removed from keyword");
  197519. if (key_len == 0)
  197520. {
  197521. png_free(png_ptr, *new_key);
  197522. *new_key=NULL;
  197523. png_warning(png_ptr, "Zero length keyword");
  197524. }
  197525. if (key_len > 79)
  197526. {
  197527. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  197528. new_key[79] = '\0';
  197529. key_len = 79;
  197530. }
  197531. return (key_len);
  197532. }
  197533. #endif
  197534. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  197535. /* write a tEXt chunk */
  197536. void /* PRIVATE */
  197537. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  197538. png_size_t text_len)
  197539. {
  197540. #ifdef PNG_USE_LOCAL_ARRAYS
  197541. PNG_tEXt;
  197542. #endif
  197543. png_size_t key_len;
  197544. png_charp new_key;
  197545. png_debug(1, "in png_write_tEXt\n");
  197546. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197547. {
  197548. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  197549. return;
  197550. }
  197551. if (text == NULL || *text == '\0')
  197552. text_len = 0;
  197553. else
  197554. text_len = png_strlen(text);
  197555. /* make sure we include the 0 after the key */
  197556. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  197557. /*
  197558. * We leave it to the application to meet PNG-1.0 requirements on the
  197559. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197560. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197561. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197562. */
  197563. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197564. if (text_len)
  197565. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  197566. png_write_chunk_end(png_ptr);
  197567. png_free(png_ptr, new_key);
  197568. }
  197569. #endif
  197570. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  197571. /* write a compressed text chunk */
  197572. void /* PRIVATE */
  197573. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  197574. png_size_t text_len, int compression)
  197575. {
  197576. #ifdef PNG_USE_LOCAL_ARRAYS
  197577. PNG_zTXt;
  197578. #endif
  197579. png_size_t key_len;
  197580. char buf[1];
  197581. png_charp new_key;
  197582. compression_state comp;
  197583. png_debug(1, "in png_write_zTXt\n");
  197584. comp.num_output_ptr = 0;
  197585. comp.max_output_ptr = 0;
  197586. comp.output_ptr = NULL;
  197587. comp.input = NULL;
  197588. comp.input_len = 0;
  197589. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197590. {
  197591. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  197592. return;
  197593. }
  197594. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  197595. {
  197596. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  197597. png_free(png_ptr, new_key);
  197598. return;
  197599. }
  197600. text_len = png_strlen(text);
  197601. /* compute the compressed data; do it now for the length */
  197602. text_len = png_text_compress(png_ptr, text, text_len, compression,
  197603. &comp);
  197604. /* write start of chunk */
  197605. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  197606. (key_len+text_len+2));
  197607. /* write key */
  197608. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197609. png_free(png_ptr, new_key);
  197610. buf[0] = (png_byte)compression;
  197611. /* write compression */
  197612. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  197613. /* write the compressed data */
  197614. png_write_compressed_data_out(png_ptr, &comp);
  197615. /* close the chunk */
  197616. png_write_chunk_end(png_ptr);
  197617. }
  197618. #endif
  197619. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197620. /* write an iTXt chunk */
  197621. void /* PRIVATE */
  197622. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  197623. png_charp lang, png_charp lang_key, png_charp text)
  197624. {
  197625. #ifdef PNG_USE_LOCAL_ARRAYS
  197626. PNG_iTXt;
  197627. #endif
  197628. png_size_t lang_len, key_len, lang_key_len, text_len;
  197629. png_charp new_lang, new_key;
  197630. png_byte cbuf[2];
  197631. compression_state comp;
  197632. png_debug(1, "in png_write_iTXt\n");
  197633. comp.num_output_ptr = 0;
  197634. comp.max_output_ptr = 0;
  197635. comp.output_ptr = NULL;
  197636. comp.input = NULL;
  197637. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197638. {
  197639. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  197640. return;
  197641. }
  197642. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  197643. {
  197644. png_warning(png_ptr, "Empty language field in iTXt chunk");
  197645. new_lang = NULL;
  197646. lang_len = 0;
  197647. }
  197648. if (lang_key == NULL)
  197649. lang_key_len = 0;
  197650. else
  197651. lang_key_len = png_strlen(lang_key);
  197652. if (text == NULL)
  197653. text_len = 0;
  197654. else
  197655. text_len = png_strlen(text);
  197656. /* compute the compressed data; do it now for the length */
  197657. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  197658. &comp);
  197659. /* make sure we include the compression flag, the compression byte,
  197660. * and the NULs after the key, lang, and lang_key parts */
  197661. png_write_chunk_start(png_ptr, png_iTXt,
  197662. (png_uint_32)(
  197663. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  197664. + key_len
  197665. + lang_len
  197666. + lang_key_len
  197667. + text_len));
  197668. /*
  197669. * We leave it to the application to meet PNG-1.0 requirements on the
  197670. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197671. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197672. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197673. */
  197674. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197675. /* set the compression flag */
  197676. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  197677. compression == PNG_TEXT_COMPRESSION_NONE)
  197678. cbuf[0] = 0;
  197679. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  197680. cbuf[0] = 1;
  197681. /* set the compression method */
  197682. cbuf[1] = 0;
  197683. png_write_chunk_data(png_ptr, cbuf, 2);
  197684. cbuf[0] = 0;
  197685. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  197686. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  197687. png_write_compressed_data_out(png_ptr, &comp);
  197688. png_write_chunk_end(png_ptr);
  197689. png_free(png_ptr, new_key);
  197690. if (new_lang)
  197691. png_free(png_ptr, new_lang);
  197692. }
  197693. #endif
  197694. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  197695. /* write the oFFs chunk */
  197696. void /* PRIVATE */
  197697. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  197698. int unit_type)
  197699. {
  197700. #ifdef PNG_USE_LOCAL_ARRAYS
  197701. PNG_oFFs;
  197702. #endif
  197703. png_byte buf[9];
  197704. png_debug(1, "in png_write_oFFs\n");
  197705. if (unit_type >= PNG_OFFSET_LAST)
  197706. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  197707. png_save_int_32(buf, x_offset);
  197708. png_save_int_32(buf + 4, y_offset);
  197709. buf[8] = (png_byte)unit_type;
  197710. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  197711. }
  197712. #endif
  197713. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  197714. /* write the pCAL chunk (described in the PNG extensions document) */
  197715. void /* PRIVATE */
  197716. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  197717. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  197718. {
  197719. #ifdef PNG_USE_LOCAL_ARRAYS
  197720. PNG_pCAL;
  197721. #endif
  197722. png_size_t purpose_len, units_len, total_len;
  197723. png_uint_32p params_len;
  197724. png_byte buf[10];
  197725. png_charp new_purpose;
  197726. int i;
  197727. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  197728. if (type >= PNG_EQUATION_LAST)
  197729. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  197730. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  197731. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  197732. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  197733. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  197734. total_len = purpose_len + units_len + 10;
  197735. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  197736. *png_sizeof(png_uint_32)));
  197737. /* Find the length of each parameter, making sure we don't count the
  197738. null terminator for the last parameter. */
  197739. for (i = 0; i < nparams; i++)
  197740. {
  197741. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  197742. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  197743. total_len += (png_size_t)params_len[i];
  197744. }
  197745. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  197746. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  197747. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  197748. png_save_int_32(buf, X0);
  197749. png_save_int_32(buf + 4, X1);
  197750. buf[8] = (png_byte)type;
  197751. buf[9] = (png_byte)nparams;
  197752. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  197753. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  197754. png_free(png_ptr, new_purpose);
  197755. for (i = 0; i < nparams; i++)
  197756. {
  197757. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  197758. (png_size_t)params_len[i]);
  197759. }
  197760. png_free(png_ptr, params_len);
  197761. png_write_chunk_end(png_ptr);
  197762. }
  197763. #endif
  197764. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  197765. /* write the sCAL chunk */
  197766. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  197767. void /* PRIVATE */
  197768. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  197769. {
  197770. #ifdef PNG_USE_LOCAL_ARRAYS
  197771. PNG_sCAL;
  197772. #endif
  197773. char buf[64];
  197774. png_size_t total_len;
  197775. png_debug(1, "in png_write_sCAL\n");
  197776. buf[0] = (char)unit;
  197777. #if defined(_WIN32_WCE)
  197778. /* sprintf() function is not supported on WindowsCE */
  197779. {
  197780. wchar_t wc_buf[32];
  197781. size_t wc_len;
  197782. swprintf(wc_buf, TEXT("%12.12e"), width);
  197783. wc_len = wcslen(wc_buf);
  197784. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  197785. total_len = wc_len + 2;
  197786. swprintf(wc_buf, TEXT("%12.12e"), height);
  197787. wc_len = wcslen(wc_buf);
  197788. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  197789. NULL, NULL);
  197790. total_len += wc_len;
  197791. }
  197792. #else
  197793. png_snprintf(buf + 1, 63, "%12.12e", width);
  197794. total_len = 1 + png_strlen(buf + 1) + 1;
  197795. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  197796. total_len += png_strlen(buf + total_len);
  197797. #endif
  197798. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197799. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  197800. }
  197801. #else
  197802. #ifdef PNG_FIXED_POINT_SUPPORTED
  197803. void /* PRIVATE */
  197804. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  197805. png_charp height)
  197806. {
  197807. #ifdef PNG_USE_LOCAL_ARRAYS
  197808. PNG_sCAL;
  197809. #endif
  197810. png_byte buf[64];
  197811. png_size_t wlen, hlen, total_len;
  197812. png_debug(1, "in png_write_sCAL_s\n");
  197813. wlen = png_strlen(width);
  197814. hlen = png_strlen(height);
  197815. total_len = wlen + hlen + 2;
  197816. if (total_len > 64)
  197817. {
  197818. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  197819. return;
  197820. }
  197821. buf[0] = (png_byte)unit;
  197822. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  197823. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  197824. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197825. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  197826. }
  197827. #endif
  197828. #endif
  197829. #endif
  197830. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  197831. /* write the pHYs chunk */
  197832. void /* PRIVATE */
  197833. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  197834. png_uint_32 y_pixels_per_unit,
  197835. int unit_type)
  197836. {
  197837. #ifdef PNG_USE_LOCAL_ARRAYS
  197838. PNG_pHYs;
  197839. #endif
  197840. png_byte buf[9];
  197841. png_debug(1, "in png_write_pHYs\n");
  197842. if (unit_type >= PNG_RESOLUTION_LAST)
  197843. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  197844. png_save_uint_32(buf, x_pixels_per_unit);
  197845. png_save_uint_32(buf + 4, y_pixels_per_unit);
  197846. buf[8] = (png_byte)unit_type;
  197847. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  197848. }
  197849. #endif
  197850. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197851. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  197852. * or png_convert_from_time_t(), or fill in the structure yourself.
  197853. */
  197854. void /* PRIVATE */
  197855. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  197856. {
  197857. #ifdef PNG_USE_LOCAL_ARRAYS
  197858. PNG_tIME;
  197859. #endif
  197860. png_byte buf[7];
  197861. png_debug(1, "in png_write_tIME\n");
  197862. if (mod_time->month > 12 || mod_time->month < 1 ||
  197863. mod_time->day > 31 || mod_time->day < 1 ||
  197864. mod_time->hour > 23 || mod_time->second > 60)
  197865. {
  197866. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  197867. return;
  197868. }
  197869. png_save_uint_16(buf, mod_time->year);
  197870. buf[2] = mod_time->month;
  197871. buf[3] = mod_time->day;
  197872. buf[4] = mod_time->hour;
  197873. buf[5] = mod_time->minute;
  197874. buf[6] = mod_time->second;
  197875. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  197876. }
  197877. #endif
  197878. /* initializes the row writing capability of libpng */
  197879. void /* PRIVATE */
  197880. png_write_start_row(png_structp png_ptr)
  197881. {
  197882. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197883. #ifdef PNG_USE_LOCAL_ARRAYS
  197884. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197885. /* start of interlace block */
  197886. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197887. /* offset to next interlace block */
  197888. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197889. /* start of interlace block in the y direction */
  197890. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197891. /* offset to next interlace block in the y direction */
  197892. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197893. #endif
  197894. #endif
  197895. png_size_t buf_size;
  197896. png_debug(1, "in png_write_start_row\n");
  197897. buf_size = (png_size_t)(PNG_ROWBYTES(
  197898. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  197899. /* set up row buffer */
  197900. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197901. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  197902. #ifndef PNG_NO_WRITE_FILTERING
  197903. /* set up filtering buffer, if using this filter */
  197904. if (png_ptr->do_filter & PNG_FILTER_SUB)
  197905. {
  197906. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  197907. (png_ptr->rowbytes + 1));
  197908. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  197909. }
  197910. /* We only need to keep the previous row if we are using one of these. */
  197911. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  197912. {
  197913. /* set up previous row buffer */
  197914. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197915. png_memset(png_ptr->prev_row, 0, buf_size);
  197916. if (png_ptr->do_filter & PNG_FILTER_UP)
  197917. {
  197918. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  197919. (png_ptr->rowbytes + 1));
  197920. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  197921. }
  197922. if (png_ptr->do_filter & PNG_FILTER_AVG)
  197923. {
  197924. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  197925. (png_ptr->rowbytes + 1));
  197926. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  197927. }
  197928. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  197929. {
  197930. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  197931. (png_ptr->rowbytes + 1));
  197932. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  197933. }
  197934. #endif /* PNG_NO_WRITE_FILTERING */
  197935. }
  197936. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197937. /* if interlaced, we need to set up width and height of pass */
  197938. if (png_ptr->interlaced)
  197939. {
  197940. if (!(png_ptr->transformations & PNG_INTERLACE))
  197941. {
  197942. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  197943. png_pass_ystart[0]) / png_pass_yinc[0];
  197944. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  197945. png_pass_start[0]) / png_pass_inc[0];
  197946. }
  197947. else
  197948. {
  197949. png_ptr->num_rows = png_ptr->height;
  197950. png_ptr->usr_width = png_ptr->width;
  197951. }
  197952. }
  197953. else
  197954. #endif
  197955. {
  197956. png_ptr->num_rows = png_ptr->height;
  197957. png_ptr->usr_width = png_ptr->width;
  197958. }
  197959. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197960. png_ptr->zstream.next_out = png_ptr->zbuf;
  197961. }
  197962. /* Internal use only. Called when finished processing a row of data. */
  197963. void /* PRIVATE */
  197964. png_write_finish_row(png_structp png_ptr)
  197965. {
  197966. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197967. #ifdef PNG_USE_LOCAL_ARRAYS
  197968. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197969. /* start of interlace block */
  197970. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197971. /* offset to next interlace block */
  197972. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197973. /* start of interlace block in the y direction */
  197974. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197975. /* offset to next interlace block in the y direction */
  197976. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197977. #endif
  197978. #endif
  197979. int ret;
  197980. png_debug(1, "in png_write_finish_row\n");
  197981. /* next row */
  197982. png_ptr->row_number++;
  197983. /* see if we are done */
  197984. if (png_ptr->row_number < png_ptr->num_rows)
  197985. return;
  197986. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197987. /* if interlaced, go to next pass */
  197988. if (png_ptr->interlaced)
  197989. {
  197990. png_ptr->row_number = 0;
  197991. if (png_ptr->transformations & PNG_INTERLACE)
  197992. {
  197993. png_ptr->pass++;
  197994. }
  197995. else
  197996. {
  197997. /* loop until we find a non-zero width or height pass */
  197998. do
  197999. {
  198000. png_ptr->pass++;
  198001. if (png_ptr->pass >= 7)
  198002. break;
  198003. png_ptr->usr_width = (png_ptr->width +
  198004. png_pass_inc[png_ptr->pass] - 1 -
  198005. png_pass_start[png_ptr->pass]) /
  198006. png_pass_inc[png_ptr->pass];
  198007. png_ptr->num_rows = (png_ptr->height +
  198008. png_pass_yinc[png_ptr->pass] - 1 -
  198009. png_pass_ystart[png_ptr->pass]) /
  198010. png_pass_yinc[png_ptr->pass];
  198011. if (png_ptr->transformations & PNG_INTERLACE)
  198012. break;
  198013. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  198014. }
  198015. /* reset the row above the image for the next pass */
  198016. if (png_ptr->pass < 7)
  198017. {
  198018. if (png_ptr->prev_row != NULL)
  198019. png_memset(png_ptr->prev_row, 0,
  198020. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  198021. png_ptr->usr_bit_depth,png_ptr->width))+1);
  198022. return;
  198023. }
  198024. }
  198025. #endif
  198026. /* if we get here, we've just written the last row, so we need
  198027. to flush the compressor */
  198028. do
  198029. {
  198030. /* tell the compressor we are done */
  198031. ret = deflate(&png_ptr->zstream, Z_FINISH);
  198032. /* check for an error */
  198033. if (ret == Z_OK)
  198034. {
  198035. /* check to see if we need more room */
  198036. if (!(png_ptr->zstream.avail_out))
  198037. {
  198038. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198039. png_ptr->zstream.next_out = png_ptr->zbuf;
  198040. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198041. }
  198042. }
  198043. else if (ret != Z_STREAM_END)
  198044. {
  198045. if (png_ptr->zstream.msg != NULL)
  198046. png_error(png_ptr, png_ptr->zstream.msg);
  198047. else
  198048. png_error(png_ptr, "zlib error");
  198049. }
  198050. } while (ret != Z_STREAM_END);
  198051. /* write any extra space */
  198052. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  198053. {
  198054. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  198055. png_ptr->zstream.avail_out);
  198056. }
  198057. deflateReset(&png_ptr->zstream);
  198058. png_ptr->zstream.data_type = Z_BINARY;
  198059. }
  198060. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198061. /* Pick out the correct pixels for the interlace pass.
  198062. * The basic idea here is to go through the row with a source
  198063. * pointer and a destination pointer (sp and dp), and copy the
  198064. * correct pixels for the pass. As the row gets compacted,
  198065. * sp will always be >= dp, so we should never overwrite anything.
  198066. * See the default: case for the easiest code to understand.
  198067. */
  198068. void /* PRIVATE */
  198069. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  198070. {
  198071. #ifdef PNG_USE_LOCAL_ARRAYS
  198072. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  198073. /* start of interlace block */
  198074. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  198075. /* offset to next interlace block */
  198076. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  198077. #endif
  198078. png_debug(1, "in png_do_write_interlace\n");
  198079. /* we don't have to do anything on the last pass (6) */
  198080. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198081. if (row != NULL && row_info != NULL && pass < 6)
  198082. #else
  198083. if (pass < 6)
  198084. #endif
  198085. {
  198086. /* each pixel depth is handled separately */
  198087. switch (row_info->pixel_depth)
  198088. {
  198089. case 1:
  198090. {
  198091. png_bytep sp;
  198092. png_bytep dp;
  198093. int shift;
  198094. int d;
  198095. int value;
  198096. png_uint_32 i;
  198097. png_uint_32 row_width = row_info->width;
  198098. dp = row;
  198099. d = 0;
  198100. shift = 7;
  198101. for (i = png_pass_start[pass]; i < row_width;
  198102. i += png_pass_inc[pass])
  198103. {
  198104. sp = row + (png_size_t)(i >> 3);
  198105. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  198106. d |= (value << shift);
  198107. if (shift == 0)
  198108. {
  198109. shift = 7;
  198110. *dp++ = (png_byte)d;
  198111. d = 0;
  198112. }
  198113. else
  198114. shift--;
  198115. }
  198116. if (shift != 7)
  198117. *dp = (png_byte)d;
  198118. break;
  198119. }
  198120. case 2:
  198121. {
  198122. png_bytep sp;
  198123. png_bytep dp;
  198124. int shift;
  198125. int d;
  198126. int value;
  198127. png_uint_32 i;
  198128. png_uint_32 row_width = row_info->width;
  198129. dp = row;
  198130. shift = 6;
  198131. d = 0;
  198132. for (i = png_pass_start[pass]; i < row_width;
  198133. i += png_pass_inc[pass])
  198134. {
  198135. sp = row + (png_size_t)(i >> 2);
  198136. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  198137. d |= (value << shift);
  198138. if (shift == 0)
  198139. {
  198140. shift = 6;
  198141. *dp++ = (png_byte)d;
  198142. d = 0;
  198143. }
  198144. else
  198145. shift -= 2;
  198146. }
  198147. if (shift != 6)
  198148. *dp = (png_byte)d;
  198149. break;
  198150. }
  198151. case 4:
  198152. {
  198153. png_bytep sp;
  198154. png_bytep dp;
  198155. int shift;
  198156. int d;
  198157. int value;
  198158. png_uint_32 i;
  198159. png_uint_32 row_width = row_info->width;
  198160. dp = row;
  198161. shift = 4;
  198162. d = 0;
  198163. for (i = png_pass_start[pass]; i < row_width;
  198164. i += png_pass_inc[pass])
  198165. {
  198166. sp = row + (png_size_t)(i >> 1);
  198167. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  198168. d |= (value << shift);
  198169. if (shift == 0)
  198170. {
  198171. shift = 4;
  198172. *dp++ = (png_byte)d;
  198173. d = 0;
  198174. }
  198175. else
  198176. shift -= 4;
  198177. }
  198178. if (shift != 4)
  198179. *dp = (png_byte)d;
  198180. break;
  198181. }
  198182. default:
  198183. {
  198184. png_bytep sp;
  198185. png_bytep dp;
  198186. png_uint_32 i;
  198187. png_uint_32 row_width = row_info->width;
  198188. png_size_t pixel_bytes;
  198189. /* start at the beginning */
  198190. dp = row;
  198191. /* find out how many bytes each pixel takes up */
  198192. pixel_bytes = (row_info->pixel_depth >> 3);
  198193. /* loop through the row, only looking at the pixels that
  198194. matter */
  198195. for (i = png_pass_start[pass]; i < row_width;
  198196. i += png_pass_inc[pass])
  198197. {
  198198. /* find out where the original pixel is */
  198199. sp = row + (png_size_t)i * pixel_bytes;
  198200. /* move the pixel */
  198201. if (dp != sp)
  198202. png_memcpy(dp, sp, pixel_bytes);
  198203. /* next pixel */
  198204. dp += pixel_bytes;
  198205. }
  198206. break;
  198207. }
  198208. }
  198209. /* set new row width */
  198210. row_info->width = (row_info->width +
  198211. png_pass_inc[pass] - 1 -
  198212. png_pass_start[pass]) /
  198213. png_pass_inc[pass];
  198214. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  198215. row_info->width);
  198216. }
  198217. }
  198218. #endif
  198219. /* This filters the row, chooses which filter to use, if it has not already
  198220. * been specified by the application, and then writes the row out with the
  198221. * chosen filter.
  198222. */
  198223. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  198224. #define PNG_HISHIFT 10
  198225. #define PNG_LOMASK ((png_uint_32)0xffffL)
  198226. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  198227. void /* PRIVATE */
  198228. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  198229. {
  198230. png_bytep best_row;
  198231. #ifndef PNG_NO_WRITE_FILTER
  198232. png_bytep prev_row, row_buf;
  198233. png_uint_32 mins, bpp;
  198234. png_byte filter_to_do = png_ptr->do_filter;
  198235. png_uint_32 row_bytes = row_info->rowbytes;
  198236. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198237. int num_p_filters = (int)png_ptr->num_prev_filters;
  198238. #endif
  198239. png_debug(1, "in png_write_find_filter\n");
  198240. /* find out how many bytes offset each pixel is */
  198241. bpp = (row_info->pixel_depth + 7) >> 3;
  198242. prev_row = png_ptr->prev_row;
  198243. #endif
  198244. best_row = png_ptr->row_buf;
  198245. #ifndef PNG_NO_WRITE_FILTER
  198246. row_buf = best_row;
  198247. mins = PNG_MAXSUM;
  198248. /* The prediction method we use is to find which method provides the
  198249. * smallest value when summing the absolute values of the distances
  198250. * from zero, using anything >= 128 as negative numbers. This is known
  198251. * as the "minimum sum of absolute differences" heuristic. Other
  198252. * heuristics are the "weighted minimum sum of absolute differences"
  198253. * (experimental and can in theory improve compression), and the "zlib
  198254. * predictive" method (not implemented yet), which does test compressions
  198255. * of lines using different filter methods, and then chooses the
  198256. * (series of) filter(s) that give minimum compressed data size (VERY
  198257. * computationally expensive).
  198258. *
  198259. * GRR 980525: consider also
  198260. * (1) minimum sum of absolute differences from running average (i.e.,
  198261. * keep running sum of non-absolute differences & count of bytes)
  198262. * [track dispersion, too? restart average if dispersion too large?]
  198263. * (1b) minimum sum of absolute differences from sliding average, probably
  198264. * with window size <= deflate window (usually 32K)
  198265. * (2) minimum sum of squared differences from zero or running average
  198266. * (i.e., ~ root-mean-square approach)
  198267. */
  198268. /* We don't need to test the 'no filter' case if this is the only filter
  198269. * that has been chosen, as it doesn't actually do anything to the data.
  198270. */
  198271. if ((filter_to_do & PNG_FILTER_NONE) &&
  198272. filter_to_do != PNG_FILTER_NONE)
  198273. {
  198274. png_bytep rp;
  198275. png_uint_32 sum = 0;
  198276. png_uint_32 i;
  198277. int v;
  198278. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  198279. {
  198280. v = *rp;
  198281. sum += (v < 128) ? v : 256 - v;
  198282. }
  198283. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198284. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198285. {
  198286. png_uint_32 sumhi, sumlo;
  198287. int j;
  198288. sumlo = sum & PNG_LOMASK;
  198289. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  198290. /* Reduce the sum if we match any of the previous rows */
  198291. for (j = 0; j < num_p_filters; j++)
  198292. {
  198293. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198294. {
  198295. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198296. PNG_WEIGHT_SHIFT;
  198297. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198298. PNG_WEIGHT_SHIFT;
  198299. }
  198300. }
  198301. /* Factor in the cost of this filter (this is here for completeness,
  198302. * but it makes no sense to have a "cost" for the NONE filter, as
  198303. * it has the minimum possible computational cost - none).
  198304. */
  198305. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198306. PNG_COST_SHIFT;
  198307. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198308. PNG_COST_SHIFT;
  198309. if (sumhi > PNG_HIMASK)
  198310. sum = PNG_MAXSUM;
  198311. else
  198312. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198313. }
  198314. #endif
  198315. mins = sum;
  198316. }
  198317. /* sub filter */
  198318. if (filter_to_do == PNG_FILTER_SUB)
  198319. /* it's the only filter so no testing is needed */
  198320. {
  198321. png_bytep rp, lp, dp;
  198322. png_uint_32 i;
  198323. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198324. i++, rp++, dp++)
  198325. {
  198326. *dp = *rp;
  198327. }
  198328. for (lp = row_buf + 1; i < row_bytes;
  198329. i++, rp++, lp++, dp++)
  198330. {
  198331. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198332. }
  198333. best_row = png_ptr->sub_row;
  198334. }
  198335. else if (filter_to_do & PNG_FILTER_SUB)
  198336. {
  198337. png_bytep rp, dp, lp;
  198338. png_uint_32 sum = 0, lmins = mins;
  198339. png_uint_32 i;
  198340. int v;
  198341. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198342. /* We temporarily increase the "minimum sum" by the factor we
  198343. * would reduce the sum of this filter, so that we can do the
  198344. * early exit comparison without scaling the sum each time.
  198345. */
  198346. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198347. {
  198348. int j;
  198349. png_uint_32 lmhi, lmlo;
  198350. lmlo = lmins & PNG_LOMASK;
  198351. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198352. for (j = 0; j < num_p_filters; j++)
  198353. {
  198354. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198355. {
  198356. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198357. PNG_WEIGHT_SHIFT;
  198358. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198359. PNG_WEIGHT_SHIFT;
  198360. }
  198361. }
  198362. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198363. PNG_COST_SHIFT;
  198364. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198365. PNG_COST_SHIFT;
  198366. if (lmhi > PNG_HIMASK)
  198367. lmins = PNG_MAXSUM;
  198368. else
  198369. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198370. }
  198371. #endif
  198372. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198373. i++, rp++, dp++)
  198374. {
  198375. v = *dp = *rp;
  198376. sum += (v < 128) ? v : 256 - v;
  198377. }
  198378. for (lp = row_buf + 1; i < row_bytes;
  198379. i++, rp++, lp++, dp++)
  198380. {
  198381. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198382. sum += (v < 128) ? v : 256 - v;
  198383. if (sum > lmins) /* We are already worse, don't continue. */
  198384. break;
  198385. }
  198386. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198387. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198388. {
  198389. int j;
  198390. png_uint_32 sumhi, sumlo;
  198391. sumlo = sum & PNG_LOMASK;
  198392. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198393. for (j = 0; j < num_p_filters; j++)
  198394. {
  198395. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198396. {
  198397. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  198398. PNG_WEIGHT_SHIFT;
  198399. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  198400. PNG_WEIGHT_SHIFT;
  198401. }
  198402. }
  198403. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198404. PNG_COST_SHIFT;
  198405. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198406. PNG_COST_SHIFT;
  198407. if (sumhi > PNG_HIMASK)
  198408. sum = PNG_MAXSUM;
  198409. else
  198410. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198411. }
  198412. #endif
  198413. if (sum < mins)
  198414. {
  198415. mins = sum;
  198416. best_row = png_ptr->sub_row;
  198417. }
  198418. }
  198419. /* up filter */
  198420. if (filter_to_do == PNG_FILTER_UP)
  198421. {
  198422. png_bytep rp, dp, pp;
  198423. png_uint_32 i;
  198424. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198425. pp = prev_row + 1; i < row_bytes;
  198426. i++, rp++, pp++, dp++)
  198427. {
  198428. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  198429. }
  198430. best_row = png_ptr->up_row;
  198431. }
  198432. else if (filter_to_do & PNG_FILTER_UP)
  198433. {
  198434. png_bytep rp, dp, pp;
  198435. png_uint_32 sum = 0, lmins = mins;
  198436. png_uint_32 i;
  198437. int v;
  198438. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198439. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198440. {
  198441. int j;
  198442. png_uint_32 lmhi, lmlo;
  198443. lmlo = lmins & PNG_LOMASK;
  198444. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198445. for (j = 0; j < num_p_filters; j++)
  198446. {
  198447. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198448. {
  198449. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198450. PNG_WEIGHT_SHIFT;
  198451. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198452. PNG_WEIGHT_SHIFT;
  198453. }
  198454. }
  198455. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198456. PNG_COST_SHIFT;
  198457. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198458. PNG_COST_SHIFT;
  198459. if (lmhi > PNG_HIMASK)
  198460. lmins = PNG_MAXSUM;
  198461. else
  198462. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198463. }
  198464. #endif
  198465. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198466. pp = prev_row + 1; i < row_bytes; i++)
  198467. {
  198468. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198469. sum += (v < 128) ? v : 256 - v;
  198470. if (sum > lmins) /* We are already worse, don't continue. */
  198471. break;
  198472. }
  198473. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198474. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198475. {
  198476. int j;
  198477. png_uint_32 sumhi, sumlo;
  198478. sumlo = sum & PNG_LOMASK;
  198479. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198480. for (j = 0; j < num_p_filters; j++)
  198481. {
  198482. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198483. {
  198484. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198485. PNG_WEIGHT_SHIFT;
  198486. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198487. PNG_WEIGHT_SHIFT;
  198488. }
  198489. }
  198490. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198491. PNG_COST_SHIFT;
  198492. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198493. PNG_COST_SHIFT;
  198494. if (sumhi > PNG_HIMASK)
  198495. sum = PNG_MAXSUM;
  198496. else
  198497. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198498. }
  198499. #endif
  198500. if (sum < mins)
  198501. {
  198502. mins = sum;
  198503. best_row = png_ptr->up_row;
  198504. }
  198505. }
  198506. /* avg filter */
  198507. if (filter_to_do == PNG_FILTER_AVG)
  198508. {
  198509. png_bytep rp, dp, pp, lp;
  198510. png_uint_32 i;
  198511. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198512. pp = prev_row + 1; i < bpp; i++)
  198513. {
  198514. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198515. }
  198516. for (lp = row_buf + 1; i < row_bytes; i++)
  198517. {
  198518. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  198519. & 0xff);
  198520. }
  198521. best_row = png_ptr->avg_row;
  198522. }
  198523. else if (filter_to_do & PNG_FILTER_AVG)
  198524. {
  198525. png_bytep rp, dp, pp, lp;
  198526. png_uint_32 sum = 0, lmins = mins;
  198527. png_uint_32 i;
  198528. int v;
  198529. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198530. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198531. {
  198532. int j;
  198533. png_uint_32 lmhi, lmlo;
  198534. lmlo = lmins & PNG_LOMASK;
  198535. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198536. for (j = 0; j < num_p_filters; j++)
  198537. {
  198538. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  198539. {
  198540. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198541. PNG_WEIGHT_SHIFT;
  198542. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198543. PNG_WEIGHT_SHIFT;
  198544. }
  198545. }
  198546. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198547. PNG_COST_SHIFT;
  198548. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198549. PNG_COST_SHIFT;
  198550. if (lmhi > PNG_HIMASK)
  198551. lmins = PNG_MAXSUM;
  198552. else
  198553. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198554. }
  198555. #endif
  198556. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198557. pp = prev_row + 1; i < bpp; i++)
  198558. {
  198559. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198560. sum += (v < 128) ? v : 256 - v;
  198561. }
  198562. for (lp = row_buf + 1; i < row_bytes; i++)
  198563. {
  198564. v = *dp++ =
  198565. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  198566. sum += (v < 128) ? v : 256 - v;
  198567. if (sum > lmins) /* We are already worse, don't continue. */
  198568. break;
  198569. }
  198570. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198571. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198572. {
  198573. int j;
  198574. png_uint_32 sumhi, sumlo;
  198575. sumlo = sum & PNG_LOMASK;
  198576. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198577. for (j = 0; j < num_p_filters; j++)
  198578. {
  198579. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198580. {
  198581. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198582. PNG_WEIGHT_SHIFT;
  198583. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198584. PNG_WEIGHT_SHIFT;
  198585. }
  198586. }
  198587. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198588. PNG_COST_SHIFT;
  198589. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198590. PNG_COST_SHIFT;
  198591. if (sumhi > PNG_HIMASK)
  198592. sum = PNG_MAXSUM;
  198593. else
  198594. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198595. }
  198596. #endif
  198597. if (sum < mins)
  198598. {
  198599. mins = sum;
  198600. best_row = png_ptr->avg_row;
  198601. }
  198602. }
  198603. /* Paeth filter */
  198604. if (filter_to_do == PNG_FILTER_PAETH)
  198605. {
  198606. png_bytep rp, dp, pp, cp, lp;
  198607. png_uint_32 i;
  198608. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198609. pp = prev_row + 1; i < bpp; i++)
  198610. {
  198611. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198612. }
  198613. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198614. {
  198615. int a, b, c, pa, pb, pc, p;
  198616. b = *pp++;
  198617. c = *cp++;
  198618. a = *lp++;
  198619. p = b - c;
  198620. pc = a - c;
  198621. #ifdef PNG_USE_ABS
  198622. pa = abs(p);
  198623. pb = abs(pc);
  198624. pc = abs(p + pc);
  198625. #else
  198626. pa = p < 0 ? -p : p;
  198627. pb = pc < 0 ? -pc : pc;
  198628. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198629. #endif
  198630. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198631. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198632. }
  198633. best_row = png_ptr->paeth_row;
  198634. }
  198635. else if (filter_to_do & PNG_FILTER_PAETH)
  198636. {
  198637. png_bytep rp, dp, pp, cp, lp;
  198638. png_uint_32 sum = 0, lmins = mins;
  198639. png_uint_32 i;
  198640. int v;
  198641. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198642. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198643. {
  198644. int j;
  198645. png_uint_32 lmhi, lmlo;
  198646. lmlo = lmins & PNG_LOMASK;
  198647. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198648. for (j = 0; j < num_p_filters; j++)
  198649. {
  198650. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198651. {
  198652. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198653. PNG_WEIGHT_SHIFT;
  198654. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198655. PNG_WEIGHT_SHIFT;
  198656. }
  198657. }
  198658. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198659. PNG_COST_SHIFT;
  198660. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198661. PNG_COST_SHIFT;
  198662. if (lmhi > PNG_HIMASK)
  198663. lmins = PNG_MAXSUM;
  198664. else
  198665. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198666. }
  198667. #endif
  198668. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198669. pp = prev_row + 1; i < bpp; i++)
  198670. {
  198671. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198672. sum += (v < 128) ? v : 256 - v;
  198673. }
  198674. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198675. {
  198676. int a, b, c, pa, pb, pc, p;
  198677. b = *pp++;
  198678. c = *cp++;
  198679. a = *lp++;
  198680. #ifndef PNG_SLOW_PAETH
  198681. p = b - c;
  198682. pc = a - c;
  198683. #ifdef PNG_USE_ABS
  198684. pa = abs(p);
  198685. pb = abs(pc);
  198686. pc = abs(p + pc);
  198687. #else
  198688. pa = p < 0 ? -p : p;
  198689. pb = pc < 0 ? -pc : pc;
  198690. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198691. #endif
  198692. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198693. #else /* PNG_SLOW_PAETH */
  198694. p = a + b - c;
  198695. pa = abs(p - a);
  198696. pb = abs(p - b);
  198697. pc = abs(p - c);
  198698. if (pa <= pb && pa <= pc)
  198699. p = a;
  198700. else if (pb <= pc)
  198701. p = b;
  198702. else
  198703. p = c;
  198704. #endif /* PNG_SLOW_PAETH */
  198705. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198706. sum += (v < 128) ? v : 256 - v;
  198707. if (sum > lmins) /* We are already worse, don't continue. */
  198708. break;
  198709. }
  198710. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198711. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198712. {
  198713. int j;
  198714. png_uint_32 sumhi, sumlo;
  198715. sumlo = sum & PNG_LOMASK;
  198716. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198717. for (j = 0; j < num_p_filters; j++)
  198718. {
  198719. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198720. {
  198721. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198722. PNG_WEIGHT_SHIFT;
  198723. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198724. PNG_WEIGHT_SHIFT;
  198725. }
  198726. }
  198727. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198728. PNG_COST_SHIFT;
  198729. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198730. PNG_COST_SHIFT;
  198731. if (sumhi > PNG_HIMASK)
  198732. sum = PNG_MAXSUM;
  198733. else
  198734. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198735. }
  198736. #endif
  198737. if (sum < mins)
  198738. {
  198739. best_row = png_ptr->paeth_row;
  198740. }
  198741. }
  198742. #endif /* PNG_NO_WRITE_FILTER */
  198743. /* Do the actual writing of the filtered row data from the chosen filter. */
  198744. png_write_filtered_row(png_ptr, best_row);
  198745. #ifndef PNG_NO_WRITE_FILTER
  198746. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198747. /* Save the type of filter we picked this time for future calculations */
  198748. if (png_ptr->num_prev_filters > 0)
  198749. {
  198750. int j;
  198751. for (j = 1; j < num_p_filters; j++)
  198752. {
  198753. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  198754. }
  198755. png_ptr->prev_filters[j] = best_row[0];
  198756. }
  198757. #endif
  198758. #endif /* PNG_NO_WRITE_FILTER */
  198759. }
  198760. /* Do the actual writing of a previously filtered row. */
  198761. void /* PRIVATE */
  198762. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  198763. {
  198764. png_debug(1, "in png_write_filtered_row\n");
  198765. png_debug1(2, "filter = %d\n", filtered_row[0]);
  198766. /* set up the zlib input buffer */
  198767. png_ptr->zstream.next_in = filtered_row;
  198768. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  198769. /* repeat until we have compressed all the data */
  198770. do
  198771. {
  198772. int ret; /* return of zlib */
  198773. /* compress the data */
  198774. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  198775. /* check for compression errors */
  198776. if (ret != Z_OK)
  198777. {
  198778. if (png_ptr->zstream.msg != NULL)
  198779. png_error(png_ptr, png_ptr->zstream.msg);
  198780. else
  198781. png_error(png_ptr, "zlib error");
  198782. }
  198783. /* see if it is time to write another IDAT */
  198784. if (!(png_ptr->zstream.avail_out))
  198785. {
  198786. /* write the IDAT and reset the zlib output buffer */
  198787. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198788. png_ptr->zstream.next_out = png_ptr->zbuf;
  198789. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198790. }
  198791. /* repeat until all data has been compressed */
  198792. } while (png_ptr->zstream.avail_in);
  198793. /* swap the current and previous rows */
  198794. if (png_ptr->prev_row != NULL)
  198795. {
  198796. png_bytep tptr;
  198797. tptr = png_ptr->prev_row;
  198798. png_ptr->prev_row = png_ptr->row_buf;
  198799. png_ptr->row_buf = tptr;
  198800. }
  198801. /* finish row - updates counters and flushes zlib if last row */
  198802. png_write_finish_row(png_ptr);
  198803. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198804. png_ptr->flush_rows++;
  198805. if (png_ptr->flush_dist > 0 &&
  198806. png_ptr->flush_rows >= png_ptr->flush_dist)
  198807. {
  198808. png_write_flush(png_ptr);
  198809. }
  198810. #endif
  198811. }
  198812. #endif /* PNG_WRITE_SUPPORTED */
  198813. /********* End of inlined file: pngwutil.c *********/
  198814. }
  198815. #else
  198816. #define PNG_INTERNAL
  198817. #define PNG_SETJMP_NOT_SUPPORTED
  198818. #include <png.h>
  198819. #include <pngconf.h>
  198820. #endif
  198821. }
  198822. #ifdef _MSC_VER
  198823. #pragma warning (pop)
  198824. #endif
  198825. BEGIN_JUCE_NAMESPACE
  198826. using namespace pnglibNamespace;
  198827. using ::calloc;
  198828. using ::malloc;
  198829. using ::free;
  198830. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  198831. {
  198832. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  198833. in->read (data, (int) length);
  198834. }
  198835. struct PNGErrorStruct {};
  198836. static void pngErrorCallback (png_structp, png_const_charp)
  198837. {
  198838. throw PNGErrorStruct();
  198839. }
  198840. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  198841. {
  198842. Image* image = 0;
  198843. png_structp pngReadStruct;
  198844. png_infop pngInfoStruct;
  198845. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198846. if (pngReadStruct != 0)
  198847. {
  198848. pngInfoStruct = png_create_info_struct (pngReadStruct);
  198849. if (pngInfoStruct == 0)
  198850. {
  198851. png_destroy_read_struct (&pngReadStruct, 0, 0);
  198852. return 0;
  198853. }
  198854. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  198855. // read the header..
  198856. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  198857. png_uint_32 width, height;
  198858. int bitDepth, colorType, interlaceType;
  198859. png_read_info (pngReadStruct, pngInfoStruct);
  198860. png_get_IHDR (pngReadStruct, pngInfoStruct,
  198861. &width, &height,
  198862. &bitDepth, &colorType,
  198863. &interlaceType, 0, 0);
  198864. if (bitDepth == 16)
  198865. png_set_strip_16 (pngReadStruct);
  198866. if (colorType == PNG_COLOR_TYPE_PALETTE)
  198867. png_set_expand (pngReadStruct);
  198868. if (bitDepth < 8)
  198869. png_set_expand (pngReadStruct);
  198870. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  198871. png_set_expand (pngReadStruct);
  198872. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  198873. png_set_gray_to_rgb (pngReadStruct);
  198874. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  198875. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  198876. || pngInfoStruct->num_trans > 0;
  198877. // Load the image into a temp buffer in the pnglib format..
  198878. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  198879. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  198880. int y;
  198881. for (y = (int) height; --y >= 0;)
  198882. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  198883. png_read_image (pngReadStruct, rows);
  198884. png_read_end (pngReadStruct, pngInfoStruct);
  198885. juce_free (rows);
  198886. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  198887. // now convert the data to a juce image format..
  198888. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  198889. width, height, hasAlphaChan);
  198890. int stride, pixelStride;
  198891. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  198892. uint8* srcRow = tempBuffer;
  198893. uint8* destRow = pixels;
  198894. for (y = 0; y < (int) height; ++y)
  198895. {
  198896. const uint8* src = srcRow;
  198897. srcRow += (width << 2);
  198898. uint8* dest = destRow;
  198899. destRow += stride;
  198900. if (hasAlphaChan)
  198901. {
  198902. for (int i = width; --i >= 0;)
  198903. {
  198904. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  198905. ((PixelARGB*) dest)->premultiply();
  198906. dest += pixelStride;
  198907. src += 4;
  198908. }
  198909. }
  198910. else
  198911. {
  198912. for (int i = width; --i >= 0;)
  198913. {
  198914. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  198915. dest += pixelStride;
  198916. src += 4;
  198917. }
  198918. }
  198919. }
  198920. image->releasePixelDataReadWrite (pixels);
  198921. juce_free (tempBuffer);
  198922. }
  198923. return image;
  198924. }
  198925. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  198926. {
  198927. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  198928. const bool ok = out->write (data, length);
  198929. (void) ok;
  198930. jassert (ok);
  198931. }
  198932. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  198933. {
  198934. const int width = image.getWidth();
  198935. const int height = image.getHeight();
  198936. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198937. if (pngWriteStruct == 0)
  198938. return false;
  198939. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  198940. if (pngInfoStruct == 0)
  198941. {
  198942. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  198943. return false;
  198944. }
  198945. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  198946. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  198947. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  198948. : PNG_COLOR_TYPE_RGB,
  198949. PNG_INTERLACE_NONE,
  198950. PNG_COMPRESSION_TYPE_BASE,
  198951. PNG_FILTER_TYPE_BASE);
  198952. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  198953. png_color_8 sig_bit;
  198954. sig_bit.red = 8;
  198955. sig_bit.green = 8;
  198956. sig_bit.blue = 8;
  198957. sig_bit.alpha = 8;
  198958. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  198959. png_write_info (pngWriteStruct, pngInfoStruct);
  198960. png_set_shift (pngWriteStruct, &sig_bit);
  198961. png_set_packing (pngWriteStruct);
  198962. for (int y = 0; y < height; ++y)
  198963. {
  198964. uint8* dst = (uint8*) rowData;
  198965. int stride, pixelStride;
  198966. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  198967. const uint8* src = pixels;
  198968. if (image.hasAlphaChannel())
  198969. {
  198970. for (int i = width; --i >= 0;)
  198971. {
  198972. PixelARGB p (*(const PixelARGB*) src);
  198973. p.unpremultiply();
  198974. *dst++ = p.getRed();
  198975. *dst++ = p.getGreen();
  198976. *dst++ = p.getBlue();
  198977. *dst++ = p.getAlpha();
  198978. src += pixelStride;
  198979. }
  198980. }
  198981. else
  198982. {
  198983. for (int i = width; --i >= 0;)
  198984. {
  198985. *dst++ = ((const PixelRGB*) src)->getRed();
  198986. *dst++ = ((const PixelRGB*) src)->getGreen();
  198987. *dst++ = ((const PixelRGB*) src)->getBlue();
  198988. src += pixelStride;
  198989. }
  198990. }
  198991. png_write_rows (pngWriteStruct, &rowData, 1);
  198992. image.releasePixelDataReadOnly (pixels);
  198993. }
  198994. juce_free (rowData);
  198995. png_write_end (pngWriteStruct, pngInfoStruct);
  198996. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  198997. out.flush();
  198998. return true;
  198999. }
  199000. END_JUCE_NAMESPACE
  199001. /********* End of inlined file: juce_PNGLoader.cpp *********/
  199002. #endif
  199003. //==============================================================================
  199004. #if JUCE_WINDOWS
  199005. /********* Start of inlined file: juce_win32_NativeCode.cpp *********/
  199006. /*
  199007. This file wraps together all the win32-specific code, so that
  199008. we can include all the native headers just once, and compile all our
  199009. platform-specific stuff in one big lump, keeping it out of the way of
  199010. the rest of the codebase.
  199011. */
  199012. BEGIN_JUCE_NAMESPACE
  199013. #define JUCE_INCLUDED_FILE 1
  199014. // Now include the actual code files..
  199015. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199016. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199017. // compiled on its own).
  199018. #if JUCE_INCLUDED_FILE
  199019. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  199020. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199021. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199022. #ifndef DOXYGEN
  199023. // use with DynamicLibraryLoader to simplify importing functions
  199024. //
  199025. // functionName: function to import
  199026. // localFunctionName: name you want to use to actually call it (must be different)
  199027. // returnType: the return type
  199028. // object: the DynamicLibraryLoader to use
  199029. // params: list of params (bracketed)
  199030. //
  199031. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  199032. typedef returnType (WINAPI *type##localFunctionName) params; \
  199033. type##localFunctionName localFunctionName \
  199034. = (type##localFunctionName)object.findProcAddress (#functionName);
  199035. // loads and unloads a DLL automatically
  199036. class JUCE_API DynamicLibraryLoader
  199037. {
  199038. public:
  199039. DynamicLibraryLoader (const String& name);
  199040. ~DynamicLibraryLoader();
  199041. void* findProcAddress (const String& functionName);
  199042. private:
  199043. void* libHandle;
  199044. };
  199045. #endif
  199046. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  199047. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  199048. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  199049. {
  199050. libHandle = LoadLibrary (name);
  199051. }
  199052. DynamicLibraryLoader::~DynamicLibraryLoader()
  199053. {
  199054. FreeLibrary ((HMODULE) libHandle);
  199055. }
  199056. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  199057. {
  199058. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  199059. }
  199060. #endif
  199061. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199062. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  199063. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199064. // compiled on its own).
  199065. #if JUCE_INCLUDED_FILE
  199066. extern void juce_updateMultiMonitorInfo() throw();
  199067. extern void juce_initialiseThreadEvents() throw();
  199068. void Logger::outputDebugString (const String& text) throw()
  199069. {
  199070. OutputDebugString (text + T("\n"));
  199071. }
  199072. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  199073. {
  199074. String text;
  199075. va_list args;
  199076. va_start (args, format);
  199077. text.vprintf(format, args);
  199078. outputDebugString (text);
  199079. }
  199080. static int64 hiResTicksPerSecond;
  199081. static double hiResTicksScaleFactor;
  199082. #if JUCE_USE_INTRINSICS
  199083. // CPU info functions using intrinsics...
  199084. #pragma intrinsic (__cpuid)
  199085. #pragma intrinsic (__rdtsc)
  199086. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  199087. {
  199088. int info [4];
  199089. __cpuid (info, 1);
  199090. if (familyModel != 0)
  199091. *familyModel = info [0];
  199092. if (extFeatures != 0)
  199093. *extFeatures = info[1];
  199094. return info[3];
  199095. }*/
  199096. const String SystemStats::getCpuVendor() throw()
  199097. {
  199098. int info [4];
  199099. __cpuid (info, 0);
  199100. char v [12];
  199101. memcpy (v, info + 1, 4);
  199102. memcpy (v + 4, info + 3, 4);
  199103. memcpy (v + 8, info + 2, 4);
  199104. return String (v, 12);
  199105. }
  199106. #else
  199107. // CPU info functions using old fashioned inline asm...
  199108. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  199109. {
  199110. unsigned int cpu = 0;
  199111. unsigned int ext = 0;
  199112. unsigned int family = 0;
  199113. #if JUCE_GCC
  199114. unsigned int dummy = 0;
  199115. #endif
  199116. #ifndef __MINGW32__
  199117. __try
  199118. #endif
  199119. {
  199120. #if JUCE_GCC
  199121. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  199122. #else
  199123. __asm
  199124. {
  199125. mov eax, 1
  199126. cpuid
  199127. mov cpu, edx
  199128. mov family, eax
  199129. mov ext, ebx
  199130. }
  199131. #endif
  199132. }
  199133. #ifndef __MINGW32__
  199134. __except (EXCEPTION_EXECUTE_HANDLER)
  199135. {
  199136. return 0;
  199137. }
  199138. #endif
  199139. if (familyModel != 0)
  199140. *familyModel = family;
  199141. if (extFeatures != 0)
  199142. *extFeatures = ext;
  199143. return cpu;
  199144. }*/
  199145. static void juce_getCpuVendor (char* const v)
  199146. {
  199147. int vendor[4];
  199148. zeromem (vendor, 16);
  199149. #ifdef JUCE_64BIT
  199150. #else
  199151. #ifndef __MINGW32__
  199152. __try
  199153. #endif
  199154. {
  199155. #if JUCE_GCC
  199156. unsigned int dummy = 0;
  199157. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  199158. #else
  199159. __asm
  199160. {
  199161. mov eax, 0
  199162. cpuid
  199163. mov [vendor], ebx
  199164. mov [vendor + 4], edx
  199165. mov [vendor + 8], ecx
  199166. }
  199167. #endif
  199168. }
  199169. #ifndef __MINGW32__
  199170. __except (EXCEPTION_EXECUTE_HANDLER)
  199171. {
  199172. *v = 0;
  199173. }
  199174. #endif
  199175. #endif
  199176. memcpy (v, vendor, 16);
  199177. }
  199178. const String SystemStats::getCpuVendor() throw()
  199179. {
  199180. char v [16];
  199181. juce_getCpuVendor (v);
  199182. return String (v, 16);
  199183. }
  199184. #endif
  199185. struct CPUFlags
  199186. {
  199187. bool hasMMX : 1;
  199188. bool hasSSE : 1;
  199189. bool hasSSE2 : 1;
  199190. bool has3DNow : 1;
  199191. };
  199192. static CPUFlags cpuFlags;
  199193. bool SystemStats::hasMMX() throw()
  199194. {
  199195. return cpuFlags.hasMMX;
  199196. }
  199197. bool SystemStats::hasSSE() throw()
  199198. {
  199199. return cpuFlags.hasSSE;
  199200. }
  199201. bool SystemStats::hasSSE2() throw()
  199202. {
  199203. return cpuFlags.hasSSE2;
  199204. }
  199205. bool SystemStats::has3DNow() throw()
  199206. {
  199207. return cpuFlags.has3DNow;
  199208. }
  199209. void SystemStats::initialiseStats() throw()
  199210. {
  199211. juce_initialiseThreadEvents();
  199212. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  199213. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  199214. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  199215. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  199216. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  199217. #else
  199218. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  199219. #endif
  199220. LARGE_INTEGER f;
  199221. QueryPerformanceFrequency (&f);
  199222. hiResTicksPerSecond = f.QuadPart;
  199223. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  199224. String s (SystemStats::getJUCEVersion());
  199225. #ifdef JUCE_DEBUG
  199226. const MMRESULT res = timeBeginPeriod (1);
  199227. jassert (res == TIMERR_NOERROR);
  199228. #else
  199229. timeBeginPeriod (1);
  199230. #endif
  199231. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199232. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  199233. #endif
  199234. }
  199235. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  199236. {
  199237. OSVERSIONINFO info;
  199238. info.dwOSVersionInfoSize = sizeof (info);
  199239. GetVersionEx (&info);
  199240. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  199241. {
  199242. switch (info.dwMajorVersion)
  199243. {
  199244. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  199245. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  199246. default: jassertfalse; break; // !! not a supported OS!
  199247. }
  199248. }
  199249. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  199250. {
  199251. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  199252. return Win98;
  199253. }
  199254. return UnknownOS;
  199255. }
  199256. const String SystemStats::getOperatingSystemName() throw()
  199257. {
  199258. const char* name = "Unknown OS";
  199259. switch (getOperatingSystemType())
  199260. {
  199261. case Windows7: name = "Windows 7"; break;
  199262. case WinVista: name = "Windows Vista"; break;
  199263. case WinXP: name = "Windows XP"; break;
  199264. case Win2000: name = "Windows 2000"; break;
  199265. case Win98: name = "Windows 98"; break;
  199266. default: jassertfalse; break; // !! new type of OS?
  199267. }
  199268. return name;
  199269. }
  199270. bool SystemStats::isOperatingSystem64Bit() throw()
  199271. {
  199272. #ifdef _WIN64
  199273. return true;
  199274. #else
  199275. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  199276. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  199277. BOOL isWow64 = FALSE;
  199278. return (fnIsWow64Process != 0)
  199279. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  199280. && (isWow64 != FALSE);
  199281. #endif
  199282. }
  199283. int SystemStats::getMemorySizeInMegabytes() throw()
  199284. {
  199285. MEMORYSTATUSEX mem;
  199286. mem.dwLength = sizeof (mem);
  199287. GlobalMemoryStatusEx (&mem);
  199288. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  199289. }
  199290. int SystemStats::getNumCpus() throw()
  199291. {
  199292. SYSTEM_INFO systemInfo;
  199293. GetSystemInfo (&systemInfo);
  199294. return systemInfo.dwNumberOfProcessors;
  199295. }
  199296. uint32 juce_millisecondsSinceStartup() throw()
  199297. {
  199298. return (uint32) GetTickCount();
  199299. }
  199300. int64 Time::getHighResolutionTicks() throw()
  199301. {
  199302. LARGE_INTEGER ticks;
  199303. QueryPerformanceCounter (&ticks);
  199304. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  199305. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  199306. // fix for a very obscure PCI hardware bug that can make the counter
  199307. // sometimes jump forwards by a few seconds..
  199308. static int64 hiResTicksOffset = 0;
  199309. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  199310. if (offsetDrift > (hiResTicksPerSecond >> 1))
  199311. hiResTicksOffset = newOffset;
  199312. return ticks.QuadPart + hiResTicksOffset;
  199313. }
  199314. double Time::getMillisecondCounterHiRes() throw()
  199315. {
  199316. return getHighResolutionTicks() * hiResTicksScaleFactor;
  199317. }
  199318. int64 Time::getHighResolutionTicksPerSecond() throw()
  199319. {
  199320. return hiResTicksPerSecond;
  199321. }
  199322. int64 SystemStats::getClockCycleCounter() throw()
  199323. {
  199324. #if JUCE_USE_INTRINSICS
  199325. // MS intrinsics version...
  199326. return __rdtsc();
  199327. #elif JUCE_GCC
  199328. // GNU inline asm version...
  199329. unsigned int hi = 0, lo = 0;
  199330. __asm__ __volatile__ (
  199331. "xor %%eax, %%eax \n\
  199332. xor %%edx, %%edx \n\
  199333. rdtsc \n\
  199334. movl %%eax, %[lo] \n\
  199335. movl %%edx, %[hi]"
  199336. :
  199337. : [hi] "m" (hi),
  199338. [lo] "m" (lo)
  199339. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  199340. return (int64) ((((uint64) hi) << 32) | lo);
  199341. #else
  199342. // MSVC inline asm version...
  199343. unsigned int hi = 0, lo = 0;
  199344. __asm
  199345. {
  199346. xor eax, eax
  199347. xor edx, edx
  199348. rdtsc
  199349. mov lo, eax
  199350. mov hi, edx
  199351. }
  199352. return (int64) ((((uint64) hi) << 32) | lo);
  199353. #endif
  199354. }
  199355. int SystemStats::getCpuSpeedInMegaherz() throw()
  199356. {
  199357. const int64 cycles = SystemStats::getClockCycleCounter();
  199358. const uint32 millis = Time::getMillisecondCounter();
  199359. int lastResult = 0;
  199360. for (;;)
  199361. {
  199362. int n = 1000000;
  199363. while (--n > 0) {}
  199364. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  199365. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  199366. if (millisElapsed > 80)
  199367. {
  199368. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  199369. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  199370. return newResult;
  199371. lastResult = newResult;
  199372. }
  199373. }
  199374. }
  199375. bool Time::setSystemTimeToThisTime() const throw()
  199376. {
  199377. SYSTEMTIME st;
  199378. st.wDayOfWeek = 0;
  199379. st.wYear = (WORD) getYear();
  199380. st.wMonth = (WORD) (getMonth() + 1);
  199381. st.wDay = (WORD) getDayOfMonth();
  199382. st.wHour = (WORD) getHours();
  199383. st.wMinute = (WORD) getMinutes();
  199384. st.wSecond = (WORD) getSeconds();
  199385. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  199386. // do this twice because of daylight saving conversion problems - the
  199387. // first one sets it up, the second one kicks it in.
  199388. return SetLocalTime (&st) != 0
  199389. && SetLocalTime (&st) != 0;
  199390. }
  199391. int SystemStats::getPageSize() throw()
  199392. {
  199393. SYSTEM_INFO systemInfo;
  199394. GetSystemInfo (&systemInfo);
  199395. return systemInfo.dwPageSize;
  199396. }
  199397. #endif
  199398. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  199399. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  199400. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199401. // compiled on its own).
  199402. #if JUCE_INCLUDED_FILE
  199403. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199404. extern HWND juce_messageWindowHandle;
  199405. #endif
  199406. CriticalSection::CriticalSection() throw()
  199407. {
  199408. // (just to check the MS haven't changed this structure and broken things...)
  199409. #if _MSC_VER >= 1400
  199410. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  199411. #else
  199412. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  199413. #endif
  199414. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  199415. }
  199416. CriticalSection::~CriticalSection() throw()
  199417. {
  199418. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  199419. }
  199420. void CriticalSection::enter() const throw()
  199421. {
  199422. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  199423. }
  199424. bool CriticalSection::tryEnter() const throw()
  199425. {
  199426. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  199427. }
  199428. void CriticalSection::exit() const throw()
  199429. {
  199430. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  199431. }
  199432. WaitableEvent::WaitableEvent() throw()
  199433. : internal (CreateEvent (0, FALSE, FALSE, 0))
  199434. {
  199435. }
  199436. WaitableEvent::~WaitableEvent() throw()
  199437. {
  199438. CloseHandle (internal);
  199439. }
  199440. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  199441. {
  199442. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  199443. }
  199444. void WaitableEvent::signal() const throw()
  199445. {
  199446. SetEvent (internal);
  199447. }
  199448. void WaitableEvent::reset() const throw()
  199449. {
  199450. ResetEvent (internal);
  199451. }
  199452. void JUCE_API juce_threadEntryPoint (void*);
  199453. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  199454. {
  199455. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199456. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  199457. GetCurrentThreadId(), TRUE);
  199458. #endif
  199459. juce_threadEntryPoint (userData);
  199460. _endthreadex (0);
  199461. return 0;
  199462. }
  199463. void juce_CloseThreadHandle (void* handle) throw()
  199464. {
  199465. CloseHandle ((HANDLE) handle);
  199466. }
  199467. void* juce_createThread (void* userData) throw()
  199468. {
  199469. unsigned int threadId;
  199470. return (void*) _beginthreadex (0, 0,
  199471. &threadEntryProc,
  199472. userData,
  199473. 0, &threadId);
  199474. }
  199475. void juce_killThread (void* handle) throw()
  199476. {
  199477. if (handle != 0)
  199478. {
  199479. #ifdef JUCE_DEBUG
  199480. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  199481. #endif
  199482. TerminateThread (handle, 0);
  199483. }
  199484. }
  199485. void juce_setCurrentThreadName (const String& name) throw()
  199486. {
  199487. #if defined (JUCE_DEBUG) && JUCE_MSVC
  199488. struct
  199489. {
  199490. DWORD dwType;
  199491. LPCSTR szName;
  199492. DWORD dwThreadID;
  199493. DWORD dwFlags;
  199494. } info;
  199495. info.dwType = 0x1000;
  199496. info.szName = name;
  199497. info.dwThreadID = GetCurrentThreadId();
  199498. info.dwFlags = 0;
  199499. #define MS_VC_EXCEPTION 0x406d1388
  199500. __try
  199501. {
  199502. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  199503. }
  199504. __except (EXCEPTION_CONTINUE_EXECUTION)
  199505. {}
  199506. #else
  199507. (void) name;
  199508. #endif
  199509. }
  199510. Thread::ThreadID Thread::getCurrentThreadId() throw()
  199511. {
  199512. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  199513. }
  199514. // priority 1 to 10 where 5=normal, 1=low
  199515. bool juce_setThreadPriority (void* threadHandle, int priority) throw()
  199516. {
  199517. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  199518. if (priority < 1)
  199519. pri = THREAD_PRIORITY_IDLE;
  199520. else if (priority < 2)
  199521. pri = THREAD_PRIORITY_LOWEST;
  199522. else if (priority < 5)
  199523. pri = THREAD_PRIORITY_BELOW_NORMAL;
  199524. else if (priority < 7)
  199525. pri = THREAD_PRIORITY_NORMAL;
  199526. else if (priority < 9)
  199527. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  199528. else if (priority < 10)
  199529. pri = THREAD_PRIORITY_HIGHEST;
  199530. if (threadHandle == 0)
  199531. threadHandle = GetCurrentThread();
  199532. return SetThreadPriority (threadHandle, pri) != FALSE;
  199533. }
  199534. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  199535. {
  199536. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  199537. }
  199538. static HANDLE sleepEvent = 0;
  199539. void juce_initialiseThreadEvents() throw()
  199540. {
  199541. if (sleepEvent == 0)
  199542. #ifdef JUCE_DEBUG
  199543. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  199544. #else
  199545. sleepEvent = CreateEvent (0, 0, 0, 0);
  199546. #endif
  199547. }
  199548. void Thread::yield() throw()
  199549. {
  199550. Sleep (0);
  199551. }
  199552. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  199553. {
  199554. if (millisecs >= 10)
  199555. {
  199556. Sleep (millisecs);
  199557. }
  199558. else
  199559. {
  199560. jassert (sleepEvent != 0);
  199561. // unlike Sleep() this is guaranteed to return to the current thread after
  199562. // the time expires, so we'll use this for short waits, which are more likely
  199563. // to need to be accurate
  199564. WaitForSingleObject (sleepEvent, millisecs);
  199565. }
  199566. }
  199567. static int lastProcessPriority = -1;
  199568. // called by WindowDriver because Windows does wierd things to process priority
  199569. // when you swap apps, and this forces an update when the app is brought to the front.
  199570. void juce_repeatLastProcessPriority() throw()
  199571. {
  199572. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  199573. {
  199574. DWORD p;
  199575. switch (lastProcessPriority)
  199576. {
  199577. case Process::LowPriority:
  199578. p = IDLE_PRIORITY_CLASS;
  199579. break;
  199580. case Process::NormalPriority:
  199581. p = NORMAL_PRIORITY_CLASS;
  199582. break;
  199583. case Process::HighPriority:
  199584. p = HIGH_PRIORITY_CLASS;
  199585. break;
  199586. case Process::RealtimePriority:
  199587. p = REALTIME_PRIORITY_CLASS;
  199588. break;
  199589. default:
  199590. jassertfalse // bad priority value
  199591. return;
  199592. }
  199593. SetPriorityClass (GetCurrentProcess(), p);
  199594. }
  199595. }
  199596. void Process::setPriority (ProcessPriority prior)
  199597. {
  199598. if (lastProcessPriority != (int) prior)
  199599. {
  199600. lastProcessPriority = (int) prior;
  199601. juce_repeatLastProcessPriority();
  199602. }
  199603. }
  199604. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  199605. {
  199606. return IsDebuggerPresent() != FALSE;
  199607. }
  199608. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  199609. {
  199610. return juce_isRunningUnderDebugger();
  199611. }
  199612. void Process::raisePrivilege()
  199613. {
  199614. jassertfalse // xxx not implemented
  199615. }
  199616. void Process::lowerPrivilege()
  199617. {
  199618. jassertfalse // xxx not implemented
  199619. }
  199620. void Process::terminate()
  199621. {
  199622. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199623. _CrtDumpMemoryLeaks();
  199624. #endif
  199625. // bullet in the head in case there's a problem shutting down..
  199626. ExitProcess (0);
  199627. }
  199628. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  199629. {
  199630. void* result = 0;
  199631. JUCE_TRY
  199632. {
  199633. result = (void*) LoadLibrary (name);
  199634. }
  199635. JUCE_CATCH_ALL
  199636. return result;
  199637. }
  199638. void PlatformUtilities::freeDynamicLibrary (void* h)
  199639. {
  199640. JUCE_TRY
  199641. {
  199642. if (h != 0)
  199643. FreeLibrary ((HMODULE) h);
  199644. }
  199645. JUCE_CATCH_ALL
  199646. }
  199647. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  199648. {
  199649. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  199650. : 0;
  199651. }
  199652. InterProcessLock::InterProcessLock (const String& name_) throw()
  199653. : internal (0),
  199654. name (name_),
  199655. reentrancyLevel (0)
  199656. {
  199657. }
  199658. InterProcessLock::~InterProcessLock() throw()
  199659. {
  199660. exit();
  199661. }
  199662. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  199663. {
  199664. if (reentrancyLevel++ == 0)
  199665. {
  199666. internal = CreateMutex (0, TRUE, name);
  199667. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  199668. {
  199669. if (timeOutMillisecs == 0
  199670. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  199671. == WAIT_TIMEOUT)
  199672. {
  199673. ReleaseMutex (internal);
  199674. CloseHandle (internal);
  199675. internal = 0;
  199676. }
  199677. }
  199678. }
  199679. return (internal != 0);
  199680. }
  199681. void InterProcessLock::exit() throw()
  199682. {
  199683. if (--reentrancyLevel == 0 && internal != 0)
  199684. {
  199685. ReleaseMutex (internal);
  199686. CloseHandle (internal);
  199687. internal = 0;
  199688. }
  199689. }
  199690. #endif
  199691. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199692. /********* Start of inlined file: juce_win32_Files.cpp *********/
  199693. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199694. // compiled on its own).
  199695. #if JUCE_INCLUDED_FILE
  199696. #ifndef CSIDL_MYMUSIC
  199697. #define CSIDL_MYMUSIC 0x000d
  199698. #endif
  199699. #ifndef CSIDL_MYVIDEO
  199700. #define CSIDL_MYVIDEO 0x000e
  199701. #endif
  199702. const tchar File::separator = T('\\');
  199703. const tchar* File::separatorString = T("\\");
  199704. bool juce_fileExists (const String& fileName,
  199705. const bool dontCountDirectories) throw()
  199706. {
  199707. if (fileName.isEmpty())
  199708. return false;
  199709. const DWORD attr = GetFileAttributes (fileName);
  199710. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  199711. : (attr != 0xffffffff);
  199712. }
  199713. bool juce_isDirectory (const String& fileName) throw()
  199714. {
  199715. const DWORD attr = GetFileAttributes (fileName);
  199716. return (attr != 0xffffffff)
  199717. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199718. }
  199719. bool juce_canWriteToFile (const String& fileName) throw()
  199720. {
  199721. const DWORD attr = GetFileAttributes (fileName);
  199722. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  199723. }
  199724. bool juce_setFileReadOnly (const String& fileName,
  199725. bool isReadOnly) throw()
  199726. {
  199727. DWORD attr = GetFileAttributes (fileName);
  199728. if (attr == 0xffffffff)
  199729. return false;
  199730. if (isReadOnly != juce_canWriteToFile (fileName))
  199731. return true;
  199732. if (isReadOnly)
  199733. attr |= FILE_ATTRIBUTE_READONLY;
  199734. else
  199735. attr &= ~FILE_ATTRIBUTE_READONLY;
  199736. return SetFileAttributes (fileName, attr) != FALSE;
  199737. }
  199738. bool File::isHidden() const throw()
  199739. {
  199740. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  199741. }
  199742. bool juce_deleteFile (const String& fileName) throw()
  199743. {
  199744. if (juce_isDirectory (fileName))
  199745. return RemoveDirectory (fileName) != 0;
  199746. return DeleteFile (fileName) != 0;
  199747. }
  199748. bool File::moveToTrash() const throw()
  199749. {
  199750. if (! exists())
  199751. return true;
  199752. SHFILEOPSTRUCT fos;
  199753. zerostruct (fos);
  199754. // The string we pass in must be double null terminated..
  199755. String doubleNullTermPath (getFullPathName() + " ");
  199756. TCHAR* p = (TCHAR*) (const TCHAR*) doubleNullTermPath;
  199757. p [getFullPathName().length()] = 0;
  199758. fos.wFunc = FO_DELETE;
  199759. fos.hwnd = (HWND) 0;
  199760. fos.pFrom = p;
  199761. fos.pTo = NULL;
  199762. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  199763. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  199764. return SHFileOperation (&fos) == 0;
  199765. }
  199766. bool juce_moveFile (const String& source, const String& dest) throw()
  199767. {
  199768. return MoveFile (source, dest) != 0;
  199769. }
  199770. bool juce_copyFile (const String& source, const String& dest) throw()
  199771. {
  199772. return CopyFile (source, dest, false) != 0;
  199773. }
  199774. void juce_createDirectory (const String& fileName) throw()
  199775. {
  199776. if (! juce_fileExists (fileName, true))
  199777. {
  199778. CreateDirectory (fileName, 0);
  199779. }
  199780. }
  199781. // return 0 if not possible
  199782. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  199783. {
  199784. HANDLE h;
  199785. if (forWriting)
  199786. {
  199787. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  199788. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  199789. if (h != INVALID_HANDLE_VALUE)
  199790. SetFilePointer (h, 0, 0, FILE_END);
  199791. else
  199792. h = 0;
  199793. }
  199794. else
  199795. {
  199796. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  199797. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  199798. if (h == INVALID_HANDLE_VALUE)
  199799. h = 0;
  199800. }
  199801. return (void*) h;
  199802. }
  199803. void juce_fileClose (void* handle) throw()
  199804. {
  199805. CloseHandle (handle);
  199806. }
  199807. int juce_fileRead (void* handle, void* buffer, int size) throw()
  199808. {
  199809. DWORD num = 0;
  199810. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  199811. return num;
  199812. }
  199813. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  199814. {
  199815. DWORD num;
  199816. WriteFile ((HANDLE) handle,
  199817. buffer, size,
  199818. &num, 0);
  199819. return num;
  199820. }
  199821. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  199822. {
  199823. LARGE_INTEGER li;
  199824. li.QuadPart = pos;
  199825. li.LowPart = SetFilePointer ((HANDLE) handle,
  199826. li.LowPart,
  199827. &li.HighPart,
  199828. FILE_BEGIN); // (returns -1 if it fails)
  199829. return li.QuadPart;
  199830. }
  199831. int64 juce_fileGetPosition (void* handle) throw()
  199832. {
  199833. LARGE_INTEGER li;
  199834. li.QuadPart = 0;
  199835. li.LowPart = SetFilePointer ((HANDLE) handle,
  199836. 0, &li.HighPart,
  199837. FILE_CURRENT); // (returns -1 if it fails)
  199838. return jmax ((int64) 0, li.QuadPart);
  199839. }
  199840. void juce_fileFlush (void* handle) throw()
  199841. {
  199842. FlushFileBuffers ((HANDLE) handle);
  199843. }
  199844. int64 juce_getFileSize (const String& fileName) throw()
  199845. {
  199846. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199847. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199848. {
  199849. return (((int64) attributes.nFileSizeHigh) << 32)
  199850. | attributes.nFileSizeLow;
  199851. }
  199852. return 0;
  199853. }
  199854. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  199855. {
  199856. // tell me if this fails!
  199857. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  199858. #if JUCE_GCC
  199859. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  199860. #else
  199861. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  199862. #endif
  199863. }
  199864. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  199865. {
  199866. #if JUCE_GCC
  199867. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  199868. #else
  199869. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  199870. #endif
  199871. }
  199872. void juce_getFileTimes (const String& fileName,
  199873. int64& modificationTime,
  199874. int64& accessTime,
  199875. int64& creationTime) throw()
  199876. {
  199877. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199878. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199879. {
  199880. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  199881. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  199882. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  199883. }
  199884. else
  199885. {
  199886. creationTime = accessTime = modificationTime = 0;
  199887. }
  199888. }
  199889. bool juce_setFileTimes (const String& fileName,
  199890. int64 modificationTime,
  199891. int64 accessTime,
  199892. int64 creationTime) throw()
  199893. {
  199894. FILETIME m, a, c;
  199895. if (modificationTime > 0)
  199896. timeToFileTime (modificationTime, &m);
  199897. if (accessTime > 0)
  199898. timeToFileTime (accessTime, &a);
  199899. if (creationTime > 0)
  199900. timeToFileTime (creationTime, &c);
  199901. void* const h = juce_fileOpen (fileName, true);
  199902. bool ok = false;
  199903. if (h != 0)
  199904. {
  199905. ok = SetFileTime ((HANDLE) h,
  199906. (creationTime > 0) ? &c : 0,
  199907. (accessTime > 0) ? &a : 0,
  199908. (modificationTime > 0) ? &m : 0) != 0;
  199909. juce_fileClose (h);
  199910. }
  199911. return ok;
  199912. }
  199913. // return '\0' separated list of strings
  199914. const StringArray juce_getFileSystemRoots() throw()
  199915. {
  199916. TCHAR buffer [2048];
  199917. buffer[0] = 0;
  199918. buffer[1] = 0;
  199919. GetLogicalDriveStrings (2048, buffer);
  199920. TCHAR* n = buffer;
  199921. StringArray roots;
  199922. while (*n != 0)
  199923. {
  199924. roots.add (String (n));
  199925. while (*n++ != 0)
  199926. {
  199927. }
  199928. }
  199929. roots.sort (true);
  199930. return roots;
  199931. }
  199932. const String juce_getVolumeLabel (const String& filenameOnVolume,
  199933. int& volumeSerialNumber) throw()
  199934. {
  199935. TCHAR n [4];
  199936. n[0] = *(const TCHAR*) filenameOnVolume;
  199937. n[1] = L':';
  199938. n[2] = L'\\';
  199939. n[3] = 0;
  199940. TCHAR dest [64];
  199941. DWORD serialNum;
  199942. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  199943. {
  199944. dest[0] = 0;
  199945. serialNum = 0;
  199946. }
  199947. volumeSerialNumber = serialNum;
  199948. return String (dest);
  199949. }
  199950. static int64 getDiskSpaceInfo (String fn, const bool total) throw()
  199951. {
  199952. if (fn[1] == T(':'))
  199953. fn = fn.substring (0, 2) + T("\\");
  199954. ULARGE_INTEGER spc, tot, totFree;
  199955. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  199956. return (int64) (total ? tot.QuadPart
  199957. : spc.QuadPart);
  199958. return 0;
  199959. }
  199960. int64 File::getBytesFreeOnVolume() const throw()
  199961. {
  199962. return getDiskSpaceInfo (getFullPathName(), false);
  199963. }
  199964. int64 File::getVolumeTotalSize() const throw()
  199965. {
  199966. return getDiskSpaceInfo (getFullPathName(), true);
  199967. }
  199968. static unsigned int getWindowsDriveType (const String& fileName) throw()
  199969. {
  199970. TCHAR n[4];
  199971. n[0] = *(const TCHAR*) fileName;
  199972. n[1] = L':';
  199973. n[2] = L'\\';
  199974. n[3] = 0;
  199975. return GetDriveType (n);
  199976. }
  199977. bool File::isOnCDRomDrive() const throw()
  199978. {
  199979. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  199980. }
  199981. bool File::isOnHardDisk() const throw()
  199982. {
  199983. if (fullPath.isEmpty())
  199984. return false;
  199985. const unsigned int n = getWindowsDriveType (getFullPathName());
  199986. if (fullPath.toLowerCase()[0] <= 'b'
  199987. && fullPath[1] == T(':'))
  199988. {
  199989. return n != DRIVE_REMOVABLE;
  199990. }
  199991. else
  199992. {
  199993. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  199994. }
  199995. }
  199996. bool File::isOnRemovableDrive() const throw()
  199997. {
  199998. if (fullPath.isEmpty())
  199999. return false;
  200000. const unsigned int n = getWindowsDriveType (getFullPathName());
  200001. return n == DRIVE_CDROM
  200002. || n == DRIVE_REMOTE
  200003. || n == DRIVE_REMOVABLE
  200004. || n == DRIVE_RAMDISK;
  200005. }
  200006. #define MAX_PATH_CHARS (MAX_PATH + 256)
  200007. static const File juce_getSpecialFolderPath (int type) throw()
  200008. {
  200009. WCHAR path [MAX_PATH_CHARS];
  200010. if (SHGetSpecialFolderPath (0, path, type, 0))
  200011. return File (String (path));
  200012. return File::nonexistent;
  200013. }
  200014. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  200015. {
  200016. int csidlType = 0;
  200017. switch (type)
  200018. {
  200019. case userHomeDirectory:
  200020. csidlType = CSIDL_PROFILE;
  200021. break;
  200022. case userDocumentsDirectory:
  200023. csidlType = CSIDL_PERSONAL;
  200024. break;
  200025. case userDesktopDirectory:
  200026. csidlType = CSIDL_DESKTOP;
  200027. break;
  200028. case userApplicationDataDirectory:
  200029. csidlType = CSIDL_APPDATA;
  200030. break;
  200031. case commonApplicationDataDirectory:
  200032. csidlType = CSIDL_COMMON_APPDATA;
  200033. break;
  200034. case globalApplicationsDirectory:
  200035. csidlType = CSIDL_PROGRAM_FILES;
  200036. break;
  200037. case userMusicDirectory:
  200038. csidlType = CSIDL_MYMUSIC;
  200039. break;
  200040. case userMoviesDirectory:
  200041. csidlType = CSIDL_MYVIDEO;
  200042. break;
  200043. case tempDirectory:
  200044. {
  200045. WCHAR dest [2048];
  200046. dest[0] = 0;
  200047. GetTempPath (2048, dest);
  200048. return File (String (dest));
  200049. }
  200050. case currentExecutableFile:
  200051. case currentApplicationFile:
  200052. {
  200053. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200054. WCHAR dest [MAX_PATH_CHARS];
  200055. dest[0] = 0;
  200056. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  200057. return File (String (dest));
  200058. }
  200059. break;
  200060. default:
  200061. jassertfalse // unknown type?
  200062. return File::nonexistent;
  200063. }
  200064. return juce_getSpecialFolderPath (csidlType);
  200065. }
  200066. const File File::getCurrentWorkingDirectory() throw()
  200067. {
  200068. WCHAR dest [MAX_PATH_CHARS];
  200069. dest[0] = 0;
  200070. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  200071. return File (String (dest));
  200072. }
  200073. bool File::setAsCurrentWorkingDirectory() const throw()
  200074. {
  200075. return SetCurrentDirectory (getFullPathName()) != FALSE;
  200076. }
  200077. const String File::getVersion() const throw()
  200078. {
  200079. String result;
  200080. DWORD handle = 0;
  200081. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  200082. void* buffer = juce_calloc (bufferSize);
  200083. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  200084. {
  200085. VS_FIXEDFILEINFO* vffi;
  200086. UINT len = 0;
  200087. if (VerQueryValue (buffer, _T("\\"), (LPVOID*) &vffi, &len))
  200088. {
  200089. result.printf (T("%d.%d.%d.%d"),
  200090. HIWORD (vffi->dwFileVersionMS),
  200091. LOWORD (vffi->dwFileVersionMS),
  200092. HIWORD (vffi->dwFileVersionLS),
  200093. LOWORD (vffi->dwFileVersionLS));
  200094. }
  200095. }
  200096. juce_free (buffer);
  200097. return result;
  200098. }
  200099. const File File::getLinkedTarget() const throw()
  200100. {
  200101. File result (*this);
  200102. String p (getFullPathName());
  200103. if (! exists())
  200104. p += T(".lnk");
  200105. else if (getFileExtension() != T(".lnk"))
  200106. return result;
  200107. ComSmartPtr <IShellLink> shellLink;
  200108. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink, CLSCTX_INPROC_SERVER)))
  200109. {
  200110. ComSmartPtr <IPersistFile> persistFile;
  200111. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  200112. {
  200113. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  200114. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  200115. {
  200116. WIN32_FIND_DATA winFindData;
  200117. WCHAR resolvedPath [MAX_PATH];
  200118. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  200119. result = File (resolvedPath);
  200120. }
  200121. }
  200122. }
  200123. return result;
  200124. }
  200125. template <class FindDataType>
  200126. static void getFindFileInfo (FindDataType& findData,
  200127. String& filename, bool* const isDir, bool* const isHidden,
  200128. int64* const fileSize, Time* const modTime, Time* const creationTime,
  200129. bool* const isReadOnly) throw()
  200130. {
  200131. filename = findData.cFileName;
  200132. if (isDir != 0)
  200133. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  200134. if (isHidden != 0)
  200135. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  200136. if (fileSize != 0)
  200137. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  200138. if (modTime != 0)
  200139. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  200140. if (creationTime != 0)
  200141. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  200142. if (isReadOnly != 0)
  200143. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  200144. }
  200145. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  200146. bool* isDir, bool* isHidden, int64* fileSize,
  200147. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  200148. {
  200149. String wc (directory);
  200150. if (! wc.endsWithChar (File::separator))
  200151. wc += File::separator;
  200152. wc += wildCard;
  200153. WIN32_FIND_DATA findData;
  200154. HANDLE h = FindFirstFile (wc, &findData);
  200155. if (h != INVALID_HANDLE_VALUE)
  200156. {
  200157. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  200158. modTime, creationTime, isReadOnly);
  200159. return h;
  200160. }
  200161. firstResult = String::empty;
  200162. return 0;
  200163. }
  200164. bool juce_findFileNext (void* handle, String& resultFile,
  200165. bool* isDir, bool* isHidden, int64* fileSize,
  200166. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  200167. {
  200168. WIN32_FIND_DATA findData;
  200169. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  200170. {
  200171. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  200172. modTime, creationTime, isReadOnly);
  200173. return true;
  200174. }
  200175. resultFile = String::empty;
  200176. return false;
  200177. }
  200178. void juce_findFileClose (void* handle) throw()
  200179. {
  200180. FindClose (handle);
  200181. }
  200182. bool juce_launchFile (const String& fileName,
  200183. const String& parameters) throw()
  200184. {
  200185. HINSTANCE hInstance = 0;
  200186. JUCE_TRY
  200187. {
  200188. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  200189. }
  200190. JUCE_CATCH_ALL
  200191. return hInstance > (HINSTANCE) 32;
  200192. }
  200193. struct NamedPipeInternal
  200194. {
  200195. HANDLE pipeH;
  200196. HANDLE cancelEvent;
  200197. bool connected, createdPipe;
  200198. NamedPipeInternal()
  200199. : pipeH (0),
  200200. cancelEvent (0),
  200201. connected (false),
  200202. createdPipe (false)
  200203. {
  200204. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  200205. }
  200206. ~NamedPipeInternal()
  200207. {
  200208. disconnect();
  200209. if (pipeH != 0)
  200210. CloseHandle (pipeH);
  200211. CloseHandle (cancelEvent);
  200212. }
  200213. bool connect (const int timeOutMs)
  200214. {
  200215. if (! createdPipe)
  200216. return true;
  200217. if (! connected)
  200218. {
  200219. OVERLAPPED over;
  200220. zerostruct (over);
  200221. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200222. if (ConnectNamedPipe (pipeH, &over))
  200223. {
  200224. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  200225. }
  200226. else
  200227. {
  200228. const int err = GetLastError();
  200229. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  200230. {
  200231. HANDLE handles[] = { over.hEvent, cancelEvent };
  200232. if (WaitForMultipleObjects (2, handles, FALSE,
  200233. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  200234. connected = true;
  200235. }
  200236. else if (err == ERROR_PIPE_CONNECTED)
  200237. {
  200238. connected = true;
  200239. }
  200240. }
  200241. CloseHandle (over.hEvent);
  200242. }
  200243. return connected;
  200244. }
  200245. void disconnect()
  200246. {
  200247. if (connected)
  200248. {
  200249. DisconnectNamedPipe (pipeH);
  200250. connected = false;
  200251. }
  200252. }
  200253. };
  200254. void NamedPipe::close()
  200255. {
  200256. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200257. delete intern;
  200258. internal = 0;
  200259. }
  200260. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  200261. {
  200262. close();
  200263. NamedPipeInternal* const intern = new NamedPipeInternal();
  200264. String file ("\\\\.\\pipe\\");
  200265. file += pipeName;
  200266. intern->createdPipe = createPipe;
  200267. if (createPipe)
  200268. {
  200269. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  200270. PIPE_UNLIMITED_INSTANCES,
  200271. 4096, 4096, 0, NULL);
  200272. }
  200273. else
  200274. {
  200275. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  200276. FILE_FLAG_OVERLAPPED, 0);
  200277. }
  200278. if (intern->pipeH != INVALID_HANDLE_VALUE)
  200279. {
  200280. internal = intern;
  200281. return true;
  200282. }
  200283. delete intern;
  200284. return false;
  200285. }
  200286. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  200287. {
  200288. int bytesRead = -1;
  200289. bool waitAgain = true;
  200290. while (waitAgain && internal != 0)
  200291. {
  200292. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200293. waitAgain = false;
  200294. if (! intern->connect (timeOutMilliseconds))
  200295. break;
  200296. if (maxBytesToRead <= 0)
  200297. return 0;
  200298. OVERLAPPED over;
  200299. zerostruct (over);
  200300. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200301. unsigned long numRead;
  200302. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  200303. {
  200304. bytesRead = (int) numRead;
  200305. }
  200306. else if (GetLastError() == ERROR_IO_PENDING)
  200307. {
  200308. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200309. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200310. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200311. : INFINITE);
  200312. if (waitResult != WAIT_OBJECT_0)
  200313. {
  200314. // if the operation timed out, let's cancel it...
  200315. CancelIo (intern->pipeH);
  200316. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  200317. }
  200318. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  200319. {
  200320. bytesRead = (int) numRead;
  200321. }
  200322. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200323. {
  200324. intern->disconnect();
  200325. waitAgain = true;
  200326. }
  200327. }
  200328. else
  200329. {
  200330. waitAgain = internal != 0;
  200331. Sleep (5);
  200332. }
  200333. CloseHandle (over.hEvent);
  200334. }
  200335. return bytesRead;
  200336. }
  200337. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  200338. {
  200339. int bytesWritten = -1;
  200340. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200341. if (intern != 0 && intern->connect (timeOutMilliseconds))
  200342. {
  200343. if (numBytesToWrite <= 0)
  200344. return 0;
  200345. OVERLAPPED over;
  200346. zerostruct (over);
  200347. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200348. unsigned long numWritten;
  200349. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  200350. {
  200351. bytesWritten = (int) numWritten;
  200352. }
  200353. else if (GetLastError() == ERROR_IO_PENDING)
  200354. {
  200355. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200356. DWORD waitResult;
  200357. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200358. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200359. : INFINITE);
  200360. if (waitResult != WAIT_OBJECT_0)
  200361. {
  200362. CancelIo (intern->pipeH);
  200363. WaitForSingleObject (over.hEvent, INFINITE);
  200364. }
  200365. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  200366. {
  200367. bytesWritten = (int) numWritten;
  200368. }
  200369. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200370. {
  200371. intern->disconnect();
  200372. }
  200373. }
  200374. CloseHandle (over.hEvent);
  200375. }
  200376. return bytesWritten;
  200377. }
  200378. void NamedPipe::cancelPendingReads()
  200379. {
  200380. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200381. if (intern != 0)
  200382. SetEvent (intern->cancelEvent);
  200383. }
  200384. #endif
  200385. /********* End of inlined file: juce_win32_Files.cpp *********/
  200386. /********* Start of inlined file: juce_win32_Network.cpp *********/
  200387. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200388. // compiled on its own).
  200389. #if JUCE_INCLUDED_FILE
  200390. #ifndef INTERNET_FLAG_NEED_FILE
  200391. #define INTERNET_FLAG_NEED_FILE 0x00000010
  200392. #endif
  200393. bool juce_isOnLine()
  200394. {
  200395. DWORD connectionType;
  200396. return InternetGetConnectedState (&connectionType, 0) != 0
  200397. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  200398. }
  200399. struct ConnectionAndRequestStruct
  200400. {
  200401. HINTERNET connection, request;
  200402. };
  200403. static HINTERNET sessionHandle = 0;
  200404. void* juce_openInternetFile (const String& url,
  200405. const String& headers,
  200406. const MemoryBlock& postData,
  200407. const bool isPost,
  200408. URL::OpenStreamProgressCallback* callback,
  200409. void* callbackContext,
  200410. int timeOutMs)
  200411. {
  200412. if (sessionHandle == 0)
  200413. sessionHandle = InternetOpen (_T("juce"),
  200414. INTERNET_OPEN_TYPE_PRECONFIG,
  200415. 0, 0, 0);
  200416. if (sessionHandle != 0)
  200417. {
  200418. // break up the url..
  200419. TCHAR file[1024], server[1024];
  200420. URL_COMPONENTS uc;
  200421. zerostruct (uc);
  200422. uc.dwStructSize = sizeof (uc);
  200423. uc.dwUrlPathLength = sizeof (file);
  200424. uc.dwHostNameLength = sizeof (server);
  200425. uc.lpszUrlPath = file;
  200426. uc.lpszHostName = server;
  200427. if (InternetCrackUrl (url, 0, 0, &uc))
  200428. {
  200429. if (timeOutMs == 0)
  200430. timeOutMs = 30000;
  200431. else if (timeOutMs < 0)
  200432. timeOutMs = -1;
  200433. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  200434. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  200435. HINTERNET connection = InternetConnect (sessionHandle,
  200436. uc.lpszHostName,
  200437. uc.nPort,
  200438. _T(""), _T(""),
  200439. isFtp ? INTERNET_SERVICE_FTP
  200440. : INTERNET_SERVICE_HTTP,
  200441. 0, 0);
  200442. if (connection != 0)
  200443. {
  200444. if (isFtp)
  200445. {
  200446. HINTERNET request = FtpOpenFile (connection,
  200447. uc.lpszUrlPath,
  200448. GENERIC_READ,
  200449. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  200450. 0);
  200451. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  200452. result->connection = connection;
  200453. result->request = request;
  200454. return result;
  200455. }
  200456. else
  200457. {
  200458. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  200459. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  200460. if (url.startsWithIgnoreCase (T("https:")))
  200461. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  200462. // IE7 seems to automatically work out when it's https)
  200463. HINTERNET request = HttpOpenRequest (connection,
  200464. isPost ? _T("POST")
  200465. : _T("GET"),
  200466. uc.lpszUrlPath,
  200467. 0, 0, mimeTypes, flags, 0);
  200468. if (request != 0)
  200469. {
  200470. INTERNET_BUFFERS buffers;
  200471. zerostruct (buffers);
  200472. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  200473. buffers.lpcszHeader = (LPCTSTR) headers;
  200474. buffers.dwHeadersLength = headers.length();
  200475. buffers.dwBufferTotal = (DWORD) postData.getSize();
  200476. ConnectionAndRequestStruct* result = 0;
  200477. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  200478. {
  200479. int bytesSent = 0;
  200480. for (;;)
  200481. {
  200482. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  200483. DWORD bytesDone = 0;
  200484. if (bytesToDo > 0
  200485. && ! InternetWriteFile (request,
  200486. ((const char*) postData.getData()) + bytesSent,
  200487. bytesToDo, &bytesDone))
  200488. {
  200489. break;
  200490. }
  200491. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  200492. {
  200493. result = new ConnectionAndRequestStruct();
  200494. result->connection = connection;
  200495. result->request = request;
  200496. HttpEndRequest (request, 0, 0, 0);
  200497. return result;
  200498. }
  200499. bytesSent += bytesDone;
  200500. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  200501. break;
  200502. }
  200503. }
  200504. InternetCloseHandle (request);
  200505. }
  200506. InternetCloseHandle (connection);
  200507. }
  200508. }
  200509. }
  200510. }
  200511. return 0;
  200512. }
  200513. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  200514. {
  200515. DWORD bytesRead = 0;
  200516. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200517. if (crs != 0)
  200518. InternetReadFile (crs->request,
  200519. buffer, bytesToRead,
  200520. &bytesRead);
  200521. return bytesRead;
  200522. }
  200523. int juce_seekInInternetFile (void* handle, int newPosition)
  200524. {
  200525. if (handle != 0)
  200526. {
  200527. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200528. return InternetSetFilePointer (crs->request,
  200529. newPosition, 0,
  200530. FILE_BEGIN, 0);
  200531. }
  200532. else
  200533. {
  200534. return -1;
  200535. }
  200536. }
  200537. int64 juce_getInternetFileContentLength (void* handle)
  200538. {
  200539. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200540. if (crs != 0)
  200541. {
  200542. DWORD index = 0;
  200543. DWORD result = 0;
  200544. DWORD size = sizeof (result);
  200545. if (HttpQueryInfo (crs->request,
  200546. HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  200547. &result,
  200548. &size,
  200549. &index))
  200550. {
  200551. return (int64) result;
  200552. }
  200553. }
  200554. return -1;
  200555. }
  200556. void juce_closeInternetFile (void* handle)
  200557. {
  200558. if (handle != 0)
  200559. {
  200560. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  200561. InternetCloseHandle (crs->request);
  200562. InternetCloseHandle (crs->connection);
  200563. delete crs;
  200564. }
  200565. }
  200566. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  200567. {
  200568. int numFound = 0;
  200569. DynamicLibraryLoader dll ("iphlpapi.dll");
  200570. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  200571. if (getAdaptersInfo != 0)
  200572. {
  200573. ULONG len = sizeof (IP_ADAPTER_INFO);
  200574. MemoryBlock mb;
  200575. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200576. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  200577. {
  200578. mb.setSize (len);
  200579. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200580. }
  200581. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  200582. {
  200583. PIP_ADAPTER_INFO adapter = adapterInfo;
  200584. while (adapter != 0)
  200585. {
  200586. int64 mac = 0;
  200587. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  200588. mac = (mac << 8) | adapter->Address[i];
  200589. if (littleEndian)
  200590. mac = (int64) swapByteOrder ((uint64) mac);
  200591. if (numFound < maxNum && mac != 0)
  200592. addresses [numFound++] = mac;
  200593. adapter = adapter->Next;
  200594. }
  200595. }
  200596. }
  200597. return numFound;
  200598. }
  200599. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  200600. {
  200601. int numFound = 0;
  200602. DynamicLibraryLoader dll ("netapi32.dll");
  200603. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  200604. if (NetbiosCall != 0)
  200605. {
  200606. NCB ncb;
  200607. zerostruct (ncb);
  200608. typedef struct _ASTAT_
  200609. {
  200610. ADAPTER_STATUS adapt;
  200611. NAME_BUFFER NameBuff [30];
  200612. } ASTAT;
  200613. ASTAT astat;
  200614. zerostruct (astat);
  200615. LANA_ENUM enums;
  200616. zerostruct (enums);
  200617. ncb.ncb_command = NCBENUM;
  200618. ncb.ncb_buffer = (unsigned char*) &enums;
  200619. ncb.ncb_length = sizeof (LANA_ENUM);
  200620. NetbiosCall (&ncb);
  200621. for (int i = 0; i < enums.length; ++i)
  200622. {
  200623. zerostruct (ncb);
  200624. ncb.ncb_command = NCBRESET;
  200625. ncb.ncb_lana_num = enums.lana[i];
  200626. if (NetbiosCall (&ncb) == 0)
  200627. {
  200628. zerostruct (ncb);
  200629. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  200630. ncb.ncb_command = NCBASTAT;
  200631. ncb.ncb_lana_num = enums.lana[i];
  200632. ncb.ncb_buffer = (unsigned char*) &astat;
  200633. ncb.ncb_length = sizeof (ASTAT);
  200634. if (NetbiosCall (&ncb) == 0)
  200635. {
  200636. if (astat.adapt.adapter_type == 0xfe)
  200637. {
  200638. uint64 mac = 0;
  200639. for (int i = 6; --i >= 0;)
  200640. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  200641. if (numFound < maxNum && mac != 0)
  200642. addresses [numFound++] = mac;
  200643. }
  200644. }
  200645. }
  200646. }
  200647. }
  200648. return numFound;
  200649. }
  200650. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  200651. {
  200652. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  200653. if (numFound == 0)
  200654. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  200655. return numFound;
  200656. }
  200657. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  200658. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  200659. const String& emailSubject,
  200660. const String& bodyText,
  200661. const StringArray& filesToAttach)
  200662. {
  200663. HMODULE h = LoadLibraryA ("MAPI32.dll");
  200664. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  200665. bool ok = false;
  200666. if (mapiSendMail != 0)
  200667. {
  200668. MapiMessage message;
  200669. zerostruct (message);
  200670. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  200671. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  200672. MapiRecipDesc recip;
  200673. zerostruct (recip);
  200674. recip.ulRecipClass = MAPI_TO;
  200675. String targetEmailAddress_ (targetEmailAddress);
  200676. if (targetEmailAddress_.isEmpty())
  200677. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  200678. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress_;
  200679. message.nRecipCount = 1;
  200680. message.lpRecips = &recip;
  200681. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  200682. mb.fillWith (0);
  200683. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  200684. message.nFileCount = filesToAttach.size();
  200685. message.lpFiles = files;
  200686. for (int i = 0; i < filesToAttach.size(); ++i)
  200687. {
  200688. files[i].nPosition = (ULONG) -1;
  200689. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  200690. }
  200691. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  200692. }
  200693. FreeLibrary (h);
  200694. return ok;
  200695. }
  200696. #endif
  200697. /********* End of inlined file: juce_win32_Network.cpp *********/
  200698. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  200699. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200700. // compiled on its own).
  200701. #if JUCE_INCLUDED_FILE
  200702. static HKEY findKeyForPath (String name,
  200703. const bool createForWriting,
  200704. String& valueName) throw()
  200705. {
  200706. HKEY rootKey = 0;
  200707. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  200708. rootKey = HKEY_CURRENT_USER;
  200709. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  200710. rootKey = HKEY_LOCAL_MACHINE;
  200711. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  200712. rootKey = HKEY_CLASSES_ROOT;
  200713. if (rootKey != 0)
  200714. {
  200715. name = name.substring (name.indexOfChar (T('\\')) + 1);
  200716. const int lastSlash = name.lastIndexOfChar (T('\\'));
  200717. valueName = name.substring (lastSlash + 1);
  200718. name = name.substring (0, lastSlash);
  200719. HKEY key;
  200720. DWORD result;
  200721. if (createForWriting)
  200722. {
  200723. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  200724. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  200725. return key;
  200726. }
  200727. else
  200728. {
  200729. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  200730. return key;
  200731. }
  200732. }
  200733. return 0;
  200734. }
  200735. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  200736. const String& defaultValue)
  200737. {
  200738. String valueName, s;
  200739. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200740. if (k != 0)
  200741. {
  200742. WCHAR buffer [2048];
  200743. unsigned long bufferSize = sizeof (buffer);
  200744. DWORD type = REG_SZ;
  200745. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  200746. s = buffer;
  200747. else
  200748. s = defaultValue;
  200749. RegCloseKey (k);
  200750. }
  200751. return s;
  200752. }
  200753. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  200754. const String& value)
  200755. {
  200756. String valueName;
  200757. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200758. if (k != 0)
  200759. {
  200760. RegSetValueEx (k, valueName, 0, REG_SZ,
  200761. (const BYTE*) (const WCHAR*) value,
  200762. sizeof (WCHAR) * (value.length() + 1));
  200763. RegCloseKey (k);
  200764. }
  200765. }
  200766. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  200767. {
  200768. bool exists = false;
  200769. String valueName;
  200770. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200771. if (k != 0)
  200772. {
  200773. unsigned char buffer [2048];
  200774. unsigned long bufferSize = sizeof (buffer);
  200775. DWORD type = 0;
  200776. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  200777. exists = true;
  200778. RegCloseKey (k);
  200779. }
  200780. return exists;
  200781. }
  200782. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  200783. {
  200784. String valueName;
  200785. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200786. if (k != 0)
  200787. {
  200788. RegDeleteValue (k, valueName);
  200789. RegCloseKey (k);
  200790. }
  200791. }
  200792. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  200793. {
  200794. String valueName;
  200795. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  200796. if (k != 0)
  200797. {
  200798. RegDeleteKey (k, valueName);
  200799. RegCloseKey (k);
  200800. }
  200801. }
  200802. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  200803. const String& symbolicDescription,
  200804. const String& fullDescription,
  200805. const File& targetExecutable,
  200806. int iconResourceNumber)
  200807. {
  200808. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  200809. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  200810. if (iconResourceNumber != 0)
  200811. setRegistryValue (key + "\\DefaultIcon\\",
  200812. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  200813. setRegistryValue (key + "\\", fullDescription);
  200814. setRegistryValue (key + "\\shell\\open\\command\\",
  200815. targetExecutable.getFullPathName() + " %1");
  200816. }
  200817. bool juce_IsRunningInWine() throw()
  200818. {
  200819. HKEY key;
  200820. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  200821. {
  200822. RegCloseKey (key);
  200823. return true;
  200824. }
  200825. return false;
  200826. }
  200827. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  200828. {
  200829. String s (::GetCommandLineW());
  200830. StringArray tokens;
  200831. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  200832. return tokens.joinIntoString (T(" "), 1);
  200833. }
  200834. static void* currentModuleHandle = 0;
  200835. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  200836. {
  200837. if (currentModuleHandle == 0)
  200838. currentModuleHandle = GetModuleHandle (0);
  200839. return currentModuleHandle;
  200840. }
  200841. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  200842. {
  200843. currentModuleHandle = newHandle;
  200844. }
  200845. void PlatformUtilities::fpuReset()
  200846. {
  200847. #if JUCE_MSVC
  200848. _clearfp();
  200849. #endif
  200850. }
  200851. void PlatformUtilities::beep()
  200852. {
  200853. MessageBeep (MB_OK);
  200854. }
  200855. #endif
  200856. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  200857. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200858. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  200859. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200860. // compiled on its own).
  200861. #if JUCE_INCLUDED_FILE
  200862. static const unsigned int specialId = WM_APP + 0x4400;
  200863. static const unsigned int broadcastId = WM_APP + 0x4403;
  200864. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  200865. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  200866. HWND juce_messageWindowHandle = 0;
  200867. extern long improbableWindowNumber; // defined in windowing.cpp
  200868. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  200869. const UINT message,
  200870. const WPARAM wParam,
  200871. const LPARAM lParam) throw()
  200872. {
  200873. JUCE_TRY
  200874. {
  200875. if (h == juce_messageWindowHandle)
  200876. {
  200877. if (message == specialCallbackId)
  200878. {
  200879. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  200880. return (LRESULT) (*func) ((void*) lParam);
  200881. }
  200882. else if (message == specialId)
  200883. {
  200884. // these are trapped early in the dispatch call, but must also be checked
  200885. // here in case there are windows modal dialog boxes doing their own
  200886. // dispatch loop and not calling our version
  200887. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  200888. return 0;
  200889. }
  200890. else if (message == broadcastId)
  200891. {
  200892. String* const messageString = (String*) lParam;
  200893. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  200894. delete messageString;
  200895. return 0;
  200896. }
  200897. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  200898. {
  200899. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  200900. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  200901. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  200902. return 0;
  200903. }
  200904. }
  200905. }
  200906. JUCE_CATCH_EXCEPTION
  200907. return DefWindowProc (h, message, wParam, lParam);
  200908. }
  200909. static bool isEventBlockedByModalComps (MSG& m)
  200910. {
  200911. if (Component::getNumCurrentlyModalComponents() == 0
  200912. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  200913. return false;
  200914. switch (m.message)
  200915. {
  200916. case WM_MOUSEMOVE:
  200917. case WM_NCMOUSEMOVE:
  200918. case 0x020A: /* WM_MOUSEWHEEL */
  200919. case 0x020E: /* WM_MOUSEHWHEEL */
  200920. case WM_KEYUP:
  200921. case WM_SYSKEYUP:
  200922. case WM_CHAR:
  200923. case WM_APPCOMMAND:
  200924. case WM_LBUTTONUP:
  200925. case WM_MBUTTONUP:
  200926. case WM_RBUTTONUP:
  200927. case WM_MOUSEACTIVATE:
  200928. case WM_NCMOUSEHOVER:
  200929. case WM_MOUSEHOVER:
  200930. return true;
  200931. case WM_NCLBUTTONDOWN:
  200932. case WM_NCLBUTTONDBLCLK:
  200933. case WM_NCRBUTTONDOWN:
  200934. case WM_NCRBUTTONDBLCLK:
  200935. case WM_NCMBUTTONDOWN:
  200936. case WM_NCMBUTTONDBLCLK:
  200937. case WM_LBUTTONDOWN:
  200938. case WM_LBUTTONDBLCLK:
  200939. case WM_MBUTTONDOWN:
  200940. case WM_MBUTTONDBLCLK:
  200941. case WM_RBUTTONDOWN:
  200942. case WM_RBUTTONDBLCLK:
  200943. case WM_KEYDOWN:
  200944. case WM_SYSKEYDOWN:
  200945. {
  200946. Component* const modal = Component::getCurrentlyModalComponent (0);
  200947. if (modal != 0)
  200948. modal->inputAttemptWhenModal();
  200949. return true;
  200950. }
  200951. default:
  200952. break;
  200953. }
  200954. return false;
  200955. }
  200956. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  200957. {
  200958. MSG m;
  200959. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  200960. return false;
  200961. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  200962. {
  200963. if (m.message == specialId
  200964. && m.hwnd == juce_messageWindowHandle)
  200965. {
  200966. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  200967. }
  200968. else if (! isEventBlockedByModalComps (m))
  200969. {
  200970. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  200971. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  200972. {
  200973. // if it's someone else's window being clicked on, and the focus is
  200974. // currently on a juce window, pass the kb focus over..
  200975. HWND currentFocus = GetFocus();
  200976. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  200977. SetFocus (m.hwnd);
  200978. }
  200979. TranslateMessage (&m);
  200980. DispatchMessage (&m);
  200981. }
  200982. }
  200983. return true;
  200984. }
  200985. bool juce_postMessageToSystemQueue (void* message)
  200986. {
  200987. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  200988. }
  200989. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  200990. void* userData)
  200991. {
  200992. if (MessageManager::getInstance()->isThisTheMessageThread())
  200993. {
  200994. return (*callback) (userData);
  200995. }
  200996. else
  200997. {
  200998. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  200999. // deadlock because the message manager is blocked from running, and can't
  201000. // call your function..
  201001. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  201002. return (void*) SendMessage (juce_messageWindowHandle,
  201003. specialCallbackId,
  201004. (WPARAM) callback,
  201005. (LPARAM) userData);
  201006. }
  201007. }
  201008. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  201009. {
  201010. if (hwnd != juce_messageWindowHandle)
  201011. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  201012. return TRUE;
  201013. }
  201014. void MessageManager::broadcastMessage (const String& value) throw()
  201015. {
  201016. VoidArray windows;
  201017. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  201018. const String localCopy (value);
  201019. COPYDATASTRUCT data;
  201020. data.dwData = broadcastId;
  201021. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  201022. data.lpData = (void*) (const juce_wchar*) localCopy;
  201023. for (int i = windows.size(); --i >= 0;)
  201024. {
  201025. HWND hwnd = (HWND) windows.getUnchecked(i);
  201026. TCHAR windowName [64]; // no need to read longer strings than this
  201027. GetWindowText (hwnd, windowName, 64);
  201028. windowName [63] = 0;
  201029. if (String (windowName) == String (messageWindowName))
  201030. {
  201031. DWORD_PTR result;
  201032. SendMessageTimeout (hwnd, WM_COPYDATA,
  201033. (WPARAM) juce_messageWindowHandle,
  201034. (LPARAM) &data,
  201035. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  201036. 8000,
  201037. &result);
  201038. }
  201039. }
  201040. }
  201041. static const String getMessageWindowClassName()
  201042. {
  201043. // this name has to be different for each app/dll instance because otherwise
  201044. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201045. // window class).
  201046. static int number = 0;
  201047. if (number == 0)
  201048. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  201049. return T("JUCEcs_") + String (number);
  201050. }
  201051. void MessageManager::doPlatformSpecificInitialisation()
  201052. {
  201053. OleInitialize (0);
  201054. const String className (getMessageWindowClassName());
  201055. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201056. WNDCLASSEX wc;
  201057. zerostruct (wc);
  201058. wc.cbSize = sizeof (wc);
  201059. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  201060. wc.cbWndExtra = 4;
  201061. wc.hInstance = hmod;
  201062. wc.lpszClassName = className;
  201063. RegisterClassEx (&wc);
  201064. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  201065. messageWindowName,
  201066. 0, 0, 0, 0, 0, 0, 0,
  201067. hmod, 0);
  201068. }
  201069. void MessageManager::doPlatformSpecificShutdown()
  201070. {
  201071. DestroyWindow (juce_messageWindowHandle);
  201072. UnregisterClass (getMessageWindowClassName(), 0);
  201073. OleUninitialize();
  201074. }
  201075. #endif
  201076. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  201077. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  201078. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  201079. // compiled on its own).
  201080. #if JUCE_INCLUDED_FILE
  201081. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  201082. // these are in the windows SDK, but need to be repeated here for GCC..
  201083. #ifndef GET_APPCOMMAND_LPARAM
  201084. #define FAPPCOMMAND_MASK 0xF000
  201085. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  201086. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  201087. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  201088. #define APPCOMMAND_MEDIA_STOP 13
  201089. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  201090. #define WM_APPCOMMAND 0x0319
  201091. #endif
  201092. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  201093. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  201094. extern bool juce_IsRunningInWine() throw();
  201095. #ifndef ULW_ALPHA
  201096. #define ULW_ALPHA 0x00000002
  201097. #endif
  201098. #ifndef AC_SRC_ALPHA
  201099. #define AC_SRC_ALPHA 0x01
  201100. #endif
  201101. #define DEBUG_REPAINT_TIMES 0
  201102. static HPALETTE palette = 0;
  201103. static bool createPaletteIfNeeded = true;
  201104. static bool shouldDeactivateTitleBar = true;
  201105. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  201106. #define WM_TRAYNOTIFY WM_USER + 100
  201107. using ::abs;
  201108. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  201109. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  201110. bool Desktop::canUseSemiTransparentWindows() throw()
  201111. {
  201112. if (updateLayeredWindow == 0)
  201113. {
  201114. if (! juce_IsRunningInWine())
  201115. {
  201116. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  201117. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  201118. }
  201119. }
  201120. return updateLayeredWindow != 0;
  201121. }
  201122. #undef DefWindowProc
  201123. #define DefWindowProc DefWindowProcW
  201124. const int extendedKeyModifier = 0x10000;
  201125. const int KeyPress::spaceKey = VK_SPACE;
  201126. const int KeyPress::returnKey = VK_RETURN;
  201127. const int KeyPress::escapeKey = VK_ESCAPE;
  201128. const int KeyPress::backspaceKey = VK_BACK;
  201129. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  201130. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  201131. const int KeyPress::tabKey = VK_TAB;
  201132. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  201133. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  201134. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  201135. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  201136. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  201137. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  201138. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  201139. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  201140. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  201141. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  201142. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  201143. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  201144. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  201145. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  201146. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  201147. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  201148. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  201149. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  201150. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  201151. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  201152. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  201153. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  201154. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  201155. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  201156. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  201157. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  201158. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  201159. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  201160. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  201161. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  201162. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  201163. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  201164. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  201165. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  201166. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  201167. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  201168. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  201169. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  201170. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  201171. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  201172. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  201173. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  201174. const int KeyPress::playKey = 0x30000;
  201175. const int KeyPress::stopKey = 0x30001;
  201176. const int KeyPress::fastForwardKey = 0x30002;
  201177. const int KeyPress::rewindKey = 0x30003;
  201178. class WindowsBitmapImage : public Image
  201179. {
  201180. public:
  201181. HBITMAP hBitmap;
  201182. BITMAPV4HEADER bitmapInfo;
  201183. HDC hdc;
  201184. unsigned char* bitmapData;
  201185. WindowsBitmapImage (const PixelFormat format_,
  201186. const int w, const int h, const bool clearImage)
  201187. : Image (format_, w, h)
  201188. {
  201189. jassert (format_ == RGB || format_ == ARGB);
  201190. pixelStride = (format_ == RGB) ? 3 : 4;
  201191. zerostruct (bitmapInfo);
  201192. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  201193. bitmapInfo.bV4Width = w;
  201194. bitmapInfo.bV4Height = h;
  201195. bitmapInfo.bV4Planes = 1;
  201196. bitmapInfo.bV4CSType = 1;
  201197. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  201198. if (format_ == ARGB)
  201199. {
  201200. bitmapInfo.bV4AlphaMask = 0xff000000;
  201201. bitmapInfo.bV4RedMask = 0xff0000;
  201202. bitmapInfo.bV4GreenMask = 0xff00;
  201203. bitmapInfo.bV4BlueMask = 0xff;
  201204. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  201205. }
  201206. else
  201207. {
  201208. bitmapInfo.bV4V4Compression = BI_RGB;
  201209. }
  201210. lineStride = -((w * pixelStride + 3) & ~3);
  201211. HDC dc = GetDC (0);
  201212. hdc = CreateCompatibleDC (dc);
  201213. ReleaseDC (0, dc);
  201214. SetMapMode (hdc, MM_TEXT);
  201215. hBitmap = CreateDIBSection (hdc,
  201216. (BITMAPINFO*) &(bitmapInfo),
  201217. DIB_RGB_COLORS,
  201218. (void**) &bitmapData,
  201219. 0, 0);
  201220. SelectObject (hdc, hBitmap);
  201221. if (format_ == ARGB && clearImage)
  201222. zeromem (bitmapData, abs (h * lineStride));
  201223. imageData = bitmapData - (lineStride * (h - 1));
  201224. }
  201225. ~WindowsBitmapImage()
  201226. {
  201227. DeleteDC (hdc);
  201228. DeleteObject (hBitmap);
  201229. imageData = 0; // to stop the base class freeing this
  201230. }
  201231. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  201232. const int x, const int y,
  201233. const RectangleList& maskedRegion) throw()
  201234. {
  201235. static HDRAWDIB hdd = 0;
  201236. static bool needToCreateDrawDib = true;
  201237. if (needToCreateDrawDib)
  201238. {
  201239. needToCreateDrawDib = false;
  201240. HDC dc = GetDC (0);
  201241. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201242. ReleaseDC (0, dc);
  201243. // only open if we're not palettised
  201244. if (n > 8)
  201245. hdd = DrawDibOpen();
  201246. }
  201247. if (createPaletteIfNeeded)
  201248. {
  201249. HDC dc = GetDC (0);
  201250. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201251. ReleaseDC (0, dc);
  201252. if (n <= 8)
  201253. palette = CreateHalftonePalette (dc);
  201254. createPaletteIfNeeded = false;
  201255. }
  201256. if (palette != 0)
  201257. {
  201258. SelectPalette (dc, palette, FALSE);
  201259. RealizePalette (dc);
  201260. SetStretchBltMode (dc, HALFTONE);
  201261. }
  201262. SetMapMode (dc, MM_TEXT);
  201263. if (transparent)
  201264. {
  201265. POINT p, pos;
  201266. SIZE size;
  201267. RECT windowBounds;
  201268. GetWindowRect (hwnd, &windowBounds);
  201269. p.x = -x;
  201270. p.y = -y;
  201271. pos.x = windowBounds.left;
  201272. pos.y = windowBounds.top;
  201273. size.cx = windowBounds.right - windowBounds.left;
  201274. size.cy = windowBounds.bottom - windowBounds.top;
  201275. BLENDFUNCTION bf;
  201276. bf.AlphaFormat = AC_SRC_ALPHA;
  201277. bf.BlendFlags = 0;
  201278. bf.BlendOp = AC_SRC_OVER;
  201279. bf.SourceConstantAlpha = 0xff;
  201280. if (! maskedRegion.isEmpty())
  201281. {
  201282. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201283. {
  201284. const Rectangle& r = *i.getRectangle();
  201285. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201286. }
  201287. }
  201288. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  201289. }
  201290. else
  201291. {
  201292. int savedDC = 0;
  201293. if (! maskedRegion.isEmpty())
  201294. {
  201295. savedDC = SaveDC (dc);
  201296. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201297. {
  201298. const Rectangle& r = *i.getRectangle();
  201299. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201300. }
  201301. }
  201302. const int w = getWidth();
  201303. const int h = getHeight();
  201304. if (hdd == 0)
  201305. {
  201306. StretchDIBits (dc,
  201307. x, y, w, h,
  201308. 0, 0, w, h,
  201309. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  201310. DIB_RGB_COLORS, SRCCOPY);
  201311. }
  201312. else
  201313. {
  201314. DrawDibDraw (hdd, dc, x, y, -1, -1,
  201315. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  201316. 0, 0, w, h, 0);
  201317. }
  201318. if (! maskedRegion.isEmpty())
  201319. RestoreDC (dc, savedDC);
  201320. }
  201321. }
  201322. juce_UseDebuggingNewOperator
  201323. private:
  201324. WindowsBitmapImage (const WindowsBitmapImage&);
  201325. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  201326. };
  201327. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  201328. static int currentModifiers = 0;
  201329. static int modifiersAtLastCallback = 0;
  201330. static void updateKeyModifiers() throw()
  201331. {
  201332. currentModifiers &= ~(ModifierKeys::shiftModifier
  201333. | ModifierKeys::ctrlModifier
  201334. | ModifierKeys::altModifier);
  201335. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  201336. currentModifiers |= ModifierKeys::shiftModifier;
  201337. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  201338. currentModifiers |= ModifierKeys::ctrlModifier;
  201339. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  201340. currentModifiers |= ModifierKeys::altModifier;
  201341. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  201342. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  201343. }
  201344. void ModifierKeys::updateCurrentModifiers() throw()
  201345. {
  201346. currentModifierFlags = currentModifiers;
  201347. }
  201348. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  201349. {
  201350. SHORT k = (SHORT) keyCode;
  201351. if ((keyCode & extendedKeyModifier) == 0
  201352. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  201353. k += (SHORT) T('A') - (SHORT) T('a');
  201354. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  201355. (SHORT) '+', VK_OEM_PLUS,
  201356. (SHORT) '-', VK_OEM_MINUS,
  201357. (SHORT) '.', VK_OEM_PERIOD,
  201358. (SHORT) ';', VK_OEM_1,
  201359. (SHORT) ':', VK_OEM_1,
  201360. (SHORT) '/', VK_OEM_2,
  201361. (SHORT) '?', VK_OEM_2,
  201362. (SHORT) '[', VK_OEM_4,
  201363. (SHORT) ']', VK_OEM_6 };
  201364. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  201365. if (k == translatedValues [i])
  201366. k = translatedValues [i + 1];
  201367. return (GetKeyState (k) & 0x8000) != 0;
  201368. }
  201369. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  201370. {
  201371. updateKeyModifiers();
  201372. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201373. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  201374. currentModifiers |= ModifierKeys::leftButtonModifier;
  201375. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  201376. currentModifiers |= ModifierKeys::rightButtonModifier;
  201377. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  201378. currentModifiers |= ModifierKeys::middleButtonModifier;
  201379. return ModifierKeys (currentModifiers);
  201380. }
  201381. static int64 getMouseEventTime() throw()
  201382. {
  201383. static int64 eventTimeOffset = 0;
  201384. static DWORD lastMessageTime = 0;
  201385. const DWORD thisMessageTime = GetMessageTime();
  201386. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  201387. {
  201388. lastMessageTime = thisMessageTime;
  201389. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  201390. }
  201391. return eventTimeOffset + thisMessageTime;
  201392. }
  201393. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  201394. {
  201395. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  201396. return callback (userData);
  201397. else
  201398. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  201399. }
  201400. class Win32ComponentPeer : public ComponentPeer
  201401. {
  201402. public:
  201403. Win32ComponentPeer (Component* const component,
  201404. const int windowStyleFlags)
  201405. : ComponentPeer (component, windowStyleFlags),
  201406. dontRepaint (false),
  201407. fullScreen (false),
  201408. isDragging (false),
  201409. isMouseOver (false),
  201410. hasCreatedCaret (false),
  201411. currentWindowIcon (0),
  201412. taskBarIcon (0),
  201413. dropTarget (0)
  201414. {
  201415. callFunctionIfNotLocked (&createWindowCallback, (void*) this);
  201416. setTitle (component->getName());
  201417. if ((windowStyleFlags & windowHasDropShadow) != 0
  201418. && Desktop::canUseSemiTransparentWindows())
  201419. {
  201420. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  201421. if (shadower != 0)
  201422. shadower->setOwner (component);
  201423. }
  201424. else
  201425. {
  201426. shadower = 0;
  201427. }
  201428. }
  201429. ~Win32ComponentPeer()
  201430. {
  201431. setTaskBarIcon (0);
  201432. deleteAndZero (shadower);
  201433. // do this before the next bit to avoid messages arriving for this window
  201434. // before it's destroyed
  201435. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  201436. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  201437. if (currentWindowIcon != 0)
  201438. DestroyIcon (currentWindowIcon);
  201439. if (dropTarget != 0)
  201440. {
  201441. dropTarget->Release();
  201442. dropTarget = 0;
  201443. }
  201444. }
  201445. void* getNativeHandle() const
  201446. {
  201447. return (void*) hwnd;
  201448. }
  201449. void setVisible (bool shouldBeVisible)
  201450. {
  201451. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  201452. if (shouldBeVisible)
  201453. InvalidateRect (hwnd, 0, 0);
  201454. else
  201455. lastPaintTime = 0;
  201456. }
  201457. void setTitle (const String& title)
  201458. {
  201459. SetWindowText (hwnd, title);
  201460. }
  201461. void setPosition (int x, int y)
  201462. {
  201463. offsetWithinParent (x, y);
  201464. SetWindowPos (hwnd, 0,
  201465. x - windowBorder.getLeft(),
  201466. y - windowBorder.getTop(),
  201467. 0, 0,
  201468. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201469. }
  201470. void repaintNowIfTransparent()
  201471. {
  201472. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  201473. handlePaintMessage();
  201474. }
  201475. void updateBorderSize()
  201476. {
  201477. WINDOWINFO info;
  201478. info.cbSize = sizeof (info);
  201479. if (GetWindowInfo (hwnd, &info))
  201480. {
  201481. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  201482. info.rcClient.left - info.rcWindow.left,
  201483. info.rcWindow.bottom - info.rcClient.bottom,
  201484. info.rcWindow.right - info.rcClient.right);
  201485. }
  201486. }
  201487. void setSize (int w, int h)
  201488. {
  201489. SetWindowPos (hwnd, 0, 0, 0,
  201490. w + windowBorder.getLeftAndRight(),
  201491. h + windowBorder.getTopAndBottom(),
  201492. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201493. updateBorderSize();
  201494. repaintNowIfTransparent();
  201495. }
  201496. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  201497. {
  201498. fullScreen = isNowFullScreen;
  201499. offsetWithinParent (x, y);
  201500. SetWindowPos (hwnd, 0,
  201501. x - windowBorder.getLeft(),
  201502. y - windowBorder.getTop(),
  201503. w + windowBorder.getLeftAndRight(),
  201504. h + windowBorder.getTopAndBottom(),
  201505. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201506. updateBorderSize();
  201507. repaintNowIfTransparent();
  201508. }
  201509. void getBounds (int& x, int& y, int& w, int& h) const
  201510. {
  201511. RECT r;
  201512. GetWindowRect (hwnd, &r);
  201513. x = r.left;
  201514. y = r.top;
  201515. w = r.right - x;
  201516. h = r.bottom - y;
  201517. HWND parentH = GetParent (hwnd);
  201518. if (parentH != 0)
  201519. {
  201520. GetWindowRect (parentH, &r);
  201521. x -= r.left;
  201522. y -= r.top;
  201523. }
  201524. x += windowBorder.getLeft();
  201525. y += windowBorder.getTop();
  201526. w -= windowBorder.getLeftAndRight();
  201527. h -= windowBorder.getTopAndBottom();
  201528. }
  201529. int getScreenX() const
  201530. {
  201531. RECT r;
  201532. GetWindowRect (hwnd, &r);
  201533. return r.left + windowBorder.getLeft();
  201534. }
  201535. int getScreenY() const
  201536. {
  201537. RECT r;
  201538. GetWindowRect (hwnd, &r);
  201539. return r.top + windowBorder.getTop();
  201540. }
  201541. void relativePositionToGlobal (int& x, int& y)
  201542. {
  201543. RECT r;
  201544. GetWindowRect (hwnd, &r);
  201545. x += r.left + windowBorder.getLeft();
  201546. y += r.top + windowBorder.getTop();
  201547. }
  201548. void globalPositionToRelative (int& x, int& y)
  201549. {
  201550. RECT r;
  201551. GetWindowRect (hwnd, &r);
  201552. x -= r.left + windowBorder.getLeft();
  201553. y -= r.top + windowBorder.getTop();
  201554. }
  201555. void setMinimised (bool shouldBeMinimised)
  201556. {
  201557. if (shouldBeMinimised != isMinimised())
  201558. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  201559. }
  201560. bool isMinimised() const
  201561. {
  201562. WINDOWPLACEMENT wp;
  201563. wp.length = sizeof (WINDOWPLACEMENT);
  201564. GetWindowPlacement (hwnd, &wp);
  201565. return wp.showCmd == SW_SHOWMINIMIZED;
  201566. }
  201567. void setFullScreen (bool shouldBeFullScreen)
  201568. {
  201569. setMinimised (false);
  201570. if (fullScreen != shouldBeFullScreen)
  201571. {
  201572. fullScreen = shouldBeFullScreen;
  201573. const ComponentDeletionWatcher deletionChecker (component);
  201574. if (! fullScreen)
  201575. {
  201576. const Rectangle boundsCopy (lastNonFullscreenBounds);
  201577. if (hasTitleBar())
  201578. ShowWindow (hwnd, SW_SHOWNORMAL);
  201579. if (! boundsCopy.isEmpty())
  201580. {
  201581. setBounds (boundsCopy.getX(),
  201582. boundsCopy.getY(),
  201583. boundsCopy.getWidth(),
  201584. boundsCopy.getHeight(),
  201585. false);
  201586. }
  201587. }
  201588. else
  201589. {
  201590. if (hasTitleBar())
  201591. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  201592. else
  201593. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  201594. }
  201595. if (! deletionChecker.hasBeenDeleted())
  201596. handleMovedOrResized();
  201597. }
  201598. }
  201599. bool isFullScreen() const
  201600. {
  201601. if (! hasTitleBar())
  201602. return fullScreen;
  201603. WINDOWPLACEMENT wp;
  201604. wp.length = sizeof (wp);
  201605. GetWindowPlacement (hwnd, &wp);
  201606. return wp.showCmd == SW_SHOWMAXIMIZED;
  201607. }
  201608. bool contains (int x, int y, bool trueIfInAChildWindow) const
  201609. {
  201610. RECT r;
  201611. GetWindowRect (hwnd, &r);
  201612. POINT p;
  201613. p.x = x + r.left + windowBorder.getLeft();
  201614. p.y = y + r.top + windowBorder.getTop();
  201615. HWND w = WindowFromPoint (p);
  201616. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  201617. }
  201618. const BorderSize getFrameSize() const
  201619. {
  201620. return windowBorder;
  201621. }
  201622. bool setAlwaysOnTop (bool alwaysOnTop)
  201623. {
  201624. const bool oldDeactivate = shouldDeactivateTitleBar;
  201625. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201626. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  201627. 0, 0, 0, 0,
  201628. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201629. shouldDeactivateTitleBar = oldDeactivate;
  201630. if (shadower != 0)
  201631. shadower->componentBroughtToFront (*component);
  201632. return true;
  201633. }
  201634. void toFront (bool makeActive)
  201635. {
  201636. setMinimised (false);
  201637. const bool oldDeactivate = shouldDeactivateTitleBar;
  201638. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201639. callFunctionIfNotLocked (makeActive ? &toFrontCallback1
  201640. : &toFrontCallback2,
  201641. (void*) hwnd);
  201642. shouldDeactivateTitleBar = oldDeactivate;
  201643. if (! makeActive)
  201644. {
  201645. // in this case a broughttofront call won't have occured, so do it now..
  201646. handleBroughtToFront();
  201647. }
  201648. }
  201649. void toBehind (ComponentPeer* other)
  201650. {
  201651. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  201652. jassert (otherPeer != 0); // wrong type of window?
  201653. if (otherPeer != 0)
  201654. {
  201655. setMinimised (false);
  201656. // must be careful not to try to put a topmost window behind a normal one, or win32
  201657. // promotes the normal one to be topmost!
  201658. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  201659. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  201660. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201661. else if (otherPeer->getComponent()->isAlwaysOnTop())
  201662. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  201663. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201664. }
  201665. }
  201666. bool isFocused() const
  201667. {
  201668. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  201669. }
  201670. void grabFocus()
  201671. {
  201672. const bool oldDeactivate = shouldDeactivateTitleBar;
  201673. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201674. callFunctionIfNotLocked (&setFocusCallback, (void*) hwnd);
  201675. shouldDeactivateTitleBar = oldDeactivate;
  201676. }
  201677. void textInputRequired (int /*x*/, int /*y*/)
  201678. {
  201679. if (! hasCreatedCaret)
  201680. {
  201681. hasCreatedCaret = true;
  201682. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  201683. }
  201684. ShowCaret (hwnd);
  201685. SetCaretPos (0, 0);
  201686. }
  201687. void repaint (int x, int y, int w, int h)
  201688. {
  201689. const RECT r = { x, y, x + w, y + h };
  201690. InvalidateRect (hwnd, &r, FALSE);
  201691. }
  201692. void performAnyPendingRepaintsNow()
  201693. {
  201694. MSG m;
  201695. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  201696. DispatchMessage (&m);
  201697. }
  201698. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  201699. {
  201700. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  201701. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  201702. return 0;
  201703. }
  201704. void setTaskBarIcon (const Image* const image)
  201705. {
  201706. if (image != 0)
  201707. {
  201708. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  201709. if (taskBarIcon == 0)
  201710. {
  201711. taskBarIcon = new NOTIFYICONDATA();
  201712. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  201713. taskBarIcon->hWnd = (HWND) hwnd;
  201714. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  201715. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  201716. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  201717. taskBarIcon->hIcon = hicon;
  201718. taskBarIcon->szTip[0] = 0;
  201719. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  201720. }
  201721. else
  201722. {
  201723. HICON oldIcon = taskBarIcon->hIcon;
  201724. taskBarIcon->hIcon = hicon;
  201725. taskBarIcon->uFlags = NIF_ICON;
  201726. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201727. DestroyIcon (oldIcon);
  201728. }
  201729. DestroyIcon (hicon);
  201730. }
  201731. else if (taskBarIcon != 0)
  201732. {
  201733. taskBarIcon->uFlags = 0;
  201734. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  201735. DestroyIcon (taskBarIcon->hIcon);
  201736. deleteAndZero (taskBarIcon);
  201737. }
  201738. }
  201739. void setTaskBarIconToolTip (const String& toolTip) const
  201740. {
  201741. if (taskBarIcon != 0)
  201742. {
  201743. taskBarIcon->uFlags = NIF_TIP;
  201744. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  201745. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201746. }
  201747. }
  201748. bool isInside (HWND h) const
  201749. {
  201750. return GetAncestor (hwnd, GA_ROOT) == h;
  201751. }
  201752. juce_UseDebuggingNewOperator
  201753. bool dontRepaint;
  201754. private:
  201755. HWND hwnd;
  201756. DropShadower* shadower;
  201757. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  201758. BorderSize windowBorder;
  201759. HICON currentWindowIcon;
  201760. NOTIFYICONDATA* taskBarIcon;
  201761. IDropTarget* dropTarget;
  201762. class TemporaryImage : public Timer
  201763. {
  201764. public:
  201765. TemporaryImage()
  201766. : image (0)
  201767. {
  201768. }
  201769. ~TemporaryImage()
  201770. {
  201771. delete image;
  201772. }
  201773. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  201774. {
  201775. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  201776. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  201777. {
  201778. delete image;
  201779. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  201780. }
  201781. startTimer (3000);
  201782. return image;
  201783. }
  201784. void timerCallback()
  201785. {
  201786. stopTimer();
  201787. deleteAndZero (image);
  201788. }
  201789. private:
  201790. WindowsBitmapImage* image;
  201791. TemporaryImage (const TemporaryImage&);
  201792. const TemporaryImage& operator= (const TemporaryImage&);
  201793. };
  201794. TemporaryImage offscreenImageGenerator;
  201795. class WindowClassHolder : public DeletedAtShutdown
  201796. {
  201797. public:
  201798. WindowClassHolder()
  201799. : windowClassName ("JUCE_")
  201800. {
  201801. // this name has to be different for each app/dll instance because otherwise
  201802. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201803. // window class).
  201804. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  201805. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201806. TCHAR moduleFile [1024];
  201807. moduleFile[0] = 0;
  201808. GetModuleFileName (moduleHandle, moduleFile, 1024);
  201809. WORD iconNum = 0;
  201810. WNDCLASSEX wcex;
  201811. wcex.cbSize = sizeof (wcex);
  201812. wcex.style = CS_OWNDC;
  201813. wcex.lpfnWndProc = (WNDPROC) windowProc;
  201814. wcex.lpszClassName = windowClassName;
  201815. wcex.cbClsExtra = 0;
  201816. wcex.cbWndExtra = 32;
  201817. wcex.hInstance = moduleHandle;
  201818. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201819. iconNum = 1;
  201820. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201821. wcex.hCursor = 0;
  201822. wcex.hbrBackground = 0;
  201823. wcex.lpszMenuName = 0;
  201824. RegisterClassEx (&wcex);
  201825. }
  201826. ~WindowClassHolder()
  201827. {
  201828. if (ComponentPeer::getNumPeers() == 0)
  201829. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  201830. clearSingletonInstance();
  201831. }
  201832. String windowClassName;
  201833. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  201834. };
  201835. static void* createWindowCallback (void* userData)
  201836. {
  201837. ((Win32ComponentPeer*) userData)->createWindow();
  201838. return 0;
  201839. }
  201840. void createWindow()
  201841. {
  201842. DWORD exstyle = WS_EX_ACCEPTFILES;
  201843. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  201844. if (hasTitleBar())
  201845. {
  201846. type |= WS_OVERLAPPED;
  201847. exstyle |= WS_EX_APPWINDOW;
  201848. if ((styleFlags & windowHasCloseButton) != 0)
  201849. {
  201850. type |= WS_SYSMENU;
  201851. }
  201852. else
  201853. {
  201854. // annoyingly, windows won't let you have a min/max button without a close button
  201855. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  201856. }
  201857. if ((styleFlags & windowIsResizable) != 0)
  201858. type |= WS_THICKFRAME;
  201859. }
  201860. else
  201861. {
  201862. type |= WS_POPUP | WS_SYSMENU;
  201863. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  201864. exstyle |= WS_EX_TOOLWINDOW;
  201865. else
  201866. exstyle |= WS_EX_APPWINDOW;
  201867. }
  201868. if ((styleFlags & windowHasMinimiseButton) != 0)
  201869. type |= WS_MINIMIZEBOX;
  201870. if ((styleFlags & windowHasMaximiseButton) != 0)
  201871. type |= WS_MAXIMIZEBOX;
  201872. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  201873. exstyle |= WS_EX_TRANSPARENT;
  201874. if ((styleFlags & windowIsSemiTransparent) != 0
  201875. && Desktop::canUseSemiTransparentWindows())
  201876. exstyle |= WS_EX_LAYERED;
  201877. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  201878. if (hwnd != 0)
  201879. {
  201880. SetWindowLongPtr (hwnd, 0, 0);
  201881. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  201882. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  201883. if (dropTarget == 0)
  201884. dropTarget = new JuceDropTarget (this);
  201885. RegisterDragDrop (hwnd, dropTarget);
  201886. updateBorderSize();
  201887. // Calling this function here is (for some reason) necessary to make Windows
  201888. // correctly enable the menu items that we specify in the wm_initmenu message.
  201889. GetSystemMenu (hwnd, false);
  201890. }
  201891. else
  201892. {
  201893. jassertfalse
  201894. }
  201895. }
  201896. static void* destroyWindowCallback (void* handle)
  201897. {
  201898. RevokeDragDrop ((HWND) handle);
  201899. DestroyWindow ((HWND) handle);
  201900. return 0;
  201901. }
  201902. static void* toFrontCallback1 (void* h)
  201903. {
  201904. SetForegroundWindow ((HWND) h);
  201905. return 0;
  201906. }
  201907. static void* toFrontCallback2 (void* h)
  201908. {
  201909. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201910. return 0;
  201911. }
  201912. static void* setFocusCallback (void* h)
  201913. {
  201914. SetFocus ((HWND) h);
  201915. return 0;
  201916. }
  201917. static void* getFocusCallback (void*)
  201918. {
  201919. return (void*) GetFocus();
  201920. }
  201921. void offsetWithinParent (int& x, int& y) const
  201922. {
  201923. if (isTransparent())
  201924. {
  201925. HWND parentHwnd = GetParent (hwnd);
  201926. if (parentHwnd != 0)
  201927. {
  201928. RECT parentRect;
  201929. GetWindowRect (parentHwnd, &parentRect);
  201930. x += parentRect.left;
  201931. y += parentRect.top;
  201932. }
  201933. }
  201934. }
  201935. bool isTransparent() const
  201936. {
  201937. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  201938. }
  201939. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  201940. void setIcon (const Image& newIcon)
  201941. {
  201942. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  201943. if (hicon != 0)
  201944. {
  201945. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  201946. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  201947. if (currentWindowIcon != 0)
  201948. DestroyIcon (currentWindowIcon);
  201949. currentWindowIcon = hicon;
  201950. }
  201951. }
  201952. void handlePaintMessage()
  201953. {
  201954. #if DEBUG_REPAINT_TIMES
  201955. const double paintStart = Time::getMillisecondCounterHiRes();
  201956. #endif
  201957. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  201958. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  201959. PAINTSTRUCT paintStruct;
  201960. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  201961. // message and become re-entrant, but that's OK
  201962. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  201963. // corrupt the image it's using to paint into, so do a check here.
  201964. static bool reentrant = false;
  201965. if (reentrant)
  201966. {
  201967. DeleteObject (rgn);
  201968. EndPaint (hwnd, &paintStruct);
  201969. return;
  201970. }
  201971. reentrant = true;
  201972. // this is the rectangle to update..
  201973. int x = paintStruct.rcPaint.left;
  201974. int y = paintStruct.rcPaint.top;
  201975. int w = paintStruct.rcPaint.right - x;
  201976. int h = paintStruct.rcPaint.bottom - y;
  201977. const bool transparent = isTransparent();
  201978. if (transparent)
  201979. {
  201980. // it's not possible to have a transparent window with a title bar at the moment!
  201981. jassert (! hasTitleBar());
  201982. RECT r;
  201983. GetWindowRect (hwnd, &r);
  201984. x = y = 0;
  201985. w = r.right - r.left;
  201986. h = r.bottom - r.top;
  201987. }
  201988. if (w > 0 && h > 0)
  201989. {
  201990. clearMaskedRegion();
  201991. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  201992. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  201993. RectangleList* const contextClip = context.getRawClipRegion();
  201994. contextClip->clear();
  201995. context.setOrigin (-x, -y);
  201996. bool needToPaintAll = true;
  201997. if (regionType == COMPLEXREGION && ! transparent)
  201998. {
  201999. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  202000. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  202001. DeleteObject (clipRgn);
  202002. char rgnData [8192];
  202003. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  202004. if (res > 0 && res <= sizeof (rgnData))
  202005. {
  202006. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  202007. if (hdr->iType == RDH_RECTANGLES
  202008. && hdr->rcBound.right - hdr->rcBound.left >= w
  202009. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  202010. {
  202011. needToPaintAll = false;
  202012. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  202013. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  202014. while (--num >= 0)
  202015. {
  202016. // (need to move this one pixel to the left because of a win32 bug)
  202017. const int cx = jmax (x, rects->left - 1);
  202018. const int cy = rects->top;
  202019. const int cw = rects->right - cx;
  202020. const int ch = rects->bottom - rects->top;
  202021. if (cx + cw - x <= w && cy + ch - y <= h)
  202022. {
  202023. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  202024. }
  202025. else
  202026. {
  202027. needToPaintAll = true;
  202028. break;
  202029. }
  202030. ++rects;
  202031. }
  202032. }
  202033. }
  202034. }
  202035. if (needToPaintAll)
  202036. {
  202037. contextClip->clear();
  202038. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  202039. }
  202040. if (transparent)
  202041. {
  202042. RectangleList::Iterator i (*contextClip);
  202043. while (i.next())
  202044. {
  202045. const Rectangle& r = *i.getRectangle();
  202046. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  202047. }
  202048. }
  202049. // if the component's not opaque, this won't draw properly unless the platform can support this
  202050. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  202051. updateCurrentModifiers();
  202052. handlePaint (context);
  202053. if (! dontRepaint)
  202054. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  202055. }
  202056. DeleteObject (rgn);
  202057. EndPaint (hwnd, &paintStruct);
  202058. reentrant = false;
  202059. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  202060. _fpreset(); // because some graphics cards can unmask FP exceptions
  202061. #endif
  202062. lastPaintTime = Time::getMillisecondCounter();
  202063. #if DEBUG_REPAINT_TIMES
  202064. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  202065. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  202066. #endif
  202067. }
  202068. void doMouseMove (const int x, const int y)
  202069. {
  202070. static uint32 lastMouseTime = 0;
  202071. // this can be set to throttle the mouse-messages to less than a
  202072. // certain number per second, as things can get unresponsive
  202073. // if each drag or move callback has to do a lot of work.
  202074. const int maxMouseMovesPerSecond = 60;
  202075. const int64 mouseEventTime = getMouseEventTime();
  202076. if (! isMouseOver)
  202077. {
  202078. isMouseOver = true;
  202079. TRACKMOUSEEVENT tme;
  202080. tme.cbSize = sizeof (tme);
  202081. tme.dwFlags = TME_LEAVE;
  202082. tme.hwndTrack = hwnd;
  202083. tme.dwHoverTime = 0;
  202084. if (! TrackMouseEvent (&tme))
  202085. {
  202086. jassertfalse;
  202087. }
  202088. updateKeyModifiers();
  202089. handleMouseEnter (x, y, mouseEventTime);
  202090. }
  202091. else if (! isDragging)
  202092. {
  202093. if (((unsigned int) x) < (unsigned int) component->getWidth()
  202094. && ((unsigned int) y) < (unsigned int) component->getHeight())
  202095. {
  202096. RECT r;
  202097. GetWindowRect (hwnd, &r);
  202098. POINT p;
  202099. p.x = x + r.left + windowBorder.getLeft();
  202100. p.y = y + r.top + windowBorder.getTop();
  202101. if (WindowFromPoint (p) == hwnd)
  202102. {
  202103. const uint32 now = Time::getMillisecondCounter();
  202104. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  202105. {
  202106. lastMouseTime = now;
  202107. handleMouseMove (x, y, mouseEventTime);
  202108. }
  202109. }
  202110. }
  202111. }
  202112. else
  202113. {
  202114. const uint32 now = Time::getMillisecondCounter();
  202115. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  202116. {
  202117. lastMouseTime = now;
  202118. handleMouseDrag (x, y, mouseEventTime);
  202119. }
  202120. }
  202121. }
  202122. void doMouseDown (const int x, const int y, const WPARAM wParam)
  202123. {
  202124. if (GetCapture() != hwnd)
  202125. SetCapture (hwnd);
  202126. doMouseMove (x, y);
  202127. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  202128. if ((wParam & MK_LBUTTON) != 0)
  202129. currentModifiers |= ModifierKeys::leftButtonModifier;
  202130. if ((wParam & MK_RBUTTON) != 0)
  202131. currentModifiers |= ModifierKeys::rightButtonModifier;
  202132. if ((wParam & MK_MBUTTON) != 0)
  202133. currentModifiers |= ModifierKeys::middleButtonModifier;
  202134. updateKeyModifiers();
  202135. isDragging = true;
  202136. handleMouseDown (x, y, getMouseEventTime());
  202137. }
  202138. void doMouseUp (const int x, const int y, const WPARAM wParam)
  202139. {
  202140. int numButtons = 0;
  202141. if ((wParam & MK_LBUTTON) != 0)
  202142. ++numButtons;
  202143. if ((wParam & MK_RBUTTON) != 0)
  202144. ++numButtons;
  202145. if ((wParam & MK_MBUTTON) != 0)
  202146. ++numButtons;
  202147. const int oldModifiers = currentModifiers;
  202148. // update the currentmodifiers only after the callback, so the callback
  202149. // knows which button was released.
  202150. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  202151. if ((wParam & MK_LBUTTON) != 0)
  202152. currentModifiers |= ModifierKeys::leftButtonModifier;
  202153. if ((wParam & MK_RBUTTON) != 0)
  202154. currentModifiers |= ModifierKeys::rightButtonModifier;
  202155. if ((wParam & MK_MBUTTON) != 0)
  202156. currentModifiers |= ModifierKeys::middleButtonModifier;
  202157. updateKeyModifiers();
  202158. isDragging = false;
  202159. // release the mouse capture if the user's not still got a button down
  202160. if (numButtons == 0 && hwnd == GetCapture())
  202161. ReleaseCapture();
  202162. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  202163. }
  202164. void doCaptureChanged()
  202165. {
  202166. if (isDragging)
  202167. {
  202168. RECT wr;
  202169. GetWindowRect (hwnd, &wr);
  202170. const DWORD mp = GetMessagePos();
  202171. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  202172. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  202173. (WPARAM) getMouseEventTime());
  202174. }
  202175. }
  202176. void doMouseExit()
  202177. {
  202178. if (isMouseOver)
  202179. {
  202180. isMouseOver = false;
  202181. RECT wr;
  202182. GetWindowRect (hwnd, &wr);
  202183. const DWORD mp = GetMessagePos();
  202184. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  202185. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  202186. getMouseEventTime());
  202187. }
  202188. }
  202189. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  202190. {
  202191. updateKeyModifiers();
  202192. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  202193. handleMouseWheel (isVertical ? 0 : amount,
  202194. isVertical ? amount : 0,
  202195. getMouseEventTime());
  202196. }
  202197. void sendModifierKeyChangeIfNeeded()
  202198. {
  202199. if (modifiersAtLastCallback != currentModifiers)
  202200. {
  202201. modifiersAtLastCallback = currentModifiers;
  202202. handleModifierKeysChange();
  202203. }
  202204. }
  202205. bool doKeyUp (const WPARAM key)
  202206. {
  202207. updateKeyModifiers();
  202208. switch (key)
  202209. {
  202210. case VK_SHIFT:
  202211. case VK_CONTROL:
  202212. case VK_MENU:
  202213. case VK_CAPITAL:
  202214. case VK_LWIN:
  202215. case VK_RWIN:
  202216. case VK_APPS:
  202217. case VK_NUMLOCK:
  202218. case VK_SCROLL:
  202219. case VK_LSHIFT:
  202220. case VK_RSHIFT:
  202221. case VK_LCONTROL:
  202222. case VK_LMENU:
  202223. case VK_RCONTROL:
  202224. case VK_RMENU:
  202225. sendModifierKeyChangeIfNeeded();
  202226. }
  202227. return handleKeyUpOrDown (false)
  202228. || Component::getCurrentlyModalComponent() != 0;
  202229. }
  202230. bool doKeyDown (const WPARAM key)
  202231. {
  202232. updateKeyModifiers();
  202233. bool used = false;
  202234. switch (key)
  202235. {
  202236. case VK_SHIFT:
  202237. case VK_LSHIFT:
  202238. case VK_RSHIFT:
  202239. case VK_CONTROL:
  202240. case VK_LCONTROL:
  202241. case VK_RCONTROL:
  202242. case VK_MENU:
  202243. case VK_LMENU:
  202244. case VK_RMENU:
  202245. case VK_LWIN:
  202246. case VK_RWIN:
  202247. case VK_CAPITAL:
  202248. case VK_NUMLOCK:
  202249. case VK_SCROLL:
  202250. case VK_APPS:
  202251. sendModifierKeyChangeIfNeeded();
  202252. break;
  202253. case VK_LEFT:
  202254. case VK_RIGHT:
  202255. case VK_UP:
  202256. case VK_DOWN:
  202257. case VK_PRIOR:
  202258. case VK_NEXT:
  202259. case VK_HOME:
  202260. case VK_END:
  202261. case VK_DELETE:
  202262. case VK_INSERT:
  202263. case VK_F1:
  202264. case VK_F2:
  202265. case VK_F3:
  202266. case VK_F4:
  202267. case VK_F5:
  202268. case VK_F6:
  202269. case VK_F7:
  202270. case VK_F8:
  202271. case VK_F9:
  202272. case VK_F10:
  202273. case VK_F11:
  202274. case VK_F12:
  202275. case VK_F13:
  202276. case VK_F14:
  202277. case VK_F15:
  202278. case VK_F16:
  202279. used = handleKeyUpOrDown (true);
  202280. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  202281. break;
  202282. case VK_ADD:
  202283. case VK_SUBTRACT:
  202284. case VK_MULTIPLY:
  202285. case VK_DIVIDE:
  202286. case VK_SEPARATOR:
  202287. case VK_DECIMAL:
  202288. used = handleKeyUpOrDown (true);
  202289. break;
  202290. default:
  202291. used = handleKeyUpOrDown (true);
  202292. {
  202293. MSG msg;
  202294. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  202295. {
  202296. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  202297. // manually generate the key-press event that matches this key-down.
  202298. const UINT keyChar = MapVirtualKey (key, 2);
  202299. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  202300. }
  202301. }
  202302. break;
  202303. }
  202304. if (Component::getCurrentlyModalComponent() != 0)
  202305. used = true;
  202306. return used;
  202307. }
  202308. bool doKeyChar (int key, const LPARAM flags)
  202309. {
  202310. updateKeyModifiers();
  202311. juce_wchar textChar = (juce_wchar) key;
  202312. const int virtualScanCode = (flags >> 16) & 0xff;
  202313. if (key >= '0' && key <= '9')
  202314. {
  202315. switch (virtualScanCode) // check for a numeric keypad scan-code
  202316. {
  202317. case 0x52:
  202318. case 0x4f:
  202319. case 0x50:
  202320. case 0x51:
  202321. case 0x4b:
  202322. case 0x4c:
  202323. case 0x4d:
  202324. case 0x47:
  202325. case 0x48:
  202326. case 0x49:
  202327. key = (key - '0') + KeyPress::numberPad0;
  202328. break;
  202329. default:
  202330. break;
  202331. }
  202332. }
  202333. else
  202334. {
  202335. // convert the scan code to an unmodified character code..
  202336. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  202337. UINT keyChar = MapVirtualKey (virtualKey, 2);
  202338. keyChar = LOWORD (keyChar);
  202339. if (keyChar != 0)
  202340. key = (int) keyChar;
  202341. // avoid sending junk text characters for some control-key combinations
  202342. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  202343. textChar = 0;
  202344. }
  202345. return handleKeyPress (key, textChar);
  202346. }
  202347. bool doAppCommand (const LPARAM lParam)
  202348. {
  202349. int key = 0;
  202350. switch (GET_APPCOMMAND_LPARAM (lParam))
  202351. {
  202352. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  202353. key = KeyPress::playKey;
  202354. break;
  202355. case APPCOMMAND_MEDIA_STOP:
  202356. key = KeyPress::stopKey;
  202357. break;
  202358. case APPCOMMAND_MEDIA_NEXTTRACK:
  202359. key = KeyPress::fastForwardKey;
  202360. break;
  202361. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  202362. key = KeyPress::rewindKey;
  202363. break;
  202364. }
  202365. if (key != 0)
  202366. {
  202367. updateKeyModifiers();
  202368. if (hwnd == GetActiveWindow())
  202369. {
  202370. handleKeyPress (key, 0);
  202371. return true;
  202372. }
  202373. }
  202374. return false;
  202375. }
  202376. class JuceDropTarget : public IDropTarget
  202377. {
  202378. public:
  202379. JuceDropTarget (Win32ComponentPeer* const owner_)
  202380. : owner (owner_),
  202381. refCount (1)
  202382. {
  202383. }
  202384. virtual ~JuceDropTarget()
  202385. {
  202386. jassert (refCount == 0);
  202387. }
  202388. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202389. {
  202390. if (id == IID_IUnknown || id == IID_IDropTarget)
  202391. {
  202392. AddRef();
  202393. *result = this;
  202394. return S_OK;
  202395. }
  202396. *result = 0;
  202397. return E_NOINTERFACE;
  202398. }
  202399. ULONG __stdcall AddRef() { return ++refCount; }
  202400. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202401. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202402. {
  202403. updateFileList (pDataObject);
  202404. int x = mousePos.x, y = mousePos.y;
  202405. owner->globalPositionToRelative (x, y);
  202406. owner->handleFileDragMove (files, x, y);
  202407. *pdwEffect = DROPEFFECT_COPY;
  202408. return S_OK;
  202409. }
  202410. HRESULT __stdcall DragLeave()
  202411. {
  202412. owner->handleFileDragExit (files);
  202413. return S_OK;
  202414. }
  202415. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202416. {
  202417. int x = mousePos.x, y = mousePos.y;
  202418. owner->globalPositionToRelative (x, y);
  202419. owner->handleFileDragMove (files, x, y);
  202420. *pdwEffect = DROPEFFECT_COPY;
  202421. return S_OK;
  202422. }
  202423. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202424. {
  202425. updateFileList (pDataObject);
  202426. int x = mousePos.x, y = mousePos.y;
  202427. owner->globalPositionToRelative (x, y);
  202428. owner->handleFileDragDrop (files, x, y);
  202429. *pdwEffect = DROPEFFECT_COPY;
  202430. return S_OK;
  202431. }
  202432. private:
  202433. Win32ComponentPeer* const owner;
  202434. int refCount;
  202435. StringArray files;
  202436. void updateFileList (IDataObject* const pDataObject)
  202437. {
  202438. files.clear();
  202439. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202440. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202441. if (pDataObject->GetData (&format, &medium) == S_OK)
  202442. {
  202443. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  202444. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  202445. unsigned int i = 0;
  202446. if (pDropFiles->fWide)
  202447. {
  202448. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  202449. for (;;)
  202450. {
  202451. unsigned int len = 0;
  202452. while (i + len < totalLen && fname [i + len] != 0)
  202453. ++len;
  202454. if (len == 0)
  202455. break;
  202456. files.add (String (fname + i, len));
  202457. i += len + 1;
  202458. }
  202459. }
  202460. else
  202461. {
  202462. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  202463. for (;;)
  202464. {
  202465. unsigned int len = 0;
  202466. while (i + len < totalLen && fname [i + len] != 0)
  202467. ++len;
  202468. if (len == 0)
  202469. break;
  202470. files.add (String (fname + i, len));
  202471. i += len + 1;
  202472. }
  202473. }
  202474. GlobalUnlock (medium.hGlobal);
  202475. }
  202476. }
  202477. JuceDropTarget (const JuceDropTarget&);
  202478. const JuceDropTarget& operator= (const JuceDropTarget&);
  202479. };
  202480. void doSettingChange()
  202481. {
  202482. Desktop::getInstance().refreshMonitorSizes();
  202483. if (fullScreen && ! isMinimised())
  202484. {
  202485. const Rectangle r (component->getParentMonitorArea());
  202486. SetWindowPos (hwnd, 0,
  202487. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  202488. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  202489. }
  202490. }
  202491. public:
  202492. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202493. {
  202494. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  202495. if (peer != 0)
  202496. return peer->peerWindowProc (h, message, wParam, lParam);
  202497. return DefWindowProc (h, message, wParam, lParam);
  202498. }
  202499. private:
  202500. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202501. {
  202502. {
  202503. if (isValidPeer (this))
  202504. {
  202505. switch (message)
  202506. {
  202507. case WM_NCHITTEST:
  202508. if (hasTitleBar())
  202509. break;
  202510. return HTCLIENT;
  202511. case WM_PAINT:
  202512. handlePaintMessage();
  202513. return 0;
  202514. case WM_NCPAINT:
  202515. if (wParam != 1)
  202516. handlePaintMessage();
  202517. if (hasTitleBar())
  202518. break;
  202519. return 0;
  202520. case WM_ERASEBKGND:
  202521. case WM_NCCALCSIZE:
  202522. if (hasTitleBar())
  202523. break;
  202524. return 1;
  202525. case WM_MOUSEMOVE:
  202526. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  202527. return 0;
  202528. case WM_MOUSELEAVE:
  202529. doMouseExit();
  202530. return 0;
  202531. case WM_LBUTTONDOWN:
  202532. case WM_MBUTTONDOWN:
  202533. case WM_RBUTTONDOWN:
  202534. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202535. return 0;
  202536. case WM_LBUTTONUP:
  202537. case WM_MBUTTONUP:
  202538. case WM_RBUTTONUP:
  202539. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202540. return 0;
  202541. case WM_CAPTURECHANGED:
  202542. doCaptureChanged();
  202543. return 0;
  202544. case WM_NCMOUSEMOVE:
  202545. if (hasTitleBar())
  202546. break;
  202547. return 0;
  202548. case 0x020A: /* WM_MOUSEWHEEL */
  202549. doMouseWheel (wParam, true);
  202550. return 0;
  202551. case 0x020E: /* WM_MOUSEHWHEEL */
  202552. doMouseWheel (wParam, false);
  202553. return 0;
  202554. case WM_WINDOWPOSCHANGING:
  202555. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  202556. {
  202557. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  202558. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  202559. {
  202560. if (constrainer != 0)
  202561. {
  202562. const Rectangle current (component->getX() - windowBorder.getLeft(),
  202563. component->getY() - windowBorder.getTop(),
  202564. component->getWidth() + windowBorder.getLeftAndRight(),
  202565. component->getHeight() + windowBorder.getTopAndBottom());
  202566. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  202567. current,
  202568. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  202569. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  202570. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  202571. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  202572. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  202573. }
  202574. }
  202575. }
  202576. return 0;
  202577. case WM_WINDOWPOSCHANGED:
  202578. handleMovedOrResized();
  202579. if (dontRepaint)
  202580. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  202581. else
  202582. return 0;
  202583. case WM_KEYDOWN:
  202584. case WM_SYSKEYDOWN:
  202585. if (doKeyDown (wParam))
  202586. return 0;
  202587. break;
  202588. case WM_KEYUP:
  202589. case WM_SYSKEYUP:
  202590. if (doKeyUp (wParam))
  202591. return 0;
  202592. break;
  202593. case WM_CHAR:
  202594. if (doKeyChar ((int) wParam, lParam))
  202595. return 0;
  202596. break;
  202597. case WM_APPCOMMAND:
  202598. if (doAppCommand (lParam))
  202599. return TRUE;
  202600. break;
  202601. case WM_SETFOCUS:
  202602. updateKeyModifiers();
  202603. handleFocusGain();
  202604. break;
  202605. case WM_KILLFOCUS:
  202606. if (hasCreatedCaret)
  202607. {
  202608. hasCreatedCaret = false;
  202609. DestroyCaret();
  202610. }
  202611. handleFocusLoss();
  202612. break;
  202613. case WM_ACTIVATEAPP:
  202614. // Windows does weird things to process priority when you swap apps,
  202615. // so this forces an update when the app is brought to the front
  202616. if (wParam != FALSE)
  202617. juce_repeatLastProcessPriority();
  202618. else
  202619. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  202620. juce_CheckCurrentlyFocusedTopLevelWindow();
  202621. modifiersAtLastCallback = -1;
  202622. return 0;
  202623. case WM_ACTIVATE:
  202624. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  202625. {
  202626. modifiersAtLastCallback = -1;
  202627. updateKeyModifiers();
  202628. if (isMinimised())
  202629. {
  202630. component->repaint();
  202631. handleMovedOrResized();
  202632. if (! isValidMessageListener())
  202633. return 0;
  202634. }
  202635. if (LOWORD (wParam) == WA_CLICKACTIVE
  202636. && component->isCurrentlyBlockedByAnotherModalComponent())
  202637. {
  202638. int mx, my;
  202639. component->getMouseXYRelative (mx, my);
  202640. Component* const underMouse = component->getComponentAt (mx, my);
  202641. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  202642. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  202643. return 0;
  202644. }
  202645. handleBroughtToFront();
  202646. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202647. Component::getCurrentlyModalComponent()->toFront (true);
  202648. return 0;
  202649. }
  202650. break;
  202651. case WM_NCACTIVATE:
  202652. // while a temporary window is being shown, prevent Windows from deactivating the
  202653. // title bars of our main windows.
  202654. if (wParam == 0 && ! shouldDeactivateTitleBar)
  202655. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  202656. break;
  202657. case WM_MOUSEACTIVATE:
  202658. if (! component->getMouseClickGrabsKeyboardFocus())
  202659. return MA_NOACTIVATE;
  202660. break;
  202661. case WM_SHOWWINDOW:
  202662. if (wParam != 0)
  202663. handleBroughtToFront();
  202664. break;
  202665. case WM_CLOSE:
  202666. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  202667. handleUserClosingWindow();
  202668. return 0;
  202669. case WM_QUIT:
  202670. if (JUCEApplication::getInstance() != 0)
  202671. JUCEApplication::getInstance()->systemRequestedQuit();
  202672. return 0;
  202673. case WM_QUERYENDSESSION:
  202674. if (JUCEApplication::getInstance() != 0)
  202675. {
  202676. JUCEApplication::getInstance()->systemRequestedQuit();
  202677. return MessageManager::getInstance()->hasStopMessageBeenSent();
  202678. }
  202679. return TRUE;
  202680. case WM_TRAYNOTIFY:
  202681. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202682. {
  202683. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  202684. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202685. {
  202686. Component* const current = Component::getCurrentlyModalComponent();
  202687. if (current != 0)
  202688. current->inputAttemptWhenModal();
  202689. }
  202690. }
  202691. else
  202692. {
  202693. const int oldModifiers = currentModifiers;
  202694. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  202695. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  202696. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  202697. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  202698. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  202699. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  202700. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  202701. {
  202702. SetFocus (hwnd);
  202703. SetForegroundWindow (hwnd);
  202704. component->mouseDown (e);
  202705. }
  202706. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  202707. {
  202708. e.mods = ModifierKeys (oldModifiers);
  202709. component->mouseUp (e);
  202710. }
  202711. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202712. {
  202713. e.mods = ModifierKeys (oldModifiers);
  202714. component->mouseDoubleClick (e);
  202715. }
  202716. else if (lParam == WM_MOUSEMOVE)
  202717. {
  202718. component->mouseMove (e);
  202719. }
  202720. }
  202721. break;
  202722. case WM_SYNCPAINT:
  202723. return 0;
  202724. case WM_PALETTECHANGED:
  202725. InvalidateRect (h, 0, 0);
  202726. break;
  202727. case WM_DISPLAYCHANGE:
  202728. InvalidateRect (h, 0, 0);
  202729. createPaletteIfNeeded = true;
  202730. // intentional fall-through...
  202731. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  202732. doSettingChange();
  202733. break;
  202734. case WM_INITMENU:
  202735. if (! hasTitleBar())
  202736. {
  202737. if (isFullScreen())
  202738. {
  202739. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  202740. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  202741. }
  202742. else if (! isMinimised())
  202743. {
  202744. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  202745. }
  202746. }
  202747. break;
  202748. case WM_SYSCOMMAND:
  202749. switch (wParam & 0xfff0)
  202750. {
  202751. case SC_CLOSE:
  202752. if (sendInputAttemptWhenModalMessage())
  202753. return 0;
  202754. if (hasTitleBar())
  202755. {
  202756. PostMessage (h, WM_CLOSE, 0, 0);
  202757. return 0;
  202758. }
  202759. break;
  202760. case SC_KEYMENU:
  202761. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  202762. // obscure situations that can arise if a modal loop is started from an alt-key
  202763. // keypress).
  202764. if (hasTitleBar() && h == GetCapture())
  202765. ReleaseCapture();
  202766. break;
  202767. case SC_MAXIMIZE:
  202768. if (sendInputAttemptWhenModalMessage())
  202769. return 0;
  202770. setFullScreen (true);
  202771. return 0;
  202772. case SC_MINIMIZE:
  202773. if (sendInputAttemptWhenModalMessage())
  202774. return 0;
  202775. if (! hasTitleBar())
  202776. {
  202777. setMinimised (true);
  202778. return 0;
  202779. }
  202780. break;
  202781. case SC_RESTORE:
  202782. if (sendInputAttemptWhenModalMessage())
  202783. return 0;
  202784. if (hasTitleBar())
  202785. {
  202786. if (isFullScreen())
  202787. {
  202788. setFullScreen (false);
  202789. return 0;
  202790. }
  202791. }
  202792. else
  202793. {
  202794. if (isMinimised())
  202795. setMinimised (false);
  202796. else if (isFullScreen())
  202797. setFullScreen (false);
  202798. return 0;
  202799. }
  202800. break;
  202801. }
  202802. break;
  202803. case WM_NCLBUTTONDOWN:
  202804. case WM_NCRBUTTONDOWN:
  202805. case WM_NCMBUTTONDOWN:
  202806. sendInputAttemptWhenModalMessage();
  202807. break;
  202808. //case WM_IME_STARTCOMPOSITION;
  202809. // return 0;
  202810. case WM_GETDLGCODE:
  202811. return DLGC_WANTALLKEYS;
  202812. default:
  202813. break;
  202814. }
  202815. }
  202816. }
  202817. // (the message manager lock exits before calling this, to avoid deadlocks if
  202818. // this calls into non-juce windows)
  202819. return DefWindowProc (h, message, wParam, lParam);
  202820. }
  202821. bool sendInputAttemptWhenModalMessage()
  202822. {
  202823. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202824. {
  202825. Component* const current = Component::getCurrentlyModalComponent();
  202826. if (current != 0)
  202827. current->inputAttemptWhenModal();
  202828. return true;
  202829. }
  202830. return false;
  202831. }
  202832. Win32ComponentPeer (const Win32ComponentPeer&);
  202833. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  202834. };
  202835. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  202836. {
  202837. return new Win32ComponentPeer (this, styleFlags);
  202838. }
  202839. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  202840. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  202841. {
  202842. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202843. if (wp != 0)
  202844. wp->setTaskBarIcon (&newImage);
  202845. }
  202846. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  202847. {
  202848. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202849. if (wp != 0)
  202850. wp->setTaskBarIconToolTip (tooltip);
  202851. }
  202852. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  202853. {
  202854. DWORD val = GetWindowLong (h, styleType);
  202855. if (bitIsSet)
  202856. val |= feature;
  202857. else
  202858. val &= ~feature;
  202859. SetWindowLongPtr (h, styleType, val);
  202860. SetWindowPos (h, 0, 0, 0, 0, 0,
  202861. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  202862. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  202863. }
  202864. bool Process::isForegroundProcess() throw()
  202865. {
  202866. HWND fg = GetForegroundWindow();
  202867. if (fg == 0)
  202868. return true;
  202869. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  202870. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  202871. // have to see if any of our windows are children of the foreground window
  202872. fg = GetAncestor (fg, GA_ROOT);
  202873. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  202874. {
  202875. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  202876. if (wp != 0 && wp->isInside (fg))
  202877. return true;
  202878. }
  202879. return false;
  202880. }
  202881. bool AlertWindow::showNativeDialogBox (const String& title,
  202882. const String& bodyText,
  202883. bool isOkCancel)
  202884. {
  202885. return MessageBox (0, bodyText, title,
  202886. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  202887. : MB_OK)) == IDOK;
  202888. }
  202889. void Desktop::getMousePosition (int& x, int& y) throw()
  202890. {
  202891. POINT mousePos;
  202892. GetCursorPos (&mousePos);
  202893. x = mousePos.x;
  202894. y = mousePos.y;
  202895. }
  202896. void Desktop::setMousePosition (int x, int y) throw()
  202897. {
  202898. SetCursorPos (x, y);
  202899. }
  202900. class ScreenSaverDefeater : public Timer,
  202901. public DeletedAtShutdown
  202902. {
  202903. public:
  202904. ScreenSaverDefeater() throw()
  202905. {
  202906. startTimer (10000);
  202907. timerCallback();
  202908. }
  202909. ~ScreenSaverDefeater() {}
  202910. void timerCallback()
  202911. {
  202912. if (Process::isForegroundProcess())
  202913. {
  202914. // simulate a shift key getting pressed..
  202915. INPUT input[2];
  202916. input[0].type = INPUT_KEYBOARD;
  202917. input[0].ki.wVk = VK_SHIFT;
  202918. input[0].ki.dwFlags = 0;
  202919. input[0].ki.dwExtraInfo = 0;
  202920. input[1].type = INPUT_KEYBOARD;
  202921. input[1].ki.wVk = VK_SHIFT;
  202922. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  202923. input[1].ki.dwExtraInfo = 0;
  202924. SendInput (2, input, sizeof (INPUT));
  202925. }
  202926. }
  202927. };
  202928. static ScreenSaverDefeater* screenSaverDefeater = 0;
  202929. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202930. {
  202931. if (isEnabled)
  202932. {
  202933. deleteAndZero (screenSaverDefeater);
  202934. }
  202935. else if (screenSaverDefeater == 0)
  202936. {
  202937. screenSaverDefeater = new ScreenSaverDefeater();
  202938. }
  202939. }
  202940. bool Desktop::isScreenSaverEnabled() throw()
  202941. {
  202942. return screenSaverDefeater == 0;
  202943. }
  202944. /* (The code below is the "correct" way to disable the screen saver, but it
  202945. completely fails on winXP when the saver is password-protected...)
  202946. static bool juce_screenSaverEnabled = true;
  202947. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202948. {
  202949. juce_screenSaverEnabled = isEnabled;
  202950. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  202951. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  202952. }
  202953. bool Desktop::isScreenSaverEnabled() throw()
  202954. {
  202955. return juce_screenSaverEnabled;
  202956. }
  202957. */
  202958. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  202959. {
  202960. if (enableOrDisable)
  202961. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  202962. }
  202963. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  202964. {
  202965. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  202966. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  202967. return TRUE;
  202968. }
  202969. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  202970. {
  202971. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  202972. // make sure the first in the list is the main monitor
  202973. for (int i = 1; i < monitorCoords.size(); ++i)
  202974. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  202975. monitorCoords.swap (i, 0);
  202976. if (monitorCoords.size() == 0)
  202977. {
  202978. RECT r;
  202979. GetWindowRect (GetDesktopWindow(), &r);
  202980. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  202981. }
  202982. if (clipToWorkArea)
  202983. {
  202984. // clip the main monitor to the active non-taskbar area
  202985. RECT r;
  202986. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  202987. Rectangle& screen = monitorCoords.getReference (0);
  202988. screen.setPosition (jmax (screen.getX(), r.left),
  202989. jmax (screen.getY(), r.top));
  202990. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  202991. jmin (screen.getBottom(), r.bottom) - screen.getY());
  202992. }
  202993. }
  202994. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  202995. {
  202996. Image* im = 0;
  202997. if (bitmap != 0)
  202998. {
  202999. BITMAP bm;
  203000. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  203001. && bm.bmWidth > 0 && bm.bmHeight > 0)
  203002. {
  203003. HDC tempDC = GetDC (0);
  203004. HDC dc = CreateCompatibleDC (tempDC);
  203005. ReleaseDC (0, tempDC);
  203006. SelectObject (dc, bitmap);
  203007. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  203008. for (int y = bm.bmHeight; --y >= 0;)
  203009. {
  203010. for (int x = bm.bmWidth; --x >= 0;)
  203011. {
  203012. COLORREF col = GetPixel (dc, x, y);
  203013. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  203014. (uint8) GetGValue (col),
  203015. (uint8) GetBValue (col)));
  203016. }
  203017. }
  203018. DeleteDC (dc);
  203019. }
  203020. }
  203021. return im;
  203022. }
  203023. static Image* createImageFromHICON (HICON icon) throw()
  203024. {
  203025. ICONINFO info;
  203026. if (GetIconInfo (icon, &info))
  203027. {
  203028. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  203029. if (mask == 0)
  203030. return 0;
  203031. Image* const image = createImageFromHBITMAP (info.hbmColor);
  203032. if (image == 0)
  203033. return mask;
  203034. for (int y = image->getHeight(); --y >= 0;)
  203035. {
  203036. for (int x = image->getWidth(); --x >= 0;)
  203037. {
  203038. const float brightness = mask->getPixelAt (x, y).getBrightness();
  203039. if (brightness > 0.0f)
  203040. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  203041. }
  203042. }
  203043. delete mask;
  203044. return image;
  203045. }
  203046. return 0;
  203047. }
  203048. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  203049. {
  203050. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  203051. ICONINFO info;
  203052. info.fIcon = isIcon;
  203053. info.xHotspot = hotspotX;
  203054. info.yHotspot = hotspotY;
  203055. info.hbmMask = mask;
  203056. HICON hi = 0;
  203057. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  203058. {
  203059. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  203060. Graphics g (bitmap);
  203061. g.drawImageAt (&image, 0, 0);
  203062. info.hbmColor = bitmap.hBitmap;
  203063. hi = CreateIconIndirect (&info);
  203064. }
  203065. else
  203066. {
  203067. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  203068. HDC colDC = CreateCompatibleDC (GetDC (0));
  203069. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  203070. SelectObject (colDC, colour);
  203071. SelectObject (alphaDC, mask);
  203072. for (int y = image.getHeight(); --y >= 0;)
  203073. {
  203074. for (int x = image.getWidth(); --x >= 0;)
  203075. {
  203076. const Colour c (image.getPixelAt (x, y));
  203077. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  203078. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  203079. }
  203080. }
  203081. DeleteDC (colDC);
  203082. DeleteDC (alphaDC);
  203083. info.hbmColor = colour;
  203084. hi = CreateIconIndirect (&info);
  203085. DeleteObject (colour);
  203086. }
  203087. DeleteObject (mask);
  203088. return hi;
  203089. }
  203090. Image* juce_createIconForFile (const File& file)
  203091. {
  203092. Image* image = 0;
  203093. TCHAR filename [1024];
  203094. file.getFullPathName().copyToBuffer (filename, 1023);
  203095. WORD iconNum = 0;
  203096. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  203097. filename, &iconNum);
  203098. if (icon != 0)
  203099. {
  203100. image = createImageFromHICON (icon);
  203101. DestroyIcon (icon);
  203102. }
  203103. return image;
  203104. }
  203105. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  203106. {
  203107. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  203108. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  203109. const Image* im = &image;
  203110. Image* newIm = 0;
  203111. if (image.getWidth() > maxW || image.getHeight() > maxH)
  203112. {
  203113. im = newIm = image.createCopy (maxW, maxH);
  203114. hotspotX = (hotspotX * maxW) / image.getWidth();
  203115. hotspotY = (hotspotY * maxH) / image.getHeight();
  203116. }
  203117. void* cursorH = 0;
  203118. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  203119. if (os == SystemStats::WinXP)
  203120. {
  203121. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  203122. }
  203123. else
  203124. {
  203125. const int stride = (maxW + 7) >> 3;
  203126. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  203127. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  203128. int index = 0;
  203129. for (int y = 0; y < maxH; ++y)
  203130. {
  203131. for (int x = 0; x < maxW; ++x)
  203132. {
  203133. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  203134. const Colour pixelColour (im->getPixelAt (x, y));
  203135. if (pixelColour.getAlpha() < 127)
  203136. andPlane [index + (x >> 3)] |= bit;
  203137. else if (pixelColour.getBrightness() >= 0.5f)
  203138. xorPlane [index + (x >> 3)] |= bit;
  203139. }
  203140. index += stride;
  203141. }
  203142. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  203143. juce_free (andPlane);
  203144. juce_free (xorPlane);
  203145. }
  203146. delete newIm;
  203147. return cursorH;
  203148. }
  203149. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  203150. {
  203151. if (cursorHandle != 0 && ! isStandard)
  203152. DestroyCursor ((HCURSOR) cursorHandle);
  203153. }
  203154. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  203155. {
  203156. LPCTSTR cursorName = IDC_ARROW;
  203157. switch (type)
  203158. {
  203159. case MouseCursor::NormalCursor:
  203160. cursorName = IDC_ARROW;
  203161. break;
  203162. case MouseCursor::NoCursor:
  203163. return 0;
  203164. case MouseCursor::DraggingHandCursor:
  203165. {
  203166. static void* dragHandCursor = 0;
  203167. if (dragHandCursor == 0)
  203168. {
  203169. static const unsigned char dragHandData[] =
  203170. { 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,
  203171. 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,
  203172. 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 };
  203173. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  203174. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  203175. delete image;
  203176. }
  203177. return dragHandCursor;
  203178. }
  203179. case MouseCursor::WaitCursor:
  203180. cursorName = IDC_WAIT;
  203181. break;
  203182. case MouseCursor::IBeamCursor:
  203183. cursorName = IDC_IBEAM;
  203184. break;
  203185. case MouseCursor::PointingHandCursor:
  203186. cursorName = MAKEINTRESOURCE(32649);
  203187. break;
  203188. case MouseCursor::LeftRightResizeCursor:
  203189. case MouseCursor::LeftEdgeResizeCursor:
  203190. case MouseCursor::RightEdgeResizeCursor:
  203191. cursorName = IDC_SIZEWE;
  203192. break;
  203193. case MouseCursor::UpDownResizeCursor:
  203194. case MouseCursor::TopEdgeResizeCursor:
  203195. case MouseCursor::BottomEdgeResizeCursor:
  203196. cursorName = IDC_SIZENS;
  203197. break;
  203198. case MouseCursor::TopLeftCornerResizeCursor:
  203199. case MouseCursor::BottomRightCornerResizeCursor:
  203200. cursorName = IDC_SIZENWSE;
  203201. break;
  203202. case MouseCursor::TopRightCornerResizeCursor:
  203203. case MouseCursor::BottomLeftCornerResizeCursor:
  203204. cursorName = IDC_SIZENESW;
  203205. break;
  203206. case MouseCursor::UpDownLeftRightResizeCursor:
  203207. cursorName = IDC_SIZEALL;
  203208. break;
  203209. case MouseCursor::CrosshairCursor:
  203210. cursorName = IDC_CROSS;
  203211. break;
  203212. case MouseCursor::CopyingCursor:
  203213. // can't seem to find one of these in the win32 list..
  203214. break;
  203215. }
  203216. HCURSOR cursorH = LoadCursor (0, cursorName);
  203217. if (cursorH == 0)
  203218. cursorH = LoadCursor (0, IDC_ARROW);
  203219. return (void*) cursorH;
  203220. }
  203221. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  203222. {
  203223. SetCursor ((HCURSOR) getHandle());
  203224. }
  203225. void MouseCursor::showInAllWindows() const throw()
  203226. {
  203227. showInWindow (0);
  203228. }
  203229. class JuceDropSource : public IDropSource
  203230. {
  203231. int refCount;
  203232. public:
  203233. JuceDropSource()
  203234. : refCount (1)
  203235. {
  203236. }
  203237. virtual ~JuceDropSource()
  203238. {
  203239. jassert (refCount == 0);
  203240. }
  203241. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203242. {
  203243. if (id == IID_IUnknown || id == IID_IDropSource)
  203244. {
  203245. AddRef();
  203246. *result = this;
  203247. return S_OK;
  203248. }
  203249. *result = 0;
  203250. return E_NOINTERFACE;
  203251. }
  203252. ULONG __stdcall AddRef() { return ++refCount; }
  203253. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203254. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  203255. {
  203256. if (escapePressed)
  203257. return DRAGDROP_S_CANCEL;
  203258. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  203259. return DRAGDROP_S_DROP;
  203260. return S_OK;
  203261. }
  203262. HRESULT __stdcall GiveFeedback (DWORD)
  203263. {
  203264. return DRAGDROP_S_USEDEFAULTCURSORS;
  203265. }
  203266. };
  203267. class JuceEnumFormatEtc : public IEnumFORMATETC
  203268. {
  203269. public:
  203270. JuceEnumFormatEtc (const FORMATETC* const format_)
  203271. : refCount (1),
  203272. format (format_),
  203273. index (0)
  203274. {
  203275. }
  203276. virtual ~JuceEnumFormatEtc()
  203277. {
  203278. jassert (refCount == 0);
  203279. }
  203280. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203281. {
  203282. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  203283. {
  203284. AddRef();
  203285. *result = this;
  203286. return S_OK;
  203287. }
  203288. *result = 0;
  203289. return E_NOINTERFACE;
  203290. }
  203291. ULONG __stdcall AddRef() { return ++refCount; }
  203292. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203293. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  203294. {
  203295. if (result == 0)
  203296. return E_POINTER;
  203297. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  203298. newOne->index = index;
  203299. *result = newOne;
  203300. return S_OK;
  203301. }
  203302. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  203303. {
  203304. if (pceltFetched != 0)
  203305. *pceltFetched = 0;
  203306. else if (celt != 1)
  203307. return S_FALSE;
  203308. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  203309. {
  203310. copyFormatEtc (lpFormatEtc [0], *format);
  203311. ++index;
  203312. if (pceltFetched != 0)
  203313. *pceltFetched = 1;
  203314. return S_OK;
  203315. }
  203316. return S_FALSE;
  203317. }
  203318. HRESULT __stdcall Skip (ULONG celt)
  203319. {
  203320. if (index + (int) celt >= 1)
  203321. return S_FALSE;
  203322. index += celt;
  203323. return S_OK;
  203324. }
  203325. HRESULT __stdcall Reset()
  203326. {
  203327. index = 0;
  203328. return S_OK;
  203329. }
  203330. private:
  203331. int refCount;
  203332. const FORMATETC* const format;
  203333. int index;
  203334. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  203335. {
  203336. dest = source;
  203337. if (source.ptd != 0)
  203338. {
  203339. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  203340. *(dest.ptd) = *(source.ptd);
  203341. }
  203342. }
  203343. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  203344. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  203345. };
  203346. class JuceDataObject : public IDataObject
  203347. {
  203348. JuceDropSource* const dropSource;
  203349. const FORMATETC* const format;
  203350. const STGMEDIUM* const medium;
  203351. int refCount;
  203352. JuceDataObject (const JuceDataObject&);
  203353. const JuceDataObject& operator= (const JuceDataObject&);
  203354. public:
  203355. JuceDataObject (JuceDropSource* const dropSource_,
  203356. const FORMATETC* const format_,
  203357. const STGMEDIUM* const medium_)
  203358. : dropSource (dropSource_),
  203359. format (format_),
  203360. medium (medium_),
  203361. refCount (1)
  203362. {
  203363. }
  203364. virtual ~JuceDataObject()
  203365. {
  203366. jassert (refCount == 0);
  203367. }
  203368. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203369. {
  203370. if (id == IID_IUnknown || id == IID_IDataObject)
  203371. {
  203372. AddRef();
  203373. *result = this;
  203374. return S_OK;
  203375. }
  203376. *result = 0;
  203377. return E_NOINTERFACE;
  203378. }
  203379. ULONG __stdcall AddRef() { return ++refCount; }
  203380. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203381. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  203382. {
  203383. if (pFormatEtc->tymed == format->tymed
  203384. && pFormatEtc->cfFormat == format->cfFormat
  203385. && pFormatEtc->dwAspect == format->dwAspect)
  203386. {
  203387. pMedium->tymed = format->tymed;
  203388. pMedium->pUnkForRelease = 0;
  203389. if (format->tymed == TYMED_HGLOBAL)
  203390. {
  203391. const SIZE_T len = GlobalSize (medium->hGlobal);
  203392. void* const src = GlobalLock (medium->hGlobal);
  203393. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  203394. memcpy (dst, src, len);
  203395. GlobalUnlock (medium->hGlobal);
  203396. pMedium->hGlobal = dst;
  203397. return S_OK;
  203398. }
  203399. }
  203400. return DV_E_FORMATETC;
  203401. }
  203402. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  203403. {
  203404. if (f == 0)
  203405. return E_INVALIDARG;
  203406. if (f->tymed == format->tymed
  203407. && f->cfFormat == format->cfFormat
  203408. && f->dwAspect == format->dwAspect)
  203409. return S_OK;
  203410. return DV_E_FORMATETC;
  203411. }
  203412. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  203413. {
  203414. pFormatEtcOut->ptd = 0;
  203415. return E_NOTIMPL;
  203416. }
  203417. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  203418. {
  203419. if (result == 0)
  203420. return E_POINTER;
  203421. if (direction == DATADIR_GET)
  203422. {
  203423. *result = new JuceEnumFormatEtc (format);
  203424. return S_OK;
  203425. }
  203426. *result = 0;
  203427. return E_NOTIMPL;
  203428. }
  203429. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  203430. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  203431. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  203432. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  203433. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  203434. };
  203435. static HDROP createHDrop (const StringArray& fileNames) throw()
  203436. {
  203437. int totalChars = 0;
  203438. for (int i = fileNames.size(); --i >= 0;)
  203439. totalChars += fileNames[i].length() + 1;
  203440. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  203441. sizeof (DROPFILES)
  203442. + sizeof (WCHAR) * (totalChars + 2));
  203443. if (hDrop != 0)
  203444. {
  203445. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  203446. pDropFiles->pFiles = sizeof (DROPFILES);
  203447. pDropFiles->fWide = true;
  203448. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  203449. for (int i = 0; i < fileNames.size(); ++i)
  203450. {
  203451. fileNames[i].copyToBuffer (fname, 2048);
  203452. fname += fileNames[i].length() + 1;
  203453. }
  203454. *fname = 0;
  203455. GlobalUnlock (hDrop);
  203456. }
  203457. return hDrop;
  203458. }
  203459. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  203460. {
  203461. JuceDropSource* const source = new JuceDropSource();
  203462. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  203463. DWORD effect;
  203464. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  203465. data->Release();
  203466. source->Release();
  203467. return res == DRAGDROP_S_DROP;
  203468. }
  203469. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  203470. {
  203471. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203472. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203473. medium.hGlobal = createHDrop (files);
  203474. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  203475. : DROPEFFECT_COPY);
  203476. }
  203477. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  203478. {
  203479. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203480. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203481. const int numChars = text.length();
  203482. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  203483. char* d = (char*) GlobalLock (medium.hGlobal);
  203484. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  203485. format.cfFormat = CF_UNICODETEXT;
  203486. GlobalUnlock (medium.hGlobal);
  203487. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  203488. }
  203489. #endif
  203490. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  203491. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  203492. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203493. // compiled on its own).
  203494. #if JUCE_INCLUDED_FILE
  203495. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  203496. NEWTEXTMETRICEXW*,
  203497. int type,
  203498. LPARAM lParam)
  203499. {
  203500. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203501. {
  203502. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203503. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  203504. }
  203505. return 1;
  203506. }
  203507. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  203508. NEWTEXTMETRICEXW*,
  203509. int type,
  203510. LPARAM lParam)
  203511. {
  203512. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203513. {
  203514. LOGFONTW lf;
  203515. zerostruct (lf);
  203516. lf.lfWeight = FW_DONTCARE;
  203517. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203518. lf.lfQuality = DEFAULT_QUALITY;
  203519. lf.lfCharSet = DEFAULT_CHARSET;
  203520. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203521. lf.lfPitchAndFamily = FF_DONTCARE;
  203522. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203523. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  203524. HDC dc = CreateCompatibleDC (0);
  203525. EnumFontFamiliesEx (dc, &lf,
  203526. (FONTENUMPROCW) &wfontEnum2,
  203527. lParam, 0);
  203528. DeleteDC (dc);
  203529. }
  203530. return 1;
  203531. }
  203532. const StringArray Font::findAllTypefaceNames() throw()
  203533. {
  203534. StringArray results;
  203535. HDC dc = CreateCompatibleDC (0);
  203536. {
  203537. LOGFONTW lf;
  203538. zerostruct (lf);
  203539. lf.lfWeight = FW_DONTCARE;
  203540. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203541. lf.lfQuality = DEFAULT_QUALITY;
  203542. lf.lfCharSet = DEFAULT_CHARSET;
  203543. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203544. lf.lfPitchAndFamily = FF_DONTCARE;
  203545. lf.lfFaceName[0] = 0;
  203546. EnumFontFamiliesEx (dc, &lf,
  203547. (FONTENUMPROCW) &wfontEnum1,
  203548. (LPARAM) &results, 0);
  203549. }
  203550. DeleteDC (dc);
  203551. results.sort (true);
  203552. return results;
  203553. }
  203554. extern bool juce_IsRunningInWine() throw();
  203555. void Typeface::getDefaultFontNames (String& defaultSans,
  203556. String& defaultSerif,
  203557. String& defaultFixed) throw()
  203558. {
  203559. if (juce_IsRunningInWine())
  203560. {
  203561. // If we're running in Wine, then use fonts that might be available on Linux..
  203562. defaultSans = "Bitstream Vera Sans";
  203563. defaultSerif = "Bitstream Vera Serif";
  203564. defaultFixed = "Bitstream Vera Sans Mono";
  203565. }
  203566. else
  203567. {
  203568. defaultSans = "Verdana";
  203569. defaultSerif = "Times";
  203570. defaultFixed = "Lucida Console";
  203571. }
  203572. }
  203573. class FontDCHolder : private DeletedAtShutdown
  203574. {
  203575. HDC dc;
  203576. String fontName;
  203577. KERNINGPAIR* kps;
  203578. int numKPs;
  203579. bool bold, italic;
  203580. int size;
  203581. FontDCHolder (const FontDCHolder&);
  203582. const FontDCHolder& operator= (const FontDCHolder&);
  203583. public:
  203584. HFONT fontH;
  203585. FontDCHolder() throw()
  203586. : dc (0),
  203587. kps (0),
  203588. numKPs (0),
  203589. bold (false),
  203590. italic (false),
  203591. size (0)
  203592. {
  203593. }
  203594. ~FontDCHolder() throw()
  203595. {
  203596. if (dc != 0)
  203597. {
  203598. DeleteDC (dc);
  203599. DeleteObject (fontH);
  203600. juce_free (kps);
  203601. }
  203602. clearSingletonInstance();
  203603. }
  203604. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  203605. HDC loadFont (const String& fontName_,
  203606. const bool bold_,
  203607. const bool italic_,
  203608. const int size_) throw()
  203609. {
  203610. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  203611. {
  203612. fontName = fontName_;
  203613. bold = bold_;
  203614. italic = italic_;
  203615. size = size_;
  203616. if (dc != 0)
  203617. {
  203618. DeleteDC (dc);
  203619. DeleteObject (fontH);
  203620. juce_free (kps);
  203621. kps = 0;
  203622. }
  203623. fontH = 0;
  203624. dc = CreateCompatibleDC (0);
  203625. SetMapperFlags (dc, 0);
  203626. SetMapMode (dc, MM_TEXT);
  203627. LOGFONTW lfw;
  203628. zerostruct (lfw);
  203629. lfw.lfCharSet = DEFAULT_CHARSET;
  203630. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203631. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203632. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  203633. lfw.lfQuality = PROOF_QUALITY;
  203634. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  203635. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  203636. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  203637. lfw.lfHeight = size > 0 ? size : -256;
  203638. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  203639. if (standardSizedFont != 0)
  203640. {
  203641. if (SelectObject (dc, standardSizedFont) != 0)
  203642. {
  203643. fontH = standardSizedFont;
  203644. if (size == 0)
  203645. {
  203646. OUTLINETEXTMETRIC otm;
  203647. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  203648. {
  203649. lfw.lfHeight = -(int) otm.otmEMSquare;
  203650. fontH = CreateFontIndirect (&lfw);
  203651. SelectObject (dc, fontH);
  203652. DeleteObject (standardSizedFont);
  203653. }
  203654. }
  203655. }
  203656. else
  203657. {
  203658. jassertfalse
  203659. }
  203660. }
  203661. else
  203662. {
  203663. jassertfalse
  203664. }
  203665. }
  203666. return dc;
  203667. }
  203668. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  203669. {
  203670. if (kps == 0)
  203671. {
  203672. numKPs = GetKerningPairs (dc, 0, 0);
  203673. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  203674. GetKerningPairs (dc, numKPs, kps);
  203675. }
  203676. numKPs_ = numKPs;
  203677. return kps;
  203678. }
  203679. };
  203680. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  203681. static bool addGlyphToTypeface (HDC dc,
  203682. juce_wchar character,
  203683. Typeface& dest,
  203684. bool addKerning)
  203685. {
  203686. Path destShape;
  203687. GLYPHMETRICS gm;
  203688. float height;
  203689. BOOL ok = false;
  203690. {
  203691. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  203692. WORD index = 0;
  203693. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  203694. && index == 0xffff)
  203695. {
  203696. return false;
  203697. }
  203698. }
  203699. TEXTMETRIC tm;
  203700. ok = GetTextMetrics (dc, &tm);
  203701. height = (float) tm.tmHeight;
  203702. if (! ok)
  203703. {
  203704. dest.addGlyph (character, destShape, 0);
  203705. return true;
  203706. }
  203707. const float scaleX = 1.0f / height;
  203708. const float scaleY = -1.0f / height;
  203709. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  203710. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  203711. &gm, 0, 0, &identityMatrix);
  203712. if (bufSize > 0)
  203713. {
  203714. char* const data = (char*) juce_malloc (bufSize);
  203715. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  203716. bufSize, data, &identityMatrix);
  203717. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  203718. while ((char*) pheader < data + bufSize)
  203719. {
  203720. #define remapX(v) (scaleX * (v).x.value)
  203721. #define remapY(v) (scaleY * (v).y.value)
  203722. float x = remapX (pheader->pfxStart);
  203723. float y = remapY (pheader->pfxStart);
  203724. destShape.startNewSubPath (x, y);
  203725. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  203726. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  203727. while ((const char*) curve < curveEnd)
  203728. {
  203729. if (curve->wType == TT_PRIM_LINE)
  203730. {
  203731. for (int i = 0; i < curve->cpfx; ++i)
  203732. {
  203733. x = remapX (curve->apfx [i]);
  203734. y = remapY (curve->apfx [i]);
  203735. destShape.lineTo (x, y);
  203736. }
  203737. }
  203738. else if (curve->wType == TT_PRIM_QSPLINE)
  203739. {
  203740. for (int i = 0; i < curve->cpfx - 1; ++i)
  203741. {
  203742. const float x2 = remapX (curve->apfx [i]);
  203743. const float y2 = remapY (curve->apfx [i]);
  203744. float x3, y3;
  203745. if (i < curve->cpfx - 2)
  203746. {
  203747. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  203748. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  203749. }
  203750. else
  203751. {
  203752. x3 = remapX (curve->apfx [i + 1]);
  203753. y3 = remapY (curve->apfx [i + 1]);
  203754. }
  203755. destShape.quadraticTo (x2, y2, x3, y3);
  203756. x = x3;
  203757. y = y3;
  203758. }
  203759. }
  203760. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  203761. }
  203762. pheader = (const TTPOLYGONHEADER*) curve;
  203763. destShape.closeSubPath();
  203764. }
  203765. juce_free (data);
  203766. }
  203767. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  203768. if (addKerning)
  203769. {
  203770. int numKPs;
  203771. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203772. for (int i = 0; i < numKPs; ++i)
  203773. {
  203774. if (kps[i].wFirst == character)
  203775. {
  203776. dest.addKerningPair (kps[i].wFirst,
  203777. kps[i].wSecond,
  203778. kps[i].iKernAmount / height);
  203779. }
  203780. }
  203781. }
  203782. return true;
  203783. }
  203784. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  203785. {
  203786. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  203787. return addGlyphToTypeface (dc, character, *this, true);
  203788. }
  203789. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  203790. {
  203791. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  203792. int bufSize;
  203793. GLYPHMETRICS gm;
  203794. const UINT format = GGO_GRAY2_BITMAP;
  203795. const int shift = 6;
  203796. if (wGetGlyphOutlineW != 0)
  203797. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  203798. else
  203799. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  203800. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  203801. if (bufSize > 0)
  203802. {
  203803. topLeftX = (float) gm.gmptGlyphOrigin.x;
  203804. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  203805. uint8* const data = (uint8*) juce_calloc (bufSize);
  203806. if (wGetGlyphOutlineW != 0)
  203807. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203808. else
  203809. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203810. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  203811. for (int y = gm.gmBlackBoxY; --y >= 0;)
  203812. {
  203813. for (int x = gm.gmBlackBoxX; --x >= 0;)
  203814. {
  203815. const int level = data [x + y * stride] << shift;
  203816. if (level > 0)
  203817. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  203818. }
  203819. }
  203820. juce_free (data);
  203821. }
  203822. return im;
  203823. }*/
  203824. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  203825. bool bold,
  203826. bool italic,
  203827. bool addAllGlyphsToFont) throw()
  203828. {
  203829. clear();
  203830. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  203831. float height;
  203832. int firstChar, lastChar;
  203833. {
  203834. TEXTMETRIC tm;
  203835. GetTextMetrics (dc, &tm);
  203836. height = (float) tm.tmHeight;
  203837. firstChar = tm.tmFirstChar;
  203838. lastChar = tm.tmLastChar;
  203839. setAscent (tm.tmAscent / height);
  203840. setDefaultCharacter (tm.tmDefaultChar);
  203841. }
  203842. setName (fontName);
  203843. setBold (bold);
  203844. setItalic (italic);
  203845. if (addAllGlyphsToFont)
  203846. {
  203847. for (int character = firstChar; character <= lastChar; ++character)
  203848. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  203849. int numKPs;
  203850. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203851. for (int i = 0; i < numKPs; ++i)
  203852. {
  203853. addKerningPair (kps[i].wFirst,
  203854. kps[i].wSecond,
  203855. kps[i].iKernAmount / height);
  203856. }
  203857. }
  203858. }
  203859. #endif
  203860. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203861. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203862. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203863. // compiled on its own).
  203864. #if JUCE_INCLUDED_FILE
  203865. static const void* defaultDirPath = 0;
  203866. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203867. static Component* currentExtraFileWin = 0;
  203868. static bool areThereAnyAlwaysOnTopWindows()
  203869. {
  203870. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203871. {
  203872. Component* c = Desktop::getInstance().getComponent (i);
  203873. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203874. return true;
  203875. }
  203876. return false;
  203877. }
  203878. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203879. {
  203880. if (msg == BFFM_INITIALIZED)
  203881. {
  203882. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203883. }
  203884. else if (msg == BFFM_VALIDATEFAILEDW)
  203885. {
  203886. returnedString = (LPCWSTR) lParam;
  203887. }
  203888. else if (msg == BFFM_VALIDATEFAILEDA)
  203889. {
  203890. returnedString = (const char*) lParam;
  203891. }
  203892. return 0;
  203893. }
  203894. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  203895. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203896. {
  203897. if (currentExtraFileWin != 0)
  203898. {
  203899. if (uiMsg == WM_INITDIALOG)
  203900. {
  203901. HWND dialogH = GetParent (hdlg);
  203902. jassert (dialogH != 0);
  203903. if (dialogH == 0)
  203904. dialogH = hdlg;
  203905. RECT r, cr;
  203906. GetWindowRect (dialogH, &r);
  203907. GetClientRect (dialogH, &cr);
  203908. SetWindowPos (dialogH, 0,
  203909. r.left, r.top,
  203910. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203911. jmax (150, r.bottom - r.top),
  203912. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203913. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203914. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203915. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203916. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203917. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203918. }
  203919. else if (uiMsg == WM_NOTIFY)
  203920. {
  203921. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203922. if (ofn->hdr.code == CDN_SELCHANGE)
  203923. {
  203924. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203925. if (comp != 0)
  203926. {
  203927. TCHAR path [MAX_PATH * 2];
  203928. path[0] = 0;
  203929. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203930. const String fn ((const WCHAR*) path);
  203931. comp->selectedFileChanged (File (fn));
  203932. }
  203933. }
  203934. }
  203935. }
  203936. return 0;
  203937. }
  203938. class FPComponentHolder : public Component
  203939. {
  203940. public:
  203941. FPComponentHolder()
  203942. {
  203943. setVisible (true);
  203944. setOpaque (true);
  203945. }
  203946. ~FPComponentHolder()
  203947. {
  203948. }
  203949. void paint (Graphics& g)
  203950. {
  203951. g.fillAll (Colours::lightgrey);
  203952. }
  203953. private:
  203954. FPComponentHolder (const FPComponentHolder&);
  203955. const FPComponentHolder& operator= (const FPComponentHolder&);
  203956. };
  203957. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203958. const String& title,
  203959. const File& currentFileOrDirectory,
  203960. const String& filter,
  203961. bool selectsDirectory,
  203962. bool isSaveDialogue,
  203963. bool warnAboutOverwritingExistingFiles,
  203964. bool selectMultipleFiles,
  203965. FilePreviewComponent* extraInfoComponent)
  203966. {
  203967. const int numCharsAvailable = 32768;
  203968. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203969. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203970. int fnameIdx = 0;
  203971. JUCE_TRY
  203972. {
  203973. // use a modal window as the parent for this dialog box
  203974. // to block input from other app windows
  203975. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203976. Component w (String::empty);
  203977. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203978. mainMon.getY() + mainMon.getHeight() / 4,
  203979. 0, 0);
  203980. w.setOpaque (true);
  203981. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203982. w.addToDesktop (0);
  203983. if (extraInfoComponent == 0)
  203984. w.enterModalState();
  203985. String initialDir;
  203986. if (currentFileOrDirectory.isDirectory())
  203987. {
  203988. initialDir = currentFileOrDirectory.getFullPathName();
  203989. }
  203990. else
  203991. {
  203992. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203993. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203994. }
  203995. if (currentExtraFileWin->isValidComponent())
  203996. {
  203997. jassertfalse
  203998. return;
  203999. }
  204000. if (selectsDirectory)
  204001. {
  204002. LPITEMIDLIST list = 0;
  204003. filenameSpace.fillWith (0);
  204004. {
  204005. BROWSEINFO bi;
  204006. zerostruct (bi);
  204007. bi.hwndOwner = (HWND) w.getWindowHandle();
  204008. bi.pszDisplayName = fname;
  204009. bi.lpszTitle = title;
  204010. bi.lpfn = browseCallbackProc;
  204011. #ifdef BIF_USENEWUI
  204012. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  204013. #else
  204014. bi.ulFlags = 0x50;
  204015. #endif
  204016. defaultDirPath = (const WCHAR*) initialDir;
  204017. list = SHBrowseForFolder (&bi);
  204018. if (! SHGetPathFromIDListW (list, fname))
  204019. {
  204020. fname[0] = 0;
  204021. returnedString = String::empty;
  204022. }
  204023. }
  204024. LPMALLOC al;
  204025. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  204026. al->Free (list);
  204027. defaultDirPath = 0;
  204028. if (returnedString.isNotEmpty())
  204029. {
  204030. const String stringFName (fname);
  204031. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  204032. returnedString = String::empty;
  204033. return;
  204034. }
  204035. }
  204036. else
  204037. {
  204038. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  204039. if (warnAboutOverwritingExistingFiles)
  204040. flags |= OFN_OVERWRITEPROMPT;
  204041. if (selectMultipleFiles)
  204042. flags |= OFN_ALLOWMULTISELECT;
  204043. if (extraInfoComponent != 0)
  204044. {
  204045. flags |= OFN_ENABLEHOOK;
  204046. currentExtraFileWin = new FPComponentHolder();
  204047. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  204048. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  204049. extraInfoComponent->getHeight());
  204050. currentExtraFileWin->addToDesktop (0);
  204051. currentExtraFileWin->enterModalState();
  204052. }
  204053. {
  204054. WCHAR filters [1024];
  204055. zeromem (filters, sizeof (filters));
  204056. filter.copyToBuffer (filters, 1024);
  204057. filter.copyToBuffer (filters + filter.length() + 1,
  204058. 1022 - filter.length());
  204059. OPENFILENAMEW of;
  204060. zerostruct (of);
  204061. #ifdef OPENFILENAME_SIZE_VERSION_400W
  204062. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  204063. #else
  204064. of.lStructSize = sizeof (of);
  204065. #endif
  204066. of.hwndOwner = (HWND) w.getWindowHandle();
  204067. of.lpstrFilter = filters;
  204068. of.nFilterIndex = 1;
  204069. of.lpstrFile = fname;
  204070. of.nMaxFile = numCharsAvailable;
  204071. of.lpstrInitialDir = initialDir;
  204072. of.lpstrTitle = title;
  204073. of.Flags = flags;
  204074. if (extraInfoComponent != 0)
  204075. of.lpfnHook = &openCallback;
  204076. if (isSaveDialogue)
  204077. {
  204078. if (! GetSaveFileName (&of))
  204079. fname[0] = 0;
  204080. else
  204081. fnameIdx = of.nFileOffset;
  204082. }
  204083. else
  204084. {
  204085. if (! GetOpenFileName (&of))
  204086. fname[0] = 0;
  204087. else
  204088. fnameIdx = of.nFileOffset;
  204089. }
  204090. }
  204091. }
  204092. }
  204093. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204094. catch (...)
  204095. {
  204096. fname[0] = 0;
  204097. }
  204098. #endif
  204099. deleteAndZero (currentExtraFileWin);
  204100. const WCHAR* const files = fname;
  204101. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  204102. {
  204103. const WCHAR* filename = files + fnameIdx;
  204104. while (*filename != 0)
  204105. {
  204106. const String filepath (String (files) + T("\\") + String (filename));
  204107. results.add (new File (filepath));
  204108. filename += CharacterFunctions::length (filename) + 1;
  204109. }
  204110. }
  204111. else if (files[0] != 0)
  204112. {
  204113. results.add (new File (files));
  204114. }
  204115. }
  204116. #endif
  204117. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  204118. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  204119. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204120. // compiled on its own).
  204121. #if JUCE_INCLUDED_FILE
  204122. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  204123. {
  204124. if (OpenClipboard (0) != 0)
  204125. {
  204126. if (EmptyClipboard() != 0)
  204127. {
  204128. const int len = text.length();
  204129. if (len > 0)
  204130. {
  204131. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  204132. (len + 1) * sizeof (wchar_t));
  204133. if (bufH != 0)
  204134. {
  204135. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  204136. text.copyToBuffer (data, len);
  204137. GlobalUnlock (bufH);
  204138. SetClipboardData (CF_UNICODETEXT, bufH);
  204139. }
  204140. }
  204141. }
  204142. CloseClipboard();
  204143. }
  204144. }
  204145. const String SystemClipboard::getTextFromClipboard() throw()
  204146. {
  204147. String result;
  204148. if (OpenClipboard (0) != 0)
  204149. {
  204150. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  204151. if (bufH != 0)
  204152. {
  204153. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  204154. if (data != 0)
  204155. {
  204156. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  204157. GlobalUnlock (bufH);
  204158. }
  204159. }
  204160. CloseClipboard();
  204161. }
  204162. return result;
  204163. }
  204164. #endif
  204165. /********* End of inlined file: juce_win32_Misc.cpp *********/
  204166. /********* Start of inlined file: juce_win32_ActiveXComponent.cpp *********/
  204167. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204168. // compiled on its own).
  204169. #if JUCE_INCLUDED_FILE
  204170. class JuceIStorage : public IStorage
  204171. {
  204172. int refCount;
  204173. public:
  204174. JuceIStorage() : refCount (1) {}
  204175. virtual ~JuceIStorage()
  204176. {
  204177. jassert (refCount == 0);
  204178. }
  204179. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204180. {
  204181. if (id == IID_IUnknown || id == IID_IStorage)
  204182. {
  204183. AddRef();
  204184. *result = this;
  204185. return S_OK;
  204186. }
  204187. *result = 0;
  204188. return E_NOINTERFACE;
  204189. }
  204190. ULONG __stdcall AddRef() { return ++refCount; }
  204191. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204192. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204193. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204194. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  204195. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  204196. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  204197. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  204198. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  204199. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  204200. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  204201. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  204202. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  204203. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  204204. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  204205. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  204206. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  204207. juce_UseDebuggingNewOperator
  204208. };
  204209. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  204210. {
  204211. int refCount;
  204212. HWND window;
  204213. public:
  204214. JuceOleInPlaceFrame (HWND window_)
  204215. : refCount (1),
  204216. window (window_)
  204217. {
  204218. }
  204219. virtual ~JuceOleInPlaceFrame()
  204220. {
  204221. jassert (refCount == 0);
  204222. }
  204223. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204224. {
  204225. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  204226. {
  204227. AddRef();
  204228. *result = this;
  204229. return S_OK;
  204230. }
  204231. *result = 0;
  204232. return E_NOINTERFACE;
  204233. }
  204234. ULONG __stdcall AddRef() { return ++refCount; }
  204235. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204236. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204237. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204238. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  204239. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204240. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204241. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  204242. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  204243. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  204244. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  204245. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  204246. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  204247. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  204248. juce_UseDebuggingNewOperator
  204249. };
  204250. class JuceIOleInPlaceSite : public IOleInPlaceSite
  204251. {
  204252. int refCount;
  204253. HWND window;
  204254. JuceOleInPlaceFrame* frame;
  204255. public:
  204256. JuceIOleInPlaceSite (HWND window_)
  204257. : refCount (1),
  204258. window (window_)
  204259. {
  204260. frame = new JuceOleInPlaceFrame (window);
  204261. }
  204262. virtual ~JuceIOleInPlaceSite()
  204263. {
  204264. jassert (refCount == 0);
  204265. frame->Release();
  204266. }
  204267. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204268. {
  204269. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  204270. {
  204271. AddRef();
  204272. *result = this;
  204273. return S_OK;
  204274. }
  204275. *result = 0;
  204276. return E_NOINTERFACE;
  204277. }
  204278. ULONG __stdcall AddRef() { return ++refCount; }
  204279. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204280. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204281. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204282. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  204283. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  204284. HRESULT __stdcall OnUIActivate() { return S_OK; }
  204285. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  204286. {
  204287. frame->AddRef();
  204288. *lplpFrame = frame;
  204289. *lplpDoc = 0;
  204290. lpFrameInfo->fMDIApp = FALSE;
  204291. lpFrameInfo->hwndFrame = window;
  204292. lpFrameInfo->haccel = 0;
  204293. lpFrameInfo->cAccelEntries = 0;
  204294. return S_OK;
  204295. }
  204296. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  204297. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  204298. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  204299. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  204300. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  204301. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  204302. juce_UseDebuggingNewOperator
  204303. };
  204304. class JuceIOleClientSite : public IOleClientSite
  204305. {
  204306. int refCount;
  204307. JuceIOleInPlaceSite* inplaceSite;
  204308. public:
  204309. JuceIOleClientSite (HWND window)
  204310. : refCount (1)
  204311. {
  204312. inplaceSite = new JuceIOleInPlaceSite (window);
  204313. }
  204314. virtual ~JuceIOleClientSite()
  204315. {
  204316. jassert (refCount == 0);
  204317. inplaceSite->Release();
  204318. }
  204319. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204320. {
  204321. if (id == IID_IUnknown || id == IID_IOleClientSite)
  204322. {
  204323. AddRef();
  204324. *result = this;
  204325. return S_OK;
  204326. }
  204327. else if (id == IID_IOleInPlaceSite)
  204328. {
  204329. inplaceSite->AddRef();
  204330. *result = inplaceSite;
  204331. return S_OK;
  204332. }
  204333. *result = 0;
  204334. return E_NOINTERFACE;
  204335. }
  204336. ULONG __stdcall AddRef() { return ++refCount; }
  204337. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204338. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  204339. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  204340. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  204341. HRESULT __stdcall ShowObject() { return S_OK; }
  204342. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  204343. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  204344. juce_UseDebuggingNewOperator
  204345. };
  204346. class ActiveXControlData : public ComponentMovementWatcher
  204347. {
  204348. ActiveXControlComponent* const owner;
  204349. bool wasShowing;
  204350. public:
  204351. HWND controlHWND;
  204352. IStorage* storage;
  204353. IOleClientSite* clientSite;
  204354. IOleObject* control;
  204355. ActiveXControlData (HWND hwnd,
  204356. ActiveXControlComponent* const owner_)
  204357. : ComponentMovementWatcher (owner_),
  204358. owner (owner_),
  204359. wasShowing (owner_ != 0 && owner_->isShowing()),
  204360. controlHWND (0),
  204361. storage (new JuceIStorage()),
  204362. clientSite (new JuceIOleClientSite (hwnd)),
  204363. control (0)
  204364. {
  204365. }
  204366. ~ActiveXControlData()
  204367. {
  204368. if (control != 0)
  204369. {
  204370. control->Close (OLECLOSE_NOSAVE);
  204371. control->Release();
  204372. }
  204373. clientSite->Release();
  204374. storage->Release();
  204375. }
  204376. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  204377. {
  204378. Component* const topComp = owner->getTopLevelComponent();
  204379. if (topComp->getPeer() != 0)
  204380. {
  204381. int x = 0, y = 0;
  204382. owner->relativePositionToOtherComponent (topComp, x, y);
  204383. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  204384. }
  204385. }
  204386. void componentPeerChanged()
  204387. {
  204388. const bool isShowingNow = owner->isShowing();
  204389. if (wasShowing != isShowingNow)
  204390. {
  204391. wasShowing = isShowingNow;
  204392. owner->setControlVisible (isShowingNow);
  204393. }
  204394. componentMovedOrResized (true, true);
  204395. }
  204396. void componentVisibilityChanged (Component&)
  204397. {
  204398. componentPeerChanged();
  204399. }
  204400. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  204401. {
  204402. return ((ActiveXControlData*) ax->control) != 0
  204403. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  204404. }
  204405. };
  204406. static VoidArray activeXComps;
  204407. static HWND getHWND (const ActiveXControlComponent* const component)
  204408. {
  204409. HWND hwnd = 0;
  204410. const IID iid = IID_IOleWindow;
  204411. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  204412. if (window != 0)
  204413. {
  204414. window->GetWindow (&hwnd);
  204415. window->Release();
  204416. }
  204417. return hwnd;
  204418. }
  204419. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  204420. {
  204421. RECT activeXRect, peerRect;
  204422. GetWindowRect (hwnd, &activeXRect);
  204423. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  204424. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  204425. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  204426. const int64 mouseEventTime = getMouseEventTime();
  204427. const int oldModifiers = currentModifiers;
  204428. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  204429. switch (message)
  204430. {
  204431. case WM_MOUSEMOVE:
  204432. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  204433. peer->handleMouseDrag (mx, my, mouseEventTime);
  204434. else
  204435. peer->handleMouseMove (mx, my, mouseEventTime);
  204436. break;
  204437. case WM_LBUTTONDOWN:
  204438. case WM_MBUTTONDOWN:
  204439. case WM_RBUTTONDOWN:
  204440. peer->handleMouseDown (mx, my, mouseEventTime);
  204441. break;
  204442. case WM_LBUTTONUP:
  204443. case WM_MBUTTONUP:
  204444. case WM_RBUTTONUP:
  204445. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  204446. break;
  204447. default:
  204448. break;
  204449. }
  204450. }
  204451. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  204452. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  204453. {
  204454. for (int i = activeXComps.size(); --i >= 0;)
  204455. {
  204456. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  204457. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  204458. {
  204459. switch (message)
  204460. {
  204461. case WM_MOUSEMOVE:
  204462. case WM_LBUTTONDOWN:
  204463. case WM_MBUTTONDOWN:
  204464. case WM_RBUTTONDOWN:
  204465. case WM_LBUTTONUP:
  204466. case WM_MBUTTONUP:
  204467. case WM_RBUTTONUP:
  204468. case WM_LBUTTONDBLCLK:
  204469. case WM_MBUTTONDBLCLK:
  204470. case WM_RBUTTONDBLCLK:
  204471. if (ax->isShowing())
  204472. {
  204473. ComponentPeer* const peer = ax->getPeer();
  204474. if (peer != 0)
  204475. {
  204476. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  204477. if (! ax->areMouseEventsAllowed())
  204478. return 0;
  204479. }
  204480. }
  204481. break;
  204482. default:
  204483. break;
  204484. }
  204485. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  204486. }
  204487. }
  204488. return DefWindowProc (hwnd, message, wParam, lParam);
  204489. }
  204490. ActiveXControlComponent::ActiveXControlComponent()
  204491. : originalWndProc (0),
  204492. control (0),
  204493. mouseEventsAllowed (true)
  204494. {
  204495. activeXComps.add (this);
  204496. }
  204497. ActiveXControlComponent::~ActiveXControlComponent()
  204498. {
  204499. deleteControl();
  204500. activeXComps.removeValue (this);
  204501. }
  204502. void ActiveXControlComponent::paint (Graphics& g)
  204503. {
  204504. if (control == 0)
  204505. g.fillAll (Colours::lightgrey);
  204506. }
  204507. bool ActiveXControlComponent::createControl (const void* controlIID)
  204508. {
  204509. deleteControl();
  204510. ComponentPeer* const peer = getPeer();
  204511. // the component must have already been added to a real window when you call this!
  204512. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  204513. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  204514. {
  204515. int x = 0, y = 0;
  204516. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  204517. HWND hwnd = (HWND) peer->getNativeHandle();
  204518. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  204519. HRESULT hr;
  204520. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  204521. info->clientSite, info->storage,
  204522. (void**) &(info->control))) == S_OK)
  204523. {
  204524. info->control->SetHostNames (L"Juce", 0);
  204525. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  204526. {
  204527. RECT rect;
  204528. rect.left = x;
  204529. rect.top = y;
  204530. rect.right = x + getWidth();
  204531. rect.bottom = y + getHeight();
  204532. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  204533. {
  204534. control = info;
  204535. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  204536. info->controlHWND = getHWND (this);
  204537. if (info->controlHWND != 0)
  204538. {
  204539. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  204540. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  204541. }
  204542. return true;
  204543. }
  204544. }
  204545. }
  204546. delete info;
  204547. }
  204548. return false;
  204549. }
  204550. void ActiveXControlComponent::deleteControl()
  204551. {
  204552. ActiveXControlData* const info = (ActiveXControlData*) control;
  204553. if (info != 0)
  204554. {
  204555. delete info;
  204556. control = 0;
  204557. originalWndProc = 0;
  204558. }
  204559. }
  204560. void* ActiveXControlComponent::queryInterface (const void* iid) const
  204561. {
  204562. ActiveXControlData* const info = (ActiveXControlData*) control;
  204563. void* result = 0;
  204564. if (info != 0 && info->control != 0
  204565. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  204566. return result;
  204567. return 0;
  204568. }
  204569. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  204570. {
  204571. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204572. if (hwnd != 0)
  204573. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  204574. }
  204575. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  204576. {
  204577. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204578. if (hwnd != 0)
  204579. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204580. }
  204581. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  204582. {
  204583. mouseEventsAllowed = eventsCanReachControl;
  204584. }
  204585. #endif
  204586. /********* End of inlined file: juce_win32_ActiveXComponent.cpp *********/
  204587. /********* Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204588. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204589. // compiled on its own).
  204590. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  204591. using namespace QTOLibrary;
  204592. using namespace QTOControlLib;
  204593. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  204594. static bool isQTAvailable = false;
  204595. struct QTMovieCompInternal
  204596. {
  204597. QTMovieCompInternal()
  204598. : dataHandle (0)
  204599. {
  204600. }
  204601. ~QTMovieCompInternal()
  204602. {
  204603. clearHandle();
  204604. }
  204605. IQTControlPtr qtControlInternal;
  204606. IQTMoviePtr qtMovieInternal;
  204607. Handle dataHandle;
  204608. void clearHandle()
  204609. {
  204610. if (dataHandle != 0)
  204611. {
  204612. DisposeHandle (dataHandle);
  204613. dataHandle = 0;
  204614. }
  204615. }
  204616. };
  204617. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  204618. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  204619. QuickTimeMovieComponent::QuickTimeMovieComponent()
  204620. : movieLoaded (false),
  204621. controllerVisible (true)
  204622. {
  204623. internal = new QTMovieCompInternal();
  204624. setMouseEventsAllowed (false);
  204625. }
  204626. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  204627. {
  204628. closeMovie();
  204629. qtControl = 0;
  204630. deleteControl();
  204631. delete internal;
  204632. internal = 0;
  204633. }
  204634. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  204635. {
  204636. if (! isQTAvailable)
  204637. {
  204638. isQTAvailable = (InitializeQTML (0) == noErr)
  204639. && (EnterMovies() == noErr);
  204640. }
  204641. return isQTAvailable;
  204642. }
  204643. void QuickTimeMovieComponent::createControlIfNeeded()
  204644. {
  204645. if (isShowing() && ! isControlCreated())
  204646. {
  204647. const IID qtIID = __uuidof (QTControl);
  204648. if (createControl (&qtIID))
  204649. {
  204650. const IID qtInterfaceIID = __uuidof (IQTControl);
  204651. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  204652. if (qtControl != 0)
  204653. {
  204654. qtControl->Release(); // it has one ref too many at this point
  204655. qtControl->QuickTimeInitialize();
  204656. qtControl->PutSizing (qtMovieFitsControl);
  204657. if (movieFile != File::nonexistent)
  204658. loadMovie (movieFile, controllerVisible);
  204659. }
  204660. }
  204661. }
  204662. }
  204663. bool QuickTimeMovieComponent::isControlCreated() const
  204664. {
  204665. return isControlOpen();
  204666. }
  204667. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  204668. const bool isControllerVisible)
  204669. {
  204670. movieFile = File::nonexistent;
  204671. movieLoaded = false;
  204672. qtMovie = 0;
  204673. controllerVisible = isControllerVisible;
  204674. createControlIfNeeded();
  204675. if (isControlCreated())
  204676. {
  204677. if (qtControl != 0)
  204678. {
  204679. qtControl->Put_MovieHandle (0);
  204680. ((QTMovieCompInternal*) internal)->clearHandle();
  204681. Movie movie;
  204682. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  204683. {
  204684. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  204685. qtMovie = qtControl->GetMovie();
  204686. if (qtMovie != 0)
  204687. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  204688. : qtMovieControllerTypeNone);
  204689. }
  204690. if (movie == 0)
  204691. ((QTMovieCompInternal*) internal)->clearHandle();
  204692. }
  204693. movieLoaded = (qtMovie != 0);
  204694. }
  204695. else
  204696. {
  204697. // You're trying to open a movie when the control hasn't yet been created, probably because
  204698. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  204699. jassertfalse
  204700. }
  204701. delete movieStream;
  204702. return movieLoaded;
  204703. }
  204704. void QuickTimeMovieComponent::closeMovie()
  204705. {
  204706. stop();
  204707. movieFile = File::nonexistent;
  204708. movieLoaded = false;
  204709. qtMovie = 0;
  204710. if (qtControl != 0)
  204711. qtControl->Put_MovieHandle (0);
  204712. ((QTMovieCompInternal*) internal)->clearHandle();
  204713. }
  204714. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  204715. {
  204716. return movieFile;
  204717. }
  204718. bool QuickTimeMovieComponent::isMovieOpen() const
  204719. {
  204720. return movieLoaded;
  204721. }
  204722. double QuickTimeMovieComponent::getMovieDuration() const
  204723. {
  204724. if (qtMovie != 0)
  204725. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  204726. return 0.0;
  204727. }
  204728. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  204729. {
  204730. if (qtMovie != 0)
  204731. {
  204732. struct QTRECT r = qtMovie->GetNaturalRect();
  204733. width = r.right - r.left;
  204734. height = r.bottom - r.top;
  204735. }
  204736. else
  204737. {
  204738. width = height = 0;
  204739. }
  204740. }
  204741. void QuickTimeMovieComponent::play()
  204742. {
  204743. if (qtMovie != 0)
  204744. qtMovie->Play();
  204745. }
  204746. void QuickTimeMovieComponent::stop()
  204747. {
  204748. if (qtMovie != 0)
  204749. qtMovie->Stop();
  204750. }
  204751. bool QuickTimeMovieComponent::isPlaying() const
  204752. {
  204753. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  204754. }
  204755. void QuickTimeMovieComponent::setPosition (const double seconds)
  204756. {
  204757. if (qtMovie != 0)
  204758. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  204759. }
  204760. double QuickTimeMovieComponent::getPosition() const
  204761. {
  204762. if (qtMovie != 0)
  204763. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  204764. return 0.0;
  204765. }
  204766. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  204767. {
  204768. if (qtMovie != 0)
  204769. qtMovie->PutRate (newSpeed);
  204770. }
  204771. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  204772. {
  204773. if (qtMovie != 0)
  204774. {
  204775. qtMovie->PutAudioVolume (newVolume);
  204776. qtMovie->PutAudioMute (newVolume <= 0);
  204777. }
  204778. }
  204779. float QuickTimeMovieComponent::getMovieVolume() const
  204780. {
  204781. if (qtMovie != 0)
  204782. return qtMovie->GetAudioVolume();
  204783. return 0.0f;
  204784. }
  204785. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  204786. {
  204787. if (qtMovie != 0)
  204788. qtMovie->PutLoop (shouldLoop);
  204789. }
  204790. bool QuickTimeMovieComponent::isLooping() const
  204791. {
  204792. return qtMovie != 0 && qtMovie->GetLoop();
  204793. }
  204794. bool QuickTimeMovieComponent::isControllerVisible() const
  204795. {
  204796. return controllerVisible;
  204797. }
  204798. void QuickTimeMovieComponent::parentHierarchyChanged()
  204799. {
  204800. createControlIfNeeded();
  204801. QTCompBaseClass::parentHierarchyChanged();
  204802. }
  204803. void QuickTimeMovieComponent::visibilityChanged()
  204804. {
  204805. createControlIfNeeded();
  204806. QTCompBaseClass::visibilityChanged();
  204807. }
  204808. void QuickTimeMovieComponent::paint (Graphics& g)
  204809. {
  204810. if (! isControlCreated())
  204811. g.fillAll (Colours::black);
  204812. }
  204813. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  204814. {
  204815. Handle dataRef = 0;
  204816. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  204817. if (err == noErr)
  204818. {
  204819. Str255 suffix;
  204820. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  204821. StringPtr name = suffix;
  204822. err = PtrAndHand (name, dataRef, name[0] + 1);
  204823. if (err == noErr)
  204824. {
  204825. long atoms[3];
  204826. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  204827. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  204828. atoms[2] = EndianU32_NtoB (MovieFileType);
  204829. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  204830. if (err == noErr)
  204831. return dataRef;
  204832. }
  204833. DisposeHandle (dataRef);
  204834. }
  204835. return 0;
  204836. }
  204837. static CFStringRef juceStringToCFString (const String& s)
  204838. {
  204839. const int len = s.length();
  204840. const juce_wchar* const t = (const juce_wchar*) s;
  204841. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  204842. for (int i = 0; i <= len; ++i)
  204843. temp[i] = t[i];
  204844. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  204845. juce_free (temp);
  204846. return result;
  204847. }
  204848. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  204849. {
  204850. Boolean trueBool = true;
  204851. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204852. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  204853. props[prop].propValueSize = sizeof (trueBool);
  204854. props[prop].propValueAddress = &trueBool;
  204855. ++prop;
  204856. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204857. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  204858. props[prop].propValueSize = sizeof (trueBool);
  204859. props[prop].propValueAddress = &trueBool;
  204860. ++prop;
  204861. Boolean isActive = true;
  204862. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  204863. props[prop].propID = kQTNewMoviePropertyID_Active;
  204864. props[prop].propValueSize = sizeof (isActive);
  204865. props[prop].propValueAddress = &isActive;
  204866. ++prop;
  204867. MacSetPort (0);
  204868. jassert (prop <= 5);
  204869. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  204870. return err == noErr;
  204871. }
  204872. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  204873. {
  204874. if (input == 0)
  204875. return false;
  204876. dataHandle = 0;
  204877. bool ok = false;
  204878. QTNewMoviePropertyElement props[5];
  204879. zeromem (props, sizeof (props));
  204880. int prop = 0;
  204881. DataReferenceRecord dr;
  204882. props[prop].propClass = kQTPropertyClass_DataLocation;
  204883. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  204884. props[prop].propValueSize = sizeof (dr);
  204885. props[prop].propValueAddress = (void*) &dr;
  204886. ++prop;
  204887. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  204888. if (fin != 0)
  204889. {
  204890. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  204891. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  204892. &dr.dataRef, &dr.dataRefType);
  204893. ok = openMovie (props, prop, movie);
  204894. DisposeHandle (dr.dataRef);
  204895. CFRelease (filePath);
  204896. }
  204897. else
  204898. {
  204899. // sanity-check because this currently needs to load the whole stream into memory..
  204900. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  204901. dataHandle = NewHandle ((Size) input->getTotalLength());
  204902. HLock (dataHandle);
  204903. // read the entire stream into memory - this is a pain, but can't get it to work
  204904. // properly using a custom callback to supply the data.
  204905. input->read (*dataHandle, (int) input->getTotalLength());
  204906. HUnlock (dataHandle);
  204907. // different types to get QT to try. (We should really be a bit smarter here by
  204908. // working out in advance which one the stream contains, rather than just trying
  204909. // each one)
  204910. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  204911. "\04.avi", "\04.m4a" };
  204912. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  204913. {
  204914. /* // this fails for some bizarre reason - it can be bodged to work with
  204915. // movies, but can't seem to do it for other file types..
  204916. QTNewMovieUserProcRecord procInfo;
  204917. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  204918. procInfo.getMovieUserProcRefcon = this;
  204919. procInfo.defaultDataRef.dataRef = dataRef;
  204920. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  204921. props[prop].propClass = kQTPropertyClass_DataLocation;
  204922. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  204923. props[prop].propValueSize = sizeof (procInfo);
  204924. props[prop].propValueAddress = (void*) &procInfo;
  204925. ++prop; */
  204926. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  204927. dr.dataRefType = HandleDataHandlerSubType;
  204928. ok = openMovie (props, prop, movie);
  204929. DisposeHandle (dr.dataRef);
  204930. }
  204931. }
  204932. return ok;
  204933. }
  204934. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  204935. const bool isControllerVisible)
  204936. {
  204937. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  204938. movieFile = movieFile_;
  204939. return ok;
  204940. }
  204941. void QuickTimeMovieComponent::goToStart()
  204942. {
  204943. setPosition (0.0);
  204944. }
  204945. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  204946. const RectanglePlacement& placement)
  204947. {
  204948. int normalWidth, normalHeight;
  204949. getMovieNormalSize (normalWidth, normalHeight);
  204950. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  204951. {
  204952. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  204953. placement.applyTo (x, y, w, h,
  204954. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  204955. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  204956. if (w > 0 && h > 0)
  204957. {
  204958. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  204959. roundDoubleToInt (w), roundDoubleToInt (h));
  204960. }
  204961. }
  204962. else
  204963. {
  204964. setBounds (spaceToFitWithin);
  204965. }
  204966. }
  204967. #endif
  204968. /********* End of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204969. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204970. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204971. // compiled on its own).
  204972. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  204973. class WebBrowserComponentInternal : public ActiveXControlComponent
  204974. {
  204975. public:
  204976. WebBrowserComponentInternal()
  204977. : browser (0),
  204978. connectionPoint (0),
  204979. adviseCookie (0)
  204980. {
  204981. }
  204982. ~WebBrowserComponentInternal()
  204983. {
  204984. if (connectionPoint != 0)
  204985. connectionPoint->Unadvise (adviseCookie);
  204986. if (browser != 0)
  204987. browser->Release();
  204988. }
  204989. void createBrowser()
  204990. {
  204991. createControl (&CLSID_WebBrowser);
  204992. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204993. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204994. if (connectionPointContainer != 0)
  204995. {
  204996. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204997. &connectionPoint);
  204998. if (connectionPoint != 0)
  204999. {
  205000. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  205001. jassert (owner != 0);
  205002. EventHandler* handler = new EventHandler (owner);
  205003. connectionPoint->Advise (handler, &adviseCookie);
  205004. }
  205005. }
  205006. }
  205007. void goToURL (const String& url,
  205008. const StringArray* headers,
  205009. const MemoryBlock* postData)
  205010. {
  205011. if (browser != 0)
  205012. {
  205013. LPSAFEARRAY sa = 0;
  205014. _variant_t flags, frame, postDataVar, headersVar;
  205015. if (headers != 0)
  205016. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  205017. if (postData != 0 && postData->getSize() > 0)
  205018. {
  205019. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  205020. if (sa != 0)
  205021. {
  205022. void* data = 0;
  205023. SafeArrayAccessData (sa, &data);
  205024. jassert (data != 0);
  205025. if (data != 0)
  205026. {
  205027. postData->copyTo (data, 0, postData->getSize());
  205028. SafeArrayUnaccessData (sa);
  205029. VARIANT postDataVar2;
  205030. VariantInit (&postDataVar2);
  205031. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  205032. V_ARRAY (&postDataVar2) = sa;
  205033. postDataVar = postDataVar2;
  205034. }
  205035. }
  205036. }
  205037. browser->Navigate ((BSTR) (const OLECHAR*) url,
  205038. &flags, &frame,
  205039. &postDataVar, &headersVar);
  205040. if (sa != 0)
  205041. SafeArrayDestroy (sa);
  205042. }
  205043. }
  205044. IWebBrowser2* browser;
  205045. juce_UseDebuggingNewOperator
  205046. private:
  205047. IConnectionPoint* connectionPoint;
  205048. DWORD adviseCookie;
  205049. class EventHandler : public IDispatch,
  205050. public ComponentMovementWatcher
  205051. {
  205052. public:
  205053. EventHandler (WebBrowserComponent* owner_)
  205054. : ComponentMovementWatcher (owner_),
  205055. owner (owner_),
  205056. refCount (0)
  205057. {
  205058. }
  205059. ~EventHandler()
  205060. {
  205061. }
  205062. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  205063. {
  205064. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  205065. {
  205066. AddRef();
  205067. *result = this;
  205068. return S_OK;
  205069. }
  205070. *result = 0;
  205071. return E_NOINTERFACE;
  205072. }
  205073. ULONG __stdcall AddRef() { return ++refCount; }
  205074. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  205075. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205076. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205077. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205078. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205079. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205080. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205081. UINT __RPC_FAR* /*puArgErr*/)
  205082. {
  205083. switch (dispIdMember)
  205084. {
  205085. case DISPID_BEFORENAVIGATE2:
  205086. {
  205087. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205088. String url;
  205089. if ((vurl->vt & VT_BYREF) != 0)
  205090. url = *vurl->pbstrVal;
  205091. else
  205092. url = vurl->bstrVal;
  205093. *pDispParams->rgvarg->pboolVal
  205094. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205095. : VARIANT_TRUE;
  205096. return S_OK;
  205097. }
  205098. default:
  205099. break;
  205100. }
  205101. return E_NOTIMPL;
  205102. }
  205103. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  205104. void componentPeerChanged() {}
  205105. void componentVisibilityChanged (Component&)
  205106. {
  205107. owner->visibilityChanged();
  205108. }
  205109. juce_UseDebuggingNewOperator
  205110. private:
  205111. WebBrowserComponent* const owner;
  205112. int refCount;
  205113. EventHandler (const EventHandler&);
  205114. const EventHandler& operator= (const EventHandler&);
  205115. };
  205116. };
  205117. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  205118. : browser (0),
  205119. blankPageShown (false),
  205120. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  205121. {
  205122. setOpaque (true);
  205123. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205124. }
  205125. WebBrowserComponent::~WebBrowserComponent()
  205126. {
  205127. delete browser;
  205128. }
  205129. void WebBrowserComponent::goToURL (const String& url,
  205130. const StringArray* headers,
  205131. const MemoryBlock* postData)
  205132. {
  205133. lastURL = url;
  205134. lastHeaders.clear();
  205135. if (headers != 0)
  205136. lastHeaders = *headers;
  205137. lastPostData.setSize (0);
  205138. if (postData != 0)
  205139. lastPostData = *postData;
  205140. blankPageShown = false;
  205141. browser->goToURL (url, headers, postData);
  205142. }
  205143. void WebBrowserComponent::stop()
  205144. {
  205145. if (browser->browser != 0)
  205146. browser->browser->Stop();
  205147. }
  205148. void WebBrowserComponent::goBack()
  205149. {
  205150. lastURL = String::empty;
  205151. blankPageShown = false;
  205152. if (browser->browser != 0)
  205153. browser->browser->GoBack();
  205154. }
  205155. void WebBrowserComponent::goForward()
  205156. {
  205157. lastURL = String::empty;
  205158. if (browser->browser != 0)
  205159. browser->browser->GoForward();
  205160. }
  205161. void WebBrowserComponent::refresh()
  205162. {
  205163. if (browser->browser != 0)
  205164. browser->browser->Refresh();
  205165. }
  205166. void WebBrowserComponent::paint (Graphics& g)
  205167. {
  205168. if (browser->browser == 0)
  205169. g.fillAll (Colours::white);
  205170. }
  205171. void WebBrowserComponent::checkWindowAssociation()
  205172. {
  205173. if (isShowing())
  205174. {
  205175. if (browser->browser == 0 && getPeer() != 0)
  205176. {
  205177. browser->createBrowser();
  205178. reloadLastURL();
  205179. }
  205180. else
  205181. {
  205182. if (blankPageShown)
  205183. goBack();
  205184. }
  205185. }
  205186. else
  205187. {
  205188. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  205189. {
  205190. // when the component becomes invisible, some stuff like flash
  205191. // carries on playing audio, so we need to force it onto a blank
  205192. // page to avoid this..
  205193. blankPageShown = true;
  205194. browser->goToURL ("about:blank", 0, 0);
  205195. }
  205196. }
  205197. }
  205198. void WebBrowserComponent::reloadLastURL()
  205199. {
  205200. if (lastURL.isNotEmpty())
  205201. {
  205202. goToURL (lastURL, &lastHeaders, &lastPostData);
  205203. lastURL = String::empty;
  205204. }
  205205. }
  205206. void WebBrowserComponent::parentHierarchyChanged()
  205207. {
  205208. checkWindowAssociation();
  205209. }
  205210. void WebBrowserComponent::resized()
  205211. {
  205212. browser->setSize (getWidth(), getHeight());
  205213. }
  205214. void WebBrowserComponent::visibilityChanged()
  205215. {
  205216. checkWindowAssociation();
  205217. }
  205218. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205219. {
  205220. return true;
  205221. }
  205222. #endif
  205223. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205224. /********* Start of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205225. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205226. // compiled on its own).
  205227. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  205228. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  205229. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  205230. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  205231. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  205232. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  205233. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  205234. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  205235. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  205236. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  205237. #define WGL_ACCELERATION_ARB 0x2003
  205238. #define WGL_SWAP_METHOD_ARB 0x2007
  205239. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  205240. #define WGL_PIXEL_TYPE_ARB 0x2013
  205241. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  205242. #define WGL_COLOR_BITS_ARB 0x2014
  205243. #define WGL_RED_BITS_ARB 0x2015
  205244. #define WGL_GREEN_BITS_ARB 0x2017
  205245. #define WGL_BLUE_BITS_ARB 0x2019
  205246. #define WGL_ALPHA_BITS_ARB 0x201B
  205247. #define WGL_DEPTH_BITS_ARB 0x2022
  205248. #define WGL_STENCIL_BITS_ARB 0x2023
  205249. #define WGL_FULL_ACCELERATION_ARB 0x2027
  205250. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  205251. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  205252. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  205253. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  205254. #define WGL_STEREO_ARB 0x2012
  205255. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  205256. #define WGL_SAMPLES_ARB 0x2042
  205257. #define WGL_TYPE_RGBA_ARB 0x202B
  205258. static void getWglExtensions (HDC dc, StringArray& result) throw()
  205259. {
  205260. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  205261. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  205262. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  205263. else
  205264. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  205265. }
  205266. class WindowedGLContext : public OpenGLContext
  205267. {
  205268. public:
  205269. WindowedGLContext (Component* const component_,
  205270. HGLRC contextToShareWith,
  205271. const OpenGLPixelFormat& pixelFormat)
  205272. : renderContext (0),
  205273. nativeWindow (0),
  205274. dc (0),
  205275. component (component_)
  205276. {
  205277. jassert (component != 0);
  205278. createNativeWindow();
  205279. // Use a default pixel format that should be supported everywhere
  205280. PIXELFORMATDESCRIPTOR pfd;
  205281. zerostruct (pfd);
  205282. pfd.nSize = sizeof (pfd);
  205283. pfd.nVersion = 1;
  205284. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  205285. pfd.iPixelType = PFD_TYPE_RGBA;
  205286. pfd.cColorBits = 24;
  205287. pfd.cDepthBits = 16;
  205288. const int format = ChoosePixelFormat (dc, &pfd);
  205289. if (format != 0)
  205290. SetPixelFormat (dc, format, &pfd);
  205291. renderContext = wglCreateContext (dc);
  205292. makeActive();
  205293. setPixelFormat (pixelFormat);
  205294. if (contextToShareWith != 0 && renderContext != 0)
  205295. wglShareLists (contextToShareWith, renderContext);
  205296. }
  205297. ~WindowedGLContext()
  205298. {
  205299. makeInactive();
  205300. wglDeleteContext (renderContext);
  205301. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205302. delete nativeWindow;
  205303. }
  205304. bool makeActive() const throw()
  205305. {
  205306. jassert (renderContext != 0);
  205307. return wglMakeCurrent (dc, renderContext) != 0;
  205308. }
  205309. bool makeInactive() const throw()
  205310. {
  205311. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  205312. }
  205313. bool isActive() const throw()
  205314. {
  205315. return wglGetCurrentContext() == renderContext;
  205316. }
  205317. const OpenGLPixelFormat getPixelFormat() const
  205318. {
  205319. OpenGLPixelFormat pf;
  205320. makeActive();
  205321. StringArray availableExtensions;
  205322. getWglExtensions (dc, availableExtensions);
  205323. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  205324. return pf;
  205325. }
  205326. void* getRawContext() const throw()
  205327. {
  205328. return renderContext;
  205329. }
  205330. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  205331. {
  205332. makeActive();
  205333. PIXELFORMATDESCRIPTOR pfd;
  205334. zerostruct (pfd);
  205335. pfd.nSize = sizeof (pfd);
  205336. pfd.nVersion = 1;
  205337. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  205338. pfd.iPixelType = PFD_TYPE_RGBA;
  205339. pfd.iLayerType = PFD_MAIN_PLANE;
  205340. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  205341. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  205342. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  205343. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  205344. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  205345. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  205346. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  205347. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  205348. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  205349. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  205350. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  205351. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  205352. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  205353. int format = 0;
  205354. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  205355. StringArray availableExtensions;
  205356. getWglExtensions (dc, availableExtensions);
  205357. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205358. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  205359. {
  205360. int attributes[64];
  205361. int n = 0;
  205362. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  205363. attributes[n++] = GL_TRUE;
  205364. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  205365. attributes[n++] = GL_TRUE;
  205366. attributes[n++] = WGL_ACCELERATION_ARB;
  205367. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  205368. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  205369. attributes[n++] = GL_TRUE;
  205370. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  205371. attributes[n++] = WGL_TYPE_RGBA_ARB;
  205372. attributes[n++] = WGL_COLOR_BITS_ARB;
  205373. attributes[n++] = pfd.cColorBits;
  205374. attributes[n++] = WGL_RED_BITS_ARB;
  205375. attributes[n++] = pixelFormat.redBits;
  205376. attributes[n++] = WGL_GREEN_BITS_ARB;
  205377. attributes[n++] = pixelFormat.greenBits;
  205378. attributes[n++] = WGL_BLUE_BITS_ARB;
  205379. attributes[n++] = pixelFormat.blueBits;
  205380. attributes[n++] = WGL_ALPHA_BITS_ARB;
  205381. attributes[n++] = pixelFormat.alphaBits;
  205382. attributes[n++] = WGL_DEPTH_BITS_ARB;
  205383. attributes[n++] = pixelFormat.depthBufferBits;
  205384. if (pixelFormat.stencilBufferBits > 0)
  205385. {
  205386. attributes[n++] = WGL_STENCIL_BITS_ARB;
  205387. attributes[n++] = pixelFormat.stencilBufferBits;
  205388. }
  205389. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  205390. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  205391. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  205392. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  205393. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  205394. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  205395. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205396. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  205397. if (availableExtensions.contains ("WGL_ARB_multisample")
  205398. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  205399. {
  205400. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  205401. attributes[n++] = 1;
  205402. attributes[n++] = WGL_SAMPLES_ARB;
  205403. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  205404. }
  205405. attributes[n++] = 0;
  205406. UINT formatsCount;
  205407. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  205408. (void) ok;
  205409. jassert (ok);
  205410. }
  205411. else
  205412. {
  205413. format = ChoosePixelFormat (dc, &pfd);
  205414. }
  205415. if (format != 0)
  205416. {
  205417. makeInactive();
  205418. // win32 can't change the pixel format of a window, so need to delete the
  205419. // old one and create a new one..
  205420. jassert (nativeWindow != 0);
  205421. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205422. delete nativeWindow;
  205423. createNativeWindow();
  205424. if (SetPixelFormat (dc, format, &pfd))
  205425. {
  205426. wglDeleteContext (renderContext);
  205427. renderContext = wglCreateContext (dc);
  205428. jassert (renderContext != 0);
  205429. return renderContext != 0;
  205430. }
  205431. }
  205432. return false;
  205433. }
  205434. void updateWindowPosition (int x, int y, int w, int h, int)
  205435. {
  205436. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  205437. x, y, w, h,
  205438. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205439. }
  205440. void repaint()
  205441. {
  205442. int x, y, w, h;
  205443. nativeWindow->getBounds (x, y, w, h);
  205444. nativeWindow->repaint (0, 0, w, h);
  205445. }
  205446. void swapBuffers()
  205447. {
  205448. SwapBuffers (dc);
  205449. }
  205450. bool setSwapInterval (const int numFramesPerSwap)
  205451. {
  205452. makeActive();
  205453. StringArray availableExtensions;
  205454. getWglExtensions (dc, availableExtensions);
  205455. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  205456. return availableExtensions.contains ("WGL_EXT_swap_control")
  205457. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  205458. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  205459. }
  205460. int getSwapInterval() const
  205461. {
  205462. makeActive();
  205463. StringArray availableExtensions;
  205464. getWglExtensions (dc, availableExtensions);
  205465. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  205466. if (availableExtensions.contains ("WGL_EXT_swap_control")
  205467. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  205468. return wglGetSwapIntervalEXT();
  205469. return 0;
  205470. }
  205471. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  205472. {
  205473. jassert (isActive());
  205474. StringArray availableExtensions;
  205475. getWglExtensions (dc, availableExtensions);
  205476. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205477. int numTypes = 0;
  205478. if (availableExtensions.contains("WGL_ARB_pixel_format")
  205479. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205480. {
  205481. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  205482. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  205483. jassertfalse
  205484. }
  205485. else
  205486. {
  205487. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  205488. }
  205489. OpenGLPixelFormat pf;
  205490. for (int i = 0; i < numTypes; ++i)
  205491. {
  205492. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  205493. {
  205494. bool alreadyListed = false;
  205495. for (int j = results.size(); --j >= 0;)
  205496. if (pf == *results.getUnchecked(j))
  205497. alreadyListed = true;
  205498. if (! alreadyListed)
  205499. results.add (new OpenGLPixelFormat (pf));
  205500. }
  205501. }
  205502. }
  205503. void* getNativeWindowHandle() const
  205504. {
  205505. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  205506. }
  205507. juce_UseDebuggingNewOperator
  205508. HGLRC renderContext;
  205509. private:
  205510. Win32ComponentPeer* nativeWindow;
  205511. Component* const component;
  205512. HDC dc;
  205513. void createNativeWindow()
  205514. {
  205515. nativeWindow = new Win32ComponentPeer (component, 0);
  205516. nativeWindow->dontRepaint = true;
  205517. nativeWindow->setVisible (true);
  205518. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  205519. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  205520. if (peer != 0)
  205521. {
  205522. SetParent (hwnd, (HWND) peer->getNativeHandle());
  205523. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  205524. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  205525. }
  205526. dc = GetDC (hwnd);
  205527. }
  205528. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  205529. OpenGLPixelFormat& result,
  205530. const StringArray& availableExtensions) const throw()
  205531. {
  205532. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205533. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205534. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205535. {
  205536. int attributes[32];
  205537. int numAttributes = 0;
  205538. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  205539. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  205540. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  205541. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  205542. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  205543. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  205544. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  205545. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  205546. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  205547. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  205548. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  205549. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  205550. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  205551. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  205552. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205553. if (availableExtensions.contains ("WGL_ARB_multisample"))
  205554. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  205555. int values[32];
  205556. zeromem (values, sizeof (values));
  205557. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  205558. {
  205559. int n = 0;
  205560. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  205561. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  205562. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  205563. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  205564. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  205565. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  205566. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  205567. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  205568. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  205569. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  205570. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  205571. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  205572. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  205573. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  205574. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  205575. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  205576. return isValidFormat;
  205577. }
  205578. else
  205579. {
  205580. jassertfalse
  205581. }
  205582. }
  205583. else
  205584. {
  205585. PIXELFORMATDESCRIPTOR pfd;
  205586. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  205587. {
  205588. result.redBits = pfd.cRedBits;
  205589. result.greenBits = pfd.cGreenBits;
  205590. result.blueBits = pfd.cBlueBits;
  205591. result.alphaBits = pfd.cAlphaBits;
  205592. result.depthBufferBits = pfd.cDepthBits;
  205593. result.stencilBufferBits = pfd.cStencilBits;
  205594. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  205595. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  205596. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  205597. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  205598. result.fullSceneAntiAliasingNumSamples = 0;
  205599. return true;
  205600. }
  205601. else
  205602. {
  205603. jassertfalse
  205604. }
  205605. }
  205606. return false;
  205607. }
  205608. WindowedGLContext (const WindowedGLContext&);
  205609. const WindowedGLContext& operator= (const WindowedGLContext&);
  205610. };
  205611. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  205612. const OpenGLPixelFormat& pixelFormat,
  205613. const OpenGLContext* const contextToShareWith)
  205614. {
  205615. WindowedGLContext* c = new WindowedGLContext (component,
  205616. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  205617. pixelFormat);
  205618. if (c->renderContext == 0)
  205619. deleteAndZero (c);
  205620. return c;
  205621. }
  205622. void* OpenGLComponent::getNativeWindowHandle() const
  205623. {
  205624. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle() : 0;
  205625. }
  205626. void juce_glViewport (const int w, const int h)
  205627. {
  205628. glViewport (0, 0, w, h);
  205629. }
  205630. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  205631. OwnedArray <OpenGLPixelFormat>& results)
  205632. {
  205633. Component tempComp;
  205634. {
  205635. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  205636. wc.makeActive();
  205637. wc.findAlternativeOpenGLPixelFormats (results);
  205638. }
  205639. }
  205640. #endif
  205641. /********* End of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205642. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  205643. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205644. // compiled on its own).
  205645. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  205646. //***************************************************************************
  205647. // %%% TARGET STATUS VALUES %%%
  205648. //***************************************************************************
  205649. #define STATUS_GOOD 0x00 // Status Good
  205650. #define STATUS_CHKCOND 0x02 // Check Condition
  205651. #define STATUS_CONDMET 0x04 // Condition Met
  205652. #define STATUS_BUSY 0x08 // Busy
  205653. #define STATUS_INTERM 0x10 // Intermediate
  205654. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  205655. #define STATUS_RESCONF 0x18 // Reservation conflict
  205656. #define STATUS_COMTERM 0x22 // Command Terminated
  205657. #define STATUS_QFULL 0x28 // Queue full
  205658. //***************************************************************************
  205659. // %%% SCSI MISCELLANEOUS EQUATES %%%
  205660. //***************************************************************************
  205661. #define MAXLUN 7 // Maximum Logical Unit Id
  205662. #define MAXTARG 7 // Maximum Target Id
  205663. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  205664. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  205665. //***************************************************************************
  205666. // %%% Commands for all Device Types %%%
  205667. //***************************************************************************
  205668. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  205669. #define SCSI_COMPARE 0x39 // Compare (O)
  205670. #define SCSI_COPY 0x18 // Copy (O)
  205671. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  205672. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  205673. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  205674. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  205675. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  205676. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  205677. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  205678. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  205679. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  205680. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  205681. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  205682. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  205683. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  205684. //***************************************************************************
  205685. // %%% Commands Unique to Direct Access Devices %%%
  205686. //***************************************************************************
  205687. #define SCSI_COMPARE 0x39 // Compare (O)
  205688. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  205689. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  205690. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  205691. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  205692. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  205693. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  205694. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  205695. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  205696. #define SCSI_READ_LONG 0x3E // Read Long (O)
  205697. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  205698. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  205699. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  205700. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  205701. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  205702. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  205703. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  205704. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  205705. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  205706. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  205707. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  205708. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  205709. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  205710. #define SCSI_VERIFY 0x2F // Verify (O)
  205711. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  205712. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  205713. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  205714. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  205715. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  205716. //***************************************************************************
  205717. // %%% Commands Unique to Sequential Access Devices %%%
  205718. //***************************************************************************
  205719. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  205720. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  205721. #define SCSI_LOCATE 0x2B // Locate (O)
  205722. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  205723. #define SCSI_READ_POS 0x34 // Read Position (O)
  205724. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  205725. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  205726. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  205727. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  205728. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  205729. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  205730. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  205731. //***************************************************************************
  205732. // %%% Commands Unique to Printer Devices %%%
  205733. //***************************************************************************
  205734. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  205735. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  205736. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  205737. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  205738. //***************************************************************************
  205739. // %%% Commands Unique to Processor Devices %%%
  205740. //***************************************************************************
  205741. #define SCSI_RECEIVE 0x08 // Receive (O)
  205742. #define SCSI_SEND 0x0A // Send (O)
  205743. //***************************************************************************
  205744. // %%% Commands Unique to Write-Once Devices %%%
  205745. //***************************************************************************
  205746. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  205747. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  205748. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  205749. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  205750. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  205751. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  205752. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  205753. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  205754. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  205755. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  205756. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  205757. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  205758. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  205759. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  205760. //***************************************************************************
  205761. // %%% Commands Unique to CD-ROM Devices %%%
  205762. //***************************************************************************
  205763. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  205764. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  205765. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  205766. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  205767. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  205768. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  205769. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  205770. #define SCSI_READHEADER 0x44 // Read Header (O)
  205771. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  205772. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  205773. //***************************************************************************
  205774. // %%% Commands Unique to Scanner Devices %%%
  205775. //***************************************************************************
  205776. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  205777. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  205778. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  205779. #define SCSI_SCAN 0x1B // Scan (O)
  205780. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  205781. //***************************************************************************
  205782. // %%% Commands Unique to Optical Memory Devices %%%
  205783. //***************************************************************************
  205784. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  205785. //***************************************************************************
  205786. // %%% Commands Unique to Medium Changer Devices %%%
  205787. //***************************************************************************
  205788. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  205789. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  205790. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  205791. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  205792. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  205793. //***************************************************************************
  205794. // %%% Commands Unique to Communication Devices %%%
  205795. //***************************************************************************
  205796. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  205797. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  205798. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  205799. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  205800. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  205801. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  205802. //***************************************************************************
  205803. // %%% Request Sense Data Format %%%
  205804. //***************************************************************************
  205805. typedef struct {
  205806. BYTE ErrorCode; // Error Code (70H or 71H)
  205807. BYTE SegmentNum; // Number of current segment descriptor
  205808. BYTE SenseKey; // Sense Key(See bit definitions too)
  205809. BYTE InfoByte0; // Information MSB
  205810. BYTE InfoByte1; // Information MID
  205811. BYTE InfoByte2; // Information MID
  205812. BYTE InfoByte3; // Information LSB
  205813. BYTE AddSenLen; // Additional Sense Length
  205814. BYTE ComSpecInf0; // Command Specific Information MSB
  205815. BYTE ComSpecInf1; // Command Specific Information MID
  205816. BYTE ComSpecInf2; // Command Specific Information MID
  205817. BYTE ComSpecInf3; // Command Specific Information LSB
  205818. BYTE AddSenseCode; // Additional Sense Code
  205819. BYTE AddSenQual; // Additional Sense Code Qualifier
  205820. BYTE FieldRepUCode; // Field Replaceable Unit Code
  205821. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  205822. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  205823. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  205824. BYTE AddSenseBytes; // Additional Sense Bytes
  205825. } SENSE_DATA_FMT;
  205826. //***************************************************************************
  205827. // %%% REQUEST SENSE ERROR CODE %%%
  205828. //***************************************************************************
  205829. #define SERROR_CURRENT 0x70 // Current Errors
  205830. #define SERROR_DEFERED 0x71 // Deferred Errors
  205831. //***************************************************************************
  205832. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  205833. //***************************************************************************
  205834. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  205835. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  205836. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  205837. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  205838. //***************************************************************************
  205839. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  205840. //***************************************************************************
  205841. #define KEY_NOSENSE 0x00 // No Sense
  205842. #define KEY_RECERROR 0x01 // Recovered Error
  205843. #define KEY_NOTREADY 0x02 // Not Ready
  205844. #define KEY_MEDIUMERR 0x03 // Medium Error
  205845. #define KEY_HARDERROR 0x04 // Hardware Error
  205846. #define KEY_ILLGLREQ 0x05 // Illegal Request
  205847. #define KEY_UNITATT 0x06 // Unit Attention
  205848. #define KEY_DATAPROT 0x07 // Data Protect
  205849. #define KEY_BLANKCHK 0x08 // Blank Check
  205850. #define KEY_VENDSPEC 0x09 // Vendor Specific
  205851. #define KEY_COPYABORT 0x0A // Copy Abort
  205852. #define KEY_EQUAL 0x0C // Equal (Search)
  205853. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  205854. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  205855. #define KEY_RESERVED 0x0F // Reserved
  205856. //***************************************************************************
  205857. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  205858. //***************************************************************************
  205859. #define DTYPE_DASD 0x00 // Disk Device
  205860. #define DTYPE_SEQD 0x01 // Tape Device
  205861. #define DTYPE_PRNT 0x02 // Printer
  205862. #define DTYPE_PROC 0x03 // Processor
  205863. #define DTYPE_WORM 0x04 // Write-once read-multiple
  205864. #define DTYPE_CROM 0x05 // CD-ROM device
  205865. #define DTYPE_SCAN 0x06 // Scanner device
  205866. #define DTYPE_OPTI 0x07 // Optical memory device
  205867. #define DTYPE_JUKE 0x08 // Medium Changer device
  205868. #define DTYPE_COMM 0x09 // Communications device
  205869. #define DTYPE_RESL 0x0A // Reserved (low)
  205870. #define DTYPE_RESH 0x1E // Reserved (high)
  205871. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  205872. //***************************************************************************
  205873. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  205874. //***************************************************************************
  205875. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  205876. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  205877. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  205878. #define ANSI_RESLO 0x3 // Reserved (low)
  205879. #define ANSI_RESHI 0x7 // Reserved (high)
  205880. typedef struct
  205881. {
  205882. USHORT Length;
  205883. UCHAR ScsiStatus;
  205884. UCHAR PathId;
  205885. UCHAR TargetId;
  205886. UCHAR Lun;
  205887. UCHAR CdbLength;
  205888. UCHAR SenseInfoLength;
  205889. UCHAR DataIn;
  205890. ULONG DataTransferLength;
  205891. ULONG TimeOutValue;
  205892. ULONG DataBufferOffset;
  205893. ULONG SenseInfoOffset;
  205894. UCHAR Cdb[16];
  205895. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  205896. typedef struct
  205897. {
  205898. USHORT Length;
  205899. UCHAR ScsiStatus;
  205900. UCHAR PathId;
  205901. UCHAR TargetId;
  205902. UCHAR Lun;
  205903. UCHAR CdbLength;
  205904. UCHAR SenseInfoLength;
  205905. UCHAR DataIn;
  205906. ULONG DataTransferLength;
  205907. ULONG TimeOutValue;
  205908. PVOID DataBuffer;
  205909. ULONG SenseInfoOffset;
  205910. UCHAR Cdb[16];
  205911. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  205912. typedef struct
  205913. {
  205914. SCSI_PASS_THROUGH_DIRECT spt;
  205915. ULONG Filler;
  205916. UCHAR ucSenseBuf[32];
  205917. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  205918. typedef struct
  205919. {
  205920. ULONG Length;
  205921. UCHAR PortNumber;
  205922. UCHAR PathId;
  205923. UCHAR TargetId;
  205924. UCHAR Lun;
  205925. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  205926. #define METHOD_BUFFERED 0
  205927. #define METHOD_IN_DIRECT 1
  205928. #define METHOD_OUT_DIRECT 2
  205929. #define METHOD_NEITHER 3
  205930. #define FILE_ANY_ACCESS 0
  205931. #ifndef FILE_READ_ACCESS
  205932. #define FILE_READ_ACCESS (0x0001)
  205933. #endif
  205934. #ifndef FILE_WRITE_ACCESS
  205935. #define FILE_WRITE_ACCESS (0x0002)
  205936. #endif
  205937. #define IOCTL_SCSI_BASE 0x00000004
  205938. #define SCSI_IOCTL_DATA_OUT 0
  205939. #define SCSI_IOCTL_DATA_IN 1
  205940. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  205941. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  205942. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  205943. )
  205944. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205945. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  205946. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205947. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  205948. #define SENSE_LEN 14
  205949. #define SRB_DIR_SCSI 0x00
  205950. #define SRB_POSTING 0x01
  205951. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  205952. #define SRB_DIR_IN 0x08
  205953. #define SRB_DIR_OUT 0x10
  205954. #define SRB_EVENT_NOTIFY 0x40
  205955. #define RESIDUAL_COUNT_SUPPORTED 0x02
  205956. #define MAX_SRB_TIMEOUT 1080001u
  205957. #define DEFAULT_SRB_TIMEOUT 1080001u
  205958. #define SC_HA_INQUIRY 0x00
  205959. #define SC_GET_DEV_TYPE 0x01
  205960. #define SC_EXEC_SCSI_CMD 0x02
  205961. #define SC_ABORT_SRB 0x03
  205962. #define SC_RESET_DEV 0x04
  205963. #define SC_SET_HA_PARMS 0x05
  205964. #define SC_GET_DISK_INFO 0x06
  205965. #define SC_RESCAN_SCSI_BUS 0x07
  205966. #define SC_GETSET_TIMEOUTS 0x08
  205967. #define SS_PENDING 0x00
  205968. #define SS_COMP 0x01
  205969. #define SS_ABORTED 0x02
  205970. #define SS_ABORT_FAIL 0x03
  205971. #define SS_ERR 0x04
  205972. #define SS_INVALID_CMD 0x80
  205973. #define SS_INVALID_HA 0x81
  205974. #define SS_NO_DEVICE 0x82
  205975. #define SS_INVALID_SRB 0xE0
  205976. #define SS_OLD_MANAGER 0xE1
  205977. #define SS_BUFFER_ALIGN 0xE1
  205978. #define SS_ILLEGAL_MODE 0xE2
  205979. #define SS_NO_ASPI 0xE3
  205980. #define SS_FAILED_INIT 0xE4
  205981. #define SS_ASPI_IS_BUSY 0xE5
  205982. #define SS_BUFFER_TO_BIG 0xE6
  205983. #define SS_BUFFER_TOO_BIG 0xE6
  205984. #define SS_MISMATCHED_COMPONENTS 0xE7
  205985. #define SS_NO_ADAPTERS 0xE8
  205986. #define SS_INSUFFICIENT_RESOURCES 0xE9
  205987. #define SS_ASPI_IS_SHUTDOWN 0xEA
  205988. #define SS_BAD_INSTALL 0xEB
  205989. #define HASTAT_OK 0x00
  205990. #define HASTAT_SEL_TO 0x11
  205991. #define HASTAT_DO_DU 0x12
  205992. #define HASTAT_BUS_FREE 0x13
  205993. #define HASTAT_PHASE_ERR 0x14
  205994. #define HASTAT_TIMEOUT 0x09
  205995. #define HASTAT_COMMAND_TIMEOUT 0x0B
  205996. #define HASTAT_MESSAGE_REJECT 0x0D
  205997. #define HASTAT_BUS_RESET 0x0E
  205998. #define HASTAT_PARITY_ERROR 0x0F
  205999. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  206000. #define PACKED
  206001. #pragma pack(1)
  206002. typedef struct
  206003. {
  206004. BYTE SRB_Cmd;
  206005. BYTE SRB_Status;
  206006. BYTE SRB_HaID;
  206007. BYTE SRB_Flags;
  206008. DWORD SRB_Hdr_Rsvd;
  206009. BYTE HA_Count;
  206010. BYTE HA_SCSI_ID;
  206011. BYTE HA_ManagerId[16];
  206012. BYTE HA_Identifier[16];
  206013. BYTE HA_Unique[16];
  206014. WORD HA_Rsvd1;
  206015. BYTE pad[20];
  206016. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  206017. typedef struct
  206018. {
  206019. BYTE SRB_Cmd;
  206020. BYTE SRB_Status;
  206021. BYTE SRB_HaID;
  206022. BYTE SRB_Flags;
  206023. DWORD SRB_Hdr_Rsvd;
  206024. BYTE SRB_Target;
  206025. BYTE SRB_Lun;
  206026. BYTE SRB_DeviceType;
  206027. BYTE SRB_Rsvd1;
  206028. BYTE pad[68];
  206029. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  206030. typedef struct
  206031. {
  206032. BYTE SRB_Cmd;
  206033. BYTE SRB_Status;
  206034. BYTE SRB_HaID;
  206035. BYTE SRB_Flags;
  206036. DWORD SRB_Hdr_Rsvd;
  206037. BYTE SRB_Target;
  206038. BYTE SRB_Lun;
  206039. WORD SRB_Rsvd1;
  206040. DWORD SRB_BufLen;
  206041. BYTE FAR *SRB_BufPointer;
  206042. BYTE SRB_SenseLen;
  206043. BYTE SRB_CDBLen;
  206044. BYTE SRB_HaStat;
  206045. BYTE SRB_TargStat;
  206046. VOID FAR *SRB_PostProc;
  206047. BYTE SRB_Rsvd2[20];
  206048. BYTE CDBByte[16];
  206049. BYTE SenseArea[SENSE_LEN+2];
  206050. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  206051. typedef struct
  206052. {
  206053. BYTE SRB_Cmd;
  206054. BYTE SRB_Status;
  206055. BYTE SRB_HaId;
  206056. BYTE SRB_Flags;
  206057. DWORD SRB_Hdr_Rsvd;
  206058. } PACKED SRB, *PSRB, FAR *LPSRB;
  206059. #pragma pack()
  206060. struct CDDeviceInfo
  206061. {
  206062. char vendor[9];
  206063. char productId[17];
  206064. char rev[5];
  206065. char vendorSpec[21];
  206066. BYTE ha;
  206067. BYTE tgt;
  206068. BYTE lun;
  206069. char scsiDriveLetter; // will be 0 if not using scsi
  206070. };
  206071. class CDReadBuffer
  206072. {
  206073. public:
  206074. int startFrame;
  206075. int numFrames;
  206076. int dataStartOffset;
  206077. int dataLength;
  206078. BYTE* buffer;
  206079. int bufferSize;
  206080. int index;
  206081. bool wantsIndex;
  206082. CDReadBuffer (const int numberOfFrames)
  206083. : startFrame (0),
  206084. numFrames (0),
  206085. dataStartOffset (0),
  206086. dataLength (0),
  206087. index (0),
  206088. wantsIndex (false)
  206089. {
  206090. bufferSize = 2352 * numberOfFrames;
  206091. buffer = (BYTE*) malloc (bufferSize);
  206092. }
  206093. ~CDReadBuffer()
  206094. {
  206095. free (buffer);
  206096. }
  206097. bool isZero() const
  206098. {
  206099. BYTE* p = buffer + dataStartOffset;
  206100. for (int i = dataLength; --i >= 0;)
  206101. if (*p++ != 0)
  206102. return false;
  206103. return true;
  206104. }
  206105. };
  206106. class CDDeviceHandle;
  206107. class CDController
  206108. {
  206109. public:
  206110. CDController();
  206111. virtual ~CDController();
  206112. virtual bool read (CDReadBuffer* t) = 0;
  206113. virtual void shutDown();
  206114. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  206115. int getLastIndex();
  206116. public:
  206117. bool initialised;
  206118. CDDeviceHandle* deviceInfo;
  206119. int framesToCheck, framesOverlap;
  206120. void prepare (SRB_ExecSCSICmd& s);
  206121. void perform (SRB_ExecSCSICmd& s);
  206122. void setPaused (bool paused);
  206123. };
  206124. #pragma pack(1)
  206125. struct TOCTRACK
  206126. {
  206127. BYTE rsvd;
  206128. BYTE ADR;
  206129. BYTE trackNumber;
  206130. BYTE rsvd2;
  206131. BYTE addr[4];
  206132. };
  206133. struct TOC
  206134. {
  206135. WORD tocLen;
  206136. BYTE firstTrack;
  206137. BYTE lastTrack;
  206138. TOCTRACK tracks[100];
  206139. };
  206140. #pragma pack()
  206141. enum
  206142. {
  206143. READTYPE_ANY = 0,
  206144. READTYPE_ATAPI1 = 1,
  206145. READTYPE_ATAPI2 = 2,
  206146. READTYPE_READ6 = 3,
  206147. READTYPE_READ10 = 4,
  206148. READTYPE_READ_D8 = 5,
  206149. READTYPE_READ_D4 = 6,
  206150. READTYPE_READ_D4_1 = 7,
  206151. READTYPE_READ10_2 = 8
  206152. };
  206153. class CDDeviceHandle
  206154. {
  206155. public:
  206156. CDDeviceHandle (const CDDeviceInfo* const device)
  206157. : scsiHandle (0),
  206158. readType (READTYPE_ANY),
  206159. controller (0)
  206160. {
  206161. memcpy (&info, device, sizeof (info));
  206162. }
  206163. ~CDDeviceHandle()
  206164. {
  206165. if (controller != 0)
  206166. {
  206167. controller->shutDown();
  206168. delete controller;
  206169. }
  206170. if (scsiHandle != 0)
  206171. CloseHandle (scsiHandle);
  206172. }
  206173. bool readTOC (TOC* lpToc, bool useMSF);
  206174. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  206175. void openDrawer (bool shouldBeOpen);
  206176. CDDeviceInfo info;
  206177. HANDLE scsiHandle;
  206178. BYTE readType;
  206179. private:
  206180. CDController* controller;
  206181. bool testController (const int readType,
  206182. CDController* const newController,
  206183. CDReadBuffer* const bufferToUse);
  206184. };
  206185. DWORD (*fGetASPI32SupportInfo)(void);
  206186. DWORD (*fSendASPI32Command)(LPSRB);
  206187. static HINSTANCE winAspiLib = 0;
  206188. static bool usingScsi = false;
  206189. static bool initialised = false;
  206190. static bool InitialiseCDRipper()
  206191. {
  206192. if (! initialised)
  206193. {
  206194. initialised = true;
  206195. OSVERSIONINFO info;
  206196. info.dwOSVersionInfoSize = sizeof (info);
  206197. GetVersionEx (&info);
  206198. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  206199. if (! usingScsi)
  206200. {
  206201. fGetASPI32SupportInfo = 0;
  206202. fSendASPI32Command = 0;
  206203. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  206204. if (winAspiLib != 0)
  206205. {
  206206. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  206207. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  206208. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  206209. return false;
  206210. }
  206211. else
  206212. {
  206213. usingScsi = true;
  206214. }
  206215. }
  206216. }
  206217. return true;
  206218. }
  206219. static void DeinitialiseCDRipper()
  206220. {
  206221. if (winAspiLib != 0)
  206222. {
  206223. fGetASPI32SupportInfo = 0;
  206224. fSendASPI32Command = 0;
  206225. FreeLibrary (winAspiLib);
  206226. winAspiLib = 0;
  206227. }
  206228. initialised = false;
  206229. }
  206230. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  206231. {
  206232. TCHAR devicePath[8];
  206233. devicePath[0] = '\\';
  206234. devicePath[1] = '\\';
  206235. devicePath[2] = '.';
  206236. devicePath[3] = '\\';
  206237. devicePath[4] = driveLetter;
  206238. devicePath[5] = ':';
  206239. devicePath[6] = 0;
  206240. OSVERSIONINFO info;
  206241. info.dwOSVersionInfoSize = sizeof (info);
  206242. GetVersionEx (&info);
  206243. DWORD flags = GENERIC_READ;
  206244. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  206245. flags = GENERIC_READ | GENERIC_WRITE;
  206246. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206247. if (h == INVALID_HANDLE_VALUE)
  206248. {
  206249. flags ^= GENERIC_WRITE;
  206250. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206251. }
  206252. return h;
  206253. }
  206254. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  206255. const char driveLetter,
  206256. HANDLE& deviceHandle,
  206257. const bool retryOnFailure = true)
  206258. {
  206259. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  206260. zerostruct (s);
  206261. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  206262. s.spt.CdbLength = srb->SRB_CDBLen;
  206263. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  206264. ? SCSI_IOCTL_DATA_IN
  206265. : ((srb->SRB_Flags & SRB_DIR_OUT)
  206266. ? SCSI_IOCTL_DATA_OUT
  206267. : SCSI_IOCTL_DATA_UNSPECIFIED));
  206268. s.spt.DataTransferLength = srb->SRB_BufLen;
  206269. s.spt.TimeOutValue = 5;
  206270. s.spt.DataBuffer = srb->SRB_BufPointer;
  206271. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206272. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  206273. srb->SRB_Status = SS_ERR;
  206274. srb->SRB_TargStat = 0x0004;
  206275. DWORD bytesReturned = 0;
  206276. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206277. &s, sizeof (s),
  206278. &s, sizeof (s),
  206279. &bytesReturned, 0) != 0)
  206280. {
  206281. srb->SRB_Status = SS_COMP;
  206282. }
  206283. else if (retryOnFailure)
  206284. {
  206285. const DWORD error = GetLastError();
  206286. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  206287. {
  206288. if (error != ERROR_INVALID_HANDLE)
  206289. CloseHandle (deviceHandle);
  206290. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  206291. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  206292. }
  206293. }
  206294. return srb->SRB_Status;
  206295. }
  206296. // Controller types..
  206297. class ControllerType1 : public CDController
  206298. {
  206299. public:
  206300. ControllerType1() {}
  206301. ~ControllerType1() {}
  206302. bool read (CDReadBuffer* rb)
  206303. {
  206304. if (rb->numFrames * 2352 > rb->bufferSize)
  206305. return false;
  206306. SRB_ExecSCSICmd s;
  206307. prepare (s);
  206308. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206309. s.SRB_BufLen = rb->bufferSize;
  206310. s.SRB_BufPointer = rb->buffer;
  206311. s.SRB_CDBLen = 12;
  206312. s.CDBByte[0] = 0xBE;
  206313. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206314. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206315. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206316. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206317. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  206318. perform (s);
  206319. if (s.SRB_Status != SS_COMP)
  206320. return false;
  206321. rb->dataLength = rb->numFrames * 2352;
  206322. rb->dataStartOffset = 0;
  206323. return true;
  206324. }
  206325. };
  206326. class ControllerType2 : public CDController
  206327. {
  206328. public:
  206329. ControllerType2() {}
  206330. ~ControllerType2() {}
  206331. void shutDown()
  206332. {
  206333. if (initialised)
  206334. {
  206335. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  206336. SRB_ExecSCSICmd s;
  206337. prepare (s);
  206338. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  206339. s.SRB_BufLen = 0x0C;
  206340. s.SRB_BufPointer = bufPointer;
  206341. s.SRB_CDBLen = 6;
  206342. s.CDBByte[0] = 0x15;
  206343. s.CDBByte[4] = 0x0C;
  206344. perform (s);
  206345. }
  206346. }
  206347. bool init()
  206348. {
  206349. SRB_ExecSCSICmd s;
  206350. s.SRB_Status = SS_ERR;
  206351. if (deviceInfo->readType == READTYPE_READ10_2)
  206352. {
  206353. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  206354. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  206355. for (int i = 0; i < 2; ++i)
  206356. {
  206357. prepare (s);
  206358. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206359. s.SRB_BufLen = 0x14;
  206360. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  206361. s.SRB_CDBLen = 6;
  206362. s.CDBByte[0] = 0x15;
  206363. s.CDBByte[1] = 0x10;
  206364. s.CDBByte[4] = 0x14;
  206365. perform (s);
  206366. if (s.SRB_Status != SS_COMP)
  206367. return false;
  206368. }
  206369. }
  206370. else
  206371. {
  206372. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  206373. prepare (s);
  206374. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206375. s.SRB_BufLen = 0x0C;
  206376. s.SRB_BufPointer = bufPointer;
  206377. s.SRB_CDBLen = 6;
  206378. s.CDBByte[0] = 0x15;
  206379. s.CDBByte[4] = 0x0C;
  206380. perform (s);
  206381. }
  206382. return s.SRB_Status == SS_COMP;
  206383. }
  206384. bool read (CDReadBuffer* rb)
  206385. {
  206386. if (rb->numFrames * 2352 > rb->bufferSize)
  206387. return false;
  206388. if (!initialised)
  206389. {
  206390. initialised = init();
  206391. if (!initialised)
  206392. return false;
  206393. }
  206394. SRB_ExecSCSICmd s;
  206395. prepare (s);
  206396. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206397. s.SRB_BufLen = rb->bufferSize;
  206398. s.SRB_BufPointer = rb->buffer;
  206399. s.SRB_CDBLen = 10;
  206400. s.CDBByte[0] = 0x28;
  206401. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206402. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206403. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206404. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206405. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206406. perform (s);
  206407. if (s.SRB_Status != SS_COMP)
  206408. return false;
  206409. rb->dataLength = rb->numFrames * 2352;
  206410. rb->dataStartOffset = 0;
  206411. return true;
  206412. }
  206413. };
  206414. class ControllerType3 : public CDController
  206415. {
  206416. public:
  206417. ControllerType3() {}
  206418. ~ControllerType3() {}
  206419. bool read (CDReadBuffer* rb)
  206420. {
  206421. if (rb->numFrames * 2352 > rb->bufferSize)
  206422. return false;
  206423. if (!initialised)
  206424. {
  206425. setPaused (false);
  206426. initialised = true;
  206427. }
  206428. SRB_ExecSCSICmd s;
  206429. prepare (s);
  206430. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206431. s.SRB_BufLen = rb->numFrames * 2352;
  206432. s.SRB_BufPointer = rb->buffer;
  206433. s.SRB_CDBLen = 12;
  206434. s.CDBByte[0] = 0xD8;
  206435. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206436. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206437. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206438. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  206439. perform (s);
  206440. if (s.SRB_Status != SS_COMP)
  206441. return false;
  206442. rb->dataLength = rb->numFrames * 2352;
  206443. rb->dataStartOffset = 0;
  206444. return true;
  206445. }
  206446. };
  206447. class ControllerType4 : public CDController
  206448. {
  206449. public:
  206450. ControllerType4() {}
  206451. ~ControllerType4() {}
  206452. bool selectD4Mode()
  206453. {
  206454. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  206455. SRB_ExecSCSICmd s;
  206456. prepare (s);
  206457. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206458. s.SRB_CDBLen = 6;
  206459. s.SRB_BufLen = 12;
  206460. s.SRB_BufPointer = bufPointer;
  206461. s.CDBByte[0] = 0x15;
  206462. s.CDBByte[1] = 0x10;
  206463. s.CDBByte[4] = 0x08;
  206464. perform (s);
  206465. return s.SRB_Status == SS_COMP;
  206466. }
  206467. bool read (CDReadBuffer* rb)
  206468. {
  206469. if (rb->numFrames * 2352 > rb->bufferSize)
  206470. return false;
  206471. if (!initialised)
  206472. {
  206473. setPaused (true);
  206474. if (deviceInfo->readType == READTYPE_READ_D4_1)
  206475. selectD4Mode();
  206476. initialised = true;
  206477. }
  206478. SRB_ExecSCSICmd s;
  206479. prepare (s);
  206480. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206481. s.SRB_BufLen = rb->bufferSize;
  206482. s.SRB_BufPointer = rb->buffer;
  206483. s.SRB_CDBLen = 10;
  206484. s.CDBByte[0] = 0xD4;
  206485. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206486. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206487. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206488. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206489. perform (s);
  206490. if (s.SRB_Status != SS_COMP)
  206491. return false;
  206492. rb->dataLength = rb->numFrames * 2352;
  206493. rb->dataStartOffset = 0;
  206494. return true;
  206495. }
  206496. };
  206497. CDController::CDController() : initialised (false)
  206498. {
  206499. }
  206500. CDController::~CDController()
  206501. {
  206502. }
  206503. void CDController::prepare (SRB_ExecSCSICmd& s)
  206504. {
  206505. zerostruct (s);
  206506. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206507. s.SRB_HaID = deviceInfo->info.ha;
  206508. s.SRB_Target = deviceInfo->info.tgt;
  206509. s.SRB_Lun = deviceInfo->info.lun;
  206510. s.SRB_SenseLen = SENSE_LEN;
  206511. }
  206512. void CDController::perform (SRB_ExecSCSICmd& s)
  206513. {
  206514. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206515. s.SRB_PostProc = (void*)event;
  206516. ResetEvent (event);
  206517. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  206518. deviceInfo->info.scsiDriveLetter,
  206519. deviceInfo->scsiHandle)
  206520. : fSendASPI32Command ((LPSRB)&s);
  206521. if (status == SS_PENDING)
  206522. WaitForSingleObject (event, 4000);
  206523. CloseHandle (event);
  206524. }
  206525. void CDController::setPaused (bool paused)
  206526. {
  206527. SRB_ExecSCSICmd s;
  206528. prepare (s);
  206529. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206530. s.SRB_CDBLen = 10;
  206531. s.CDBByte[0] = 0x4B;
  206532. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  206533. perform (s);
  206534. }
  206535. void CDController::shutDown()
  206536. {
  206537. }
  206538. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  206539. {
  206540. if (overlapBuffer != 0)
  206541. {
  206542. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  206543. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  206544. if (doJitter
  206545. && overlapBuffer->startFrame > 0
  206546. && overlapBuffer->numFrames > 0
  206547. && overlapBuffer->dataLength > 0)
  206548. {
  206549. const int numFrames = rb->numFrames;
  206550. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  206551. {
  206552. rb->startFrame -= framesOverlap;
  206553. if (framesToCheck < framesOverlap
  206554. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  206555. rb->numFrames += framesOverlap;
  206556. }
  206557. else
  206558. {
  206559. overlapBuffer->dataLength = 0;
  206560. overlapBuffer->startFrame = 0;
  206561. overlapBuffer->numFrames = 0;
  206562. }
  206563. }
  206564. if (! read (rb))
  206565. return false;
  206566. if (doJitter)
  206567. {
  206568. const int checkLen = framesToCheck * 2352;
  206569. const int maxToCheck = rb->dataLength - checkLen;
  206570. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  206571. return true;
  206572. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  206573. bool found = false;
  206574. for (int i = 0; i < maxToCheck; ++i)
  206575. {
  206576. if (!memcmp (p, rb->buffer + i, checkLen))
  206577. {
  206578. i += checkLen;
  206579. rb->dataStartOffset = i;
  206580. rb->dataLength -= i;
  206581. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  206582. found = true;
  206583. break;
  206584. }
  206585. }
  206586. rb->numFrames = rb->dataLength / 2352;
  206587. rb->dataLength = 2352 * rb->numFrames;
  206588. if (!found)
  206589. return false;
  206590. }
  206591. if (canDoJitter)
  206592. {
  206593. memcpy (overlapBuffer->buffer,
  206594. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  206595. 2352 * framesToCheck);
  206596. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  206597. overlapBuffer->numFrames = framesToCheck;
  206598. overlapBuffer->dataLength = 2352 * framesToCheck;
  206599. overlapBuffer->dataStartOffset = 0;
  206600. }
  206601. else
  206602. {
  206603. overlapBuffer->startFrame = 0;
  206604. overlapBuffer->numFrames = 0;
  206605. overlapBuffer->dataLength = 0;
  206606. }
  206607. return true;
  206608. }
  206609. else
  206610. {
  206611. return read (rb);
  206612. }
  206613. }
  206614. int CDController::getLastIndex()
  206615. {
  206616. char qdata[100];
  206617. SRB_ExecSCSICmd s;
  206618. prepare (s);
  206619. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206620. s.SRB_BufLen = sizeof (qdata);
  206621. s.SRB_BufPointer = (BYTE*)qdata;
  206622. s.SRB_CDBLen = 12;
  206623. s.CDBByte[0] = 0x42;
  206624. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206625. s.CDBByte[2] = 64;
  206626. s.CDBByte[3] = 1; // get current position
  206627. s.CDBByte[7] = 0;
  206628. s.CDBByte[8] = (BYTE)sizeof (qdata);
  206629. perform (s);
  206630. if (s.SRB_Status == SS_COMP)
  206631. return qdata[7];
  206632. return 0;
  206633. }
  206634. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  206635. {
  206636. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206637. SRB_ExecSCSICmd s;
  206638. zerostruct (s);
  206639. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206640. s.SRB_HaID = info.ha;
  206641. s.SRB_Target = info.tgt;
  206642. s.SRB_Lun = info.lun;
  206643. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206644. s.SRB_BufLen = 0x324;
  206645. s.SRB_BufPointer = (BYTE*)lpToc;
  206646. s.SRB_SenseLen = 0x0E;
  206647. s.SRB_CDBLen = 0x0A;
  206648. s.SRB_PostProc = (void*)event;
  206649. s.CDBByte[0] = 0x43;
  206650. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  206651. s.CDBByte[7] = 0x03;
  206652. s.CDBByte[8] = 0x24;
  206653. ResetEvent (event);
  206654. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206655. : fSendASPI32Command ((LPSRB)&s);
  206656. if (status == SS_PENDING)
  206657. WaitForSingleObject (event, 4000);
  206658. CloseHandle (event);
  206659. return (s.SRB_Status == SS_COMP);
  206660. }
  206661. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  206662. CDReadBuffer* const overlapBuffer)
  206663. {
  206664. if (controller == 0)
  206665. {
  206666. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  206667. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  206668. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  206669. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  206670. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  206671. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  206672. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  206673. }
  206674. buffer->index = 0;
  206675. if ((controller != 0)
  206676. && controller->readAudio (buffer, overlapBuffer))
  206677. {
  206678. if (buffer->wantsIndex)
  206679. buffer->index = controller->getLastIndex();
  206680. return true;
  206681. }
  206682. return false;
  206683. }
  206684. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  206685. {
  206686. if (shouldBeOpen)
  206687. {
  206688. if (controller != 0)
  206689. {
  206690. controller->shutDown();
  206691. delete controller;
  206692. controller = 0;
  206693. }
  206694. if (scsiHandle != 0)
  206695. {
  206696. CloseHandle (scsiHandle);
  206697. scsiHandle = 0;
  206698. }
  206699. }
  206700. SRB_ExecSCSICmd s;
  206701. zerostruct (s);
  206702. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206703. s.SRB_HaID = info.ha;
  206704. s.SRB_Target = info.tgt;
  206705. s.SRB_Lun = info.lun;
  206706. s.SRB_SenseLen = SENSE_LEN;
  206707. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206708. s.SRB_BufLen = 0;
  206709. s.SRB_BufPointer = 0;
  206710. s.SRB_CDBLen = 12;
  206711. s.CDBByte[0] = 0x1b;
  206712. s.CDBByte[1] = (BYTE)(info.lun << 5);
  206713. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  206714. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206715. s.SRB_PostProc = (void*)event;
  206716. ResetEvent (event);
  206717. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206718. : fSendASPI32Command ((LPSRB)&s);
  206719. if (status == SS_PENDING)
  206720. WaitForSingleObject (event, 4000);
  206721. CloseHandle (event);
  206722. }
  206723. bool CDDeviceHandle::testController (const int type,
  206724. CDController* const newController,
  206725. CDReadBuffer* const rb)
  206726. {
  206727. controller = newController;
  206728. readType = (BYTE)type;
  206729. controller->deviceInfo = this;
  206730. controller->framesToCheck = 1;
  206731. controller->framesOverlap = 3;
  206732. bool passed = false;
  206733. memset (rb->buffer, 0xcd, rb->bufferSize);
  206734. if (controller->read (rb))
  206735. {
  206736. passed = true;
  206737. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  206738. int wrong = 0;
  206739. for (int i = rb->dataLength / 4; --i >= 0;)
  206740. {
  206741. if (*p++ == (int) 0xcdcdcdcd)
  206742. {
  206743. if (++wrong == 4)
  206744. {
  206745. passed = false;
  206746. break;
  206747. }
  206748. }
  206749. else
  206750. {
  206751. wrong = 0;
  206752. }
  206753. }
  206754. }
  206755. if (! passed)
  206756. {
  206757. controller->shutDown();
  206758. delete controller;
  206759. controller = 0;
  206760. }
  206761. return passed;
  206762. }
  206763. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  206764. {
  206765. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206766. const int bufSize = 128;
  206767. BYTE buffer[bufSize];
  206768. zeromem (buffer, bufSize);
  206769. SRB_ExecSCSICmd s;
  206770. zerostruct (s);
  206771. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206772. s.SRB_HaID = ha;
  206773. s.SRB_Target = tgt;
  206774. s.SRB_Lun = lun;
  206775. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206776. s.SRB_BufLen = bufSize;
  206777. s.SRB_BufPointer = buffer;
  206778. s.SRB_SenseLen = SENSE_LEN;
  206779. s.SRB_CDBLen = 6;
  206780. s.SRB_PostProc = (void*)event;
  206781. s.CDBByte[0] = SCSI_INQUIRY;
  206782. s.CDBByte[4] = 100;
  206783. ResetEvent (event);
  206784. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  206785. WaitForSingleObject (event, 4000);
  206786. CloseHandle (event);
  206787. if (s.SRB_Status == SS_COMP)
  206788. {
  206789. memcpy (dev->vendor, &buffer[8], 8);
  206790. memcpy (dev->productId, &buffer[16], 16);
  206791. memcpy (dev->rev, &buffer[32], 4);
  206792. memcpy (dev->vendorSpec, &buffer[36], 20);
  206793. }
  206794. }
  206795. static int FindCDDevices (CDDeviceInfo* const list,
  206796. int maxItems)
  206797. {
  206798. int count = 0;
  206799. if (usingScsi)
  206800. {
  206801. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  206802. {
  206803. TCHAR drivePath[8];
  206804. drivePath[0] = driveLetter;
  206805. drivePath[1] = ':';
  206806. drivePath[2] = '\\';
  206807. drivePath[3] = 0;
  206808. if (GetDriveType (drivePath) == DRIVE_CDROM)
  206809. {
  206810. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  206811. if (h != INVALID_HANDLE_VALUE)
  206812. {
  206813. BYTE buffer[100], passThroughStruct[1024];
  206814. zeromem (buffer, sizeof (buffer));
  206815. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206816. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  206817. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  206818. p->spt.CdbLength = 6;
  206819. p->spt.SenseInfoLength = 24;
  206820. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  206821. p->spt.DataTransferLength = 100;
  206822. p->spt.TimeOutValue = 2;
  206823. p->spt.DataBuffer = buffer;
  206824. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206825. p->spt.Cdb[0] = 0x12;
  206826. p->spt.Cdb[4] = 100;
  206827. DWORD bytesReturned = 0;
  206828. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206829. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206830. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206831. &bytesReturned, 0) != 0)
  206832. {
  206833. zeromem (&list[count], sizeof (CDDeviceInfo));
  206834. list[count].scsiDriveLetter = driveLetter;
  206835. memcpy (list[count].vendor, &buffer[8], 8);
  206836. memcpy (list[count].productId, &buffer[16], 16);
  206837. memcpy (list[count].rev, &buffer[32], 4);
  206838. memcpy (list[count].vendorSpec, &buffer[36], 20);
  206839. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206840. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  206841. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  206842. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  206843. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  206844. &bytesReturned, 0) != 0)
  206845. {
  206846. list[count].ha = scsiAddr->PortNumber;
  206847. list[count].tgt = scsiAddr->TargetId;
  206848. list[count].lun = scsiAddr->Lun;
  206849. ++count;
  206850. }
  206851. }
  206852. CloseHandle (h);
  206853. }
  206854. }
  206855. }
  206856. }
  206857. else
  206858. {
  206859. const DWORD d = fGetASPI32SupportInfo();
  206860. BYTE status = HIBYTE (LOWORD (d));
  206861. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  206862. return 0;
  206863. const int numAdapters = LOBYTE (LOWORD (d));
  206864. for (BYTE ha = 0; ha < numAdapters; ++ha)
  206865. {
  206866. SRB_HAInquiry s;
  206867. zerostruct (s);
  206868. s.SRB_Cmd = SC_HA_INQUIRY;
  206869. s.SRB_HaID = ha;
  206870. fSendASPI32Command ((LPSRB)&s);
  206871. if (s.SRB_Status == SS_COMP)
  206872. {
  206873. maxItems = (int)s.HA_Unique[3];
  206874. if (maxItems == 0)
  206875. maxItems = 8;
  206876. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  206877. {
  206878. for (BYTE lun = 0; lun < 8; ++lun)
  206879. {
  206880. SRB_GDEVBlock sb;
  206881. zerostruct (sb);
  206882. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  206883. sb.SRB_HaID = ha;
  206884. sb.SRB_Target = tgt;
  206885. sb.SRB_Lun = lun;
  206886. fSendASPI32Command ((LPSRB) &sb);
  206887. if (sb.SRB_Status == SS_COMP
  206888. && sb.SRB_DeviceType == DTYPE_CROM)
  206889. {
  206890. zeromem (&list[count], sizeof (CDDeviceInfo));
  206891. list[count].ha = ha;
  206892. list[count].tgt = tgt;
  206893. list[count].lun = lun;
  206894. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  206895. ++count;
  206896. }
  206897. }
  206898. }
  206899. }
  206900. }
  206901. }
  206902. return count;
  206903. }
  206904. static int ripperUsers = 0;
  206905. static bool initialisedOk = false;
  206906. class DeinitialiseTimer : private Timer,
  206907. private DeletedAtShutdown
  206908. {
  206909. DeinitialiseTimer (const DeinitialiseTimer&);
  206910. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  206911. public:
  206912. DeinitialiseTimer()
  206913. {
  206914. startTimer (4000);
  206915. }
  206916. ~DeinitialiseTimer()
  206917. {
  206918. if (--ripperUsers == 0)
  206919. DeinitialiseCDRipper();
  206920. }
  206921. void timerCallback()
  206922. {
  206923. delete this;
  206924. }
  206925. juce_UseDebuggingNewOperator
  206926. };
  206927. static void incUserCount()
  206928. {
  206929. if (ripperUsers++ == 0)
  206930. initialisedOk = InitialiseCDRipper();
  206931. }
  206932. static void decUserCount()
  206933. {
  206934. new DeinitialiseTimer();
  206935. }
  206936. struct CDDeviceWrapper
  206937. {
  206938. CDDeviceHandle* cdH;
  206939. CDReadBuffer* overlapBuffer;
  206940. bool jitter;
  206941. };
  206942. static int getAddressOf (const TOCTRACK* const t)
  206943. {
  206944. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  206945. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  206946. }
  206947. static int getMSFAddressOf (const TOCTRACK* const t)
  206948. {
  206949. return 60 * t->addr[1] + t->addr[2];
  206950. }
  206951. static const int samplesPerFrame = 44100 / 75;
  206952. static const int bytesPerFrame = samplesPerFrame * 4;
  206953. const StringArray AudioCDReader::getAvailableCDNames()
  206954. {
  206955. StringArray results;
  206956. incUserCount();
  206957. if (initialisedOk)
  206958. {
  206959. CDDeviceInfo list[8];
  206960. const int num = FindCDDevices (list, 8);
  206961. decUserCount();
  206962. for (int i = 0; i < num; ++i)
  206963. {
  206964. String s;
  206965. if (list[i].scsiDriveLetter > 0)
  206966. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  206967. s << String (list[i].vendor).trim()
  206968. << T(" ") << String (list[i].productId).trim()
  206969. << T(" ") << String (list[i].rev).trim();
  206970. results.add (s);
  206971. }
  206972. }
  206973. return results;
  206974. }
  206975. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  206976. {
  206977. SRB_GDEVBlock s;
  206978. zerostruct (s);
  206979. s.SRB_Cmd = SC_GET_DEV_TYPE;
  206980. s.SRB_HaID = device->ha;
  206981. s.SRB_Target = device->tgt;
  206982. s.SRB_Lun = device->lun;
  206983. if (usingScsi)
  206984. {
  206985. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  206986. if (h != INVALID_HANDLE_VALUE)
  206987. {
  206988. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  206989. cdh->scsiHandle = h;
  206990. return cdh;
  206991. }
  206992. }
  206993. else
  206994. {
  206995. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  206996. && s.SRB_DeviceType == DTYPE_CROM)
  206997. {
  206998. return new CDDeviceHandle (device);
  206999. }
  207000. }
  207001. return 0;
  207002. }
  207003. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  207004. {
  207005. incUserCount();
  207006. if (initialisedOk)
  207007. {
  207008. CDDeviceInfo list[8];
  207009. const int num = FindCDDevices (list, 8);
  207010. if (((unsigned int) deviceIndex) < (unsigned int) num)
  207011. {
  207012. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  207013. if (handle != 0)
  207014. {
  207015. CDDeviceWrapper* const d = new CDDeviceWrapper();
  207016. d->cdH = handle;
  207017. d->overlapBuffer = new CDReadBuffer(3);
  207018. return new AudioCDReader (d);
  207019. }
  207020. }
  207021. }
  207022. decUserCount();
  207023. return 0;
  207024. }
  207025. AudioCDReader::AudioCDReader (void* handle_)
  207026. : AudioFormatReader (0, T("CD Audio")),
  207027. handle (handle_),
  207028. indexingEnabled (false),
  207029. lastIndex (0),
  207030. firstFrameInBuffer (0),
  207031. samplesInBuffer (0)
  207032. {
  207033. jassert (handle_ != 0);
  207034. refreshTrackLengths();
  207035. sampleRate = 44100.0;
  207036. bitsPerSample = 16;
  207037. lengthInSamples = getPositionOfTrackStart (numTracks);
  207038. numChannels = 2;
  207039. usesFloatingPointData = false;
  207040. buffer.setSize (4 * bytesPerFrame, true);
  207041. }
  207042. AudioCDReader::~AudioCDReader()
  207043. {
  207044. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  207045. delete device->cdH;
  207046. delete device->overlapBuffer;
  207047. delete device;
  207048. decUserCount();
  207049. }
  207050. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  207051. int64 startSampleInFile, int numSamples)
  207052. {
  207053. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207054. bool ok = true;
  207055. while (numSamples > 0)
  207056. {
  207057. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  207058. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  207059. if (startSampleInFile >= bufferStartSample
  207060. && startSampleInFile < bufferEndSample)
  207061. {
  207062. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  207063. int* const l = destSamples[0] + startOffsetInDestBuffer;
  207064. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207065. const short* src = (const short*) buffer.getData();
  207066. src += 2 * (startSampleInFile - bufferStartSample);
  207067. for (int i = 0; i < toDo; ++i)
  207068. {
  207069. l[i] = src [i << 1] << 16;
  207070. if (r != 0)
  207071. r[i] = src [(i << 1) + 1] << 16;
  207072. }
  207073. startOffsetInDestBuffer += toDo;
  207074. startSampleInFile += toDo;
  207075. numSamples -= toDo;
  207076. }
  207077. else
  207078. {
  207079. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  207080. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  207081. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  207082. {
  207083. device->overlapBuffer->dataLength = 0;
  207084. device->overlapBuffer->startFrame = 0;
  207085. device->overlapBuffer->numFrames = 0;
  207086. device->jitter = false;
  207087. }
  207088. firstFrameInBuffer = frameNeeded;
  207089. lastIndex = 0;
  207090. CDReadBuffer readBuffer (framesInBuffer + 4);
  207091. readBuffer.wantsIndex = indexingEnabled;
  207092. int i;
  207093. for (i = 5; --i >= 0;)
  207094. {
  207095. readBuffer.startFrame = frameNeeded;
  207096. readBuffer.numFrames = framesInBuffer;
  207097. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  207098. break;
  207099. else
  207100. device->overlapBuffer->dataLength = 0;
  207101. }
  207102. if (i >= 0)
  207103. {
  207104. memcpy ((char*) buffer.getData(),
  207105. readBuffer.buffer + readBuffer.dataStartOffset,
  207106. readBuffer.dataLength);
  207107. samplesInBuffer = readBuffer.dataLength >> 2;
  207108. lastIndex = readBuffer.index;
  207109. }
  207110. else
  207111. {
  207112. int* l = destSamples[0] + startOffsetInDestBuffer;
  207113. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  207114. while (--numSamples >= 0)
  207115. {
  207116. *l++ = 0;
  207117. if (r != 0)
  207118. *r++ = 0;
  207119. }
  207120. // sometimes the read fails for just the very last couple of blocks, so
  207121. // we'll ignore and errors in the last half-second of the disk..
  207122. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  207123. break;
  207124. }
  207125. }
  207126. }
  207127. return ok;
  207128. }
  207129. bool AudioCDReader::isCDStillPresent() const
  207130. {
  207131. TOC toc;
  207132. zerostruct (toc);
  207133. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  207134. }
  207135. int AudioCDReader::getNumTracks() const
  207136. {
  207137. return numTracks;
  207138. }
  207139. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  207140. {
  207141. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  207142. : 0;
  207143. }
  207144. void AudioCDReader::refreshTrackLengths()
  207145. {
  207146. zeromem (trackStarts, sizeof (trackStarts));
  207147. zeromem (audioTracks, sizeof (audioTracks));
  207148. TOC toc;
  207149. zerostruct (toc);
  207150. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  207151. {
  207152. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  207153. for (int i = 0; i <= numTracks; ++i)
  207154. {
  207155. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  207156. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  207157. }
  207158. }
  207159. else
  207160. {
  207161. numTracks = 0;
  207162. }
  207163. }
  207164. bool AudioCDReader::isTrackAudio (int trackNum) const
  207165. {
  207166. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  207167. : false;
  207168. }
  207169. void AudioCDReader::enableIndexScanning (bool b)
  207170. {
  207171. indexingEnabled = b;
  207172. }
  207173. int AudioCDReader::getLastIndex() const
  207174. {
  207175. return lastIndex;
  207176. }
  207177. const int framesPerIndexRead = 4;
  207178. int AudioCDReader::getIndexAt (int samplePos)
  207179. {
  207180. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207181. const int frameNeeded = samplePos / samplesPerFrame;
  207182. device->overlapBuffer->dataLength = 0;
  207183. device->overlapBuffer->startFrame = 0;
  207184. device->overlapBuffer->numFrames = 0;
  207185. device->jitter = false;
  207186. firstFrameInBuffer = 0;
  207187. lastIndex = 0;
  207188. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  207189. readBuffer.wantsIndex = true;
  207190. int i;
  207191. for (i = 5; --i >= 0;)
  207192. {
  207193. readBuffer.startFrame = frameNeeded;
  207194. readBuffer.numFrames = framesPerIndexRead;
  207195. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207196. break;
  207197. }
  207198. if (i >= 0)
  207199. return readBuffer.index;
  207200. return -1;
  207201. }
  207202. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  207203. {
  207204. Array <int> indexes;
  207205. const int trackStart = getPositionOfTrackStart (trackNumber);
  207206. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  207207. bool needToScan = true;
  207208. if (trackEnd - trackStart > 20 * 44100)
  207209. {
  207210. // check the end of the track for indexes before scanning the whole thing
  207211. needToScan = false;
  207212. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  207213. bool seenAnIndex = false;
  207214. while (pos <= trackEnd - samplesPerFrame)
  207215. {
  207216. const int index = getIndexAt (pos);
  207217. if (index == 0)
  207218. {
  207219. // lead-out, so skip back a bit if we've not found any indexes yet..
  207220. if (seenAnIndex)
  207221. break;
  207222. pos -= 44100 * 5;
  207223. if (pos < trackStart)
  207224. break;
  207225. }
  207226. else
  207227. {
  207228. if (index > 0)
  207229. seenAnIndex = true;
  207230. if (index > 1)
  207231. {
  207232. needToScan = true;
  207233. break;
  207234. }
  207235. pos += samplesPerFrame * framesPerIndexRead;
  207236. }
  207237. }
  207238. }
  207239. if (needToScan)
  207240. {
  207241. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207242. int pos = trackStart;
  207243. int last = -1;
  207244. while (pos < trackEnd - samplesPerFrame * 10)
  207245. {
  207246. const int frameNeeded = pos / samplesPerFrame;
  207247. device->overlapBuffer->dataLength = 0;
  207248. device->overlapBuffer->startFrame = 0;
  207249. device->overlapBuffer->numFrames = 0;
  207250. device->jitter = false;
  207251. firstFrameInBuffer = 0;
  207252. CDReadBuffer readBuffer (4);
  207253. readBuffer.wantsIndex = true;
  207254. int i;
  207255. for (i = 5; --i >= 0;)
  207256. {
  207257. readBuffer.startFrame = frameNeeded;
  207258. readBuffer.numFrames = framesPerIndexRead;
  207259. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207260. break;
  207261. }
  207262. if (i < 0)
  207263. break;
  207264. if (readBuffer.index > last && readBuffer.index > 1)
  207265. {
  207266. last = readBuffer.index;
  207267. indexes.add (pos);
  207268. }
  207269. pos += samplesPerFrame * framesPerIndexRead;
  207270. }
  207271. indexes.removeValue (trackStart);
  207272. }
  207273. return indexes;
  207274. }
  207275. int AudioCDReader::getCDDBId()
  207276. {
  207277. refreshTrackLengths();
  207278. if (numTracks > 0)
  207279. {
  207280. TOC toc;
  207281. zerostruct (toc);
  207282. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  207283. {
  207284. int n = 0;
  207285. for (int i = numTracks; --i >= 0;)
  207286. {
  207287. int j = getMSFAddressOf (&toc.tracks[i]);
  207288. while (j > 0)
  207289. {
  207290. n += (j % 10);
  207291. j /= 10;
  207292. }
  207293. }
  207294. if (n != 0)
  207295. {
  207296. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  207297. - getMSFAddressOf (&toc.tracks[0]);
  207298. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  207299. }
  207300. }
  207301. }
  207302. return 0;
  207303. }
  207304. void AudioCDReader::ejectDisk()
  207305. {
  207306. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  207307. }
  207308. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  207309. {
  207310. CoInitialize (0);
  207311. IDiscMaster* dm;
  207312. IDiscRecorder* result = 0;
  207313. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  207314. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  207315. IID_IDiscMaster,
  207316. (void**) &dm)))
  207317. {
  207318. if (SUCCEEDED (dm->Open()))
  207319. {
  207320. IEnumDiscRecorders* drEnum = 0;
  207321. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  207322. {
  207323. IDiscRecorder* dr = 0;
  207324. DWORD dummy;
  207325. int index = 0;
  207326. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  207327. {
  207328. if (indexToOpen == index)
  207329. {
  207330. result = dr;
  207331. break;
  207332. }
  207333. else if (list != 0)
  207334. {
  207335. BSTR path;
  207336. if (SUCCEEDED (dr->GetPath (&path)))
  207337. list->add ((const WCHAR*) path);
  207338. }
  207339. ++index;
  207340. dr->Release();
  207341. }
  207342. drEnum->Release();
  207343. }
  207344. /*if (redbookFormat != 0)
  207345. {
  207346. IEnumDiscMasterFormats* mfEnum;
  207347. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  207348. {
  207349. IID formatIID;
  207350. DWORD dummy;
  207351. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  207352. {
  207353. }
  207354. mfEnum->Release();
  207355. }
  207356. redbookFormat
  207357. }*/
  207358. if (master == 0)
  207359. dm->Close();
  207360. }
  207361. if (master != 0)
  207362. *master = dm;
  207363. else
  207364. dm->Release();
  207365. }
  207366. return result;
  207367. }
  207368. const StringArray AudioCDBurner::findAvailableDevices()
  207369. {
  207370. StringArray devs;
  207371. enumCDBurners (&devs, -1, 0);
  207372. return devs;
  207373. }
  207374. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  207375. {
  207376. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  207377. if (b->internal == 0)
  207378. deleteAndZero (b);
  207379. return b;
  207380. }
  207381. class CDBurnerInfo : public IDiscMasterProgressEvents
  207382. {
  207383. public:
  207384. CDBurnerInfo()
  207385. : refCount (1),
  207386. progress (0),
  207387. shouldCancel (false),
  207388. listener (0)
  207389. {
  207390. }
  207391. ~CDBurnerInfo()
  207392. {
  207393. }
  207394. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207395. {
  207396. if (result == 0)
  207397. return E_POINTER;
  207398. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  207399. {
  207400. AddRef();
  207401. *result = this;
  207402. return S_OK;
  207403. }
  207404. *result = 0;
  207405. return E_NOINTERFACE;
  207406. }
  207407. ULONG __stdcall AddRef() { return ++refCount; }
  207408. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207409. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  207410. {
  207411. if (listener != 0 && ! shouldCancel)
  207412. shouldCancel = listener->audioCDBurnProgress (progress);
  207413. *pbCancel = shouldCancel;
  207414. return S_OK;
  207415. }
  207416. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  207417. {
  207418. progress = nCompleted / (float) nTotal;
  207419. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  207420. return E_NOTIMPL;
  207421. }
  207422. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  207423. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  207424. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  207425. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207426. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207427. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207428. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207429. IDiscMaster* discMaster;
  207430. IDiscRecorder* discRecorder;
  207431. IRedbookDiscMaster* redbook;
  207432. AudioCDBurner::BurnProgressListener* listener;
  207433. float progress;
  207434. bool shouldCancel;
  207435. private:
  207436. int refCount;
  207437. };
  207438. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  207439. : internal (0)
  207440. {
  207441. IDiscMaster* discMaster;
  207442. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  207443. if (dr != 0)
  207444. {
  207445. IRedbookDiscMaster* redbook;
  207446. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  207447. hr = discMaster->SetActiveDiscRecorder (dr);
  207448. CDBurnerInfo* const info = new CDBurnerInfo();
  207449. internal = info;
  207450. info->discMaster = discMaster;
  207451. info->discRecorder = dr;
  207452. info->redbook = redbook;
  207453. }
  207454. }
  207455. AudioCDBurner::~AudioCDBurner()
  207456. {
  207457. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207458. if (info != 0)
  207459. {
  207460. info->discRecorder->Close();
  207461. info->redbook->Release();
  207462. info->discRecorder->Release();
  207463. info->discMaster->Release();
  207464. info->Release();
  207465. }
  207466. }
  207467. bool AudioCDBurner::isDiskPresent() const
  207468. {
  207469. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207470. HRESULT hr = info->discRecorder->OpenExclusive();
  207471. long type, flags;
  207472. hr = info->discRecorder->QueryMediaType (&type, &flags);
  207473. info->discRecorder->Close();
  207474. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  207475. }
  207476. int AudioCDBurner::getNumAvailableAudioBlocks() const
  207477. {
  207478. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207479. long blocksFree = 0;
  207480. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  207481. return blocksFree;
  207482. }
  207483. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  207484. const bool ejectDiscAfterwards,
  207485. const bool performFakeBurnForTesting)
  207486. {
  207487. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207488. info->listener = listener;
  207489. info->progress = 0;
  207490. info->shouldCancel = false;
  207491. UINT_PTR cookie;
  207492. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  207493. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  207494. ejectDiscAfterwards);
  207495. String error;
  207496. if (hr != S_OK)
  207497. {
  207498. const char* e = "Couldn't open or write to the CD device";
  207499. if (hr == IMAPI_E_USERABORT)
  207500. e = "User cancelled the write operation";
  207501. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  207502. e = "No Disk present";
  207503. error = e;
  207504. }
  207505. info->discMaster->ProgressUnadvise (cookie);
  207506. info->listener = 0;
  207507. return error;
  207508. }
  207509. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  207510. {
  207511. if (source == 0)
  207512. return false;
  207513. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207514. long bytesPerBlock;
  207515. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  207516. const int samplesPerBlock = bytesPerBlock / 4;
  207517. bool ok = true;
  207518. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  207519. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  207520. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  207521. int samplesDone = 0;
  207522. source->prepareToPlay (samplesPerBlock, 44100.0);
  207523. while (ok)
  207524. {
  207525. {
  207526. AudioSourceChannelInfo info;
  207527. info.buffer = &sourceBuffer;
  207528. info.numSamples = samplesPerBlock;
  207529. info.startSample = 0;
  207530. sourceBuffer.clear();
  207531. source->getNextAudioBlock (info);
  207532. }
  207533. zeromem (buffer, bytesPerBlock);
  207534. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  207535. buffer, samplesPerBlock, 4);
  207536. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  207537. buffer + 2, samplesPerBlock, 4);
  207538. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  207539. if (hr != S_OK)
  207540. ok = false;
  207541. samplesDone += samplesPerBlock;
  207542. if (samplesDone >= numSamples)
  207543. break;
  207544. }
  207545. juce_free (buffer);
  207546. hr = info->redbook->CloseAudioTrack();
  207547. delete source;
  207548. return ok && hr == S_OK;
  207549. }
  207550. #endif
  207551. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  207552. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  207553. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207554. // compiled on its own).
  207555. #if JUCE_INCLUDED_FILE
  207556. static const int midiBufferSize = 1024 * 10;
  207557. static const int numInHeaders = 32;
  207558. static const int inBufferSize = 256;
  207559. static Array <void*, CriticalSection> activeMidiThreads;
  207560. using ::free;
  207561. class MidiInThread : public Thread
  207562. {
  207563. public:
  207564. MidiInThread (MidiInput* const input_,
  207565. MidiInputCallback* const callback_)
  207566. : Thread ("Juce Midi"),
  207567. hIn (0),
  207568. input (input_),
  207569. callback (callback_),
  207570. isStarted (false),
  207571. startTime (0),
  207572. pendingLength(0)
  207573. {
  207574. for (int i = numInHeaders; --i >= 0;)
  207575. {
  207576. zeromem (&hdr[i], sizeof (MIDIHDR));
  207577. hdr[i].lpData = inData[i];
  207578. hdr[i].dwBufferLength = inBufferSize;
  207579. }
  207580. };
  207581. ~MidiInThread()
  207582. {
  207583. stop();
  207584. if (hIn != 0)
  207585. {
  207586. int count = 5;
  207587. while (--count >= 0)
  207588. {
  207589. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  207590. break;
  207591. Sleep (20);
  207592. }
  207593. }
  207594. }
  207595. void handle (const uint32 message, const uint32 timeStamp) throw()
  207596. {
  207597. const int byte = message & 0xff;
  207598. if (byte < 0x80)
  207599. return;
  207600. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  207601. const double time = timeStampToTime (timeStamp);
  207602. lock.enter();
  207603. if (pendingLength < midiBufferSize - 12)
  207604. {
  207605. char* const p = pending + pendingLength;
  207606. *(double*) p = time;
  207607. *(uint32*) (p + 8) = numBytes;
  207608. *(uint32*) (p + 12) = message;
  207609. pendingLength += 12 + numBytes;
  207610. }
  207611. else
  207612. {
  207613. jassertfalse // midi buffer overflow! You might need to increase the size..
  207614. }
  207615. lock.exit();
  207616. notify();
  207617. }
  207618. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  207619. {
  207620. const int num = hdr->dwBytesRecorded;
  207621. if (num > 0)
  207622. {
  207623. const double time = timeStampToTime (timeStamp);
  207624. lock.enter();
  207625. if (pendingLength < midiBufferSize - (8 + num))
  207626. {
  207627. char* const p = pending + pendingLength;
  207628. *(double*) p = time;
  207629. *(uint32*) (p + 8) = num;
  207630. memcpy (p + 12, hdr->lpData, num);
  207631. pendingLength += 12 + num;
  207632. }
  207633. else
  207634. {
  207635. jassertfalse // midi buffer overflow! You might need to increase the size..
  207636. }
  207637. lock.exit();
  207638. notify();
  207639. }
  207640. }
  207641. void writeBlock (const int i) throw()
  207642. {
  207643. hdr[i].dwBytesRecorded = 0;
  207644. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207645. jassert (res == MMSYSERR_NOERROR);
  207646. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  207647. jassert (res == MMSYSERR_NOERROR);
  207648. }
  207649. void run()
  207650. {
  207651. MemoryBlock pendingCopy (64);
  207652. while (! threadShouldExit())
  207653. {
  207654. for (int i = 0; i < numInHeaders; ++i)
  207655. {
  207656. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207657. {
  207658. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207659. (void) res;
  207660. jassert (res == MMSYSERR_NOERROR);
  207661. writeBlock (i);
  207662. }
  207663. }
  207664. lock.enter();
  207665. int len = pendingLength;
  207666. if (len > 0)
  207667. {
  207668. pendingCopy.ensureSize (len);
  207669. pendingCopy.copyFrom (pending, 0, len);
  207670. pendingLength = 0;
  207671. }
  207672. lock.exit();
  207673. //xxx needs to figure out if blocks are broken up or not
  207674. if (len == 0)
  207675. {
  207676. wait (500);
  207677. }
  207678. else
  207679. {
  207680. const char* p = (const char*) pendingCopy.getData();
  207681. while (len > 0)
  207682. {
  207683. const double time = *(const double*) p;
  207684. const int messageLen = *(const int*) (p + 8);
  207685. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  207686. callback->handleIncomingMidiMessage (input, message);
  207687. p += 12 + messageLen;
  207688. len -= 12 + messageLen;
  207689. }
  207690. }
  207691. }
  207692. }
  207693. void start() throw()
  207694. {
  207695. jassert (hIn != 0);
  207696. if (hIn != 0 && ! isStarted)
  207697. {
  207698. stop();
  207699. activeMidiThreads.addIfNotAlreadyThere (this);
  207700. int i;
  207701. for (i = 0; i < numInHeaders; ++i)
  207702. writeBlock (i);
  207703. startTime = Time::getMillisecondCounter();
  207704. MMRESULT res = midiInStart (hIn);
  207705. jassert (res == MMSYSERR_NOERROR);
  207706. if (res == MMSYSERR_NOERROR)
  207707. {
  207708. isStarted = true;
  207709. pendingLength = 0;
  207710. startThread (6);
  207711. }
  207712. }
  207713. }
  207714. void stop() throw()
  207715. {
  207716. if (isStarted)
  207717. {
  207718. stopThread (5000);
  207719. midiInReset (hIn);
  207720. midiInStop (hIn);
  207721. activeMidiThreads.removeValue (this);
  207722. lock.enter();
  207723. lock.exit();
  207724. for (int i = numInHeaders; --i >= 0;)
  207725. {
  207726. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207727. {
  207728. int c = 10;
  207729. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  207730. Sleep (20);
  207731. jassert (c >= 0);
  207732. }
  207733. }
  207734. isStarted = false;
  207735. pendingLength = 0;
  207736. }
  207737. }
  207738. juce_UseDebuggingNewOperator
  207739. HMIDIIN hIn;
  207740. private:
  207741. MidiInput* input;
  207742. MidiInputCallback* callback;
  207743. bool isStarted;
  207744. uint32 startTime;
  207745. CriticalSection lock;
  207746. MIDIHDR hdr [numInHeaders];
  207747. char inData [numInHeaders] [inBufferSize];
  207748. int pendingLength;
  207749. char pending [midiBufferSize];
  207750. double timeStampToTime (uint32 timeStamp) throw()
  207751. {
  207752. timeStamp += startTime;
  207753. const uint32 now = Time::getMillisecondCounter();
  207754. if (timeStamp > now)
  207755. {
  207756. if (timeStamp > now + 2)
  207757. --startTime;
  207758. timeStamp = now;
  207759. }
  207760. return 0.001 * timeStamp;
  207761. }
  207762. MidiInThread (const MidiInThread&);
  207763. const MidiInThread& operator= (const MidiInThread&);
  207764. };
  207765. static void CALLBACK midiInCallback (HMIDIIN,
  207766. UINT uMsg,
  207767. DWORD_PTR dwInstance,
  207768. DWORD_PTR midiMessage,
  207769. DWORD_PTR timeStamp)
  207770. {
  207771. MidiInThread* const thread = (MidiInThread*) dwInstance;
  207772. if (thread != 0 && activeMidiThreads.contains (thread))
  207773. {
  207774. if (uMsg == MIM_DATA)
  207775. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  207776. else if (uMsg == MIM_LONGDATA)
  207777. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  207778. }
  207779. }
  207780. const StringArray MidiInput::getDevices()
  207781. {
  207782. StringArray s;
  207783. const int num = midiInGetNumDevs();
  207784. for (int i = 0; i < num; ++i)
  207785. {
  207786. MIDIINCAPS mc;
  207787. zerostruct (mc);
  207788. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207789. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207790. }
  207791. return s;
  207792. }
  207793. int MidiInput::getDefaultDeviceIndex()
  207794. {
  207795. return 0;
  207796. }
  207797. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  207798. {
  207799. if (callback == 0)
  207800. return 0;
  207801. UINT deviceId = MIDI_MAPPER;
  207802. int n = 0;
  207803. String name;
  207804. const int num = midiInGetNumDevs();
  207805. for (int i = 0; i < num; ++i)
  207806. {
  207807. MIDIINCAPS mc;
  207808. zerostruct (mc);
  207809. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207810. {
  207811. if (index == n)
  207812. {
  207813. deviceId = i;
  207814. name = String (mc.szPname, sizeof (mc.szPname));
  207815. break;
  207816. }
  207817. ++n;
  207818. }
  207819. }
  207820. MidiInput* const in = new MidiInput (name);
  207821. MidiInThread* const thread = new MidiInThread (in, callback);
  207822. HMIDIIN h;
  207823. HRESULT err = midiInOpen (&h, deviceId,
  207824. (DWORD_PTR) &midiInCallback,
  207825. (DWORD_PTR) thread,
  207826. CALLBACK_FUNCTION);
  207827. if (err == MMSYSERR_NOERROR)
  207828. {
  207829. thread->hIn = h;
  207830. in->internal = (void*) thread;
  207831. return in;
  207832. }
  207833. else
  207834. {
  207835. delete in;
  207836. delete thread;
  207837. return 0;
  207838. }
  207839. }
  207840. MidiInput::MidiInput (const String& name_)
  207841. : name (name_),
  207842. internal (0)
  207843. {
  207844. }
  207845. MidiInput::~MidiInput()
  207846. {
  207847. if (internal != 0)
  207848. {
  207849. MidiInThread* const thread = (MidiInThread*) internal;
  207850. delete thread;
  207851. }
  207852. }
  207853. void MidiInput::start()
  207854. {
  207855. ((MidiInThread*) internal)->start();
  207856. }
  207857. void MidiInput::stop()
  207858. {
  207859. ((MidiInThread*) internal)->stop();
  207860. }
  207861. struct MidiOutHandle
  207862. {
  207863. int refCount;
  207864. UINT deviceId;
  207865. HMIDIOUT handle;
  207866. juce_UseDebuggingNewOperator
  207867. };
  207868. static VoidArray handles (4);
  207869. const StringArray MidiOutput::getDevices()
  207870. {
  207871. StringArray s;
  207872. const int num = midiOutGetNumDevs();
  207873. for (int i = 0; i < num; ++i)
  207874. {
  207875. MIDIOUTCAPS mc;
  207876. zerostruct (mc);
  207877. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207878. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207879. }
  207880. return s;
  207881. }
  207882. int MidiOutput::getDefaultDeviceIndex()
  207883. {
  207884. const int num = midiOutGetNumDevs();
  207885. int n = 0;
  207886. for (int i = 0; i < num; ++i)
  207887. {
  207888. MIDIOUTCAPS mc;
  207889. zerostruct (mc);
  207890. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207891. {
  207892. if ((mc.wTechnology & MOD_MAPPER) != 0)
  207893. return n;
  207894. ++n;
  207895. }
  207896. }
  207897. return 0;
  207898. }
  207899. MidiOutput* MidiOutput::openDevice (int index)
  207900. {
  207901. UINT deviceId = MIDI_MAPPER;
  207902. const int num = midiOutGetNumDevs();
  207903. int i, n = 0;
  207904. for (i = 0; i < num; ++i)
  207905. {
  207906. MIDIOUTCAPS mc;
  207907. zerostruct (mc);
  207908. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207909. {
  207910. // use the microsoft sw synth as a default - best not to allow deviceId
  207911. // to be MIDI_MAPPER, or else device sharing breaks
  207912. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  207913. deviceId = i;
  207914. if (index == n)
  207915. {
  207916. deviceId = i;
  207917. break;
  207918. }
  207919. ++n;
  207920. }
  207921. }
  207922. for (i = handles.size(); --i >= 0;)
  207923. {
  207924. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  207925. if (han != 0 && han->deviceId == deviceId)
  207926. {
  207927. han->refCount++;
  207928. MidiOutput* const out = new MidiOutput();
  207929. out->internal = (void*) han;
  207930. return out;
  207931. }
  207932. }
  207933. for (i = 4; --i >= 0;)
  207934. {
  207935. HMIDIOUT h = 0;
  207936. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  207937. if (res == MMSYSERR_NOERROR)
  207938. {
  207939. MidiOutHandle* const han = new MidiOutHandle();
  207940. han->deviceId = deviceId;
  207941. han->refCount = 1;
  207942. han->handle = h;
  207943. handles.add (han);
  207944. MidiOutput* const out = new MidiOutput();
  207945. out->internal = (void*) han;
  207946. return out;
  207947. }
  207948. else if (res == MMSYSERR_ALLOCATED)
  207949. {
  207950. Sleep (100);
  207951. }
  207952. else
  207953. {
  207954. break;
  207955. }
  207956. }
  207957. return 0;
  207958. }
  207959. MidiOutput::~MidiOutput()
  207960. {
  207961. MidiOutHandle* const h = (MidiOutHandle*) internal;
  207962. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  207963. {
  207964. midiOutClose (h->handle);
  207965. handles.removeValue ((void*) h);
  207966. delete h;
  207967. }
  207968. }
  207969. void MidiOutput::reset()
  207970. {
  207971. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  207972. midiOutReset (h->handle);
  207973. }
  207974. bool MidiOutput::getVolume (float& leftVol,
  207975. float& rightVol)
  207976. {
  207977. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207978. DWORD n;
  207979. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  207980. {
  207981. const unsigned short* const nn = (const unsigned short*) &n;
  207982. rightVol = nn[0] / (float) 0xffff;
  207983. leftVol = nn[1] / (float) 0xffff;
  207984. return true;
  207985. }
  207986. else
  207987. {
  207988. rightVol = leftVol = 1.0f;
  207989. return false;
  207990. }
  207991. }
  207992. void MidiOutput::setVolume (float leftVol,
  207993. float rightVol)
  207994. {
  207995. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  207996. DWORD n;
  207997. unsigned short* const nn = (unsigned short*) &n;
  207998. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  207999. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  208000. midiOutSetVolume (handle->handle, n);
  208001. }
  208002. void MidiOutput::sendMessageNow (const MidiMessage& message)
  208003. {
  208004. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  208005. if (message.getRawDataSize() > 3
  208006. || message.isSysEx())
  208007. {
  208008. MIDIHDR h;
  208009. zerostruct (h);
  208010. h.lpData = (char*) message.getRawData();
  208011. h.dwBufferLength = message.getRawDataSize();
  208012. h.dwBytesRecorded = message.getRawDataSize();
  208013. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  208014. {
  208015. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  208016. if (res == MMSYSERR_NOERROR)
  208017. {
  208018. while ((h.dwFlags & MHDR_DONE) == 0)
  208019. Sleep (1);
  208020. int count = 500; // 1 sec timeout
  208021. while (--count >= 0)
  208022. {
  208023. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  208024. if (res == MIDIERR_STILLPLAYING)
  208025. Sleep (2);
  208026. else
  208027. break;
  208028. }
  208029. }
  208030. }
  208031. }
  208032. else
  208033. {
  208034. midiOutShortMsg (handle->handle,
  208035. *(unsigned int*) message.getRawData());
  208036. }
  208037. }
  208038. #endif
  208039. /********* End of inlined file: juce_win32_Midi.cpp *********/
  208040. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  208041. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208042. // compiled on its own).
  208043. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  208044. #undef WINDOWS
  208045. // #define ASIO_DEBUGGING
  208046. #ifdef ASIO_DEBUGGING
  208047. #define log(a) { Logger::writeToLog (a); DBG (a) }
  208048. #else
  208049. #define log(a) {}
  208050. #endif
  208051. #ifdef ASIO_DEBUGGING
  208052. static void logError (const String& context, long error)
  208053. {
  208054. String err ("unknown error");
  208055. if (error == ASE_NotPresent)
  208056. err = "Not Present";
  208057. else if (error == ASE_HWMalfunction)
  208058. err = "Hardware Malfunction";
  208059. else if (error == ASE_InvalidParameter)
  208060. err = "Invalid Parameter";
  208061. else if (error == ASE_InvalidMode)
  208062. err = "Invalid Mode";
  208063. else if (error == ASE_SPNotAdvancing)
  208064. err = "Sample position not advancing";
  208065. else if (error == ASE_NoClock)
  208066. err = "No Clock";
  208067. else if (error == ASE_NoMemory)
  208068. err = "Out of memory";
  208069. log (T("!!error: ") + context + T(" - ") + err);
  208070. }
  208071. #else
  208072. #define logError(a, b) {}
  208073. #endif
  208074. class ASIOAudioIODevice;
  208075. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  208076. static const int maxASIOChannels = 160;
  208077. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  208078. private Timer
  208079. {
  208080. public:
  208081. Component ourWindow;
  208082. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  208083. const String& optionalDllForDirectLoading_)
  208084. : AudioIODevice (name_, T("ASIO")),
  208085. asioObject (0),
  208086. classId (classId_),
  208087. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  208088. currentBitDepth (16),
  208089. currentSampleRate (0),
  208090. tempBuffer (0),
  208091. isOpen_ (false),
  208092. isStarted (false),
  208093. postOutput (true),
  208094. insideControlPanelModalLoop (false),
  208095. shouldUsePreferredSize (false)
  208096. {
  208097. name = name_;
  208098. ourWindow.addToDesktop (0);
  208099. windowHandle = ourWindow.getWindowHandle();
  208100. jassert (currentASIODev [slotNumber] == 0);
  208101. currentASIODev [slotNumber] = this;
  208102. openDevice();
  208103. }
  208104. ~ASIOAudioIODevice()
  208105. {
  208106. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  208107. if (currentASIODev[i] == this)
  208108. currentASIODev[i] = 0;
  208109. close();
  208110. log ("ASIO - exiting");
  208111. removeCurrentDriver();
  208112. juce_free (tempBuffer);
  208113. }
  208114. void updateSampleRates()
  208115. {
  208116. // find a list of sample rates..
  208117. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  208118. sampleRates.clear();
  208119. if (asioObject != 0)
  208120. {
  208121. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  208122. {
  208123. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  208124. if (err == 0)
  208125. {
  208126. sampleRates.add ((int) possibleSampleRates[index]);
  208127. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  208128. }
  208129. else if (err != ASE_NoClock)
  208130. {
  208131. logError (T("CanSampleRate"), err);
  208132. }
  208133. }
  208134. if (sampleRates.size() == 0)
  208135. {
  208136. double cr = 0;
  208137. const long err = asioObject->getSampleRate (&cr);
  208138. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  208139. if (err == 0)
  208140. sampleRates.add ((int) cr);
  208141. }
  208142. }
  208143. }
  208144. const StringArray getOutputChannelNames()
  208145. {
  208146. return outputChannelNames;
  208147. }
  208148. const StringArray getInputChannelNames()
  208149. {
  208150. return inputChannelNames;
  208151. }
  208152. int getNumSampleRates()
  208153. {
  208154. return sampleRates.size();
  208155. }
  208156. double getSampleRate (int index)
  208157. {
  208158. return sampleRates [index];
  208159. }
  208160. int getNumBufferSizesAvailable()
  208161. {
  208162. return bufferSizes.size();
  208163. }
  208164. int getBufferSizeSamples (int index)
  208165. {
  208166. return bufferSizes [index];
  208167. }
  208168. int getDefaultBufferSize()
  208169. {
  208170. return preferredSize;
  208171. }
  208172. const String open (const BitArray& inputChannels,
  208173. const BitArray& outputChannels,
  208174. double sr,
  208175. int bufferSizeSamples)
  208176. {
  208177. close();
  208178. currentCallback = 0;
  208179. if (bufferSizeSamples <= 0)
  208180. shouldUsePreferredSize = true;
  208181. if (asioObject == 0 || ! isASIOOpen)
  208182. {
  208183. log ("Warning: device not open");
  208184. const String err (openDevice());
  208185. if (asioObject == 0 || ! isASIOOpen)
  208186. return err;
  208187. }
  208188. isStarted = false;
  208189. bufferIndex = -1;
  208190. long err = 0;
  208191. long newPreferredSize = 0;
  208192. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  208193. minSize = 0;
  208194. maxSize = 0;
  208195. newPreferredSize = 0;
  208196. granularity = 0;
  208197. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  208198. {
  208199. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  208200. shouldUsePreferredSize = true;
  208201. preferredSize = newPreferredSize;
  208202. }
  208203. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  208204. // dynamic changes to the buffer size...
  208205. shouldUsePreferredSize = shouldUsePreferredSize
  208206. || getName().containsIgnoreCase (T("Digidesign"));
  208207. if (shouldUsePreferredSize)
  208208. {
  208209. log ("Using preferred size for buffer..");
  208210. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208211. {
  208212. bufferSizeSamples = preferredSize;
  208213. }
  208214. else
  208215. {
  208216. bufferSizeSamples = 1024;
  208217. logError ("GetBufferSize1", err);
  208218. }
  208219. shouldUsePreferredSize = false;
  208220. }
  208221. int sampleRate = roundDoubleToInt (sr);
  208222. currentSampleRate = sampleRate;
  208223. currentBlockSizeSamples = bufferSizeSamples;
  208224. currentChansOut.clear();
  208225. currentChansIn.clear();
  208226. zeromem (inBuffers, sizeof (inBuffers));
  208227. zeromem (outBuffers, sizeof (outBuffers));
  208228. updateSampleRates();
  208229. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  208230. sampleRate = sampleRates[0];
  208231. jassert (sampleRate != 0);
  208232. if (sampleRate == 0)
  208233. sampleRate = 44100;
  208234. long numSources = 32;
  208235. ASIOClockSource clocks[32];
  208236. zeromem (clocks, sizeof (clocks));
  208237. asioObject->getClockSources (clocks, &numSources);
  208238. bool isSourceSet = false;
  208239. // careful not to remove this loop because it does more than just logging!
  208240. int i;
  208241. for (i = 0; i < numSources; ++i)
  208242. {
  208243. String s ("clock: ");
  208244. s += clocks[i].name;
  208245. if (clocks[i].isCurrentSource)
  208246. {
  208247. isSourceSet = true;
  208248. s << " (cur)";
  208249. }
  208250. log (s);
  208251. }
  208252. if (numSources > 1 && ! isSourceSet)
  208253. {
  208254. log ("setting clock source");
  208255. asioObject->setClockSource (clocks[0].index);
  208256. Thread::sleep (20);
  208257. }
  208258. else
  208259. {
  208260. if (numSources == 0)
  208261. {
  208262. log ("ASIO - no clock sources!");
  208263. }
  208264. }
  208265. double cr = 0;
  208266. err = asioObject->getSampleRate (&cr);
  208267. if (err == 0)
  208268. {
  208269. currentSampleRate = cr;
  208270. }
  208271. else
  208272. {
  208273. logError ("GetSampleRate", err);
  208274. currentSampleRate = 0;
  208275. }
  208276. error = String::empty;
  208277. needToReset = false;
  208278. isReSync = false;
  208279. err = 0;
  208280. bool buffersCreated = false;
  208281. if (currentSampleRate != sampleRate)
  208282. {
  208283. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  208284. err = asioObject->setSampleRate (sampleRate);
  208285. if (err == ASE_NoClock && numSources > 0)
  208286. {
  208287. log ("trying to set a clock source..");
  208288. Thread::sleep (10);
  208289. err = asioObject->setClockSource (clocks[0].index);
  208290. if (err != 0)
  208291. {
  208292. logError ("SetClock", err);
  208293. }
  208294. Thread::sleep (10);
  208295. err = asioObject->setSampleRate (sampleRate);
  208296. }
  208297. }
  208298. if (err == 0)
  208299. {
  208300. currentSampleRate = sampleRate;
  208301. if (needToReset)
  208302. {
  208303. if (isReSync)
  208304. {
  208305. log ("Resync request");
  208306. }
  208307. log ("! Resetting ASIO after sample rate change");
  208308. removeCurrentDriver();
  208309. loadDriver();
  208310. const String error (initDriver());
  208311. if (error.isNotEmpty())
  208312. {
  208313. log (T("ASIOInit: ") + error);
  208314. }
  208315. needToReset = false;
  208316. isReSync = false;
  208317. }
  208318. numActiveInputChans = 0;
  208319. numActiveOutputChans = 0;
  208320. ASIOBufferInfo* info = bufferInfos;
  208321. int i;
  208322. for (i = 0; i < totalNumInputChans; ++i)
  208323. {
  208324. if (inputChannels[i])
  208325. {
  208326. currentChansIn.setBit (i);
  208327. info->isInput = 1;
  208328. info->channelNum = i;
  208329. info->buffers[0] = info->buffers[1] = 0;
  208330. ++info;
  208331. ++numActiveInputChans;
  208332. }
  208333. }
  208334. for (i = 0; i < totalNumOutputChans; ++i)
  208335. {
  208336. if (outputChannels[i])
  208337. {
  208338. currentChansOut.setBit (i);
  208339. info->isInput = 0;
  208340. info->channelNum = i;
  208341. info->buffers[0] = info->buffers[1] = 0;
  208342. ++info;
  208343. ++numActiveOutputChans;
  208344. }
  208345. }
  208346. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  208347. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208348. if (currentASIODev[0] == this)
  208349. {
  208350. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208351. callbacks.asioMessage = &asioMessagesCallback0;
  208352. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208353. }
  208354. else if (currentASIODev[1] == this)
  208355. {
  208356. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208357. callbacks.asioMessage = &asioMessagesCallback1;
  208358. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208359. }
  208360. else if (currentASIODev[2] == this)
  208361. {
  208362. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208363. callbacks.asioMessage = &asioMessagesCallback2;
  208364. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208365. }
  208366. else
  208367. {
  208368. jassertfalse
  208369. }
  208370. log ("disposing buffers");
  208371. err = asioObject->disposeBuffers();
  208372. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  208373. err = asioObject->createBuffers (bufferInfos,
  208374. totalBuffers,
  208375. currentBlockSizeSamples,
  208376. &callbacks);
  208377. if (err != 0)
  208378. {
  208379. currentBlockSizeSamples = preferredSize;
  208380. logError ("create buffers 2", err);
  208381. asioObject->disposeBuffers();
  208382. err = asioObject->createBuffers (bufferInfos,
  208383. totalBuffers,
  208384. currentBlockSizeSamples,
  208385. &callbacks);
  208386. }
  208387. if (err == 0)
  208388. {
  208389. buffersCreated = true;
  208390. juce_free (tempBuffer);
  208391. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  208392. int n = 0;
  208393. Array <int> types;
  208394. currentBitDepth = 16;
  208395. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  208396. {
  208397. if (inputChannels[i])
  208398. {
  208399. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  208400. ASIOChannelInfo channelInfo;
  208401. zerostruct (channelInfo);
  208402. channelInfo.channel = i;
  208403. channelInfo.isInput = 1;
  208404. asioObject->getChannelInfo (&channelInfo);
  208405. types.addIfNotAlreadyThere (channelInfo.type);
  208406. typeToFormatParameters (channelInfo.type,
  208407. inputChannelBitDepths[n],
  208408. inputChannelBytesPerSample[n],
  208409. inputChannelIsFloat[n],
  208410. inputChannelLittleEndian[n]);
  208411. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  208412. ++n;
  208413. }
  208414. }
  208415. jassert (numActiveInputChans == n);
  208416. n = 0;
  208417. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  208418. {
  208419. if (outputChannels[i])
  208420. {
  208421. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  208422. ASIOChannelInfo channelInfo;
  208423. zerostruct (channelInfo);
  208424. channelInfo.channel = i;
  208425. channelInfo.isInput = 0;
  208426. asioObject->getChannelInfo (&channelInfo);
  208427. types.addIfNotAlreadyThere (channelInfo.type);
  208428. typeToFormatParameters (channelInfo.type,
  208429. outputChannelBitDepths[n],
  208430. outputChannelBytesPerSample[n],
  208431. outputChannelIsFloat[n],
  208432. outputChannelLittleEndian[n]);
  208433. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  208434. ++n;
  208435. }
  208436. }
  208437. jassert (numActiveOutputChans == n);
  208438. for (i = types.size(); --i >= 0;)
  208439. {
  208440. log (T("channel format: ") + String (types[i]));
  208441. }
  208442. jassert (n <= totalBuffers);
  208443. for (i = 0; i < numActiveOutputChans; ++i)
  208444. {
  208445. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  208446. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  208447. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  208448. {
  208449. log ("!! Null buffers");
  208450. }
  208451. else
  208452. {
  208453. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  208454. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  208455. }
  208456. }
  208457. inputLatency = outputLatency = 0;
  208458. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208459. {
  208460. log ("ASIO - no latencies");
  208461. }
  208462. else
  208463. {
  208464. log (T("ASIO latencies: ")
  208465. + String ((int) outputLatency)
  208466. + T(", ")
  208467. + String ((int) inputLatency));
  208468. }
  208469. isOpen_ = true;
  208470. log ("starting ASIO");
  208471. calledback = false;
  208472. err = asioObject->start();
  208473. if (err != 0)
  208474. {
  208475. isOpen_ = false;
  208476. log ("ASIO - stop on failure");
  208477. Thread::sleep (10);
  208478. asioObject->stop();
  208479. error = "Can't start device";
  208480. Thread::sleep (10);
  208481. }
  208482. else
  208483. {
  208484. int count = 300;
  208485. while (--count > 0 && ! calledback)
  208486. Thread::sleep (10);
  208487. isStarted = true;
  208488. if (! calledback)
  208489. {
  208490. error = "Device didn't start correctly";
  208491. log ("ASIO didn't callback - stopping..");
  208492. asioObject->stop();
  208493. }
  208494. }
  208495. }
  208496. else
  208497. {
  208498. error = "Can't create i/o buffers";
  208499. }
  208500. }
  208501. else
  208502. {
  208503. error = "Can't set sample rate: ";
  208504. error << sampleRate;
  208505. }
  208506. if (error.isNotEmpty())
  208507. {
  208508. logError (error, err);
  208509. if (asioObject != 0 && buffersCreated)
  208510. asioObject->disposeBuffers();
  208511. Thread::sleep (20);
  208512. isStarted = false;
  208513. isOpen_ = false;
  208514. close();
  208515. }
  208516. needToReset = false;
  208517. isReSync = false;
  208518. return error;
  208519. }
  208520. void close()
  208521. {
  208522. error = String::empty;
  208523. stopTimer();
  208524. stop();
  208525. if (isASIOOpen && isOpen_)
  208526. {
  208527. const ScopedLock sl (callbackLock);
  208528. isOpen_ = false;
  208529. isStarted = false;
  208530. needToReset = false;
  208531. isReSync = false;
  208532. log ("ASIO - stopping");
  208533. if (asioObject != 0)
  208534. {
  208535. Thread::sleep (20);
  208536. asioObject->stop();
  208537. Thread::sleep (10);
  208538. asioObject->disposeBuffers();
  208539. }
  208540. Thread::sleep (10);
  208541. }
  208542. }
  208543. bool isOpen()
  208544. {
  208545. return isOpen_ || insideControlPanelModalLoop;
  208546. }
  208547. int getCurrentBufferSizeSamples()
  208548. {
  208549. return currentBlockSizeSamples;
  208550. }
  208551. double getCurrentSampleRate()
  208552. {
  208553. return currentSampleRate;
  208554. }
  208555. const BitArray getActiveOutputChannels() const
  208556. {
  208557. return currentChansOut;
  208558. }
  208559. const BitArray getActiveInputChannels() const
  208560. {
  208561. return currentChansIn;
  208562. }
  208563. int getCurrentBitDepth()
  208564. {
  208565. return currentBitDepth;
  208566. }
  208567. int getOutputLatencyInSamples()
  208568. {
  208569. return outputLatency + currentBlockSizeSamples / 4;
  208570. }
  208571. int getInputLatencyInSamples()
  208572. {
  208573. return inputLatency + currentBlockSizeSamples / 4;
  208574. }
  208575. void start (AudioIODeviceCallback* callback)
  208576. {
  208577. if (callback != 0)
  208578. {
  208579. callback->audioDeviceAboutToStart (this);
  208580. const ScopedLock sl (callbackLock);
  208581. currentCallback = callback;
  208582. }
  208583. }
  208584. void stop()
  208585. {
  208586. AudioIODeviceCallback* const lastCallback = currentCallback;
  208587. {
  208588. const ScopedLock sl (callbackLock);
  208589. currentCallback = 0;
  208590. }
  208591. if (lastCallback != 0)
  208592. lastCallback->audioDeviceStopped();
  208593. }
  208594. bool isPlaying()
  208595. {
  208596. return isASIOOpen && (currentCallback != 0);
  208597. }
  208598. const String getLastError()
  208599. {
  208600. return error;
  208601. }
  208602. bool hasControlPanel() const
  208603. {
  208604. return true;
  208605. }
  208606. bool showControlPanel()
  208607. {
  208608. log ("ASIO - showing control panel");
  208609. Component modalWindow (String::empty);
  208610. modalWindow.setOpaque (true);
  208611. modalWindow.addToDesktop (0);
  208612. modalWindow.enterModalState();
  208613. bool done = false;
  208614. JUCE_TRY
  208615. {
  208616. // are there are devices that need to be closed before showing their control panel?
  208617. // close();
  208618. insideControlPanelModalLoop = true;
  208619. const uint32 started = Time::getMillisecondCounter();
  208620. if (asioObject != 0)
  208621. {
  208622. asioObject->controlPanel();
  208623. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  208624. log (T("spent: ") + String (spent));
  208625. if (spent > 300)
  208626. {
  208627. shouldUsePreferredSize = true;
  208628. done = true;
  208629. }
  208630. }
  208631. }
  208632. JUCE_CATCH_ALL
  208633. insideControlPanelModalLoop = false;
  208634. return done;
  208635. }
  208636. void resetRequest() throw()
  208637. {
  208638. needToReset = true;
  208639. }
  208640. void resyncRequest() throw()
  208641. {
  208642. needToReset = true;
  208643. isReSync = true;
  208644. }
  208645. void timerCallback()
  208646. {
  208647. if (! insideControlPanelModalLoop)
  208648. {
  208649. stopTimer();
  208650. // used to cause a reset
  208651. log ("! ASIO restart request!");
  208652. if (isOpen_)
  208653. {
  208654. AudioIODeviceCallback* const oldCallback = currentCallback;
  208655. close();
  208656. open (BitArray (currentChansIn), BitArray (currentChansOut),
  208657. currentSampleRate, currentBlockSizeSamples);
  208658. if (oldCallback != 0)
  208659. start (oldCallback);
  208660. }
  208661. }
  208662. else
  208663. {
  208664. startTimer (100);
  208665. }
  208666. }
  208667. juce_UseDebuggingNewOperator
  208668. private:
  208669. IASIO* volatile asioObject;
  208670. ASIOCallbacks callbacks;
  208671. void* windowHandle;
  208672. CLSID classId;
  208673. const String optionalDllForDirectLoading;
  208674. String error;
  208675. long totalNumInputChans, totalNumOutputChans;
  208676. StringArray inputChannelNames, outputChannelNames;
  208677. Array<int> sampleRates, bufferSizes;
  208678. long inputLatency, outputLatency;
  208679. long minSize, maxSize, preferredSize, granularity;
  208680. int volatile currentBlockSizeSamples;
  208681. int volatile currentBitDepth;
  208682. double volatile currentSampleRate;
  208683. BitArray currentChansOut, currentChansIn;
  208684. AudioIODeviceCallback* volatile currentCallback;
  208685. CriticalSection callbackLock;
  208686. ASIOBufferInfo bufferInfos [maxASIOChannels];
  208687. float* inBuffers [maxASIOChannels];
  208688. float* outBuffers [maxASIOChannels];
  208689. int inputChannelBitDepths [maxASIOChannels];
  208690. int outputChannelBitDepths [maxASIOChannels];
  208691. int inputChannelBytesPerSample [maxASIOChannels];
  208692. int outputChannelBytesPerSample [maxASIOChannels];
  208693. bool inputChannelIsFloat [maxASIOChannels];
  208694. bool outputChannelIsFloat [maxASIOChannels];
  208695. bool inputChannelLittleEndian [maxASIOChannels];
  208696. bool outputChannelLittleEndian [maxASIOChannels];
  208697. WaitableEvent event1;
  208698. float* tempBuffer;
  208699. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  208700. bool isOpen_, isStarted;
  208701. bool volatile isASIOOpen;
  208702. bool volatile calledback;
  208703. bool volatile littleEndian, postOutput, needToReset, isReSync;
  208704. bool volatile insideControlPanelModalLoop;
  208705. bool volatile shouldUsePreferredSize;
  208706. void removeCurrentDriver()
  208707. {
  208708. if (asioObject != 0)
  208709. {
  208710. asioObject->Release();
  208711. asioObject = 0;
  208712. }
  208713. }
  208714. bool loadDriver()
  208715. {
  208716. removeCurrentDriver();
  208717. JUCE_TRY
  208718. {
  208719. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  208720. classId, (void**) &asioObject) == S_OK)
  208721. {
  208722. return true;
  208723. }
  208724. // If a class isn't registered but we have a path for it, we can fallback to
  208725. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  208726. if (optionalDllForDirectLoading.isNotEmpty())
  208727. {
  208728. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  208729. if (h != 0)
  208730. {
  208731. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  208732. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  208733. if (dllGetClassObject != 0)
  208734. {
  208735. IClassFactory* classFactory = 0;
  208736. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  208737. if (classFactory != 0)
  208738. {
  208739. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  208740. classFactory->Release();
  208741. }
  208742. return asioObject != 0;
  208743. }
  208744. }
  208745. }
  208746. }
  208747. JUCE_CATCH_ALL
  208748. asioObject = 0;
  208749. return false;
  208750. }
  208751. const String initDriver()
  208752. {
  208753. if (asioObject != 0)
  208754. {
  208755. char buffer [256];
  208756. zeromem (buffer, sizeof (buffer));
  208757. if (! asioObject->init (windowHandle))
  208758. {
  208759. asioObject->getErrorMessage (buffer);
  208760. return String (buffer, sizeof (buffer) - 1);
  208761. }
  208762. // just in case any daft drivers expect this to be called..
  208763. asioObject->getDriverName (buffer);
  208764. return String::empty;
  208765. }
  208766. return "No Driver";
  208767. }
  208768. const String openDevice()
  208769. {
  208770. // use this in case the driver starts opening dialog boxes..
  208771. Component modalWindow (String::empty);
  208772. modalWindow.setOpaque (true);
  208773. modalWindow.addToDesktop (0);
  208774. modalWindow.enterModalState();
  208775. // open the device and get its info..
  208776. log (T("opening ASIO device: ") + getName());
  208777. needToReset = false;
  208778. isReSync = false;
  208779. outputChannelNames.clear();
  208780. inputChannelNames.clear();
  208781. bufferSizes.clear();
  208782. sampleRates.clear();
  208783. isASIOOpen = false;
  208784. isOpen_ = false;
  208785. totalNumInputChans = 0;
  208786. totalNumOutputChans = 0;
  208787. numActiveInputChans = 0;
  208788. numActiveOutputChans = 0;
  208789. currentCallback = 0;
  208790. error = String::empty;
  208791. if (getName().isEmpty())
  208792. return error;
  208793. long err = 0;
  208794. if (loadDriver())
  208795. {
  208796. if ((error = initDriver()).isEmpty())
  208797. {
  208798. numActiveInputChans = 0;
  208799. numActiveOutputChans = 0;
  208800. totalNumInputChans = 0;
  208801. totalNumOutputChans = 0;
  208802. if (asioObject != 0
  208803. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  208804. {
  208805. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  208806. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208807. {
  208808. // find a list of buffer sizes..
  208809. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  208810. if (granularity >= 0)
  208811. {
  208812. granularity = jmax (1, (int) granularity);
  208813. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  208814. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  208815. }
  208816. else if (granularity < 0)
  208817. {
  208818. for (int i = 0; i < 18; ++i)
  208819. {
  208820. const int s = (1 << i);
  208821. if (s >= minSize && s <= maxSize)
  208822. bufferSizes.add (s);
  208823. }
  208824. }
  208825. if (! bufferSizes.contains (preferredSize))
  208826. bufferSizes.insert (0, preferredSize);
  208827. double currentRate = 0;
  208828. asioObject->getSampleRate (&currentRate);
  208829. if (currentRate <= 0.0 || currentRate > 192001.0)
  208830. {
  208831. log ("setting sample rate");
  208832. err = asioObject->setSampleRate (44100.0);
  208833. if (err != 0)
  208834. {
  208835. logError ("setting sample rate", err);
  208836. }
  208837. asioObject->getSampleRate (&currentRate);
  208838. }
  208839. currentSampleRate = currentRate;
  208840. postOutput = (asioObject->outputReady() == 0);
  208841. if (postOutput)
  208842. {
  208843. log ("ASIO outputReady = ok");
  208844. }
  208845. updateSampleRates();
  208846. // ..because cubase does it at this point
  208847. inputLatency = outputLatency = 0;
  208848. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208849. {
  208850. log ("ASIO - no latencies");
  208851. }
  208852. log (String ("latencies: ")
  208853. + String ((int) inputLatency)
  208854. + T(", ") + String ((int) outputLatency));
  208855. // create some dummy buffers now.. because cubase does..
  208856. numActiveInputChans = 0;
  208857. numActiveOutputChans = 0;
  208858. ASIOBufferInfo* info = bufferInfos;
  208859. int i, numChans = 0;
  208860. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  208861. {
  208862. info->isInput = 1;
  208863. info->channelNum = i;
  208864. info->buffers[0] = info->buffers[1] = 0;
  208865. ++info;
  208866. ++numChans;
  208867. }
  208868. const int outputBufferIndex = numChans;
  208869. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  208870. {
  208871. info->isInput = 0;
  208872. info->channelNum = i;
  208873. info->buffers[0] = info->buffers[1] = 0;
  208874. ++info;
  208875. ++numChans;
  208876. }
  208877. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208878. if (currentASIODev[0] == this)
  208879. {
  208880. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208881. callbacks.asioMessage = &asioMessagesCallback0;
  208882. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208883. }
  208884. else if (currentASIODev[1] == this)
  208885. {
  208886. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208887. callbacks.asioMessage = &asioMessagesCallback1;
  208888. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208889. }
  208890. else if (currentASIODev[2] == this)
  208891. {
  208892. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208893. callbacks.asioMessage = &asioMessagesCallback2;
  208894. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208895. }
  208896. else
  208897. {
  208898. jassertfalse
  208899. }
  208900. log (T("creating buffers (dummy): ") + String (numChans)
  208901. + T(", ") + String ((int) preferredSize));
  208902. if (preferredSize > 0)
  208903. {
  208904. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  208905. if (err != 0)
  208906. {
  208907. logError ("dummy buffers", err);
  208908. }
  208909. }
  208910. long newInps = 0, newOuts = 0;
  208911. asioObject->getChannels (&newInps, &newOuts);
  208912. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  208913. {
  208914. totalNumInputChans = newInps;
  208915. totalNumOutputChans = newOuts;
  208916. log (String ((int) totalNumInputChans) + T(" in; ")
  208917. + String ((int) totalNumOutputChans) + T(" out"));
  208918. }
  208919. updateSampleRates();
  208920. ASIOChannelInfo channelInfo;
  208921. channelInfo.type = 0;
  208922. for (i = 0; i < totalNumInputChans; ++i)
  208923. {
  208924. zerostruct (channelInfo);
  208925. channelInfo.channel = i;
  208926. channelInfo.isInput = 1;
  208927. asioObject->getChannelInfo (&channelInfo);
  208928. inputChannelNames.add (String (channelInfo.name));
  208929. }
  208930. for (i = 0; i < totalNumOutputChans; ++i)
  208931. {
  208932. zerostruct (channelInfo);
  208933. channelInfo.channel = i;
  208934. channelInfo.isInput = 0;
  208935. asioObject->getChannelInfo (&channelInfo);
  208936. outputChannelNames.add (String (channelInfo.name));
  208937. typeToFormatParameters (channelInfo.type,
  208938. outputChannelBitDepths[i],
  208939. outputChannelBytesPerSample[i],
  208940. outputChannelIsFloat[i],
  208941. outputChannelLittleEndian[i]);
  208942. if (i < 2)
  208943. {
  208944. // clear the channels that are used with the dummy stuff
  208945. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  208946. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  208947. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  208948. }
  208949. }
  208950. outputChannelNames.trim();
  208951. inputChannelNames.trim();
  208952. outputChannelNames.appendNumbersToDuplicates (false, true);
  208953. inputChannelNames.appendNumbersToDuplicates (false, true);
  208954. // start and stop because cubase does it..
  208955. asioObject->getLatencies (&inputLatency, &outputLatency);
  208956. if ((err = asioObject->start()) != 0)
  208957. {
  208958. // ignore an error here, as it might start later after setting other stuff up
  208959. logError ("ASIO start", err);
  208960. }
  208961. Thread::sleep (100);
  208962. asioObject->stop();
  208963. }
  208964. else
  208965. {
  208966. error = "Can't detect buffer sizes";
  208967. }
  208968. }
  208969. else
  208970. {
  208971. error = "Can't detect asio channels";
  208972. }
  208973. }
  208974. }
  208975. else
  208976. {
  208977. error = "No such device";
  208978. }
  208979. if (error.isNotEmpty())
  208980. {
  208981. logError (error, err);
  208982. if (asioObject != 0)
  208983. asioObject->disposeBuffers();
  208984. removeCurrentDriver();
  208985. isASIOOpen = false;
  208986. }
  208987. else
  208988. {
  208989. isASIOOpen = true;
  208990. log ("ASIO device open");
  208991. }
  208992. isOpen_ = false;
  208993. needToReset = false;
  208994. isReSync = false;
  208995. return error;
  208996. }
  208997. void callback (const long index) throw()
  208998. {
  208999. if (isStarted)
  209000. {
  209001. bufferIndex = index;
  209002. processBuffer();
  209003. }
  209004. else
  209005. {
  209006. if (postOutput && (asioObject != 0))
  209007. asioObject->outputReady();
  209008. }
  209009. calledback = true;
  209010. }
  209011. void processBuffer() throw()
  209012. {
  209013. const ASIOBufferInfo* const infos = bufferInfos;
  209014. const int bi = bufferIndex;
  209015. const ScopedLock sl (callbackLock);
  209016. if (needToReset)
  209017. {
  209018. needToReset = false;
  209019. if (isReSync)
  209020. {
  209021. log ("! ASIO resync");
  209022. isReSync = false;
  209023. }
  209024. else
  209025. {
  209026. startTimer (20);
  209027. }
  209028. }
  209029. if (bi >= 0)
  209030. {
  209031. const int samps = currentBlockSizeSamples;
  209032. if (currentCallback != 0)
  209033. {
  209034. int i;
  209035. for (i = 0; i < numActiveInputChans; ++i)
  209036. {
  209037. float* const dst = inBuffers[i];
  209038. jassert (dst != 0);
  209039. const char* const src = (const char*) (infos[i].buffers[bi]);
  209040. if (inputChannelIsFloat[i])
  209041. {
  209042. memcpy (dst, src, samps * sizeof (float));
  209043. }
  209044. else
  209045. {
  209046. jassert (dst == tempBuffer + (samps * i));
  209047. switch (inputChannelBitDepths[i])
  209048. {
  209049. case 16:
  209050. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  209051. samps, inputChannelLittleEndian[i]);
  209052. break;
  209053. case 24:
  209054. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  209055. samps, inputChannelLittleEndian[i]);
  209056. break;
  209057. case 32:
  209058. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  209059. samps, inputChannelLittleEndian[i]);
  209060. break;
  209061. case 64:
  209062. jassertfalse
  209063. break;
  209064. }
  209065. }
  209066. }
  209067. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  209068. numActiveInputChans,
  209069. outBuffers,
  209070. numActiveOutputChans,
  209071. samps);
  209072. for (i = 0; i < numActiveOutputChans; ++i)
  209073. {
  209074. float* const src = outBuffers[i];
  209075. jassert (src != 0);
  209076. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  209077. if (outputChannelIsFloat[i])
  209078. {
  209079. memcpy (dst, src, samps * sizeof (float));
  209080. }
  209081. else
  209082. {
  209083. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  209084. switch (outputChannelBitDepths[i])
  209085. {
  209086. case 16:
  209087. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  209088. samps, outputChannelLittleEndian[i]);
  209089. break;
  209090. case 24:
  209091. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  209092. samps, outputChannelLittleEndian[i]);
  209093. break;
  209094. case 32:
  209095. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  209096. samps, outputChannelLittleEndian[i]);
  209097. break;
  209098. case 64:
  209099. jassertfalse
  209100. break;
  209101. }
  209102. }
  209103. }
  209104. }
  209105. else
  209106. {
  209107. for (int i = 0; i < numActiveOutputChans; ++i)
  209108. {
  209109. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  209110. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  209111. }
  209112. }
  209113. }
  209114. if (postOutput)
  209115. asioObject->outputReady();
  209116. }
  209117. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  209118. {
  209119. if (currentASIODev[0] != 0)
  209120. currentASIODev[0]->callback (index);
  209121. return 0;
  209122. }
  209123. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  209124. {
  209125. if (currentASIODev[1] != 0)
  209126. currentASIODev[1]->callback (index);
  209127. return 0;
  209128. }
  209129. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  209130. {
  209131. if (currentASIODev[2] != 0)
  209132. currentASIODev[2]->callback (index);
  209133. return 0;
  209134. }
  209135. static void bufferSwitchCallback0 (long index, long) throw()
  209136. {
  209137. if (currentASIODev[0] != 0)
  209138. currentASIODev[0]->callback (index);
  209139. }
  209140. static void bufferSwitchCallback1 (long index, long) throw()
  209141. {
  209142. if (currentASIODev[1] != 0)
  209143. currentASIODev[1]->callback (index);
  209144. }
  209145. static void bufferSwitchCallback2 (long index, long) throw()
  209146. {
  209147. if (currentASIODev[2] != 0)
  209148. currentASIODev[2]->callback (index);
  209149. }
  209150. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  209151. {
  209152. return asioMessagesCallback (selector, value, 0);
  209153. }
  209154. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  209155. {
  209156. return asioMessagesCallback (selector, value, 1);
  209157. }
  209158. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  209159. {
  209160. return asioMessagesCallback (selector, value, 2);
  209161. }
  209162. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  209163. {
  209164. switch (selector)
  209165. {
  209166. case kAsioSelectorSupported:
  209167. if (value == kAsioResetRequest
  209168. || value == kAsioEngineVersion
  209169. || value == kAsioResyncRequest
  209170. || value == kAsioLatenciesChanged
  209171. || value == kAsioSupportsInputMonitor)
  209172. return 1;
  209173. break;
  209174. case kAsioBufferSizeChange:
  209175. break;
  209176. case kAsioResetRequest:
  209177. if (currentASIODev[deviceIndex] != 0)
  209178. currentASIODev[deviceIndex]->resetRequest();
  209179. return 1;
  209180. case kAsioResyncRequest:
  209181. if (currentASIODev[deviceIndex] != 0)
  209182. currentASIODev[deviceIndex]->resyncRequest();
  209183. return 1;
  209184. case kAsioLatenciesChanged:
  209185. return 1;
  209186. case kAsioEngineVersion:
  209187. return 2;
  209188. case kAsioSupportsTimeInfo:
  209189. case kAsioSupportsTimeCode:
  209190. return 0;
  209191. }
  209192. return 0;
  209193. }
  209194. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  209195. {
  209196. }
  209197. static void convertInt16ToFloat (const char* src,
  209198. float* dest,
  209199. const int srcStrideBytes,
  209200. int numSamples,
  209201. const bool littleEndian) throw()
  209202. {
  209203. const double g = 1.0 / 32768.0;
  209204. if (littleEndian)
  209205. {
  209206. while (--numSamples >= 0)
  209207. {
  209208. *dest++ = (float) (g * (short) littleEndianShort (src));
  209209. src += srcStrideBytes;
  209210. }
  209211. }
  209212. else
  209213. {
  209214. while (--numSamples >= 0)
  209215. {
  209216. *dest++ = (float) (g * (short) bigEndianShort (src));
  209217. src += srcStrideBytes;
  209218. }
  209219. }
  209220. }
  209221. static void convertFloatToInt16 (const float* src,
  209222. char* dest,
  209223. const int dstStrideBytes,
  209224. int numSamples,
  209225. const bool littleEndian) throw()
  209226. {
  209227. const double maxVal = (double) 0x7fff;
  209228. if (littleEndian)
  209229. {
  209230. while (--numSamples >= 0)
  209231. {
  209232. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209233. dest += dstStrideBytes;
  209234. }
  209235. }
  209236. else
  209237. {
  209238. while (--numSamples >= 0)
  209239. {
  209240. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209241. dest += dstStrideBytes;
  209242. }
  209243. }
  209244. }
  209245. static void convertInt24ToFloat (const char* src,
  209246. float* dest,
  209247. const int srcStrideBytes,
  209248. int numSamples,
  209249. const bool littleEndian) throw()
  209250. {
  209251. const double g = 1.0 / 0x7fffff;
  209252. if (littleEndian)
  209253. {
  209254. while (--numSamples >= 0)
  209255. {
  209256. *dest++ = (float) (g * littleEndian24Bit (src));
  209257. src += srcStrideBytes;
  209258. }
  209259. }
  209260. else
  209261. {
  209262. while (--numSamples >= 0)
  209263. {
  209264. *dest++ = (float) (g * bigEndian24Bit (src));
  209265. src += srcStrideBytes;
  209266. }
  209267. }
  209268. }
  209269. static void convertFloatToInt24 (const float* src,
  209270. char* dest,
  209271. const int dstStrideBytes,
  209272. int numSamples,
  209273. const bool littleEndian) throw()
  209274. {
  209275. const double maxVal = (double) 0x7fffff;
  209276. if (littleEndian)
  209277. {
  209278. while (--numSamples >= 0)
  209279. {
  209280. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209281. dest += dstStrideBytes;
  209282. }
  209283. }
  209284. else
  209285. {
  209286. while (--numSamples >= 0)
  209287. {
  209288. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209289. dest += dstStrideBytes;
  209290. }
  209291. }
  209292. }
  209293. static void convertInt32ToFloat (const char* src,
  209294. float* dest,
  209295. const int srcStrideBytes,
  209296. int numSamples,
  209297. const bool littleEndian) throw()
  209298. {
  209299. const double g = 1.0 / 0x7fffffff;
  209300. if (littleEndian)
  209301. {
  209302. while (--numSamples >= 0)
  209303. {
  209304. *dest++ = (float) (g * (int) littleEndianInt (src));
  209305. src += srcStrideBytes;
  209306. }
  209307. }
  209308. else
  209309. {
  209310. while (--numSamples >= 0)
  209311. {
  209312. *dest++ = (float) (g * (int) bigEndianInt (src));
  209313. src += srcStrideBytes;
  209314. }
  209315. }
  209316. }
  209317. static void convertFloatToInt32 (const float* src,
  209318. char* dest,
  209319. const int dstStrideBytes,
  209320. int numSamples,
  209321. const bool littleEndian) throw()
  209322. {
  209323. const double maxVal = (double) 0x7fffffff;
  209324. if (littleEndian)
  209325. {
  209326. while (--numSamples >= 0)
  209327. {
  209328. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209329. dest += dstStrideBytes;
  209330. }
  209331. }
  209332. else
  209333. {
  209334. while (--numSamples >= 0)
  209335. {
  209336. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209337. dest += dstStrideBytes;
  209338. }
  209339. }
  209340. }
  209341. static void typeToFormatParameters (const long type,
  209342. int& bitDepth,
  209343. int& byteStride,
  209344. bool& formatIsFloat,
  209345. bool& littleEndian) throw()
  209346. {
  209347. bitDepth = 0;
  209348. littleEndian = false;
  209349. formatIsFloat = false;
  209350. switch (type)
  209351. {
  209352. case ASIOSTInt16MSB:
  209353. case ASIOSTInt16LSB:
  209354. case ASIOSTInt32MSB16:
  209355. case ASIOSTInt32LSB16:
  209356. bitDepth = 16; break;
  209357. case ASIOSTFloat32MSB:
  209358. case ASIOSTFloat32LSB:
  209359. formatIsFloat = true;
  209360. bitDepth = 32; break;
  209361. case ASIOSTInt32MSB:
  209362. case ASIOSTInt32LSB:
  209363. bitDepth = 32; break;
  209364. case ASIOSTInt24MSB:
  209365. case ASIOSTInt24LSB:
  209366. case ASIOSTInt32MSB24:
  209367. case ASIOSTInt32LSB24:
  209368. case ASIOSTInt32MSB18:
  209369. case ASIOSTInt32MSB20:
  209370. case ASIOSTInt32LSB18:
  209371. case ASIOSTInt32LSB20:
  209372. bitDepth = 24; break;
  209373. case ASIOSTFloat64MSB:
  209374. case ASIOSTFloat64LSB:
  209375. default:
  209376. bitDepth = 64;
  209377. break;
  209378. }
  209379. switch (type)
  209380. {
  209381. case ASIOSTInt16MSB:
  209382. case ASIOSTInt32MSB16:
  209383. case ASIOSTFloat32MSB:
  209384. case ASIOSTFloat64MSB:
  209385. case ASIOSTInt32MSB:
  209386. case ASIOSTInt32MSB18:
  209387. case ASIOSTInt32MSB20:
  209388. case ASIOSTInt32MSB24:
  209389. case ASIOSTInt24MSB:
  209390. littleEndian = false; break;
  209391. case ASIOSTInt16LSB:
  209392. case ASIOSTInt32LSB16:
  209393. case ASIOSTFloat32LSB:
  209394. case ASIOSTFloat64LSB:
  209395. case ASIOSTInt32LSB:
  209396. case ASIOSTInt32LSB18:
  209397. case ASIOSTInt32LSB20:
  209398. case ASIOSTInt32LSB24:
  209399. case ASIOSTInt24LSB:
  209400. littleEndian = true; break;
  209401. default:
  209402. break;
  209403. }
  209404. switch (type)
  209405. {
  209406. case ASIOSTInt16LSB:
  209407. case ASIOSTInt16MSB:
  209408. byteStride = 2; break;
  209409. case ASIOSTInt24LSB:
  209410. case ASIOSTInt24MSB:
  209411. byteStride = 3; break;
  209412. case ASIOSTInt32MSB16:
  209413. case ASIOSTInt32LSB16:
  209414. case ASIOSTInt32MSB:
  209415. case ASIOSTInt32MSB18:
  209416. case ASIOSTInt32MSB20:
  209417. case ASIOSTInt32MSB24:
  209418. case ASIOSTInt32LSB:
  209419. case ASIOSTInt32LSB18:
  209420. case ASIOSTInt32LSB20:
  209421. case ASIOSTInt32LSB24:
  209422. case ASIOSTFloat32LSB:
  209423. case ASIOSTFloat32MSB:
  209424. byteStride = 4; break;
  209425. case ASIOSTFloat64MSB:
  209426. case ASIOSTFloat64LSB:
  209427. byteStride = 8; break;
  209428. default:
  209429. break;
  209430. }
  209431. }
  209432. };
  209433. class ASIOAudioIODeviceType : public AudioIODeviceType
  209434. {
  209435. public:
  209436. ASIOAudioIODeviceType()
  209437. : AudioIODeviceType (T("ASIO")),
  209438. classIds (2),
  209439. hasScanned (false)
  209440. {
  209441. CoInitialize (0);
  209442. }
  209443. ~ASIOAudioIODeviceType()
  209444. {
  209445. }
  209446. void scanForDevices()
  209447. {
  209448. hasScanned = true;
  209449. deviceNames.clear();
  209450. classIds.clear();
  209451. HKEY hk = 0;
  209452. int index = 0;
  209453. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  209454. {
  209455. for (;;)
  209456. {
  209457. char name [256];
  209458. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  209459. {
  209460. addDriverInfo (name, hk);
  209461. }
  209462. else
  209463. {
  209464. break;
  209465. }
  209466. }
  209467. RegCloseKey (hk);
  209468. }
  209469. }
  209470. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  209471. {
  209472. jassert (hasScanned); // need to call scanForDevices() before doing this
  209473. return deviceNames;
  209474. }
  209475. int getDefaultDeviceIndex (const bool) const
  209476. {
  209477. jassert (hasScanned); // need to call scanForDevices() before doing this
  209478. for (int i = deviceNames.size(); --i >= 0;)
  209479. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  209480. return i; // asio4all is a safe choice for a default..
  209481. #if JUCE_DEBUG
  209482. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  209483. return 1; // (the digi m-box driver crashes the app when you run
  209484. // it in the debugger, which can be a bit annoying)
  209485. #endif
  209486. return 0;
  209487. }
  209488. static int findFreeSlot()
  209489. {
  209490. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209491. if (currentASIODev[i] == 0)
  209492. return i;
  209493. jassertfalse; // unfortunately you can only have a finite number
  209494. // of ASIO devices open at the same time..
  209495. return -1;
  209496. }
  209497. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  209498. {
  209499. jassert (hasScanned); // need to call scanForDevices() before doing this
  209500. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  209501. }
  209502. bool hasSeparateInputsAndOutputs() const { return false; }
  209503. AudioIODevice* createDevice (const String& outputDeviceName,
  209504. const String& inputDeviceName)
  209505. {
  209506. // ASIO can't open two different devices for input and output - they must be the same one.
  209507. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  209508. jassert (hasScanned); // need to call scanForDevices() before doing this
  209509. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  209510. : inputDeviceName);
  209511. if (index >= 0)
  209512. {
  209513. const int freeSlot = findFreeSlot();
  209514. if (freeSlot >= 0)
  209515. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  209516. }
  209517. return 0;
  209518. }
  209519. juce_UseDebuggingNewOperator
  209520. private:
  209521. StringArray deviceNames;
  209522. OwnedArray <CLSID> classIds;
  209523. bool hasScanned;
  209524. static bool checkClassIsOk (const String& classId)
  209525. {
  209526. HKEY hk = 0;
  209527. bool ok = false;
  209528. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  209529. {
  209530. int index = 0;
  209531. for (;;)
  209532. {
  209533. char buf [512];
  209534. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  209535. {
  209536. if (classId.equalsIgnoreCase (buf))
  209537. {
  209538. HKEY subKey, pathKey;
  209539. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209540. {
  209541. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  209542. {
  209543. char pathName [600];
  209544. DWORD dtype = REG_SZ;
  209545. DWORD dsize = sizeof (pathName);
  209546. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  209547. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  209548. {
  209549. OFSTRUCT of;
  209550. zerostruct (of);
  209551. of.cBytes = sizeof (of);
  209552. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  209553. }
  209554. RegCloseKey (pathKey);
  209555. }
  209556. RegCloseKey (subKey);
  209557. }
  209558. break;
  209559. }
  209560. }
  209561. else
  209562. {
  209563. break;
  209564. }
  209565. }
  209566. RegCloseKey (hk);
  209567. }
  209568. return ok;
  209569. }
  209570. void addDriverInfo (const String& keyName, HKEY hk)
  209571. {
  209572. HKEY subKey;
  209573. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209574. {
  209575. char buf [256];
  209576. DWORD dtype = REG_SZ;
  209577. DWORD dsize = sizeof (buf);
  209578. zeromem (buf, dsize);
  209579. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209580. {
  209581. if (dsize > 0 && checkClassIsOk (buf))
  209582. {
  209583. wchar_t classIdStr [130];
  209584. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  209585. String deviceName;
  209586. CLSID classId;
  209587. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  209588. {
  209589. dtype = REG_SZ;
  209590. dsize = sizeof (buf);
  209591. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209592. deviceName = buf;
  209593. else
  209594. deviceName = keyName;
  209595. log (T("found ") + deviceName);
  209596. deviceNames.add (deviceName);
  209597. classIds.add (new CLSID (classId));
  209598. }
  209599. }
  209600. RegCloseKey (subKey);
  209601. }
  209602. }
  209603. }
  209604. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  209605. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  209606. };
  209607. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  209608. {
  209609. return new ASIOAudioIODeviceType();
  209610. }
  209611. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  209612. void* guid,
  209613. const String& optionalDllForDirectLoading)
  209614. {
  209615. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  209616. if (freeSlot < 0)
  209617. return 0;
  209618. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  209619. }
  209620. #undef log
  209621. #endif
  209622. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  209623. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  209624. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209625. // compiled on its own).
  209626. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  209627. END_JUCE_NAMESPACE
  209628. extern "C"
  209629. {
  209630. // Declare just the minimum number of interfaces for the DSound objects that we need..
  209631. typedef struct typeDSBUFFERDESC
  209632. {
  209633. DWORD dwSize;
  209634. DWORD dwFlags;
  209635. DWORD dwBufferBytes;
  209636. DWORD dwReserved;
  209637. LPWAVEFORMATEX lpwfxFormat;
  209638. GUID guid3DAlgorithm;
  209639. } DSBUFFERDESC;
  209640. struct IDirectSoundBuffer;
  209641. #undef INTERFACE
  209642. #define INTERFACE IDirectSound
  209643. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  209644. {
  209645. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209646. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209647. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209648. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  209649. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209650. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  209651. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  209652. STDMETHOD(Compact) (THIS) PURE;
  209653. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  209654. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  209655. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209656. };
  209657. #undef INTERFACE
  209658. #define INTERFACE IDirectSoundBuffer
  209659. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  209660. {
  209661. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209662. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209663. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209664. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209665. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209666. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209667. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  209668. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  209669. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  209670. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209671. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  209672. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209673. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  209674. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  209675. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  209676. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  209677. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  209678. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  209679. STDMETHOD(Stop) (THIS) PURE;
  209680. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209681. STDMETHOD(Restore) (THIS) PURE;
  209682. };
  209683. typedef struct typeDSCBUFFERDESC
  209684. {
  209685. DWORD dwSize;
  209686. DWORD dwFlags;
  209687. DWORD dwBufferBytes;
  209688. DWORD dwReserved;
  209689. LPWAVEFORMATEX lpwfxFormat;
  209690. } DSCBUFFERDESC;
  209691. struct IDirectSoundCaptureBuffer;
  209692. #undef INTERFACE
  209693. #define INTERFACE IDirectSoundCapture
  209694. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  209695. {
  209696. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209697. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209698. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209699. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  209700. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209701. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209702. };
  209703. #undef INTERFACE
  209704. #define INTERFACE IDirectSoundCaptureBuffer
  209705. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  209706. {
  209707. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209708. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209709. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209710. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209711. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209712. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209713. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209714. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  209715. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209716. STDMETHOD(Start) (THIS_ DWORD) PURE;
  209717. STDMETHOD(Stop) (THIS) PURE;
  209718. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209719. };
  209720. };
  209721. BEGIN_JUCE_NAMESPACE
  209722. static const String getDSErrorMessage (HRESULT hr)
  209723. {
  209724. const char* result = 0;
  209725. switch (hr)
  209726. {
  209727. case MAKE_HRESULT(1, 0x878, 10):
  209728. result = "Device already allocated";
  209729. break;
  209730. case MAKE_HRESULT(1, 0x878, 30):
  209731. result = "Control unavailable";
  209732. break;
  209733. case E_INVALIDARG:
  209734. result = "Invalid parameter";
  209735. break;
  209736. case MAKE_HRESULT(1, 0x878, 50):
  209737. result = "Invalid call";
  209738. break;
  209739. case E_FAIL:
  209740. result = "Generic error";
  209741. break;
  209742. case MAKE_HRESULT(1, 0x878, 70):
  209743. result = "Priority level error";
  209744. break;
  209745. case E_OUTOFMEMORY:
  209746. result = "Out of memory";
  209747. break;
  209748. case MAKE_HRESULT(1, 0x878, 100):
  209749. result = "Bad format";
  209750. break;
  209751. case E_NOTIMPL:
  209752. result = "Unsupported function";
  209753. break;
  209754. case MAKE_HRESULT(1, 0x878, 120):
  209755. result = "No driver";
  209756. break;
  209757. case MAKE_HRESULT(1, 0x878, 130):
  209758. result = "Already initialised";
  209759. break;
  209760. case CLASS_E_NOAGGREGATION:
  209761. result = "No aggregation";
  209762. break;
  209763. case MAKE_HRESULT(1, 0x878, 150):
  209764. result = "Buffer lost";
  209765. break;
  209766. case MAKE_HRESULT(1, 0x878, 160):
  209767. result = "Another app has priority";
  209768. break;
  209769. case MAKE_HRESULT(1, 0x878, 170):
  209770. result = "Uninitialised";
  209771. break;
  209772. case E_NOINTERFACE:
  209773. result = "No interface";
  209774. break;
  209775. case S_OK:
  209776. result = "No error";
  209777. break;
  209778. default:
  209779. return "Unknown error: " + String ((int) hr);
  209780. }
  209781. return result;
  209782. }
  209783. #define DS_DEBUGGING 1
  209784. #ifdef DS_DEBUGGING
  209785. #define CATCH JUCE_CATCH_EXCEPTION
  209786. #undef log
  209787. #define log(a) Logger::writeToLog(a);
  209788. #undef logError
  209789. #define logError(a) logDSError(a, __LINE__);
  209790. static void logDSError (HRESULT hr, int lineNum)
  209791. {
  209792. if (hr != S_OK)
  209793. {
  209794. String error ("DS error at line ");
  209795. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  209796. log (error);
  209797. }
  209798. }
  209799. #else
  209800. #define CATCH JUCE_CATCH_ALL
  209801. #define log(a)
  209802. #define logError(a)
  209803. #endif
  209804. #define DSOUND_FUNCTION(functionName, params) \
  209805. typedef HRESULT (WINAPI *type##functionName) params; \
  209806. static type##functionName ds##functionName = 0;
  209807. #define DSOUND_FUNCTION_LOAD(functionName) \
  209808. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  209809. jassert (ds##functionName != 0);
  209810. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  209811. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  209812. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  209813. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  209814. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209815. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209816. static void initialiseDSoundFunctions()
  209817. {
  209818. if (dsDirectSoundCreate == 0)
  209819. {
  209820. HMODULE h = LoadLibraryA ("dsound.dll");
  209821. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  209822. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  209823. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  209824. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  209825. }
  209826. }
  209827. class DSoundInternalOutChannel
  209828. {
  209829. String name;
  209830. LPGUID guid;
  209831. int sampleRate, bufferSizeSamples;
  209832. float* leftBuffer;
  209833. float* rightBuffer;
  209834. IDirectSound* pDirectSound;
  209835. IDirectSoundBuffer* pOutputBuffer;
  209836. DWORD writeOffset;
  209837. int totalBytesPerBuffer;
  209838. int bytesPerBuffer;
  209839. unsigned int lastPlayCursor;
  209840. public:
  209841. int bitDepth;
  209842. bool doneFlag;
  209843. DSoundInternalOutChannel (const String& name_,
  209844. LPGUID guid_,
  209845. int rate,
  209846. int bufferSize,
  209847. float* left,
  209848. float* right)
  209849. : name (name_),
  209850. guid (guid_),
  209851. sampleRate (rate),
  209852. bufferSizeSamples (bufferSize),
  209853. leftBuffer (left),
  209854. rightBuffer (right),
  209855. pDirectSound (0),
  209856. pOutputBuffer (0),
  209857. bitDepth (16)
  209858. {
  209859. }
  209860. ~DSoundInternalOutChannel()
  209861. {
  209862. close();
  209863. }
  209864. void close()
  209865. {
  209866. HRESULT hr;
  209867. if (pOutputBuffer != 0)
  209868. {
  209869. JUCE_TRY
  209870. {
  209871. log (T("closing dsound out: ") + name);
  209872. hr = pOutputBuffer->Stop();
  209873. logError (hr);
  209874. }
  209875. CATCH
  209876. JUCE_TRY
  209877. {
  209878. hr = pOutputBuffer->Release();
  209879. logError (hr);
  209880. }
  209881. CATCH
  209882. pOutputBuffer = 0;
  209883. }
  209884. if (pDirectSound != 0)
  209885. {
  209886. JUCE_TRY
  209887. {
  209888. hr = pDirectSound->Release();
  209889. logError (hr);
  209890. }
  209891. CATCH
  209892. pDirectSound = 0;
  209893. }
  209894. }
  209895. const String open()
  209896. {
  209897. log (T("opening dsound out device: ") + name
  209898. + T(" rate=") + String (sampleRate)
  209899. + T(" bits=") + String (bitDepth)
  209900. + T(" buf=") + String (bufferSizeSamples));
  209901. pDirectSound = 0;
  209902. pOutputBuffer = 0;
  209903. writeOffset = 0;
  209904. String error;
  209905. HRESULT hr = E_NOINTERFACE;
  209906. if (dsDirectSoundCreate != 0)
  209907. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  209908. if (hr == S_OK)
  209909. {
  209910. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209911. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209912. const int numChannels = 2;
  209913. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  209914. logError (hr);
  209915. if (hr == S_OK)
  209916. {
  209917. IDirectSoundBuffer* pPrimaryBuffer;
  209918. DSBUFFERDESC primaryDesc;
  209919. zerostruct (primaryDesc);
  209920. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209921. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  209922. primaryDesc.dwBufferBytes = 0;
  209923. primaryDesc.lpwfxFormat = 0;
  209924. log ("opening dsound out step 2");
  209925. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  209926. logError (hr);
  209927. if (hr == S_OK)
  209928. {
  209929. WAVEFORMATEX wfFormat;
  209930. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209931. wfFormat.nChannels = (unsigned short) numChannels;
  209932. wfFormat.nSamplesPerSec = sampleRate;
  209933. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  209934. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  209935. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209936. wfFormat.cbSize = 0;
  209937. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  209938. logError (hr);
  209939. if (hr == S_OK)
  209940. {
  209941. DSBUFFERDESC secondaryDesc;
  209942. zerostruct (secondaryDesc);
  209943. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209944. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  209945. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  209946. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  209947. secondaryDesc.lpwfxFormat = &wfFormat;
  209948. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  209949. logError (hr);
  209950. if (hr == S_OK)
  209951. {
  209952. log ("opening dsound out step 3");
  209953. DWORD dwDataLen;
  209954. unsigned char* pDSBuffData;
  209955. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  209956. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  209957. logError (hr);
  209958. if (hr == S_OK)
  209959. {
  209960. zeromem (pDSBuffData, dwDataLen);
  209961. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  209962. if (hr == S_OK)
  209963. {
  209964. hr = pOutputBuffer->SetCurrentPosition (0);
  209965. if (hr == S_OK)
  209966. {
  209967. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  209968. if (hr == S_OK)
  209969. return String::empty;
  209970. }
  209971. }
  209972. }
  209973. }
  209974. }
  209975. }
  209976. }
  209977. }
  209978. error = getDSErrorMessage (hr);
  209979. close();
  209980. return error;
  209981. }
  209982. void synchronisePosition()
  209983. {
  209984. if (pOutputBuffer != 0)
  209985. {
  209986. DWORD playCursor;
  209987. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  209988. }
  209989. }
  209990. bool service()
  209991. {
  209992. if (pOutputBuffer == 0)
  209993. return true;
  209994. DWORD playCursor, writeCursor;
  209995. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  209996. if (hr != S_OK)
  209997. {
  209998. logError (hr);
  209999. jassertfalse
  210000. return true;
  210001. }
  210002. int playWriteGap = writeCursor - playCursor;
  210003. if (playWriteGap < 0)
  210004. playWriteGap += totalBytesPerBuffer;
  210005. int bytesEmpty = playCursor - writeOffset;
  210006. if (bytesEmpty < 0)
  210007. bytesEmpty += totalBytesPerBuffer;
  210008. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  210009. {
  210010. writeOffset = writeCursor;
  210011. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  210012. }
  210013. if (bytesEmpty >= bytesPerBuffer)
  210014. {
  210015. LPBYTE lpbuf1 = 0;
  210016. LPBYTE lpbuf2 = 0;
  210017. DWORD dwSize1 = 0;
  210018. DWORD dwSize2 = 0;
  210019. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  210020. bytesPerBuffer,
  210021. (void**) &lpbuf1, &dwSize1,
  210022. (void**) &lpbuf2, &dwSize2, 0);
  210023. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  210024. {
  210025. pOutputBuffer->Restore();
  210026. hr = pOutputBuffer->Lock (writeOffset,
  210027. bytesPerBuffer,
  210028. (void**) &lpbuf1, &dwSize1,
  210029. (void**) &lpbuf2, &dwSize2, 0);
  210030. }
  210031. if (hr == S_OK)
  210032. {
  210033. if (bitDepth == 16)
  210034. {
  210035. const float gainL = 32767.0f;
  210036. const float gainR = 32767.0f;
  210037. int* dest = (int*)lpbuf1;
  210038. const float* left = leftBuffer;
  210039. const float* right = rightBuffer;
  210040. int samples1 = dwSize1 >> 2;
  210041. int samples2 = dwSize2 >> 2;
  210042. if (left == 0)
  210043. {
  210044. while (--samples1 >= 0)
  210045. {
  210046. int r = roundFloatToInt (gainR * *right++);
  210047. if (r < -32768)
  210048. r = -32768;
  210049. else if (r > 32767)
  210050. r = 32767;
  210051. *dest++ = (r << 16);
  210052. }
  210053. dest = (int*)lpbuf2;
  210054. while (--samples2 >= 0)
  210055. {
  210056. int r = roundFloatToInt (gainR * *right++);
  210057. if (r < -32768)
  210058. r = -32768;
  210059. else if (r > 32767)
  210060. r = 32767;
  210061. *dest++ = (r << 16);
  210062. }
  210063. }
  210064. else if (right == 0)
  210065. {
  210066. while (--samples1 >= 0)
  210067. {
  210068. int l = roundFloatToInt (gainL * *left++);
  210069. if (l < -32768)
  210070. l = -32768;
  210071. else if (l > 32767)
  210072. l = 32767;
  210073. l &= 0xffff;
  210074. *dest++ = l;
  210075. }
  210076. dest = (int*)lpbuf2;
  210077. while (--samples2 >= 0)
  210078. {
  210079. int l = roundFloatToInt (gainL * *left++);
  210080. if (l < -32768)
  210081. l = -32768;
  210082. else if (l > 32767)
  210083. l = 32767;
  210084. l &= 0xffff;
  210085. *dest++ = l;
  210086. }
  210087. }
  210088. else
  210089. {
  210090. while (--samples1 >= 0)
  210091. {
  210092. int l = roundFloatToInt (gainL * *left++);
  210093. if (l < -32768)
  210094. l = -32768;
  210095. else if (l > 32767)
  210096. l = 32767;
  210097. l &= 0xffff;
  210098. int r = roundFloatToInt (gainR * *right++);
  210099. if (r < -32768)
  210100. r = -32768;
  210101. else if (r > 32767)
  210102. r = 32767;
  210103. *dest++ = (r << 16) | l;
  210104. }
  210105. dest = (int*)lpbuf2;
  210106. while (--samples2 >= 0)
  210107. {
  210108. int l = roundFloatToInt (gainL * *left++);
  210109. if (l < -32768)
  210110. l = -32768;
  210111. else if (l > 32767)
  210112. l = 32767;
  210113. l &= 0xffff;
  210114. int r = roundFloatToInt (gainR * *right++);
  210115. if (r < -32768)
  210116. r = -32768;
  210117. else if (r > 32767)
  210118. r = 32767;
  210119. *dest++ = (r << 16) | l;
  210120. }
  210121. }
  210122. }
  210123. else
  210124. {
  210125. jassertfalse
  210126. }
  210127. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  210128. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  210129. }
  210130. else
  210131. {
  210132. jassertfalse
  210133. logError (hr);
  210134. }
  210135. bytesEmpty -= bytesPerBuffer;
  210136. return true;
  210137. }
  210138. else
  210139. {
  210140. return false;
  210141. }
  210142. }
  210143. };
  210144. struct DSoundInternalInChannel
  210145. {
  210146. String name;
  210147. LPGUID guid;
  210148. int sampleRate, bufferSizeSamples;
  210149. float* leftBuffer;
  210150. float* rightBuffer;
  210151. IDirectSound* pDirectSound;
  210152. IDirectSoundCapture* pDirectSoundCapture;
  210153. IDirectSoundCaptureBuffer* pInputBuffer;
  210154. public:
  210155. unsigned int readOffset;
  210156. int bytesPerBuffer, totalBytesPerBuffer;
  210157. int bitDepth;
  210158. bool doneFlag;
  210159. DSoundInternalInChannel (const String& name_,
  210160. LPGUID guid_,
  210161. int rate,
  210162. int bufferSize,
  210163. float* left,
  210164. float* right)
  210165. : name (name_),
  210166. guid (guid_),
  210167. sampleRate (rate),
  210168. bufferSizeSamples (bufferSize),
  210169. leftBuffer (left),
  210170. rightBuffer (right),
  210171. pDirectSound (0),
  210172. pDirectSoundCapture (0),
  210173. pInputBuffer (0),
  210174. bitDepth (16)
  210175. {
  210176. }
  210177. ~DSoundInternalInChannel()
  210178. {
  210179. close();
  210180. }
  210181. void close()
  210182. {
  210183. HRESULT hr;
  210184. if (pInputBuffer != 0)
  210185. {
  210186. JUCE_TRY
  210187. {
  210188. log (T("closing dsound in: ") + name);
  210189. hr = pInputBuffer->Stop();
  210190. logError (hr);
  210191. }
  210192. CATCH
  210193. JUCE_TRY
  210194. {
  210195. hr = pInputBuffer->Release();
  210196. logError (hr);
  210197. }
  210198. CATCH
  210199. pInputBuffer = 0;
  210200. }
  210201. if (pDirectSoundCapture != 0)
  210202. {
  210203. JUCE_TRY
  210204. {
  210205. hr = pDirectSoundCapture->Release();
  210206. logError (hr);
  210207. }
  210208. CATCH
  210209. pDirectSoundCapture = 0;
  210210. }
  210211. if (pDirectSound != 0)
  210212. {
  210213. JUCE_TRY
  210214. {
  210215. hr = pDirectSound->Release();
  210216. logError (hr);
  210217. }
  210218. CATCH
  210219. pDirectSound = 0;
  210220. }
  210221. }
  210222. const String open()
  210223. {
  210224. log (T("opening dsound in device: ") + name
  210225. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  210226. pDirectSound = 0;
  210227. pDirectSoundCapture = 0;
  210228. pInputBuffer = 0;
  210229. readOffset = 0;
  210230. totalBytesPerBuffer = 0;
  210231. String error;
  210232. HRESULT hr = E_NOINTERFACE;
  210233. if (dsDirectSoundCaptureCreate != 0)
  210234. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  210235. logError (hr);
  210236. if (hr == S_OK)
  210237. {
  210238. const int numChannels = 2;
  210239. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210240. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210241. WAVEFORMATEX wfFormat;
  210242. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210243. wfFormat.nChannels = (unsigned short)numChannels;
  210244. wfFormat.nSamplesPerSec = sampleRate;
  210245. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  210246. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  210247. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210248. wfFormat.cbSize = 0;
  210249. DSCBUFFERDESC captureDesc;
  210250. zerostruct (captureDesc);
  210251. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  210252. captureDesc.dwFlags = 0;
  210253. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  210254. captureDesc.lpwfxFormat = &wfFormat;
  210255. log (T("opening dsound in step 2"));
  210256. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  210257. logError (hr);
  210258. if (hr == S_OK)
  210259. {
  210260. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  210261. logError (hr);
  210262. if (hr == S_OK)
  210263. return String::empty;
  210264. }
  210265. }
  210266. error = getDSErrorMessage (hr);
  210267. close();
  210268. return error;
  210269. }
  210270. void synchronisePosition()
  210271. {
  210272. if (pInputBuffer != 0)
  210273. {
  210274. DWORD capturePos;
  210275. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  210276. }
  210277. }
  210278. bool service()
  210279. {
  210280. if (pInputBuffer == 0)
  210281. return true;
  210282. DWORD capturePos, readPos;
  210283. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  210284. logError (hr);
  210285. if (hr != S_OK)
  210286. return true;
  210287. int bytesFilled = readPos - readOffset;
  210288. if (bytesFilled < 0)
  210289. bytesFilled += totalBytesPerBuffer;
  210290. if (bytesFilled >= bytesPerBuffer)
  210291. {
  210292. LPBYTE lpbuf1 = 0;
  210293. LPBYTE lpbuf2 = 0;
  210294. DWORD dwsize1 = 0;
  210295. DWORD dwsize2 = 0;
  210296. HRESULT hr = pInputBuffer->Lock (readOffset,
  210297. bytesPerBuffer,
  210298. (void**) &lpbuf1, &dwsize1,
  210299. (void**) &lpbuf2, &dwsize2, 0);
  210300. if (hr == S_OK)
  210301. {
  210302. if (bitDepth == 16)
  210303. {
  210304. const float g = 1.0f / 32768.0f;
  210305. float* destL = leftBuffer;
  210306. float* destR = rightBuffer;
  210307. int samples1 = dwsize1 >> 2;
  210308. int samples2 = dwsize2 >> 2;
  210309. const short* src = (const short*)lpbuf1;
  210310. if (destL == 0)
  210311. {
  210312. while (--samples1 >= 0)
  210313. {
  210314. ++src;
  210315. *destR++ = *src++ * g;
  210316. }
  210317. src = (const short*)lpbuf2;
  210318. while (--samples2 >= 0)
  210319. {
  210320. ++src;
  210321. *destR++ = *src++ * g;
  210322. }
  210323. }
  210324. else if (destR == 0)
  210325. {
  210326. while (--samples1 >= 0)
  210327. {
  210328. *destL++ = *src++ * g;
  210329. ++src;
  210330. }
  210331. src = (const short*)lpbuf2;
  210332. while (--samples2 >= 0)
  210333. {
  210334. *destL++ = *src++ * g;
  210335. ++src;
  210336. }
  210337. }
  210338. else
  210339. {
  210340. while (--samples1 >= 0)
  210341. {
  210342. *destL++ = *src++ * g;
  210343. *destR++ = *src++ * g;
  210344. }
  210345. src = (const short*)lpbuf2;
  210346. while (--samples2 >= 0)
  210347. {
  210348. *destL++ = *src++ * g;
  210349. *destR++ = *src++ * g;
  210350. }
  210351. }
  210352. }
  210353. else
  210354. {
  210355. jassertfalse
  210356. }
  210357. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  210358. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  210359. }
  210360. else
  210361. {
  210362. logError (hr);
  210363. jassertfalse
  210364. }
  210365. bytesFilled -= bytesPerBuffer;
  210366. return true;
  210367. }
  210368. else
  210369. {
  210370. return false;
  210371. }
  210372. }
  210373. };
  210374. class DSoundAudioIODevice : public AudioIODevice,
  210375. public Thread
  210376. {
  210377. public:
  210378. DSoundAudioIODevice (const String& deviceName,
  210379. const int outputDeviceIndex_,
  210380. const int inputDeviceIndex_)
  210381. : AudioIODevice (deviceName, "DirectSound"),
  210382. Thread ("Juce DSound"),
  210383. isOpen_ (false),
  210384. isStarted (false),
  210385. outputDeviceIndex (outputDeviceIndex_),
  210386. inputDeviceIndex (inputDeviceIndex_),
  210387. inChans (4),
  210388. outChans (4),
  210389. numInputBuffers (0),
  210390. numOutputBuffers (0),
  210391. totalSamplesOut (0),
  210392. sampleRate (0.0),
  210393. inputBuffers (0),
  210394. outputBuffers (0),
  210395. callback (0),
  210396. bufferSizeSamples (0)
  210397. {
  210398. if (outputDeviceIndex_ >= 0)
  210399. {
  210400. outChannels.add (TRANS("Left"));
  210401. outChannels.add (TRANS("Right"));
  210402. }
  210403. if (inputDeviceIndex_ >= 0)
  210404. {
  210405. inChannels.add (TRANS("Left"));
  210406. inChannels.add (TRANS("Right"));
  210407. }
  210408. }
  210409. ~DSoundAudioIODevice()
  210410. {
  210411. close();
  210412. }
  210413. const StringArray getOutputChannelNames()
  210414. {
  210415. return outChannels;
  210416. }
  210417. const StringArray getInputChannelNames()
  210418. {
  210419. return inChannels;
  210420. }
  210421. int getNumSampleRates()
  210422. {
  210423. return 4;
  210424. }
  210425. double getSampleRate (int index)
  210426. {
  210427. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210428. return samps [jlimit (0, 3, index)];
  210429. }
  210430. int getNumBufferSizesAvailable()
  210431. {
  210432. return 50;
  210433. }
  210434. int getBufferSizeSamples (int index)
  210435. {
  210436. int n = 64;
  210437. for (int i = 0; i < index; ++i)
  210438. n += (n < 512) ? 32
  210439. : ((n < 1024) ? 64
  210440. : ((n < 2048) ? 128 : 256));
  210441. return n;
  210442. }
  210443. int getDefaultBufferSize()
  210444. {
  210445. return 2560;
  210446. }
  210447. const String open (const BitArray& inputChannels,
  210448. const BitArray& outputChannels,
  210449. double sampleRate,
  210450. int bufferSizeSamples)
  210451. {
  210452. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  210453. isOpen_ = lastError.isEmpty();
  210454. return lastError;
  210455. }
  210456. void close()
  210457. {
  210458. stop();
  210459. if (isOpen_)
  210460. {
  210461. closeDevice();
  210462. isOpen_ = false;
  210463. }
  210464. }
  210465. bool isOpen()
  210466. {
  210467. return isOpen_ && isThreadRunning();
  210468. }
  210469. int getCurrentBufferSizeSamples()
  210470. {
  210471. return bufferSizeSamples;
  210472. }
  210473. double getCurrentSampleRate()
  210474. {
  210475. return sampleRate;
  210476. }
  210477. int getCurrentBitDepth()
  210478. {
  210479. int i, bits = 256;
  210480. for (i = inChans.size(); --i >= 0;)
  210481. bits = jmin (bits, inChans[i]->bitDepth);
  210482. for (i = outChans.size(); --i >= 0;)
  210483. bits = jmin (bits, outChans[i]->bitDepth);
  210484. if (bits > 32)
  210485. bits = 16;
  210486. return bits;
  210487. }
  210488. const BitArray getActiveOutputChannels() const
  210489. {
  210490. return enabledOutputs;
  210491. }
  210492. const BitArray getActiveInputChannels() const
  210493. {
  210494. return enabledInputs;
  210495. }
  210496. int getOutputLatencyInSamples()
  210497. {
  210498. return (int) (getCurrentBufferSizeSamples() * 1.5);
  210499. }
  210500. int getInputLatencyInSamples()
  210501. {
  210502. return getOutputLatencyInSamples();
  210503. }
  210504. void start (AudioIODeviceCallback* call)
  210505. {
  210506. if (isOpen_ && call != 0 && ! isStarted)
  210507. {
  210508. if (! isThreadRunning())
  210509. {
  210510. // something gone wrong and the thread's stopped..
  210511. isOpen_ = false;
  210512. return;
  210513. }
  210514. call->audioDeviceAboutToStart (this);
  210515. const ScopedLock sl (startStopLock);
  210516. callback = call;
  210517. isStarted = true;
  210518. }
  210519. }
  210520. void stop()
  210521. {
  210522. if (isStarted)
  210523. {
  210524. AudioIODeviceCallback* const callbackLocal = callback;
  210525. {
  210526. const ScopedLock sl (startStopLock);
  210527. isStarted = false;
  210528. }
  210529. if (callbackLocal != 0)
  210530. callbackLocal->audioDeviceStopped();
  210531. }
  210532. }
  210533. bool isPlaying()
  210534. {
  210535. return isStarted && isOpen_ && isThreadRunning();
  210536. }
  210537. const String getLastError()
  210538. {
  210539. return lastError;
  210540. }
  210541. juce_UseDebuggingNewOperator
  210542. StringArray inChannels, outChannels;
  210543. int outputDeviceIndex, inputDeviceIndex;
  210544. private:
  210545. bool isOpen_;
  210546. bool isStarted;
  210547. String lastError;
  210548. OwnedArray <DSoundInternalInChannel> inChans;
  210549. OwnedArray <DSoundInternalOutChannel> outChans;
  210550. WaitableEvent startEvent;
  210551. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  210552. int volatile totalSamplesOut;
  210553. int64 volatile lastBlockTime;
  210554. double sampleRate;
  210555. BitArray enabledInputs, enabledOutputs;
  210556. float** inputBuffers;
  210557. float** outputBuffers;
  210558. AudioIODeviceCallback* callback;
  210559. CriticalSection startStopLock;
  210560. DSoundAudioIODevice (const DSoundAudioIODevice&);
  210561. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  210562. const String openDevice (const BitArray& inputChannels,
  210563. const BitArray& outputChannels,
  210564. double sampleRate_,
  210565. int bufferSizeSamples_);
  210566. void closeDevice()
  210567. {
  210568. isStarted = false;
  210569. stopThread (5000);
  210570. inChans.clear();
  210571. outChans.clear();
  210572. int i;
  210573. for (i = 0; i < numInputBuffers; ++i)
  210574. juce_free (inputBuffers[i]);
  210575. delete[] inputBuffers;
  210576. inputBuffers = 0;
  210577. numInputBuffers = 0;
  210578. for (i = 0; i < numOutputBuffers; ++i)
  210579. juce_free (outputBuffers[i]);
  210580. delete[] outputBuffers;
  210581. outputBuffers = 0;
  210582. numOutputBuffers = 0;
  210583. }
  210584. void resync()
  210585. {
  210586. if (! threadShouldExit())
  210587. {
  210588. sleep (5);
  210589. int i;
  210590. for (i = 0; i < outChans.size(); ++i)
  210591. outChans.getUnchecked(i)->synchronisePosition();
  210592. for (i = 0; i < inChans.size(); ++i)
  210593. inChans.getUnchecked(i)->synchronisePosition();
  210594. }
  210595. }
  210596. public:
  210597. void run()
  210598. {
  210599. while (! threadShouldExit())
  210600. {
  210601. if (wait (100))
  210602. break;
  210603. }
  210604. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  210605. const int maxTimeMS = jmax (5, 3 * latencyMs);
  210606. while (! threadShouldExit())
  210607. {
  210608. int numToDo = 0;
  210609. uint32 startTime = Time::getMillisecondCounter();
  210610. int i;
  210611. for (i = inChans.size(); --i >= 0;)
  210612. {
  210613. inChans.getUnchecked(i)->doneFlag = false;
  210614. ++numToDo;
  210615. }
  210616. for (i = outChans.size(); --i >= 0;)
  210617. {
  210618. outChans.getUnchecked(i)->doneFlag = false;
  210619. ++numToDo;
  210620. }
  210621. if (numToDo > 0)
  210622. {
  210623. const int maxCount = 3;
  210624. int count = maxCount;
  210625. for (;;)
  210626. {
  210627. for (i = inChans.size(); --i >= 0;)
  210628. {
  210629. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  210630. if ((! in->doneFlag) && in->service())
  210631. {
  210632. in->doneFlag = true;
  210633. --numToDo;
  210634. }
  210635. }
  210636. for (i = outChans.size(); --i >= 0;)
  210637. {
  210638. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  210639. if ((! out->doneFlag) && out->service())
  210640. {
  210641. out->doneFlag = true;
  210642. --numToDo;
  210643. }
  210644. }
  210645. if (numToDo <= 0)
  210646. break;
  210647. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  210648. {
  210649. resync();
  210650. break;
  210651. }
  210652. if (--count <= 0)
  210653. {
  210654. Sleep (1);
  210655. count = maxCount;
  210656. }
  210657. if (threadShouldExit())
  210658. return;
  210659. }
  210660. }
  210661. else
  210662. {
  210663. sleep (1);
  210664. }
  210665. const ScopedLock sl (startStopLock);
  210666. if (isStarted)
  210667. {
  210668. JUCE_TRY
  210669. {
  210670. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  210671. numInputBuffers,
  210672. outputBuffers,
  210673. numOutputBuffers,
  210674. bufferSizeSamples);
  210675. }
  210676. JUCE_CATCH_EXCEPTION
  210677. totalSamplesOut += bufferSizeSamples;
  210678. }
  210679. else
  210680. {
  210681. for (i = 0; i < numOutputBuffers; ++i)
  210682. if (outputBuffers[i] != 0)
  210683. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  210684. totalSamplesOut = 0;
  210685. sleep (1);
  210686. }
  210687. }
  210688. }
  210689. };
  210690. class DSoundAudioIODeviceType : public AudioIODeviceType
  210691. {
  210692. public:
  210693. DSoundAudioIODeviceType()
  210694. : AudioIODeviceType (T("DirectSound")),
  210695. hasScanned (false)
  210696. {
  210697. initialiseDSoundFunctions();
  210698. }
  210699. ~DSoundAudioIODeviceType()
  210700. {
  210701. }
  210702. void scanForDevices()
  210703. {
  210704. hasScanned = true;
  210705. outputDeviceNames.clear();
  210706. outputGuids.clear();
  210707. inputDeviceNames.clear();
  210708. inputGuids.clear();
  210709. if (dsDirectSoundEnumerateW != 0)
  210710. {
  210711. dsDirectSoundEnumerateW (outputEnumProcW, this);
  210712. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  210713. }
  210714. }
  210715. const StringArray getDeviceNames (const bool wantInputNames) const
  210716. {
  210717. jassert (hasScanned); // need to call scanForDevices() before doing this
  210718. return wantInputNames ? inputDeviceNames
  210719. : outputDeviceNames;
  210720. }
  210721. int getDefaultDeviceIndex (const bool /*forInput*/) const
  210722. {
  210723. jassert (hasScanned); // need to call scanForDevices() before doing this
  210724. return 0;
  210725. }
  210726. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  210727. {
  210728. jassert (hasScanned); // need to call scanForDevices() before doing this
  210729. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  210730. if (d == 0)
  210731. return -1;
  210732. return asInput ? d->inputDeviceIndex
  210733. : d->outputDeviceIndex;
  210734. }
  210735. bool hasSeparateInputsAndOutputs() const { return true; }
  210736. AudioIODevice* createDevice (const String& outputDeviceName,
  210737. const String& inputDeviceName)
  210738. {
  210739. jassert (hasScanned); // need to call scanForDevices() before doing this
  210740. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  210741. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  210742. if (outputIndex >= 0 || inputIndex >= 0)
  210743. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  210744. : inputDeviceName,
  210745. outputIndex, inputIndex);
  210746. return 0;
  210747. }
  210748. juce_UseDebuggingNewOperator
  210749. StringArray outputDeviceNames;
  210750. OwnedArray <GUID> outputGuids;
  210751. StringArray inputDeviceNames;
  210752. OwnedArray <GUID> inputGuids;
  210753. private:
  210754. bool hasScanned;
  210755. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  210756. {
  210757. desc = desc.trim();
  210758. if (desc.isNotEmpty())
  210759. {
  210760. const String origDesc (desc);
  210761. int n = 2;
  210762. while (outputDeviceNames.contains (desc))
  210763. desc = origDesc + T(" (") + String (n++) + T(")");
  210764. outputDeviceNames.add (desc);
  210765. if (lpGUID != 0)
  210766. outputGuids.add (new GUID (*lpGUID));
  210767. else
  210768. outputGuids.add (0);
  210769. }
  210770. return TRUE;
  210771. }
  210772. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210773. {
  210774. return ((DSoundAudioIODeviceType*) object)
  210775. ->outputEnumProc (lpGUID, String (description));
  210776. }
  210777. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210778. {
  210779. return ((DSoundAudioIODeviceType*) object)
  210780. ->outputEnumProc (lpGUID, String (description));
  210781. }
  210782. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  210783. {
  210784. desc = desc.trim();
  210785. if (desc.isNotEmpty())
  210786. {
  210787. const String origDesc (desc);
  210788. int n = 2;
  210789. while (inputDeviceNames.contains (desc))
  210790. desc = origDesc + T(" (") + String (n++) + T(")");
  210791. inputDeviceNames.add (desc);
  210792. if (lpGUID != 0)
  210793. inputGuids.add (new GUID (*lpGUID));
  210794. else
  210795. inputGuids.add (0);
  210796. }
  210797. return TRUE;
  210798. }
  210799. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210800. {
  210801. return ((DSoundAudioIODeviceType*) object)
  210802. ->inputEnumProc (lpGUID, String (description));
  210803. }
  210804. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210805. {
  210806. return ((DSoundAudioIODeviceType*) object)
  210807. ->inputEnumProc (lpGUID, String (description));
  210808. }
  210809. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  210810. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  210811. };
  210812. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  210813. const BitArray& outputChannels,
  210814. double sampleRate_,
  210815. int bufferSizeSamples_)
  210816. {
  210817. closeDevice();
  210818. totalSamplesOut = 0;
  210819. sampleRate = sampleRate_;
  210820. if (bufferSizeSamples_ <= 0)
  210821. bufferSizeSamples_ = 960; // use as a default size if none is set.
  210822. bufferSizeSamples = bufferSizeSamples_ & ~7;
  210823. DSoundAudioIODeviceType dlh;
  210824. dlh.scanForDevices();
  210825. enabledInputs = inputChannels;
  210826. enabledInputs.setRange (inChannels.size(),
  210827. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  210828. false);
  210829. numInputBuffers = enabledInputs.countNumberOfSetBits();
  210830. inputBuffers = new float* [numInputBuffers + 2];
  210831. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  210832. int i, numIns = 0;
  210833. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  210834. {
  210835. float* left = 0;
  210836. float* right = 0;
  210837. if (enabledInputs[i])
  210838. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210839. if (enabledInputs[i + 1])
  210840. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210841. if (left != 0 || right != 0)
  210842. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  210843. dlh.inputGuids [inputDeviceIndex],
  210844. (int) sampleRate, bufferSizeSamples,
  210845. left, right));
  210846. }
  210847. enabledOutputs = outputChannels;
  210848. enabledOutputs.setRange (outChannels.size(),
  210849. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  210850. false);
  210851. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  210852. outputBuffers = new float* [numOutputBuffers + 2];
  210853. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  210854. int numOuts = 0;
  210855. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  210856. {
  210857. float* left = 0;
  210858. float* right = 0;
  210859. if (enabledOutputs[i])
  210860. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210861. if (enabledOutputs[i + 1])
  210862. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210863. if (left != 0 || right != 0)
  210864. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  210865. dlh.outputGuids [outputDeviceIndex],
  210866. (int) sampleRate, bufferSizeSamples,
  210867. left, right));
  210868. }
  210869. String error;
  210870. // boost our priority while opening the devices to try to get better sync between them
  210871. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  210872. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  210873. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  210874. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  210875. for (i = 0; i < outChans.size(); ++i)
  210876. {
  210877. error = outChans[i]->open();
  210878. if (error.isNotEmpty())
  210879. {
  210880. error = T("Error opening ") + dlh.outputDeviceNames[i]
  210881. + T(": \"") + error + T("\"");
  210882. break;
  210883. }
  210884. }
  210885. if (error.isEmpty())
  210886. {
  210887. for (i = 0; i < inChans.size(); ++i)
  210888. {
  210889. error = inChans[i]->open();
  210890. if (error.isNotEmpty())
  210891. {
  210892. error = T("Error opening ") + dlh.inputDeviceNames[i]
  210893. + T(": \"") + error + T("\"");
  210894. break;
  210895. }
  210896. }
  210897. }
  210898. if (error.isEmpty())
  210899. {
  210900. totalSamplesOut = 0;
  210901. for (i = 0; i < outChans.size(); ++i)
  210902. outChans.getUnchecked(i)->synchronisePosition();
  210903. for (i = 0; i < inChans.size(); ++i)
  210904. inChans.getUnchecked(i)->synchronisePosition();
  210905. startThread (9);
  210906. sleep (10);
  210907. notify();
  210908. }
  210909. else
  210910. {
  210911. log (error);
  210912. }
  210913. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  210914. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  210915. return error;
  210916. }
  210917. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  210918. {
  210919. return new DSoundAudioIODeviceType();
  210920. }
  210921. #undef log
  210922. #endif
  210923. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  210924. /********* Start of inlined file: juce_win32_WASAPI.cpp *********/
  210925. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210926. // compiled on its own).
  210927. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  210928. #if 1
  210929. const String getAudioErrorDesc (HRESULT hr)
  210930. {
  210931. const char* e = 0;
  210932. switch (hr)
  210933. {
  210934. case E_POINTER: e = "E_POINTER"; break;
  210935. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  210936. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  210937. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  210938. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  210939. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  210940. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  210941. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  210942. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  210943. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  210944. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  210945. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  210946. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  210947. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  210948. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  210949. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  210950. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  210951. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  210952. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  210953. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  210954. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  210955. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  210956. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  210957. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  210958. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  210959. default: return String::toHexString ((int) hr);
  210960. }
  210961. return e;
  210962. }
  210963. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  210964. #define OK(a) wasapi_checkResult(a)
  210965. static bool wasapi_checkResult (HRESULT hr)
  210966. {
  210967. logFailure (hr);
  210968. return SUCCEEDED (hr);
  210969. }
  210970. #else
  210971. #define logFailure(hr) {}
  210972. #define OK(a) SUCCEEDED(a)
  210973. #endif
  210974. static const String wasapi_getDeviceID (IMMDevice* const device)
  210975. {
  210976. String s;
  210977. WCHAR* deviceId = 0;
  210978. if (OK (device->GetId (&deviceId)))
  210979. {
  210980. s = String (deviceId);
  210981. CoTaskMemFree (deviceId);
  210982. }
  210983. return s;
  210984. }
  210985. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  210986. {
  210987. EDataFlow flow = eRender;
  210988. ComSmartPtr <IMMEndpoint> endPoint;
  210989. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  210990. (void) OK (endPoint->GetDataFlow (&flow));
  210991. return flow;
  210992. }
  210993. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  210994. {
  210995. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  210996. }
  210997. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  210998. {
  210999. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  211000. : sizeof (WAVEFORMATEX));
  211001. }
  211002. class WASAPIDeviceBase
  211003. {
  211004. public:
  211005. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_)
  211006. : device (device_),
  211007. sampleRate (0),
  211008. numChannels (0),
  211009. actualNumChannels (0),
  211010. defaultSampleRate (0),
  211011. minBufferSize (0),
  211012. defaultBufferSize (0),
  211013. latencySamples (0)
  211014. {
  211015. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  211016. ComSmartPtr <IAudioClient> tempClient (createClient());
  211017. if (tempClient == 0)
  211018. return;
  211019. REFERENCE_TIME defaultPeriod, minPeriod;
  211020. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  211021. return;
  211022. WAVEFORMATEX* mixFormat = 0;
  211023. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  211024. return;
  211025. WAVEFORMATEXTENSIBLE format;
  211026. wasapi_copyWavFormat (format, mixFormat);
  211027. CoTaskMemFree (mixFormat);
  211028. actualNumChannels = numChannels = format.Format.nChannels;
  211029. defaultSampleRate = format.Format.nSamplesPerSec;
  211030. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  211031. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  211032. FloatElementComparator<double> comparator;
  211033. rates.addSorted (comparator, defaultSampleRate);
  211034. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  211035. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  211036. {
  211037. if (ratesToTest[i] == defaultSampleRate)
  211038. continue;
  211039. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  211040. if (SUCCEEDED (tempClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, 0)))
  211041. if (! rates.contains (ratesToTest[i]))
  211042. rates.addSorted (comparator, ratesToTest[i]);
  211043. }
  211044. }
  211045. ~WASAPIDeviceBase()
  211046. {
  211047. device = 0;
  211048. CloseHandle (clientEvent);
  211049. }
  211050. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  211051. bool openClient (const double newSampleRate, const BitArray& newChannels)
  211052. {
  211053. sampleRate = newSampleRate;
  211054. channels = newChannels;
  211055. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  211056. numChannels = channels.getHighestBit() + 1;
  211057. if (numChannels == 0)
  211058. return true;
  211059. client = createClient();
  211060. if (client != 0
  211061. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  211062. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  211063. {
  211064. channelMaps.clear();
  211065. for (int i = 0; i <= channels.getHighestBit(); ++i)
  211066. if (channels[i])
  211067. channelMaps.add (i);
  211068. REFERENCE_TIME latency;
  211069. if (OK (client->GetStreamLatency (&latency)))
  211070. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  211071. (void) OK (client->GetBufferSize (&actualBufferSize));
  211072. return OK (client->SetEventHandle (clientEvent));
  211073. }
  211074. return false;
  211075. }
  211076. void closeClient()
  211077. {
  211078. if (client != 0)
  211079. client->Stop();
  211080. client = 0;
  211081. ResetEvent (clientEvent);
  211082. }
  211083. ComSmartPtr <IMMDevice> device;
  211084. ComSmartPtr <IAudioClient> client;
  211085. double sampleRate, defaultSampleRate;
  211086. int numChannels, actualNumChannels;
  211087. int minBufferSize, defaultBufferSize, latencySamples;
  211088. Array <double> rates;
  211089. HANDLE clientEvent;
  211090. BitArray channels;
  211091. AudioDataConverters::DataFormat dataFormat;
  211092. Array <int> channelMaps;
  211093. UINT32 actualBufferSize;
  211094. int bytesPerSample;
  211095. private:
  211096. const ComSmartPtr <IAudioClient> createClient()
  211097. {
  211098. ComSmartPtr <IAudioClient> client;
  211099. if (device != 0)
  211100. {
  211101. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  211102. logFailure (hr);
  211103. }
  211104. return client;
  211105. }
  211106. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  211107. {
  211108. WAVEFORMATEXTENSIBLE format;
  211109. zerostruct (format);
  211110. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  211111. {
  211112. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  211113. }
  211114. else
  211115. {
  211116. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  211117. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  211118. }
  211119. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  211120. format.Format.nChannels = (WORD) numChannels;
  211121. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  211122. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  211123. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  211124. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  211125. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  211126. switch (numChannels)
  211127. {
  211128. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  211129. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  211130. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211131. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  211132. 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;
  211133. default: break;
  211134. }
  211135. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  211136. HRESULT hr = client->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, (WAVEFORMATEX**) &nearestFormat);
  211137. logFailure (hr);
  211138. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  211139. {
  211140. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  211141. hr = S_OK;
  211142. }
  211143. CoTaskMemFree (nearestFormat);
  211144. GUID session;
  211145. if (hr == S_OK
  211146. && OK (client->Initialize (AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  211147. 0, 0, (WAVEFORMATEX*) &format, &session)))
  211148. {
  211149. actualNumChannels = format.Format.nChannels;
  211150. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  211151. bytesPerSample = format.Format.wBitsPerSample / 8;
  211152. dataFormat = isFloat ? AudioDataConverters::float32LE
  211153. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  211154. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  211155. : AudioDataConverters::int16LE)));
  211156. return true;
  211157. }
  211158. return false;
  211159. }
  211160. };
  211161. class WASAPIInputDevice : public WASAPIDeviceBase
  211162. {
  211163. public:
  211164. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_)
  211165. : WASAPIDeviceBase (device_),
  211166. reservoir (1, 1)
  211167. {
  211168. }
  211169. ~WASAPIInputDevice()
  211170. {
  211171. close();
  211172. }
  211173. bool open (const double newSampleRate, const BitArray& newChannels)
  211174. {
  211175. reservoirSize = 0;
  211176. reservoirCapacity = 16384;
  211177. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  211178. return openClient (newSampleRate, newChannels)
  211179. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  211180. }
  211181. void close()
  211182. {
  211183. closeClient();
  211184. captureClient = 0;
  211185. reservoir.setSize (0);
  211186. }
  211187. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  211188. {
  211189. if (numChannels <= 0)
  211190. return;
  211191. int offset = 0;
  211192. while (bufferSize > 0)
  211193. {
  211194. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  211195. {
  211196. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  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 (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211205. break;
  211206. case AudioDataConverters::int32LE:
  211207. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211208. break;
  211209. case AudioDataConverters::int24LE:
  211210. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211211. break;
  211212. case AudioDataConverters::int16LE:
  211213. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211214. break;
  211215. default: jassertfalse; break;
  211216. }
  211217. }
  211218. bufferSize -= samplesToDo;
  211219. offset += samplesToDo;
  211220. reservoirSize -= samplesToDo;
  211221. }
  211222. else
  211223. {
  211224. UINT32 packetLength = 0;
  211225. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  211226. break;
  211227. if (packetLength == 0)
  211228. {
  211229. if (thread.threadShouldExit())
  211230. break;
  211231. Thread::sleep (1);
  211232. continue;
  211233. }
  211234. uint8* inputData = 0;
  211235. UINT32 numSamplesAvailable;
  211236. DWORD flags;
  211237. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  211238. {
  211239. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  211240. for (int i = 0; i < numDestBuffers; ++i)
  211241. {
  211242. float* const dest = destBuffers[i] + offset;
  211243. const int srcChan = channelMaps.getUnchecked(i);
  211244. switch (dataFormat)
  211245. {
  211246. case AudioDataConverters::float32LE:
  211247. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211248. break;
  211249. case AudioDataConverters::int32LE:
  211250. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211251. break;
  211252. case AudioDataConverters::int24LE:
  211253. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211254. break;
  211255. case AudioDataConverters::int16LE:
  211256. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211257. break;
  211258. default: jassertfalse; break;
  211259. }
  211260. }
  211261. bufferSize -= samplesToDo;
  211262. offset += samplesToDo;
  211263. if (samplesToDo < numSamplesAvailable)
  211264. {
  211265. reservoirSize = jmin (numSamplesAvailable - samplesToDo, reservoirCapacity);
  211266. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  211267. bytesPerSample * actualNumChannels * reservoirSize);
  211268. }
  211269. captureClient->ReleaseBuffer (numSamplesAvailable);
  211270. }
  211271. }
  211272. }
  211273. }
  211274. ComSmartPtr <IAudioCaptureClient> captureClient;
  211275. MemoryBlock reservoir;
  211276. int reservoirSize, reservoirCapacity;
  211277. };
  211278. class WASAPIOutputDevice : public WASAPIDeviceBase
  211279. {
  211280. public:
  211281. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_)
  211282. : WASAPIDeviceBase (device_)
  211283. {
  211284. }
  211285. ~WASAPIOutputDevice()
  211286. {
  211287. close();
  211288. }
  211289. bool open (const double newSampleRate, const BitArray& newChannels)
  211290. {
  211291. return openClient (newSampleRate, newChannels)
  211292. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  211293. }
  211294. void close()
  211295. {
  211296. closeClient();
  211297. renderClient = 0;
  211298. }
  211299. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  211300. {
  211301. if (numChannels <= 0)
  211302. return;
  211303. int offset = 0;
  211304. while (bufferSize > 0)
  211305. {
  211306. UINT32 padding = 0;
  211307. if (! OK (client->GetCurrentPadding (&padding)))
  211308. return;
  211309. const int samplesToDo = jmin ((int) (actualBufferSize - padding), bufferSize);
  211310. if (samplesToDo <= 0)
  211311. {
  211312. if (thread.threadShouldExit())
  211313. break;
  211314. Thread::sleep (0);
  211315. continue;
  211316. }
  211317. uint8* outputData = 0;
  211318. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  211319. {
  211320. for (int i = 0; i < numSrcBuffers; ++i)
  211321. {
  211322. const float* const source = srcBuffers[i] + offset;
  211323. const int destChan = channelMaps.getUnchecked(i);
  211324. switch (dataFormat)
  211325. {
  211326. case AudioDataConverters::float32LE:
  211327. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211328. break;
  211329. case AudioDataConverters::int32LE:
  211330. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211331. break;
  211332. case AudioDataConverters::int24LE:
  211333. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  211334. break;
  211335. case AudioDataConverters::int16LE:
  211336. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  211337. break;
  211338. default: jassertfalse; break;
  211339. }
  211340. }
  211341. renderClient->ReleaseBuffer (samplesToDo, 0);
  211342. offset += samplesToDo;
  211343. bufferSize -= samplesToDo;
  211344. }
  211345. }
  211346. }
  211347. ComSmartPtr <IAudioRenderClient> renderClient;
  211348. };
  211349. class WASAPIAudioIODevice : public AudioIODevice,
  211350. public Thread
  211351. {
  211352. public:
  211353. WASAPIAudioIODevice (const String& deviceName,
  211354. const String& outputDeviceId_,
  211355. const String& inputDeviceId_)
  211356. : AudioIODevice (deviceName, "Windows Audio"),
  211357. Thread ("Juce WASAPI"),
  211358. isOpen_ (false),
  211359. isStarted (false),
  211360. outputDevice (0),
  211361. outputDeviceId (outputDeviceId_),
  211362. inputDevice (0),
  211363. inputDeviceId (inputDeviceId_),
  211364. currentBufferSizeSamples (0),
  211365. currentSampleRate (0),
  211366. callback (0)
  211367. {
  211368. }
  211369. ~WASAPIAudioIODevice()
  211370. {
  211371. close();
  211372. deleteAndZero (inputDevice);
  211373. deleteAndZero (outputDevice);
  211374. }
  211375. bool initialise()
  211376. {
  211377. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  211378. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  211379. latencyIn = latencyOut = 0;
  211380. Array <double> ratesIn, ratesOut;
  211381. if (createDevices())
  211382. {
  211383. jassert (inputDevice != 0 || outputDevice != 0);
  211384. if (inputDevice != 0 && outputDevice != 0)
  211385. {
  211386. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  211387. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  211388. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  211389. sampleRates = inputDevice->rates;
  211390. sampleRates.removeValuesNotIn (outputDevice->rates);
  211391. }
  211392. else
  211393. {
  211394. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  211395. defaultSampleRate = d->defaultSampleRate;
  211396. minBufferSize = d->minBufferSize;
  211397. defaultBufferSize = d->defaultBufferSize;
  211398. sampleRates = d->rates;
  211399. }
  211400. IntegerElementComparator<int> comparator;
  211401. bufferSizes.addSorted (comparator, defaultBufferSize);
  211402. if (minBufferSize != defaultBufferSize)
  211403. bufferSizes.addSorted (comparator, minBufferSize);
  211404. int n = 64;
  211405. for (int i = 0; i < 40; ++i)
  211406. {
  211407. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  211408. bufferSizes.addSorted (comparator, n);
  211409. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  211410. }
  211411. return true;
  211412. }
  211413. return false;
  211414. }
  211415. const StringArray getOutputChannelNames()
  211416. {
  211417. StringArray outChannels;
  211418. if (outputDevice != 0)
  211419. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  211420. outChannels.add ("Output channel " + String (i));
  211421. return outChannels;
  211422. }
  211423. const StringArray getInputChannelNames()
  211424. {
  211425. StringArray inChannels;
  211426. if (inputDevice != 0)
  211427. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  211428. inChannels.add ("Input channel " + String (i));
  211429. return inChannels;
  211430. }
  211431. int getNumSampleRates() { return sampleRates.size(); }
  211432. double getSampleRate (int index) { return sampleRates [index]; }
  211433. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  211434. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  211435. int getDefaultBufferSize() { return defaultBufferSize; }
  211436. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  211437. double getCurrentSampleRate() { return currentSampleRate; }
  211438. int getCurrentBitDepth() { return 32; }
  211439. int getOutputLatencyInSamples() { return latencyOut; }
  211440. int getInputLatencyInSamples() { return latencyIn; }
  211441. const BitArray getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BitArray(); }
  211442. const BitArray getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BitArray(); }
  211443. const String getLastError() { return lastError; }
  211444. const String open (const BitArray& inputChannels, const BitArray& outputChannels,
  211445. double sampleRate, int bufferSizeSamples)
  211446. {
  211447. close();
  211448. lastError = String::empty;
  211449. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  211450. {
  211451. lastError = "The input and output devices don't share a common sample rate!";
  211452. return lastError;
  211453. }
  211454. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  211455. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  211456. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  211457. {
  211458. lastError = "Couldn't open the input device!";
  211459. return lastError;
  211460. }
  211461. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  211462. {
  211463. close();
  211464. lastError = "Couldn't open the output device!";
  211465. return lastError;
  211466. }
  211467. if (inputDevice != 0)
  211468. ResetEvent (inputDevice->clientEvent);
  211469. if (outputDevice != 0)
  211470. ResetEvent (outputDevice->clientEvent);
  211471. startThread (8);
  211472. Thread::sleep (5);
  211473. if (inputDevice != 0 && inputDevice->client != 0)
  211474. {
  211475. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  211476. HRESULT hr = inputDevice->client->Start();
  211477. logFailure (hr); //xxx handle this
  211478. }
  211479. if (outputDevice != 0 && outputDevice->client != 0)
  211480. {
  211481. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  211482. HRESULT hr = outputDevice->client->Start();
  211483. logFailure (hr); //xxx handle this
  211484. }
  211485. isOpen_ = true;
  211486. return lastError;
  211487. }
  211488. void close()
  211489. {
  211490. stop();
  211491. if (inputDevice != 0)
  211492. SetEvent (inputDevice->clientEvent);
  211493. if (outputDevice != 0)
  211494. SetEvent (outputDevice->clientEvent);
  211495. stopThread (5000);
  211496. if (inputDevice != 0)
  211497. inputDevice->close();
  211498. if (outputDevice != 0)
  211499. outputDevice->close();
  211500. isOpen_ = false;
  211501. }
  211502. bool isOpen() { return isOpen_ && isThreadRunning(); }
  211503. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  211504. void start (AudioIODeviceCallback* call)
  211505. {
  211506. if (isOpen_ && call != 0 && ! isStarted)
  211507. {
  211508. if (! isThreadRunning())
  211509. {
  211510. // something's gone wrong and the thread's stopped..
  211511. isOpen_ = false;
  211512. return;
  211513. }
  211514. call->audioDeviceAboutToStart (this);
  211515. const ScopedLock sl (startStopLock);
  211516. callback = call;
  211517. isStarted = true;
  211518. }
  211519. }
  211520. void stop()
  211521. {
  211522. if (isStarted)
  211523. {
  211524. AudioIODeviceCallback* const callbackLocal = callback;
  211525. {
  211526. const ScopedLock sl (startStopLock);
  211527. isStarted = false;
  211528. }
  211529. if (callbackLocal != 0)
  211530. callbackLocal->audioDeviceStopped();
  211531. }
  211532. }
  211533. void run()
  211534. {
  211535. const int bufferSize = currentBufferSizeSamples;
  211536. HANDLE events[2];
  211537. int numEvents = 0;
  211538. if (inputDevice != 0)
  211539. events [numEvents++] = inputDevice->clientEvent;
  211540. if (outputDevice != 0)
  211541. events [numEvents++] = outputDevice->clientEvent;
  211542. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  211543. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  211544. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  211545. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  211546. float** const inputBuffers = ins.getArrayOfChannels();
  211547. float** const outputBuffers = outs.getArrayOfChannels();
  211548. ins.clear();
  211549. while (! threadShouldExit())
  211550. {
  211551. const DWORD result = WaitForMultipleObjects (numEvents, events, true, 1000);
  211552. if (result == WAIT_TIMEOUT)
  211553. continue;
  211554. if (threadShouldExit())
  211555. break;
  211556. if (inputDevice != 0)
  211557. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  211558. // Make the callback..
  211559. {
  211560. const ScopedLock sl (startStopLock);
  211561. if (isStarted)
  211562. {
  211563. JUCE_TRY
  211564. {
  211565. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  211566. numInputBuffers,
  211567. outputBuffers,
  211568. numOutputBuffers,
  211569. bufferSize);
  211570. }
  211571. JUCE_CATCH_EXCEPTION
  211572. }
  211573. else
  211574. {
  211575. outs.clear();
  211576. }
  211577. }
  211578. if (outputDevice != 0)
  211579. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  211580. }
  211581. }
  211582. juce_UseDebuggingNewOperator
  211583. String outputDeviceId, inputDeviceId;
  211584. String lastError;
  211585. private:
  211586. // Device stats...
  211587. WASAPIInputDevice* inputDevice;
  211588. WASAPIOutputDevice* outputDevice;
  211589. double defaultSampleRate;
  211590. int minBufferSize, defaultBufferSize;
  211591. int latencyIn, latencyOut;
  211592. Array <double> sampleRates;
  211593. Array <int> bufferSizes;
  211594. // Active state...
  211595. bool isOpen_, isStarted;
  211596. int currentBufferSizeSamples;
  211597. double currentSampleRate;
  211598. AudioIODeviceCallback* callback;
  211599. CriticalSection startStopLock;
  211600. bool createDevices()
  211601. {
  211602. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211603. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211604. return false;
  211605. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211606. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  211607. return false;
  211608. UINT32 numDevices = 0;
  211609. if (! OK (deviceCollection->GetCount (&numDevices)))
  211610. return false;
  211611. for (UINT32 i = 0; i < numDevices; ++i)
  211612. {
  211613. ComSmartPtr <IMMDevice> device;
  211614. if (! OK (deviceCollection->Item (i, &device)))
  211615. continue;
  211616. const String deviceId (wasapi_getDeviceID (device));
  211617. if (deviceId.isEmpty())
  211618. continue;
  211619. const EDataFlow flow = wasapi_getDataFlow (device);
  211620. if (deviceId == inputDeviceId && flow == eCapture)
  211621. inputDevice = new WASAPIInputDevice (device);
  211622. else if (deviceId == outputDeviceId && flow == eRender)
  211623. outputDevice = new WASAPIOutputDevice (device);
  211624. }
  211625. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  211626. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  211627. }
  211628. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  211629. const WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  211630. };
  211631. class WASAPIAudioIODeviceType : public AudioIODeviceType
  211632. {
  211633. public:
  211634. WASAPIAudioIODeviceType()
  211635. : AudioIODeviceType (T("Windows Audio")),
  211636. hasScanned (false)
  211637. {
  211638. }
  211639. ~WASAPIAudioIODeviceType()
  211640. {
  211641. }
  211642. void scanForDevices()
  211643. {
  211644. hasScanned = true;
  211645. outputDeviceNames.clear();
  211646. inputDeviceNames.clear();
  211647. outputDeviceIds.clear();
  211648. inputDeviceIds.clear();
  211649. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211650. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211651. return;
  211652. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  211653. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  211654. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211655. UINT32 numDevices = 0;
  211656. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  211657. && OK (deviceCollection->GetCount (&numDevices))))
  211658. return;
  211659. for (UINT32 i = 0; i < numDevices; ++i)
  211660. {
  211661. ComSmartPtr <IMMDevice> device;
  211662. if (! OK (deviceCollection->Item (i, &device)))
  211663. continue;
  211664. const String deviceId (wasapi_getDeviceID (device));
  211665. DWORD state = 0;
  211666. if (! OK (device->GetState (&state)))
  211667. continue;
  211668. if (state != DEVICE_STATE_ACTIVE)
  211669. continue;
  211670. String name;
  211671. {
  211672. ComSmartPtr <IPropertyStore> properties;
  211673. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  211674. continue;
  211675. PROPVARIANT value;
  211676. PropVariantInit (&value);
  211677. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  211678. name = value.pwszVal;
  211679. PropVariantClear (&value);
  211680. }
  211681. const EDataFlow flow = wasapi_getDataFlow (device);
  211682. if (flow == eRender)
  211683. {
  211684. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  211685. outputDeviceIds.insert (index, deviceId);
  211686. outputDeviceNames.insert (index, name);
  211687. }
  211688. else if (flow == eCapture)
  211689. {
  211690. const int index = (deviceId == defaultCapture) ? 0 : -1;
  211691. inputDeviceIds.insert (index, deviceId);
  211692. inputDeviceNames.insert (index, name);
  211693. }
  211694. }
  211695. inputDeviceNames.appendNumbersToDuplicates (false, false);
  211696. outputDeviceNames.appendNumbersToDuplicates (false, false);
  211697. }
  211698. const StringArray getDeviceNames (const bool wantInputNames) const
  211699. {
  211700. jassert (hasScanned); // need to call scanForDevices() before doing this
  211701. return wantInputNames ? inputDeviceNames
  211702. : outputDeviceNames;
  211703. }
  211704. int getDefaultDeviceIndex (const bool /*forInput*/) const
  211705. {
  211706. jassert (hasScanned); // need to call scanForDevices() before doing this
  211707. return 0;
  211708. }
  211709. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  211710. {
  211711. jassert (hasScanned); // need to call scanForDevices() before doing this
  211712. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  211713. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  211714. : outputDeviceIds.indexOf (d->outputDeviceId));
  211715. }
  211716. bool hasSeparateInputsAndOutputs() const { return true; }
  211717. AudioIODevice* createDevice (const String& outputDeviceName,
  211718. const String& inputDeviceName)
  211719. {
  211720. jassert (hasScanned); // need to call scanForDevices() before doing this
  211721. WASAPIAudioIODevice* d = 0;
  211722. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211723. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211724. if (outputIndex >= 0 || inputIndex >= 0)
  211725. {
  211726. d = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211727. : inputDeviceName,
  211728. outputDeviceIds [outputIndex],
  211729. inputDeviceIds [inputIndex]);
  211730. if (! d->initialise())
  211731. deleteAndZero (d);
  211732. }
  211733. return d;
  211734. }
  211735. juce_UseDebuggingNewOperator
  211736. StringArray outputDeviceNames, outputDeviceIds;
  211737. StringArray inputDeviceNames, inputDeviceIds;
  211738. private:
  211739. bool hasScanned;
  211740. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  211741. {
  211742. String s;
  211743. IMMDevice* dev = 0;
  211744. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  211745. eMultimedia, &dev)))
  211746. {
  211747. WCHAR* deviceId = 0;
  211748. if (OK (dev->GetId (&deviceId)))
  211749. {
  211750. s = String (deviceId);
  211751. CoTaskMemFree (deviceId);
  211752. }
  211753. dev->Release();
  211754. }
  211755. return s;
  211756. }
  211757. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  211758. const WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  211759. };
  211760. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  211761. {
  211762. return new WASAPIAudioIODeviceType();
  211763. }
  211764. #undef logFailure
  211765. #undef OK
  211766. #endif
  211767. /********* End of inlined file: juce_win32_WASAPI.cpp *********/
  211768. /********* Start of inlined file: juce_win32_CameraDevice.cpp *********/
  211769. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211770. // compiled on its own).
  211771. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  211772. class DShowCameraDeviceInteral : public ChangeBroadcaster
  211773. {
  211774. public:
  211775. DShowCameraDeviceInteral (CameraDevice* const owner_,
  211776. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  211777. const ComSmartPtr <IBaseFilter>& filter_,
  211778. int minWidth, int minHeight,
  211779. int maxWidth, int maxHeight)
  211780. : owner (owner_),
  211781. captureGraphBuilder (captureGraphBuilder_),
  211782. filter (filter_),
  211783. ok (false),
  211784. imageNeedsFlipping (false),
  211785. width (0),
  211786. height (0),
  211787. activeUsers (0),
  211788. recordNextFrameTime (false)
  211789. {
  211790. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph, CLSCTX_INPROC);
  211791. if (FAILED (hr))
  211792. return;
  211793. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  211794. if (FAILED (hr))
  211795. return;
  211796. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  211797. if (FAILED (hr))
  211798. return;
  211799. {
  211800. ComSmartPtr <IAMStreamConfig> streamConfig;
  211801. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE,
  211802. 0,
  211803. filter,
  211804. IID_IAMStreamConfig,
  211805. (void**) &streamConfig);
  211806. if (streamConfig != 0)
  211807. {
  211808. getVideoSizes (streamConfig);
  211809. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  211810. return;
  211811. }
  211812. }
  211813. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  211814. if (FAILED (hr))
  211815. return;
  211816. hr = smartTee.CoCreateInstance (CLSID_SmartTee, CLSCTX_INPROC_SERVER);
  211817. if (FAILED (hr))
  211818. return;
  211819. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  211820. if (FAILED (hr))
  211821. return;
  211822. if (! connectFilters (filter, smartTee))
  211823. return;
  211824. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  211825. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber, CLSCTX_INPROC_SERVER);
  211826. if (FAILED (hr))
  211827. return;
  211828. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  211829. if (FAILED (hr))
  211830. return;
  211831. AM_MEDIA_TYPE mt;
  211832. zerostruct (mt);
  211833. mt.majortype = MEDIATYPE_Video;
  211834. mt.subtype = MEDIASUBTYPE_RGB24;
  211835. mt.formattype = FORMAT_VideoInfo;
  211836. sampleGrabber->SetMediaType (&mt);
  211837. callback = new GrabberCallback (*this);
  211838. sampleGrabber->SetCallback (callback, 1);
  211839. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  211840. if (FAILED (hr))
  211841. return;
  211842. ComSmartPtr <IPin> grabberInputPin;
  211843. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  211844. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  211845. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  211846. return;
  211847. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  211848. if (FAILED (hr))
  211849. return;
  211850. zerostruct (mt);
  211851. hr = sampleGrabber->GetConnectedMediaType (&mt);
  211852. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  211853. width = pVih->bmiHeader.biWidth;
  211854. height = pVih->bmiHeader.biHeight;
  211855. ComSmartPtr <IBaseFilter> nullFilter;
  211856. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer, CLSCTX_INPROC_SERVER);
  211857. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  211858. if (connectFilters (sampleGrabberBase, nullFilter)
  211859. && addGraphToRot())
  211860. {
  211861. activeImage = new Image (Image::RGB, width, height, true);
  211862. loadingImage = new Image (Image::RGB, width, height, true);
  211863. ok = true;
  211864. }
  211865. }
  211866. ~DShowCameraDeviceInteral()
  211867. {
  211868. mediaControl->Stop();
  211869. removeGraphFromRot();
  211870. for (int i = viewerComps.size(); --i >= 0;)
  211871. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  211872. callback = 0;
  211873. graphBuilder = 0;
  211874. sampleGrabber = 0;
  211875. mediaControl = 0;
  211876. filter = 0;
  211877. captureGraphBuilder = 0;
  211878. smartTee = 0;
  211879. smartTeePreviewOutputPin = 0;
  211880. smartTeeCaptureOutputPin = 0;
  211881. mux = 0;
  211882. fileWriter = 0;
  211883. delete activeImage;
  211884. delete loadingImage;
  211885. }
  211886. void addUser()
  211887. {
  211888. if (ok && activeUsers++ == 0)
  211889. mediaControl->Run();
  211890. }
  211891. void removeUser()
  211892. {
  211893. if (ok && --activeUsers == 0)
  211894. mediaControl->Stop();
  211895. }
  211896. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  211897. {
  211898. if (recordNextFrameTime)
  211899. {
  211900. firstRecordedTime = Time::getCurrentTime();
  211901. recordNextFrameTime = false;
  211902. }
  211903. imageSwapLock.enter();
  211904. int ls, ps;
  211905. const int lineStride = width * 3;
  211906. uint8* const dest = loadingImage->lockPixelDataReadWrite (0, 0, width, height, ls, ps);
  211907. for (int i = 0; i < height; ++i)
  211908. memcpy (dest + ls * ((height - 1) - i),
  211909. buffer + lineStride * i,
  211910. lineStride);
  211911. loadingImage->releasePixelDataReadWrite (dest);
  211912. imageNeedsFlipping = true;
  211913. imageSwapLock.exit();
  211914. callListeners (*loadingImage);
  211915. sendChangeMessage (this);
  211916. }
  211917. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  211918. {
  211919. if (imageNeedsFlipping)
  211920. {
  211921. imageSwapLock.enter();
  211922. swapVariables (loadingImage, activeImage);
  211923. imageNeedsFlipping = false;
  211924. imageSwapLock.exit();
  211925. }
  211926. RectanglePlacement rp (RectanglePlacement::centred);
  211927. double dx = 0, dy = 0, dw = width, dh = height;
  211928. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  211929. const int rx = roundDoubleToInt (dx), ry = roundDoubleToInt (dy);
  211930. const int rw = roundDoubleToInt (dw), rh = roundDoubleToInt (dh);
  211931. g.saveState();
  211932. g.excludeClipRegion (rx, ry, rw, rh);
  211933. g.fillAll (Colours::black);
  211934. g.restoreState();
  211935. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  211936. }
  211937. bool createFileCaptureFilter (const File& file)
  211938. {
  211939. removeFileCaptureFilter();
  211940. file.deleteFile();
  211941. mediaControl->Stop();
  211942. firstRecordedTime = Time();
  211943. recordNextFrameTime = true;
  211944. HRESULT hr = mux.CoCreateInstance (CLSID_AviDest, CLSCTX_INPROC_SERVER);
  211945. if (SUCCEEDED (hr))
  211946. {
  211947. hr = graphBuilder->AddFilter (mux, _T("AVI Mux"));
  211948. if (SUCCEEDED (hr))
  211949. {
  211950. fileWriter.CoCreateInstance (CLSID_FileWriter, CLSCTX_INPROC_SERVER);
  211951. if (SUCCEEDED (hr))
  211952. {
  211953. ComSmartPtr <IFileSinkFilter> fileSink;
  211954. hr = fileWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  211955. if (SUCCEEDED (hr))
  211956. {
  211957. AM_MEDIA_TYPE mt;
  211958. zerostruct (mt);
  211959. mt.majortype = MEDIATYPE_Stream;
  211960. mt.subtype = MEDIASUBTYPE_Avi;
  211961. mt.formattype = FORMAT_VideoInfo;
  211962. hr = fileSink->SetFileName (file.getFullPathName(), &mt);
  211963. if (SUCCEEDED (hr))
  211964. {
  211965. hr = graphBuilder->AddFilter (fileWriter, _T("File Writer"));
  211966. if (SUCCEEDED (hr))
  211967. {
  211968. ComSmartPtr <IPin> muxInputPin, muxOutputPin, writerInput;
  211969. if (getPin (mux, PINDIR_INPUT, &muxInputPin)
  211970. && getPin (mux, PINDIR_OUTPUT, &muxOutputPin)
  211971. && getPin (fileWriter, PINDIR_INPUT, &writerInput))
  211972. {
  211973. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, muxInputPin);
  211974. if (SUCCEEDED (hr))
  211975. {
  211976. hr = graphBuilder->Connect (muxOutputPin, writerInput);
  211977. if (SUCCEEDED (hr))
  211978. {
  211979. if (ok && activeUsers > 0)
  211980. mediaControl->Run();
  211981. return true;
  211982. }
  211983. }
  211984. }
  211985. }
  211986. }
  211987. }
  211988. }
  211989. }
  211990. }
  211991. removeFileCaptureFilter();
  211992. if (ok && activeUsers > 0)
  211993. mediaControl->Run();
  211994. return false;
  211995. }
  211996. void removeFileCaptureFilter()
  211997. {
  211998. mediaControl->Stop();
  211999. if (mux != 0)
  212000. {
  212001. graphBuilder->RemoveFilter (mux);
  212002. mux = 0;
  212003. }
  212004. if (fileWriter != 0)
  212005. {
  212006. graphBuilder->RemoveFilter (fileWriter);
  212007. fileWriter = 0;
  212008. }
  212009. if (ok && activeUsers > 0)
  212010. mediaControl->Run();
  212011. }
  212012. void addListener (CameraImageListener* listenerToAdd)
  212013. {
  212014. const ScopedLock sl (listenerLock);
  212015. if (listeners.size() == 0)
  212016. addUser();
  212017. listeners.addIfNotAlreadyThere (listenerToAdd);
  212018. }
  212019. void removeListener (CameraImageListener* listenerToRemove)
  212020. {
  212021. const ScopedLock sl (listenerLock);
  212022. listeners.removeValue (listenerToRemove);
  212023. if (listeners.size() == 0)
  212024. removeUser();
  212025. }
  212026. void callListeners (Image& image)
  212027. {
  212028. const ScopedLock sl (listenerLock);
  212029. for (int i = listeners.size(); --i >= 0;)
  212030. {
  212031. CameraImageListener* l = (CameraImageListener*) listeners[i];
  212032. if (l != 0)
  212033. l->imageReceived (image);
  212034. }
  212035. }
  212036. class DShowCaptureViewerComp : public Component,
  212037. public ChangeListener
  212038. {
  212039. public:
  212040. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  212041. : owner (owner_)
  212042. {
  212043. setOpaque (true);
  212044. owner->addChangeListener (this);
  212045. owner->addUser();
  212046. owner->viewerComps.add (this);
  212047. setSize (owner_->width, owner_->height);
  212048. }
  212049. ~DShowCaptureViewerComp()
  212050. {
  212051. if (owner != 0)
  212052. {
  212053. owner->viewerComps.removeValue (this);
  212054. owner->removeUser();
  212055. owner->removeChangeListener (this);
  212056. }
  212057. }
  212058. void ownerDeleted()
  212059. {
  212060. owner = 0;
  212061. }
  212062. void paint (Graphics& g)
  212063. {
  212064. g.setColour (Colours::black);
  212065. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  212066. if (owner != 0)
  212067. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  212068. else
  212069. g.fillAll (Colours::black);
  212070. }
  212071. void changeListenerCallback (void*)
  212072. {
  212073. repaint();
  212074. }
  212075. private:
  212076. DShowCameraDeviceInteral* owner;
  212077. };
  212078. bool ok;
  212079. int width, height;
  212080. Time firstRecordedTime;
  212081. VoidArray viewerComps;
  212082. private:
  212083. CameraDevice* const owner;
  212084. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212085. ComSmartPtr <IBaseFilter> filter;
  212086. ComSmartPtr <IBaseFilter> smartTee;
  212087. ComSmartPtr <IGraphBuilder> graphBuilder;
  212088. ComSmartPtr <ISampleGrabber> sampleGrabber;
  212089. ComSmartPtr <IMediaControl> mediaControl;
  212090. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  212091. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  212092. ComSmartPtr <IBaseFilter> mux, fileWriter;
  212093. int activeUsers;
  212094. Array <int> widths, heights;
  212095. DWORD graphRegistrationID;
  212096. CriticalSection imageSwapLock;
  212097. bool imageNeedsFlipping;
  212098. Image* loadingImage;
  212099. Image* activeImage;
  212100. bool recordNextFrameTime;
  212101. void getVideoSizes (IAMStreamConfig* const streamConfig)
  212102. {
  212103. widths.clear();
  212104. heights.clear();
  212105. int count = 0, size = 0;
  212106. streamConfig->GetNumberOfCapabilities (&count, &size);
  212107. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212108. {
  212109. for (int i = 0; i < count; ++i)
  212110. {
  212111. VIDEO_STREAM_CONFIG_CAPS scc;
  212112. AM_MEDIA_TYPE* config;
  212113. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212114. if (SUCCEEDED (hr))
  212115. {
  212116. const int w = scc.InputSize.cx;
  212117. const int h = scc.InputSize.cy;
  212118. bool duplicate = false;
  212119. for (int j = widths.size(); --j >= 0;)
  212120. {
  212121. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  212122. {
  212123. duplicate = true;
  212124. break;
  212125. }
  212126. }
  212127. if (! duplicate)
  212128. {
  212129. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  212130. widths.add (w);
  212131. heights.add (h);
  212132. }
  212133. deleteMediaType (config);
  212134. }
  212135. }
  212136. }
  212137. }
  212138. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  212139. const int minWidth, const int minHeight,
  212140. const int maxWidth, const int maxHeight)
  212141. {
  212142. int count = 0, size = 0;
  212143. streamConfig->GetNumberOfCapabilities (&count, &size);
  212144. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  212145. {
  212146. for (int i = 0; i < count; ++i)
  212147. {
  212148. VIDEO_STREAM_CONFIG_CAPS scc;
  212149. AM_MEDIA_TYPE* config;
  212150. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  212151. if (SUCCEEDED (hr))
  212152. {
  212153. if (scc.InputSize.cx >= minWidth
  212154. && scc.InputSize.cy >= minHeight
  212155. && scc.InputSize.cx <= maxWidth
  212156. && scc.InputSize.cy <= maxHeight)
  212157. {
  212158. hr = streamConfig->SetFormat (config);
  212159. deleteMediaType (config);
  212160. return SUCCEEDED (hr);
  212161. }
  212162. deleteMediaType (config);
  212163. }
  212164. }
  212165. }
  212166. return false;
  212167. }
  212168. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  212169. {
  212170. ComSmartPtr <IEnumPins> enumerator;
  212171. ComSmartPtr <IPin> pin;
  212172. filter->EnumPins (&enumerator);
  212173. while (enumerator->Next (1, &pin, 0) == S_OK)
  212174. {
  212175. PIN_DIRECTION dir;
  212176. pin->QueryDirection (&dir);
  212177. if (wantedDirection == dir)
  212178. {
  212179. PIN_INFO info;
  212180. zerostruct (info);
  212181. pin->QueryPinInfo (&info);
  212182. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  212183. {
  212184. pin.p->AddRef();
  212185. *result = pin;
  212186. return true;
  212187. }
  212188. }
  212189. }
  212190. return false;
  212191. }
  212192. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  212193. {
  212194. ComSmartPtr <IPin> in, out;
  212195. return getPin (first, PINDIR_OUTPUT, &out)
  212196. && getPin (second, PINDIR_INPUT, &in)
  212197. && SUCCEEDED (graphBuilder->Connect (out, in));
  212198. }
  212199. bool addGraphToRot()
  212200. {
  212201. ComSmartPtr <IRunningObjectTable> rot;
  212202. if (FAILED (GetRunningObjectTable (0, &rot)))
  212203. return false;
  212204. ComSmartPtr <IMoniker> moniker;
  212205. WCHAR buffer[128];
  212206. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  212207. if (FAILED (hr))
  212208. return false;
  212209. graphRegistrationID = 0;
  212210. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  212211. }
  212212. void removeGraphFromRot()
  212213. {
  212214. ComSmartPtr <IRunningObjectTable> rot;
  212215. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  212216. rot->Revoke (graphRegistrationID);
  212217. }
  212218. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  212219. {
  212220. if (pmt->cbFormat != 0)
  212221. CoTaskMemFree ((PVOID) pmt->pbFormat);
  212222. if (pmt->pUnk != 0)
  212223. pmt->pUnk->Release();
  212224. CoTaskMemFree (pmt);
  212225. }
  212226. class GrabberCallback : public ISampleGrabberCB
  212227. {
  212228. public:
  212229. GrabberCallback (DShowCameraDeviceInteral& owner_)
  212230. : owner (owner_)
  212231. {
  212232. }
  212233. HRESULT __stdcall QueryInterface (REFIID id, void** result)
  212234. {
  212235. if (id == IID_IUnknown)
  212236. *result = dynamic_cast <IUnknown*> (this);
  212237. else if (id == IID_ISampleGrabberCB)
  212238. *result = dynamic_cast <ISampleGrabberCB*> (this);
  212239. else
  212240. {
  212241. *result = 0;
  212242. return E_NOINTERFACE;
  212243. }
  212244. AddRef();
  212245. return S_OK;
  212246. }
  212247. ULONG __stdcall AddRef() { return ++refCount; }
  212248. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  212249. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  212250. {
  212251. return E_FAIL;
  212252. }
  212253. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  212254. {
  212255. owner.handleFrame (time, buffer, bufferSize);
  212256. return S_OK;
  212257. }
  212258. private:
  212259. int refCount;
  212260. DShowCameraDeviceInteral& owner;
  212261. GrabberCallback (const GrabberCallback&);
  212262. const GrabberCallback& operator= (const GrabberCallback&);
  212263. };
  212264. ComSmartPtr <GrabberCallback> callback;
  212265. VoidArray listeners;
  212266. CriticalSection listenerLock;
  212267. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  212268. const DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  212269. };
  212270. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  212271. : name (name_)
  212272. {
  212273. isRecording = false;
  212274. }
  212275. CameraDevice::~CameraDevice()
  212276. {
  212277. stopRecording();
  212278. delete (DShowCameraDeviceInteral*) internal;
  212279. internal = 0;
  212280. }
  212281. Component* CameraDevice::createViewerComponent()
  212282. {
  212283. return new DShowCameraDeviceInteral::DShowCaptureViewerComp ((DShowCameraDeviceInteral*) internal);
  212284. }
  212285. const String CameraDevice::getFileExtension()
  212286. {
  212287. return ".avi";
  212288. }
  212289. void CameraDevice::startRecordingToFile (const File& file)
  212290. {
  212291. stopRecording();
  212292. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212293. d->addUser();
  212294. isRecording = d->createFileCaptureFilter (file);
  212295. }
  212296. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  212297. {
  212298. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212299. return d->firstRecordedTime;
  212300. }
  212301. void CameraDevice::stopRecording()
  212302. {
  212303. if (isRecording)
  212304. {
  212305. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212306. d->removeFileCaptureFilter();
  212307. d->removeUser();
  212308. isRecording = false;
  212309. }
  212310. }
  212311. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  212312. {
  212313. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212314. if (listenerToAdd != 0)
  212315. d->addListener (listenerToAdd);
  212316. }
  212317. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  212318. {
  212319. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212320. if (listenerToRemove != 0)
  212321. d->removeListener (listenerToRemove);
  212322. }
  212323. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  212324. const int deviceIndexToOpen,
  212325. String& name)
  212326. {
  212327. int index = 0;
  212328. ComSmartPtr <IBaseFilter> result;
  212329. ComSmartPtr <ICreateDevEnum> pDevEnum;
  212330. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum, CLSCTX_INPROC);
  212331. if (SUCCEEDED (hr))
  212332. {
  212333. ComSmartPtr <IEnumMoniker> enumerator;
  212334. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  212335. if (SUCCEEDED (hr) && enumerator != 0)
  212336. {
  212337. ComSmartPtr <IBaseFilter> captureFilter;
  212338. ComSmartPtr <IMoniker> moniker;
  212339. ULONG fetched;
  212340. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  212341. {
  212342. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  212343. if (SUCCEEDED (hr))
  212344. {
  212345. ComSmartPtr <IPropertyBag> propertyBag;
  212346. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  212347. if (SUCCEEDED (hr))
  212348. {
  212349. VARIANT var;
  212350. var.vt = VT_BSTR;
  212351. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  212352. propertyBag = 0;
  212353. if (SUCCEEDED (hr))
  212354. {
  212355. if (names != 0)
  212356. names->add (var.bstrVal);
  212357. if (index == deviceIndexToOpen)
  212358. {
  212359. name = var.bstrVal;
  212360. result = captureFilter;
  212361. captureFilter = 0;
  212362. break;
  212363. }
  212364. ++index;
  212365. }
  212366. moniker = 0;
  212367. }
  212368. captureFilter = 0;
  212369. }
  212370. }
  212371. }
  212372. }
  212373. return result;
  212374. }
  212375. const StringArray CameraDevice::getAvailableDevices()
  212376. {
  212377. StringArray devs;
  212378. String dummy;
  212379. enumerateCameras (&devs, -1, dummy);
  212380. return devs;
  212381. }
  212382. CameraDevice* CameraDevice::openDevice (int index,
  212383. int minWidth, int minHeight,
  212384. int maxWidth, int maxHeight)
  212385. {
  212386. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212387. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2, CLSCTX_INPROC);
  212388. if (SUCCEEDED (hr))
  212389. {
  212390. String name;
  212391. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  212392. if (filter != 0)
  212393. {
  212394. CameraDevice* const cam = new CameraDevice (name, index);
  212395. DShowCameraDeviceInteral* const intern
  212396. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  212397. minWidth, minHeight, maxWidth, maxHeight);
  212398. cam->internal = intern;
  212399. if (intern->ok)
  212400. return cam;
  212401. else
  212402. delete cam;
  212403. }
  212404. }
  212405. return 0;
  212406. }
  212407. #endif
  212408. /********* End of inlined file: juce_win32_CameraDevice.cpp *********/
  212409. #endif
  212410. // Auto-link the other win32 libs that are needed by library calls..
  212411. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  212412. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212413. // Auto-links to various win32 libs that are needed by library calls..
  212414. #pragma comment(lib, "kernel32.lib")
  212415. #pragma comment(lib, "user32.lib")
  212416. #pragma comment(lib, "shell32.lib")
  212417. #pragma comment(lib, "gdi32.lib")
  212418. #pragma comment(lib, "vfw32.lib")
  212419. #pragma comment(lib, "comdlg32.lib")
  212420. #pragma comment(lib, "winmm.lib")
  212421. #pragma comment(lib, "wininet.lib")
  212422. #pragma comment(lib, "ole32.lib")
  212423. #pragma comment(lib, "advapi32.lib")
  212424. #pragma comment(lib, "ws2_32.lib")
  212425. #pragma comment(lib, "comsupp.lib")
  212426. #pragma comment(lib, "version.lib")
  212427. #if JUCE_OPENGL
  212428. #pragma comment(lib, "OpenGL32.Lib")
  212429. #pragma comment(lib, "GlU32.Lib")
  212430. #endif
  212431. #if JUCE_QUICKTIME
  212432. #pragma comment (lib, "QTMLClient.lib")
  212433. #endif
  212434. #if JUCE_USE_CAMERA
  212435. #pragma comment (lib, "Strmiids.lib")
  212436. #endif
  212437. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212438. #endif
  212439. END_JUCE_NAMESPACE
  212440. /********* End of inlined file: juce_win32_NativeCode.cpp *********/
  212441. #endif
  212442. #if JUCE_LINUX
  212443. /********* Start of inlined file: juce_linux_NativeCode.cpp *********/
  212444. /*
  212445. This file wraps together all the mac-specific code, so that
  212446. we can include all the native headers just once, and compile all our
  212447. platform-specific stuff in one big lump, keeping it out of the way of
  212448. the rest of the codebase.
  212449. */
  212450. BEGIN_JUCE_NAMESPACE
  212451. /* Remove this macro if you're having problems compiling the cpu affinity
  212452. calls (the API for these has changed about quite a bit in various Linux
  212453. versions, and a lot of distros seem to ship with obsolete versions)
  212454. */
  212455. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  212456. #define SUPPORT_AFFINITIES 1
  212457. #endif
  212458. #define JUCE_INCLUDED_FILE 1
  212459. // Now include the actual code files..
  212460. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  212461. /*
  212462. This file contains posix routines that are common to both the Linux and Mac builds.
  212463. It gets included directly in the cpp files for these platforms.
  212464. */
  212465. CriticalSection::CriticalSection() throw()
  212466. {
  212467. pthread_mutexattr_t atts;
  212468. pthread_mutexattr_init (&atts);
  212469. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  212470. pthread_mutex_init (&internal, &atts);
  212471. }
  212472. CriticalSection::~CriticalSection() throw()
  212473. {
  212474. pthread_mutex_destroy (&internal);
  212475. }
  212476. void CriticalSection::enter() const throw()
  212477. {
  212478. pthread_mutex_lock (&internal);
  212479. }
  212480. bool CriticalSection::tryEnter() const throw()
  212481. {
  212482. return pthread_mutex_trylock (&internal) == 0;
  212483. }
  212484. void CriticalSection::exit() const throw()
  212485. {
  212486. pthread_mutex_unlock (&internal);
  212487. }
  212488. struct EventStruct
  212489. {
  212490. pthread_cond_t condition;
  212491. pthread_mutex_t mutex;
  212492. bool triggered;
  212493. };
  212494. WaitableEvent::WaitableEvent() throw()
  212495. {
  212496. EventStruct* const es = new EventStruct();
  212497. es->triggered = false;
  212498. pthread_cond_init (&es->condition, 0);
  212499. pthread_mutex_init (&es->mutex, 0);
  212500. internal = es;
  212501. }
  212502. WaitableEvent::~WaitableEvent() throw()
  212503. {
  212504. EventStruct* const es = (EventStruct*) internal;
  212505. pthread_cond_destroy (&es->condition);
  212506. pthread_mutex_destroy (&es->mutex);
  212507. delete es;
  212508. }
  212509. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  212510. {
  212511. EventStruct* const es = (EventStruct*) internal;
  212512. bool ok = true;
  212513. pthread_mutex_lock (&es->mutex);
  212514. if (timeOutMillisecs < 0)
  212515. {
  212516. while (! es->triggered)
  212517. pthread_cond_wait (&es->condition, &es->mutex);
  212518. }
  212519. else
  212520. {
  212521. while (! es->triggered)
  212522. {
  212523. struct timeval t;
  212524. gettimeofday (&t, 0);
  212525. struct timespec time;
  212526. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  212527. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  212528. if (time.tv_nsec >= 1000000000)
  212529. {
  212530. time.tv_nsec -= 1000000000;
  212531. time.tv_sec++;
  212532. }
  212533. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  212534. {
  212535. ok = false;
  212536. break;
  212537. }
  212538. }
  212539. }
  212540. es->triggered = false;
  212541. pthread_mutex_unlock (&es->mutex);
  212542. return ok;
  212543. }
  212544. void WaitableEvent::signal() const throw()
  212545. {
  212546. EventStruct* const es = (EventStruct*) internal;
  212547. pthread_mutex_lock (&es->mutex);
  212548. es->triggered = true;
  212549. pthread_cond_broadcast (&es->condition);
  212550. pthread_mutex_unlock (&es->mutex);
  212551. }
  212552. void WaitableEvent::reset() const throw()
  212553. {
  212554. EventStruct* const es = (EventStruct*) internal;
  212555. pthread_mutex_lock (&es->mutex);
  212556. es->triggered = false;
  212557. pthread_mutex_unlock (&es->mutex);
  212558. }
  212559. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  212560. {
  212561. struct timespec time;
  212562. time.tv_sec = millisecs / 1000;
  212563. time.tv_nsec = (millisecs % 1000) * 1000000;
  212564. nanosleep (&time, 0);
  212565. }
  212566. const tchar File::separator = T('/');
  212567. const tchar* File::separatorString = T("/");
  212568. bool juce_copyFile (const String& s, const String& d) throw();
  212569. static bool juce_stat (const String& fileName, struct stat& info) throw()
  212570. {
  212571. return fileName.isNotEmpty()
  212572. && (stat (fileName.toUTF8(), &info) == 0);
  212573. }
  212574. bool juce_isDirectory (const String& fileName) throw()
  212575. {
  212576. struct stat info;
  212577. return fileName.isEmpty()
  212578. || (juce_stat (fileName, info)
  212579. && ((info.st_mode & S_IFDIR) != 0));
  212580. }
  212581. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  212582. {
  212583. if (fileName.isEmpty())
  212584. return false;
  212585. const char* const fileNameUTF8 = fileName.toUTF8();
  212586. bool exists = access (fileNameUTF8, F_OK) == 0;
  212587. if (exists && dontCountDirectories)
  212588. {
  212589. struct stat info;
  212590. const int res = stat (fileNameUTF8, &info);
  212591. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  212592. exists = false;
  212593. }
  212594. return exists;
  212595. }
  212596. int64 juce_getFileSize (const String& fileName) throw()
  212597. {
  212598. struct stat info;
  212599. return juce_stat (fileName, info) ? info.st_size : 0;
  212600. }
  212601. bool juce_canWriteToFile (const String& fileName) throw()
  212602. {
  212603. return access (fileName.toUTF8(), W_OK) == 0;
  212604. }
  212605. bool juce_deleteFile (const String& fileName) throw()
  212606. {
  212607. if (juce_isDirectory (fileName))
  212608. return rmdir ((const char*) fileName.toUTF8()) == 0;
  212609. else
  212610. return remove ((const char*) fileName.toUTF8()) == 0;
  212611. }
  212612. bool juce_moveFile (const String& source, const String& dest) throw()
  212613. {
  212614. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  212615. return true;
  212616. if (juce_canWriteToFile (source)
  212617. && juce_copyFile (source, dest))
  212618. {
  212619. if (juce_deleteFile (source))
  212620. return true;
  212621. juce_deleteFile (dest);
  212622. }
  212623. return false;
  212624. }
  212625. void juce_createDirectory (const String& fileName) throw()
  212626. {
  212627. mkdir (fileName.toUTF8(), 0777);
  212628. }
  212629. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  212630. {
  212631. int flags = O_RDONLY;
  212632. if (forWriting)
  212633. {
  212634. if (juce_fileExists (fileName, false))
  212635. {
  212636. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  212637. if (f != -1)
  212638. lseek (f, 0, SEEK_END);
  212639. return (void*) f;
  212640. }
  212641. else
  212642. {
  212643. flags = O_RDWR + O_CREAT;
  212644. }
  212645. }
  212646. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  212647. }
  212648. void juce_fileClose (void* handle) throw()
  212649. {
  212650. if (handle != 0)
  212651. close ((int) (pointer_sized_int) handle);
  212652. }
  212653. int juce_fileRead (void* handle, void* buffer, int size) throw()
  212654. {
  212655. if (handle != 0)
  212656. return read ((int) (pointer_sized_int) handle, buffer, size);
  212657. return 0;
  212658. }
  212659. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  212660. {
  212661. if (handle != 0)
  212662. return write ((int) (pointer_sized_int) handle, buffer, size);
  212663. return 0;
  212664. }
  212665. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  212666. {
  212667. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  212668. return pos;
  212669. return -1;
  212670. }
  212671. int64 juce_fileGetPosition (void* handle) throw()
  212672. {
  212673. if (handle != 0)
  212674. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  212675. else
  212676. return -1;
  212677. }
  212678. void juce_fileFlush (void* handle) throw()
  212679. {
  212680. if (handle != 0)
  212681. fsync ((int) (pointer_sized_int) handle);
  212682. }
  212683. const File juce_getExecutableFile()
  212684. {
  212685. Dl_info exeInfo;
  212686. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  212687. return File (exeInfo.dli_fname);
  212688. }
  212689. // if this file doesn't exist, find a parent of it that does..
  212690. static bool doStatFS (const File* file, struct statfs& result) throw()
  212691. {
  212692. File f (*file);
  212693. for (int i = 5; --i >= 0;)
  212694. {
  212695. if (f.exists())
  212696. break;
  212697. f = f.getParentDirectory();
  212698. }
  212699. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  212700. }
  212701. int64 File::getBytesFreeOnVolume() const throw()
  212702. {
  212703. struct statfs buf;
  212704. if (doStatFS (this, buf))
  212705. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  212706. return 0;
  212707. }
  212708. int64 File::getVolumeTotalSize() const throw()
  212709. {
  212710. struct statfs buf;
  212711. if (doStatFS (this, buf))
  212712. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  212713. return 0;
  212714. }
  212715. const String juce_getVolumeLabel (const String& filenameOnVolume,
  212716. int& volumeSerialNumber) throw()
  212717. {
  212718. volumeSerialNumber = 0;
  212719. #if JUCE_MAC
  212720. struct VolAttrBuf
  212721. {
  212722. u_int32_t length;
  212723. attrreference_t mountPointRef;
  212724. char mountPointSpace [MAXPATHLEN];
  212725. } attrBuf;
  212726. struct attrlist attrList;
  212727. zerostruct (attrList);
  212728. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  212729. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  212730. File f (filenameOnVolume);
  212731. for (;;)
  212732. {
  212733. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  212734. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  212735. {
  212736. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  212737. (int) attrBuf.mountPointRef.attr_length);
  212738. }
  212739. const File parent (f.getParentDirectory());
  212740. if (f == parent)
  212741. break;
  212742. f = parent;
  212743. }
  212744. #endif
  212745. return String::empty;
  212746. }
  212747. void juce_runSystemCommand (const String& command)
  212748. {
  212749. int result = system ((const char*) command.toUTF8());
  212750. (void) result;
  212751. }
  212752. const String juce_getOutputFromCommand (const String& command)
  212753. {
  212754. // slight bodge here, as we just pipe the output into a temp file and read it...
  212755. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  212756. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  212757. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  212758. String result (tempFile.loadFileAsString());
  212759. tempFile.deleteFile();
  212760. return result;
  212761. }
  212762. #if JUCE_64BIT
  212763. #define filedesc ((long long) internal)
  212764. #else
  212765. #define filedesc ((int) internal)
  212766. #endif
  212767. InterProcessLock::InterProcessLock (const String& name_) throw()
  212768. : internal (0),
  212769. name (name_),
  212770. reentrancyLevel (0)
  212771. {
  212772. #if JUCE_MAC
  212773. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  212774. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  212775. #else
  212776. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  212777. #endif
  212778. temp.create();
  212779. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  212780. }
  212781. InterProcessLock::~InterProcessLock() throw()
  212782. {
  212783. while (reentrancyLevel > 0)
  212784. this->exit();
  212785. close (filedesc);
  212786. }
  212787. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  212788. {
  212789. if (internal == 0)
  212790. return false;
  212791. if (reentrancyLevel != 0)
  212792. return true;
  212793. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  212794. struct flock fl;
  212795. zerostruct (fl);
  212796. fl.l_whence = SEEK_SET;
  212797. fl.l_type = F_WRLCK;
  212798. for (;;)
  212799. {
  212800. const int result = fcntl (filedesc, F_SETLK, &fl);
  212801. if (result >= 0)
  212802. {
  212803. ++reentrancyLevel;
  212804. return true;
  212805. }
  212806. if (errno != EINTR)
  212807. {
  212808. if (timeOutMillisecs == 0
  212809. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  212810. break;
  212811. Thread::sleep (10);
  212812. }
  212813. }
  212814. return false;
  212815. }
  212816. void InterProcessLock::exit() throw()
  212817. {
  212818. if (reentrancyLevel > 0 && internal != 0)
  212819. {
  212820. --reentrancyLevel;
  212821. struct flock fl;
  212822. zerostruct (fl);
  212823. fl.l_whence = SEEK_SET;
  212824. fl.l_type = F_UNLCK;
  212825. for (;;)
  212826. {
  212827. const int result = fcntl (filedesc, F_SETLKW, &fl);
  212828. if (result >= 0 || errno != EINTR)
  212829. break;
  212830. }
  212831. }
  212832. }
  212833. /********* End of inlined file: juce_posix_SharedCode.h *********/
  212834. /********* Start of inlined file: juce_linux_Files.cpp *********/
  212835. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212836. // compiled on its own).
  212837. #if JUCE_INCLUDED_FILE
  212838. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  212839. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  212840. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  212841. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  212842. void juce_getFileTimes (const String& fileName,
  212843. int64& modificationTime,
  212844. int64& accessTime,
  212845. int64& creationTime) throw()
  212846. {
  212847. modificationTime = 0;
  212848. accessTime = 0;
  212849. creationTime = 0;
  212850. struct stat info;
  212851. const int res = stat (fileName.toUTF8(), &info);
  212852. if (res == 0)
  212853. {
  212854. modificationTime = (int64) info.st_mtime * 1000;
  212855. accessTime = (int64) info.st_atime * 1000;
  212856. creationTime = (int64) info.st_ctime * 1000;
  212857. }
  212858. }
  212859. bool juce_setFileTimes (const String& fileName,
  212860. int64 modificationTime,
  212861. int64 accessTime,
  212862. int64 creationTime) throw()
  212863. {
  212864. struct utimbuf times;
  212865. times.actime = (time_t) (accessTime / 1000);
  212866. times.modtime = (time_t) (modificationTime / 1000);
  212867. return utime (fileName.toUTF8(), &times) == 0;
  212868. }
  212869. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  212870. {
  212871. struct stat info;
  212872. const int res = stat (fileName.toUTF8(), &info);
  212873. if (res != 0)
  212874. return false;
  212875. info.st_mode &= 0777; // Just permissions
  212876. if( isReadOnly )
  212877. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  212878. else
  212879. // Give everybody write permission?
  212880. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  212881. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  212882. }
  212883. bool juce_copyFile (const String& s, const String& d) throw()
  212884. {
  212885. const File source (s), dest (d);
  212886. FileInputStream* in = source.createInputStream();
  212887. bool ok = false;
  212888. if (in != 0)
  212889. {
  212890. if (dest.deleteFile())
  212891. {
  212892. FileOutputStream* const out = dest.createOutputStream();
  212893. if (out != 0)
  212894. {
  212895. const int bytesCopied = out->writeFromInputStream (*in, -1);
  212896. delete out;
  212897. ok = (bytesCopied == source.getSize());
  212898. if (! ok)
  212899. dest.deleteFile();
  212900. }
  212901. }
  212902. delete in;
  212903. }
  212904. return ok;
  212905. }
  212906. const StringArray juce_getFileSystemRoots() throw()
  212907. {
  212908. StringArray s;
  212909. s.add (T("/"));
  212910. return s;
  212911. }
  212912. bool File::isOnCDRomDrive() const throw()
  212913. {
  212914. struct statfs buf;
  212915. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212916. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  212917. // Assume not if this fails for some reason
  212918. return false;
  212919. }
  212920. bool File::isOnHardDisk() const throw()
  212921. {
  212922. struct statfs buf;
  212923. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212924. {
  212925. switch (buf.f_type)
  212926. {
  212927. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  212928. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  212929. case U_NFS_SUPER_MAGIC: // Network NFS
  212930. case U_SMB_SUPER_MAGIC: // Network Samba
  212931. return false;
  212932. default:
  212933. // Assume anything else is a hard-disk (but note it could
  212934. // be a RAM disk. There isn't a good way of determining
  212935. // this for sure)
  212936. return true;
  212937. }
  212938. }
  212939. // Assume so if this fails for some reason
  212940. return true;
  212941. }
  212942. bool File::isOnRemovableDrive() const throw()
  212943. {
  212944. jassertfalse // xxx not implemented for linux!
  212945. return false;
  212946. }
  212947. bool File::isHidden() const throw()
  212948. {
  212949. return getFileName().startsWithChar (T('.'));
  212950. }
  212951. const File File::getSpecialLocation (const SpecialLocationType type)
  212952. {
  212953. switch (type)
  212954. {
  212955. case userHomeDirectory:
  212956. {
  212957. const char* homeDir = getenv ("HOME");
  212958. if (homeDir == 0)
  212959. {
  212960. struct passwd* const pw = getpwuid (getuid());
  212961. if (pw != 0)
  212962. homeDir = pw->pw_dir;
  212963. }
  212964. return File (String::fromUTF8 ((const uint8*) homeDir));
  212965. }
  212966. case userDocumentsDirectory:
  212967. case userMusicDirectory:
  212968. case userMoviesDirectory:
  212969. case userApplicationDataDirectory:
  212970. return File ("~");
  212971. case userDesktopDirectory:
  212972. return File ("~/Desktop");
  212973. case commonApplicationDataDirectory:
  212974. return File ("/var");
  212975. case globalApplicationsDirectory:
  212976. return File ("/usr");
  212977. case tempDirectory:
  212978. {
  212979. File tmp ("/var/tmp");
  212980. if (! tmp.isDirectory())
  212981. {
  212982. tmp = T("/tmp");
  212983. if (! tmp.isDirectory())
  212984. tmp = File::getCurrentWorkingDirectory();
  212985. }
  212986. return tmp;
  212987. }
  212988. case currentExecutableFile:
  212989. case currentApplicationFile:
  212990. return juce_getExecutableFile();
  212991. default:
  212992. jassertfalse // unknown type?
  212993. break;
  212994. }
  212995. return File::nonexistent;
  212996. }
  212997. const File File::getCurrentWorkingDirectory() throw()
  212998. {
  212999. char buf [2048];
  213000. return File (String::fromUTF8 ((const uint8*) getcwd (buf, sizeof (buf))));
  213001. }
  213002. bool File::setAsCurrentWorkingDirectory() const throw()
  213003. {
  213004. return chdir (getFullPathName().toUTF8()) == 0;
  213005. }
  213006. const String File::getVersion() const throw()
  213007. {
  213008. return String::empty; // xxx not yet implemented
  213009. }
  213010. const File File::getLinkedTarget() const throw()
  213011. {
  213012. char buffer [4096];
  213013. size_t numChars = readlink ((const char*) getFullPathName().toUTF8(),
  213014. buffer, sizeof (buffer));
  213015. if (numChars > 0 && numChars <= sizeof (buffer))
  213016. return File (String::fromUTF8 ((const uint8*) buffer, (int) numChars));
  213017. return *this;
  213018. }
  213019. bool File::moveToTrash() const throw()
  213020. {
  213021. if (! exists())
  213022. return true;
  213023. File trashCan (T("~/.Trash"));
  213024. if (! trashCan.isDirectory())
  213025. trashCan = T("~/.local/share/Trash/files");
  213026. if (! trashCan.isDirectory())
  213027. return false;
  213028. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  213029. getFileExtension()));
  213030. }
  213031. struct FindFileStruct
  213032. {
  213033. String parentDir, wildCard;
  213034. DIR* dir;
  213035. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  213036. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  213037. {
  213038. const char* const wildcardUTF8 = wildCard.toUTF8();
  213039. for (;;)
  213040. {
  213041. struct dirent* const de = readdir (dir);
  213042. if (de == 0)
  213043. break;
  213044. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  213045. {
  213046. result = String::fromUTF8 ((const uint8*) de->d_name);
  213047. const String path (parentDir + result);
  213048. if (isDir != 0 || fileSize != 0)
  213049. {
  213050. struct stat info;
  213051. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  213052. if (isDir != 0)
  213053. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  213054. if (isHidden != 0)
  213055. *isHidden = (de->d_name[0] == '.');
  213056. if (fileSize != 0)
  213057. *fileSize = statOk ? info.st_size : 0;
  213058. }
  213059. if (modTime != 0 || creationTime != 0)
  213060. {
  213061. int64 m, a, c;
  213062. juce_getFileTimes (path, m, a, c);
  213063. if (modTime != 0)
  213064. *modTime = m;
  213065. if (creationTime != 0)
  213066. *creationTime = c;
  213067. }
  213068. if (isReadOnly != 0)
  213069. *isReadOnly = ! juce_canWriteToFile (path);
  213070. return true;
  213071. }
  213072. }
  213073. return false;
  213074. }
  213075. };
  213076. // returns 0 on failure
  213077. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  213078. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  213079. Time* creationTime, bool* isReadOnly) throw()
  213080. {
  213081. DIR* d = opendir (directory.toUTF8());
  213082. if (d != 0)
  213083. {
  213084. FindFileStruct* ff = new FindFileStruct();
  213085. ff->parentDir = directory;
  213086. if (!ff->parentDir.endsWithChar (File::separator))
  213087. ff->parentDir += File::separator;
  213088. ff->wildCard = wildCard;
  213089. if (wildCard == T("*.*"))
  213090. ff->wildCard = T("*");
  213091. ff->dir = d;
  213092. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  213093. {
  213094. return ff;
  213095. }
  213096. else
  213097. {
  213098. firstResultFile = String::empty;
  213099. isDir = false;
  213100. isHidden = false;
  213101. closedir (d);
  213102. delete ff;
  213103. }
  213104. }
  213105. return 0;
  213106. }
  213107. bool juce_findFileNext (void* handle, String& resultFile,
  213108. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  213109. {
  213110. FindFileStruct* const ff = (FindFileStruct*) handle;
  213111. if (ff != 0)
  213112. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  213113. return false;
  213114. }
  213115. void juce_findFileClose (void* handle) throw()
  213116. {
  213117. FindFileStruct* const ff = (FindFileStruct*) handle;
  213118. if (ff != 0)
  213119. {
  213120. closedir (ff->dir);
  213121. delete ff;
  213122. }
  213123. }
  213124. bool juce_launchFile (const String& fileName,
  213125. const String& parameters) throw()
  213126. {
  213127. String cmdString (fileName);
  213128. cmdString << " " << parameters;
  213129. if (URL::isProbablyAWebsiteURL (fileName)
  213130. || URL::isProbablyAnEmailAddress (fileName))
  213131. {
  213132. // create a command that tries to launch a bunch of likely browsers
  213133. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  213134. StringArray cmdLines;
  213135. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  213136. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  213137. cmdString = cmdLines.joinIntoString (T(" || "));
  213138. }
  213139. if (cmdString.startsWithIgnoreCase (T("file:")))
  213140. cmdString = cmdString.substring (5);
  213141. const char* const argv[4] = { "/bin/sh", "-c", (const char*) cmdString.toUTF8(), 0 };
  213142. const int cpid = fork();
  213143. if (cpid == 0)
  213144. {
  213145. setsid();
  213146. // Child process
  213147. execve (argv[0], (char**) argv, environ);
  213148. exit (0);
  213149. }
  213150. return cpid >= 0;
  213151. }
  213152. #endif
  213153. /********* End of inlined file: juce_linux_Files.cpp *********/
  213154. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  213155. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  213156. // compiled on its own).
  213157. #if JUCE_INCLUDED_FILE
  213158. struct NamedPipeInternal
  213159. {
  213160. String pipeInName, pipeOutName;
  213161. int pipeIn, pipeOut;
  213162. bool volatile createdPipe, blocked, stopReadOperation;
  213163. static void signalHandler (int) {}
  213164. };
  213165. void NamedPipe::cancelPendingReads()
  213166. {
  213167. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  213168. {
  213169. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213170. intern->stopReadOperation = true;
  213171. char buffer [1] = { 0 };
  213172. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  213173. (void) bytesWritten;
  213174. int timeout = 2000;
  213175. while (intern->blocked && --timeout >= 0)
  213176. Thread::sleep (2);
  213177. intern->stopReadOperation = false;
  213178. }
  213179. }
  213180. void NamedPipe::close()
  213181. {
  213182. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213183. if (intern != 0)
  213184. {
  213185. internal = 0;
  213186. if (intern->pipeIn != -1)
  213187. ::close (intern->pipeIn);
  213188. if (intern->pipeOut != -1)
  213189. ::close (intern->pipeOut);
  213190. if (intern->createdPipe)
  213191. {
  213192. unlink (intern->pipeInName);
  213193. unlink (intern->pipeOutName);
  213194. }
  213195. delete intern;
  213196. }
  213197. }
  213198. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  213199. {
  213200. close();
  213201. NamedPipeInternal* const intern = new NamedPipeInternal();
  213202. internal = intern;
  213203. intern->createdPipe = createPipe;
  213204. intern->blocked = false;
  213205. intern->stopReadOperation = false;
  213206. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  213207. siginterrupt (SIGPIPE, 1);
  213208. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  213209. intern->pipeInName = pipePath + T("_in");
  213210. intern->pipeOutName = pipePath + T("_out");
  213211. intern->pipeIn = -1;
  213212. intern->pipeOut = -1;
  213213. if (createPipe)
  213214. {
  213215. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  213216. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  213217. {
  213218. delete intern;
  213219. internal = 0;
  213220. return false;
  213221. }
  213222. }
  213223. return true;
  213224. }
  213225. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  213226. {
  213227. int bytesRead = -1;
  213228. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213229. if (intern != 0)
  213230. {
  213231. intern->blocked = true;
  213232. if (intern->pipeIn == -1)
  213233. {
  213234. if (intern->createdPipe)
  213235. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  213236. else
  213237. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  213238. if (intern->pipeIn == -1)
  213239. {
  213240. intern->blocked = false;
  213241. return -1;
  213242. }
  213243. }
  213244. bytesRead = 0;
  213245. char* p = (char*) destBuffer;
  213246. while (bytesRead < maxBytesToRead)
  213247. {
  213248. const int bytesThisTime = maxBytesToRead - bytesRead;
  213249. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  213250. if (numRead <= 0 || intern->stopReadOperation)
  213251. {
  213252. bytesRead = -1;
  213253. break;
  213254. }
  213255. bytesRead += numRead;
  213256. p += bytesRead;
  213257. }
  213258. intern->blocked = false;
  213259. }
  213260. return bytesRead;
  213261. }
  213262. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  213263. {
  213264. int bytesWritten = -1;
  213265. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213266. if (intern != 0)
  213267. {
  213268. if (intern->pipeOut == -1)
  213269. {
  213270. if (intern->createdPipe)
  213271. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  213272. else
  213273. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  213274. if (intern->pipeOut == -1)
  213275. {
  213276. return -1;
  213277. }
  213278. }
  213279. const char* p = (const char*) sourceBuffer;
  213280. bytesWritten = 0;
  213281. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  213282. while (bytesWritten < numBytesToWrite
  213283. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  213284. {
  213285. const int bytesThisTime = numBytesToWrite - bytesWritten;
  213286. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  213287. if (numWritten <= 0)
  213288. {
  213289. bytesWritten = -1;
  213290. break;
  213291. }
  213292. bytesWritten += numWritten;
  213293. p += bytesWritten;
  213294. }
  213295. }
  213296. return bytesWritten;
  213297. }
  213298. #endif
  213299. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  213300. /********* Start of inlined file: juce_linux_Network.cpp *********/
  213301. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213302. // compiled on its own).
  213303. #if JUCE_INCLUDED_FILE
  213304. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  213305. {
  213306. int numResults = 0;
  213307. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  213308. if (s != -1)
  213309. {
  213310. char buf [1024];
  213311. struct ifconf ifc;
  213312. ifc.ifc_len = sizeof (buf);
  213313. ifc.ifc_buf = buf;
  213314. ioctl (s, SIOCGIFCONF, &ifc);
  213315. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  213316. {
  213317. struct ifreq ifr;
  213318. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  213319. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  213320. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  213321. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  213322. && numResults < maxNum)
  213323. {
  213324. int64 a = 0;
  213325. for (int j = 6; --j >= 0;)
  213326. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  213327. *addresses++ = a;
  213328. ++numResults;
  213329. }
  213330. }
  213331. close (s);
  213332. }
  213333. return numResults;
  213334. }
  213335. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  213336. const String& emailSubject,
  213337. const String& bodyText,
  213338. const StringArray& filesToAttach)
  213339. {
  213340. jassertfalse // xxx todo
  213341. return false;
  213342. }
  213343. /** A HTTP input stream that uses sockets.
  213344. */
  213345. class JUCE_HTTPSocketStream
  213346. {
  213347. public:
  213348. JUCE_HTTPSocketStream()
  213349. : readPosition (0),
  213350. socketHandle (-1),
  213351. levelsOfRedirection (0),
  213352. timeoutSeconds (15)
  213353. {
  213354. }
  213355. ~JUCE_HTTPSocketStream()
  213356. {
  213357. closeSocket();
  213358. }
  213359. bool open (const String& url,
  213360. const String& headers,
  213361. const MemoryBlock& postData,
  213362. const bool isPost,
  213363. URL::OpenStreamProgressCallback* callback,
  213364. void* callbackContext,
  213365. int timeOutMs)
  213366. {
  213367. closeSocket();
  213368. uint32 timeOutTime = Time::getMillisecondCounter();
  213369. if (timeOutMs == 0)
  213370. timeOutTime += 60000;
  213371. else if (timeOutMs < 0)
  213372. timeOutTime = 0xffffffff;
  213373. else
  213374. timeOutTime += timeOutMs;
  213375. String hostName, hostPath;
  213376. int hostPort;
  213377. if (! decomposeURL (url, hostName, hostPath, hostPort))
  213378. return false;
  213379. const struct hostent* host = 0;
  213380. int port = 0;
  213381. String proxyName, proxyPath;
  213382. int proxyPort = 0;
  213383. String proxyURL (getenv ("http_proxy"));
  213384. if (proxyURL.startsWithIgnoreCase (T("http://")))
  213385. {
  213386. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  213387. return false;
  213388. host = gethostbyname ((const char*) proxyName.toUTF8());
  213389. port = proxyPort;
  213390. }
  213391. else
  213392. {
  213393. host = gethostbyname ((const char*) hostName.toUTF8());
  213394. port = hostPort;
  213395. }
  213396. if (host == 0)
  213397. return false;
  213398. struct sockaddr_in address;
  213399. zerostruct (address);
  213400. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  213401. address.sin_family = host->h_addrtype;
  213402. address.sin_port = htons (port);
  213403. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  213404. if (socketHandle == -1)
  213405. return false;
  213406. int receiveBufferSize = 16384;
  213407. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  213408. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  213409. #if JUCE_MAC
  213410. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  213411. #endif
  213412. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  213413. {
  213414. closeSocket();
  213415. return false;
  213416. }
  213417. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  213418. proxyName, proxyPort,
  213419. hostPath, url,
  213420. headers, postData,
  213421. isPost));
  213422. int totalHeaderSent = 0;
  213423. while (totalHeaderSent < requestHeader.getSize())
  213424. {
  213425. if (Time::getMillisecondCounter() > timeOutTime)
  213426. {
  213427. closeSocket();
  213428. return false;
  213429. }
  213430. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  213431. if (send (socketHandle,
  213432. ((const char*) requestHeader.getData()) + totalHeaderSent,
  213433. numToSend, 0)
  213434. != numToSend)
  213435. {
  213436. closeSocket();
  213437. return false;
  213438. }
  213439. totalHeaderSent += numToSend;
  213440. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  213441. {
  213442. closeSocket();
  213443. return false;
  213444. }
  213445. }
  213446. const String responseHeader (readResponse (timeOutTime));
  213447. if (responseHeader.isNotEmpty())
  213448. {
  213449. //DBG (responseHeader);
  213450. StringArray lines;
  213451. lines.addLines (responseHeader);
  213452. // NB - using charToString() here instead of just T(" "), because that was
  213453. // causing a mysterious gcc internal compiler error...
  213454. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  213455. .substring (0, 3).getIntValue();
  213456. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  213457. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  213458. String location (findHeaderItem (lines, T("Location:")));
  213459. if (statusCode >= 300 && statusCode < 400
  213460. && location.isNotEmpty())
  213461. {
  213462. if (! location.startsWithIgnoreCase (T("http://")))
  213463. location = T("http://") + location;
  213464. if (levelsOfRedirection++ < 3)
  213465. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  213466. }
  213467. else
  213468. {
  213469. levelsOfRedirection = 0;
  213470. return true;
  213471. }
  213472. }
  213473. closeSocket();
  213474. return false;
  213475. }
  213476. int read (void* buffer, int bytesToRead)
  213477. {
  213478. fd_set readbits;
  213479. FD_ZERO (&readbits);
  213480. FD_SET (socketHandle, &readbits);
  213481. struct timeval tv;
  213482. tv.tv_sec = timeoutSeconds;
  213483. tv.tv_usec = 0;
  213484. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213485. return 0; // (timeout)
  213486. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  213487. readPosition += bytesRead;
  213488. return bytesRead;
  213489. }
  213490. int readPosition;
  213491. juce_UseDebuggingNewOperator
  213492. private:
  213493. int socketHandle, levelsOfRedirection;
  213494. const int timeoutSeconds;
  213495. void closeSocket()
  213496. {
  213497. if (socketHandle >= 0)
  213498. close (socketHandle);
  213499. socketHandle = -1;
  213500. }
  213501. const MemoryBlock createRequestHeader (const String& hostName,
  213502. const int hostPort,
  213503. const String& proxyName,
  213504. const int proxyPort,
  213505. const String& hostPath,
  213506. const String& originalURL,
  213507. const String& headers,
  213508. const MemoryBlock& postData,
  213509. const bool isPost)
  213510. {
  213511. String header (isPost ? "POST " : "GET ");
  213512. if (proxyName.isEmpty())
  213513. {
  213514. header << hostPath << " HTTP/1.0\r\nHost: "
  213515. << hostName << ':' << hostPort;
  213516. }
  213517. else
  213518. {
  213519. header << originalURL << " HTTP/1.0\r\nHost: "
  213520. << proxyName << ':' << proxyPort;
  213521. }
  213522. header << "\r\nUser-Agent: JUCE/"
  213523. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  213524. << "\r\nConnection: Close\r\nContent-Length: "
  213525. << postData.getSize() << "\r\n"
  213526. << headers << "\r\n";
  213527. MemoryBlock mb;
  213528. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  213529. mb.append (postData.getData(), postData.getSize());
  213530. return mb;
  213531. }
  213532. const String readResponse (const uint32 timeOutTime)
  213533. {
  213534. int bytesRead = 0, numConsecutiveLFs = 0;
  213535. MemoryBlock buffer (1024, true);
  213536. while (numConsecutiveLFs < 2 && bytesRead < 32768
  213537. && Time::getMillisecondCounter() <= timeOutTime)
  213538. {
  213539. fd_set readbits;
  213540. FD_ZERO (&readbits);
  213541. FD_SET (socketHandle, &readbits);
  213542. struct timeval tv;
  213543. tv.tv_sec = timeoutSeconds;
  213544. tv.tv_usec = 0;
  213545. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213546. return String::empty; // (timeout)
  213547. buffer.ensureSize (bytesRead + 8, true);
  213548. char* const dest = (char*) buffer.getData() + bytesRead;
  213549. if (recv (socketHandle, dest, 1, 0) == -1)
  213550. return String::empty;
  213551. const char lastByte = *dest;
  213552. ++bytesRead;
  213553. if (lastByte == '\n')
  213554. ++numConsecutiveLFs;
  213555. else if (lastByte != '\r')
  213556. numConsecutiveLFs = 0;
  213557. }
  213558. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  213559. if (header.startsWithIgnoreCase (T("HTTP/")))
  213560. return header.trimEnd();
  213561. return String::empty;
  213562. }
  213563. static bool decomposeURL (const String& url,
  213564. String& host, String& path, int& port)
  213565. {
  213566. if (! url.startsWithIgnoreCase (T("http://")))
  213567. return false;
  213568. const int nextSlash = url.indexOfChar (7, '/');
  213569. int nextColon = url.indexOfChar (7, ':');
  213570. if (nextColon > nextSlash && nextSlash > 0)
  213571. nextColon = -1;
  213572. if (nextColon >= 0)
  213573. {
  213574. host = url.substring (7, nextColon);
  213575. if (nextSlash >= 0)
  213576. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  213577. else
  213578. port = url.substring (nextColon + 1).getIntValue();
  213579. }
  213580. else
  213581. {
  213582. port = 80;
  213583. if (nextSlash >= 0)
  213584. host = url.substring (7, nextSlash);
  213585. else
  213586. host = url.substring (7);
  213587. }
  213588. if (nextSlash >= 0)
  213589. path = url.substring (nextSlash);
  213590. else
  213591. path = T("/");
  213592. return true;
  213593. }
  213594. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  213595. {
  213596. for (int i = 0; i < lines.size(); ++i)
  213597. if (lines[i].startsWithIgnoreCase (itemName))
  213598. return lines[i].substring (itemName.length()).trim();
  213599. return String::empty;
  213600. }
  213601. };
  213602. bool juce_isOnLine()
  213603. {
  213604. return true;
  213605. }
  213606. void* juce_openInternetFile (const String& url,
  213607. const String& headers,
  213608. const MemoryBlock& postData,
  213609. const bool isPost,
  213610. URL::OpenStreamProgressCallback* callback,
  213611. void* callbackContext,
  213612. int timeOutMs)
  213613. {
  213614. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  213615. if (s->open (url, headers, postData, isPost,
  213616. callback, callbackContext, timeOutMs))
  213617. return s;
  213618. delete s;
  213619. return 0;
  213620. }
  213621. void juce_closeInternetFile (void* handle)
  213622. {
  213623. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213624. if (s != 0)
  213625. delete s;
  213626. }
  213627. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  213628. {
  213629. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213630. if (s != 0)
  213631. return s->read (buffer, bytesToRead);
  213632. return 0;
  213633. }
  213634. int64 juce_getInternetFileContentLength (void* handle)
  213635. {
  213636. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213637. if (s != 0)
  213638. {
  213639. //xxx todo
  213640. jassertfalse
  213641. }
  213642. return -1;
  213643. }
  213644. int juce_seekInInternetFile (void* handle, int newPosition)
  213645. {
  213646. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213647. if (s != 0)
  213648. return s->readPosition;
  213649. return 0;
  213650. }
  213651. #endif
  213652. /********* End of inlined file: juce_linux_Network.cpp *********/
  213653. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  213654. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213655. // compiled on its own).
  213656. #if JUCE_INCLUDED_FILE
  213657. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  213658. {
  213659. unsigned int cpu = 0;
  213660. unsigned int ext = 0;
  213661. unsigned int family = 0;
  213662. unsigned int dummy = 0;
  213663. #if JUCE_64BIT
  213664. __asm__ ("cpuid"
  213665. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213666. #else
  213667. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  213668. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213669. #endif
  213670. if (familyModel != 0)
  213671. *familyModel = family;
  213672. if (extFeatures != 0)
  213673. *extFeatures = ext;
  213674. return cpu;
  213675. }*/
  213676. void Logger::outputDebugString (const String& text) throw()
  213677. {
  213678. fputs (text.toUTF8(), stdout);
  213679. fputs ("\n", stdout);
  213680. }
  213681. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  213682. {
  213683. String text;
  213684. va_list args;
  213685. va_start (args, format);
  213686. text.vprintf(format, args);
  213687. outputDebugString(text);
  213688. }
  213689. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  213690. {
  213691. return Linux;
  213692. }
  213693. const String SystemStats::getOperatingSystemName() throw()
  213694. {
  213695. return T("Linux");
  213696. }
  213697. bool SystemStats::isOperatingSystem64Bit() throw()
  213698. {
  213699. #if JUCE_64BIT
  213700. return true;
  213701. #else
  213702. //xxx not sure how to find this out?..
  213703. return false;
  213704. #endif
  213705. }
  213706. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  213707. {
  213708. String info;
  213709. char buf [256];
  213710. FILE* f = fopen ("/proc/cpuinfo", "r");
  213711. while (f != 0 && fgets (buf, sizeof(buf), f))
  213712. {
  213713. if (strncmp (buf, key, strlen (key)) == 0)
  213714. {
  213715. char* p = buf;
  213716. while (*p && *p != '\n')
  213717. ++p;
  213718. if (*p != 0)
  213719. *p = 0;
  213720. p = buf;
  213721. while (*p != 0 && *p != ':')
  213722. ++p;
  213723. if (*p != 0 && *(p + 1) != 0)
  213724. info = p + 2;
  213725. if (! lastOne)
  213726. break;
  213727. }
  213728. }
  213729. fclose (f);
  213730. return info;
  213731. }
  213732. bool SystemStats::hasMMX() throw()
  213733. {
  213734. return getCpuInfo ("flags").contains (T("mmx"));
  213735. }
  213736. bool SystemStats::hasSSE() throw()
  213737. {
  213738. return getCpuInfo ("flags").contains (T("sse"));
  213739. }
  213740. bool SystemStats::hasSSE2() throw()
  213741. {
  213742. return getCpuInfo ("flags").contains (T("sse2"));
  213743. }
  213744. bool SystemStats::has3DNow() throw()
  213745. {
  213746. return getCpuInfo ("flags").contains (T("3dnow"));
  213747. }
  213748. const String SystemStats::getCpuVendor() throw()
  213749. {
  213750. return getCpuInfo ("vendor_id");
  213751. }
  213752. int SystemStats::getCpuSpeedInMegaherz() throw()
  213753. {
  213754. const String speed (getCpuInfo ("cpu MHz"));
  213755. return (int) (speed.getFloatValue() + 0.5f);
  213756. }
  213757. int SystemStats::getMemorySizeInMegabytes() throw()
  213758. {
  213759. struct sysinfo sysi;
  213760. if (sysinfo (&sysi) == 0)
  213761. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  213762. return 0;
  213763. }
  213764. uint32 juce_millisecondsSinceStartup() throw()
  213765. {
  213766. static unsigned int calibrate = 0;
  213767. static bool calibrated = false;
  213768. timeval t;
  213769. unsigned int ret = 0;
  213770. if (! gettimeofday (&t, 0))
  213771. {
  213772. if (! calibrated)
  213773. {
  213774. struct sysinfo sysi;
  213775. if (sysinfo (&sysi) == 0)
  213776. // Safe to assume system was not brought up earlier than 1970!
  213777. calibrate = t.tv_sec - sysi.uptime;
  213778. calibrated = true;
  213779. }
  213780. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  213781. }
  213782. return ret;
  213783. }
  213784. double Time::getMillisecondCounterHiRes() throw()
  213785. {
  213786. return getHighResolutionTicks() * 0.001;
  213787. }
  213788. int64 Time::getHighResolutionTicks() throw()
  213789. {
  213790. timeval t;
  213791. if (gettimeofday (&t, 0))
  213792. return 0;
  213793. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  213794. }
  213795. int64 Time::getHighResolutionTicksPerSecond() throw()
  213796. {
  213797. // Microseconds
  213798. return 1000000;
  213799. }
  213800. bool Time::setSystemTimeToThisTime() const throw()
  213801. {
  213802. timeval t;
  213803. t.tv_sec = millisSinceEpoch % 1000000;
  213804. t.tv_usec = millisSinceEpoch - t.tv_sec;
  213805. return settimeofday (&t, NULL) ? false : true;
  213806. }
  213807. int SystemStats::getPageSize() throw()
  213808. {
  213809. static int systemPageSize = 0;
  213810. if (systemPageSize == 0)
  213811. systemPageSize = sysconf (_SC_PAGESIZE);
  213812. return systemPageSize;
  213813. }
  213814. int SystemStats::getNumCpus() throw()
  213815. {
  213816. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  213817. return lastCpu + 1;
  213818. }
  213819. void SystemStats::initialiseStats() throw()
  213820. {
  213821. // Process starts off as root when running suid
  213822. Process::lowerPrivilege();
  213823. String s (SystemStats::getJUCEVersion());
  213824. }
  213825. void PlatformUtilities::fpuReset()
  213826. {
  213827. }
  213828. #endif
  213829. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  213830. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  213831. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213832. // compiled on its own).
  213833. #if JUCE_INCLUDED_FILE
  213834. /*
  213835. Note that a lot of methods that you'd expect to find in this file actually
  213836. live in juce_posix_SharedCode.h!
  213837. */
  213838. void JUCE_API juce_threadEntryPoint (void*);
  213839. void* threadEntryProc (void* value) throw()
  213840. {
  213841. // New threads start off as root when running suid
  213842. Process::lowerPrivilege();
  213843. juce_threadEntryPoint (value);
  213844. return 0;
  213845. }
  213846. void* juce_createThread (void* userData) throw()
  213847. {
  213848. pthread_t handle = 0;
  213849. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  213850. {
  213851. pthread_detach (handle);
  213852. return (void*)handle;
  213853. }
  213854. return 0;
  213855. }
  213856. void juce_killThread (void* handle) throw()
  213857. {
  213858. if (handle != 0)
  213859. pthread_cancel ((pthread_t)handle);
  213860. }
  213861. void juce_setCurrentThreadName (const String& /*name*/) throw()
  213862. {
  213863. }
  213864. Thread::ThreadID Thread::getCurrentThreadId() throw()
  213865. {
  213866. return (ThreadID) pthread_self();
  213867. }
  213868. /*
  213869. * This is all a bit non-ideal... the trouble is that on Linux you
  213870. * need to call setpriority to affect the dynamic priority for
  213871. * non-realtime processes, but this requires the pid, which is not
  213872. * accessible from the pthread_t. We could get it by calling getpid
  213873. * once each thread has started, but then we would need a list of
  213874. * running threads etc etc.
  213875. * Also there is no such thing as IDLE priority on Linux.
  213876. * For the moment, map idle, low and normal process priorities to
  213877. * SCHED_OTHER, with the thread priority ignored for these classes.
  213878. * Map high priority processes to the lower half of the SCHED_RR
  213879. * range, and realtime to the upper half
  213880. */
  213881. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  213882. // priority of the current thread
  213883. bool juce_setThreadPriority (void* handle, int priority) throw()
  213884. {
  213885. struct sched_param param;
  213886. int policy, maxp, minp, pri;
  213887. if (handle == 0)
  213888. handle = (void*) pthread_self();
  213889. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  213890. && policy != SCHED_OTHER)
  213891. {
  213892. minp = sched_get_priority_min(policy);
  213893. maxp = sched_get_priority_max(policy);
  213894. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  213895. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  213896. // Realtime process priority
  213897. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  213898. else
  213899. // High process priority
  213900. param.__sched_priority = minp + pri;
  213901. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  213902. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  213903. }
  213904. return false;
  213905. }
  213906. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  213907. {
  213908. #if SUPPORT_AFFINITIES
  213909. cpu_set_t affinity;
  213910. CPU_ZERO (&affinity);
  213911. for (int i = 0; i < 32; ++i)
  213912. if ((affinityMask & (1 << i)) != 0)
  213913. CPU_SET (i, &affinity);
  213914. /*
  213915. N.B. If this line causes a compile error, then you've probably not got the latest
  213916. version of glibc installed.
  213917. If you don't want to update your copy of glibc and don't care about cpu affinities,
  213918. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  213919. from the linuxincludes.h file.
  213920. */
  213921. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  213922. sched_yield();
  213923. #else
  213924. /* affinities aren't supported because either the appropriate header files weren't found,
  213925. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  213926. */
  213927. jassertfalse
  213928. #endif
  213929. }
  213930. void Thread::yield() throw()
  213931. {
  213932. sched_yield();
  213933. }
  213934. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  213935. void Process::setPriority (ProcessPriority prior)
  213936. {
  213937. struct sched_param param;
  213938. int policy, maxp, minp;
  213939. const int p = (int) prior;
  213940. if (p <= 1)
  213941. policy = SCHED_OTHER;
  213942. else
  213943. policy = SCHED_RR;
  213944. minp = sched_get_priority_min (policy);
  213945. maxp = sched_get_priority_max (policy);
  213946. if (p < 2)
  213947. param.__sched_priority = 0;
  213948. else if (p == 2 )
  213949. // Set to middle of lower realtime priority range
  213950. param.__sched_priority = minp + (maxp - minp) / 4;
  213951. else
  213952. // Set to middle of higher realtime priority range
  213953. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  213954. pthread_setschedparam (pthread_self(), policy, &param);
  213955. }
  213956. void Process::terminate()
  213957. {
  213958. exit (0);
  213959. }
  213960. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  213961. {
  213962. static char testResult = 0;
  213963. if (testResult == 0)
  213964. {
  213965. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  213966. if (testResult >= 0)
  213967. {
  213968. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  213969. testResult = 1;
  213970. }
  213971. }
  213972. return testResult < 0;
  213973. }
  213974. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  213975. {
  213976. return juce_isRunningUnderDebugger();
  213977. }
  213978. void Process::raisePrivilege()
  213979. {
  213980. // If running suid root, change effective user
  213981. // to root
  213982. if (geteuid() != 0 && getuid() == 0)
  213983. {
  213984. setreuid (geteuid(), getuid());
  213985. setregid (getegid(), getgid());
  213986. }
  213987. }
  213988. void Process::lowerPrivilege()
  213989. {
  213990. // If runing suid root, change effective user
  213991. // back to real user
  213992. if (geteuid() == 0 && getuid() != 0)
  213993. {
  213994. setreuid (geteuid(), getuid());
  213995. setregid (getegid(), getgid());
  213996. }
  213997. }
  213998. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213999. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  214000. {
  214001. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  214002. }
  214003. void PlatformUtilities::freeDynamicLibrary (void* handle)
  214004. {
  214005. dlclose(handle);
  214006. }
  214007. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  214008. {
  214009. return dlsym (libraryHandle, (const char*) procedureName);
  214010. }
  214011. #endif
  214012. #endif
  214013. /********* End of inlined file: juce_linux_Threads.cpp *********/
  214014. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  214015. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  214016. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214017. // compiled on its own).
  214018. #if JUCE_INCLUDED_FILE
  214019. #ifdef JUCE_DEBUG
  214020. #define JUCE_DEBUG_XERRORS 1
  214021. #endif
  214022. Display* display = 0; // This is also referenced from WindowDriver.cpp
  214023. static Window juce_messageWindowHandle = None;
  214024. #define SpecialAtom "JUCESpecialAtom"
  214025. #define BroadcastAtom "JUCEBroadcastAtom"
  214026. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  214027. static Atom specialId;
  214028. static Atom broadcastId;
  214029. static Atom specialCallbackId;
  214030. // This is referenced from WindowDriver.cpp
  214031. XContext improbableNumber;
  214032. // Defined in WindowDriver.cpp
  214033. extern void juce_windowMessageReceive (XEvent* event);
  214034. struct MessageThreadFuncCall
  214035. {
  214036. MessageCallbackFunction* func;
  214037. void* parameter;
  214038. void* result;
  214039. CriticalSection lock;
  214040. WaitableEvent event;
  214041. };
  214042. static bool errorCondition = false;
  214043. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  214044. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  214045. // (defined in another file to avoid problems including certain headers in this one)
  214046. extern bool juce_isRunningAsApplication();
  214047. // Usually happens when client-server connection is broken
  214048. static int ioErrorHandler (Display* display)
  214049. {
  214050. DBG (T("ERROR: connection to X server broken.. terminating."));
  214051. errorCondition = true;
  214052. if (juce_isRunningAsApplication())
  214053. Process::terminate();
  214054. return 0;
  214055. }
  214056. // A protocol error has occurred
  214057. static int errorHandler (Display* display, XErrorEvent* event)
  214058. {
  214059. #ifdef JUCE_DEBUG_XERRORS
  214060. char errorStr[64] = { 0 };
  214061. char requestStr[64] = { 0 };
  214062. XGetErrorText (display, event->error_code, errorStr, 64);
  214063. XGetErrorDatabaseText (display,
  214064. "XRequest",
  214065. (const char*) String (event->request_code),
  214066. "Unknown",
  214067. requestStr,
  214068. 64);
  214069. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  214070. #endif
  214071. return 0;
  214072. }
  214073. static bool breakIn = false;
  214074. // Breakin from keyboard
  214075. static void sig_handler (int sig)
  214076. {
  214077. if (sig == SIGINT)
  214078. {
  214079. breakIn = true;
  214080. return;
  214081. }
  214082. static bool reentrant = false;
  214083. if (reentrant == false)
  214084. {
  214085. reentrant = true;
  214086. // Illegal instruction
  214087. fflush (stdout);
  214088. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  214089. errorCondition = true;
  214090. if (juce_isRunningAsApplication())
  214091. Process::terminate();
  214092. }
  214093. else
  214094. {
  214095. if (juce_isRunningAsApplication())
  214096. exit(0);
  214097. }
  214098. }
  214099. void MessageManager::doPlatformSpecificInitialisation()
  214100. {
  214101. // Initialise xlib for multiple thread support
  214102. static bool initThreadCalled = false;
  214103. if (! initThreadCalled)
  214104. {
  214105. if (! XInitThreads())
  214106. {
  214107. // This is fatal! Print error and closedown
  214108. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  214109. if (juce_isRunningAsApplication())
  214110. Process::terminate();
  214111. return;
  214112. }
  214113. initThreadCalled = true;
  214114. }
  214115. // This is called if the client/server connection is broken
  214116. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  214117. // This is called if a protocol error occurs
  214118. oldErrorHandler = XSetErrorHandler (errorHandler);
  214119. // Install signal handler for break-in
  214120. struct sigaction saction;
  214121. sigset_t maskSet;
  214122. sigemptyset (&maskSet);
  214123. saction.sa_handler = sig_handler;
  214124. saction.sa_mask = maskSet;
  214125. saction.sa_flags = 0;
  214126. sigaction (SIGINT, &saction, NULL);
  214127. #ifndef _DEBUG
  214128. // Setup signal handlers for various fatal errors
  214129. sigaction (SIGILL, &saction, NULL);
  214130. sigaction (SIGBUS, &saction, NULL);
  214131. sigaction (SIGFPE, &saction, NULL);
  214132. sigaction (SIGSEGV, &saction, NULL);
  214133. sigaction (SIGSYS, &saction, NULL);
  214134. #endif
  214135. String displayName (getenv ("DISPLAY"));
  214136. if (displayName.isEmpty())
  214137. displayName = T(":0.0");
  214138. display = XOpenDisplay (displayName);
  214139. if (display == 0)
  214140. {
  214141. // This is fatal! Print error and closedown
  214142. Logger::outputDebugString ("Failed to open the X display.");
  214143. if (juce_isRunningAsApplication())
  214144. Process::terminate();
  214145. return;
  214146. }
  214147. // Get defaults for various properties
  214148. int screen = DefaultScreen (display);
  214149. Window root = RootWindow (display, screen);
  214150. Visual* visual = DefaultVisual (display, screen);
  214151. // Create atoms for our ClientMessages (these cannot be deleted)
  214152. specialId = XInternAtom (display, SpecialAtom, false);
  214153. broadcastId = XInternAtom (display, BroadcastAtom, false);
  214154. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  214155. // Create a context to store user data associated with Windows we
  214156. // create in WindowDriver
  214157. improbableNumber = XUniqueContext();
  214158. // We're only interested in client messages for this window
  214159. // which are always sent
  214160. XSetWindowAttributes swa;
  214161. swa.event_mask = NoEventMask;
  214162. // Create our message window (this will never be mapped)
  214163. juce_messageWindowHandle = XCreateWindow (display, root,
  214164. 0, 0, 1, 1, 0, 0, InputOnly,
  214165. visual, CWEventMask, &swa);
  214166. }
  214167. void MessageManager::doPlatformSpecificShutdown()
  214168. {
  214169. if (errorCondition == false)
  214170. {
  214171. XDestroyWindow (display, juce_messageWindowHandle);
  214172. XCloseDisplay (display);
  214173. // reset pointers
  214174. juce_messageWindowHandle = 0;
  214175. display = 0;
  214176. // Restore original error handlers
  214177. XSetIOErrorHandler (oldIOErrorHandler);
  214178. oldIOErrorHandler = 0;
  214179. XSetErrorHandler (oldErrorHandler);
  214180. oldErrorHandler = 0;
  214181. }
  214182. }
  214183. bool juce_postMessageToSystemQueue (void* message)
  214184. {
  214185. if (errorCondition)
  214186. return false;
  214187. XClientMessageEvent clientMsg;
  214188. clientMsg.display = display;
  214189. clientMsg.window = juce_messageWindowHandle;
  214190. clientMsg.type = ClientMessage;
  214191. clientMsg.format = 32;
  214192. clientMsg.message_type = specialId;
  214193. #if JUCE_64BIT
  214194. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  214195. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  214196. #else
  214197. clientMsg.data.l[0] = (long) message;
  214198. #endif
  214199. XSendEvent (display, juce_messageWindowHandle, false,
  214200. NoEventMask, (XEvent*) &clientMsg);
  214201. XFlush (display); // This is necessary to ensure the event is delivered
  214202. return true;
  214203. }
  214204. void MessageManager::broadcastMessage (const String& value) throw()
  214205. {
  214206. }
  214207. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  214208. void* parameter)
  214209. {
  214210. void* retVal = 0;
  214211. if (! errorCondition)
  214212. {
  214213. if (! isThisTheMessageThread())
  214214. {
  214215. static MessageThreadFuncCall messageFuncCallContext;
  214216. const ScopedLock sl (messageFuncCallContext.lock);
  214217. XClientMessageEvent clientMsg;
  214218. clientMsg.display = display;
  214219. clientMsg.window = juce_messageWindowHandle;
  214220. clientMsg.type = ClientMessage;
  214221. clientMsg.format = 32;
  214222. clientMsg.message_type = specialCallbackId;
  214223. #if JUCE_64BIT
  214224. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  214225. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  214226. #else
  214227. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  214228. #endif
  214229. messageFuncCallContext.func = func;
  214230. messageFuncCallContext.parameter = parameter;
  214231. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  214232. return 0;
  214233. XFlush (display); // This is necessary to ensure the event is delivered
  214234. // Wait for it to complete before continuing
  214235. messageFuncCallContext.event.wait();
  214236. retVal = messageFuncCallContext.result;
  214237. }
  214238. else
  214239. {
  214240. // Just call the function directly
  214241. retVal = func (parameter);
  214242. }
  214243. }
  214244. return retVal;
  214245. }
  214246. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  214247. {
  214248. if (errorCondition)
  214249. return false;
  214250. if (breakIn)
  214251. {
  214252. errorCondition = true;
  214253. if (juce_isRunningAsApplication())
  214254. Process::terminate();
  214255. return false;
  214256. }
  214257. if (returnIfNoPendingMessages && ! XPending (display))
  214258. return false;
  214259. XEvent evt;
  214260. XNextEvent (display, &evt);
  214261. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  214262. {
  214263. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  214264. if (clientMsg->format != 32)
  214265. {
  214266. jassertfalse
  214267. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  214268. }
  214269. else
  214270. {
  214271. JUCE_TRY
  214272. {
  214273. #if JUCE_64BIT
  214274. void* const messagePtr
  214275. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  214276. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  214277. #else
  214278. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  214279. #endif
  214280. if (clientMsg->message_type == specialId)
  214281. {
  214282. MessageManager::getInstance()->deliverMessage (messagePtr);
  214283. }
  214284. else if (clientMsg->message_type == specialCallbackId)
  214285. {
  214286. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  214287. MessageCallbackFunction* func = call->func;
  214288. call->result = (*func) (call->parameter);
  214289. call->event.signal();
  214290. }
  214291. else if (clientMsg->message_type == broadcastId)
  214292. {
  214293. #if 0
  214294. TCHAR buffer[8192];
  214295. zeromem (buffer, sizeof (buffer));
  214296. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  214297. mq->deliverBroadcastMessage (String (buffer));
  214298. #endif
  214299. }
  214300. else
  214301. {
  214302. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  214303. }
  214304. }
  214305. JUCE_CATCH_ALL
  214306. }
  214307. }
  214308. else if (evt.xany.window != juce_messageWindowHandle)
  214309. {
  214310. juce_windowMessageReceive (&evt);
  214311. }
  214312. return true;
  214313. }
  214314. #endif
  214315. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  214316. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  214317. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214318. // compiled on its own).
  214319. #if JUCE_INCLUDED_FILE
  214320. class FreeTypeFontFace
  214321. {
  214322. public:
  214323. enum FontStyle
  214324. {
  214325. Plain = 0,
  214326. Bold = 1,
  214327. Italic = 2
  214328. };
  214329. struct FontNameIndex
  214330. {
  214331. String fileName;
  214332. int faceIndex;
  214333. };
  214334. FreeTypeFontFace (const String& familyName)
  214335. : hasSerif (false),
  214336. monospaced (false)
  214337. {
  214338. family = familyName;
  214339. }
  214340. void setFileName (const String& name,
  214341. const int faceIndex,
  214342. FontStyle style)
  214343. {
  214344. if (names[(int) style].fileName.isEmpty())
  214345. {
  214346. names[(int) style].fileName = name;
  214347. names[(int) style].faceIndex = faceIndex;
  214348. }
  214349. }
  214350. const String& getFamilyName() const throw()
  214351. {
  214352. return family;
  214353. }
  214354. const String& getFileName (int style, int* faceIndex) const throw()
  214355. {
  214356. *faceIndex = names [style].faceIndex;
  214357. return names[style].fileName;
  214358. }
  214359. void setMonospaced (bool mono) { monospaced = mono; }
  214360. bool getMonospaced () const throw() { return monospaced; }
  214361. void setSerif (const bool serif) { hasSerif = serif; }
  214362. bool getSerif () const throw() { return hasSerif; }
  214363. private:
  214364. String family;
  214365. FontNameIndex names[4];
  214366. bool hasSerif, monospaced;
  214367. };
  214368. class FreeTypeInterface : public DeletedAtShutdown
  214369. {
  214370. public:
  214371. FreeTypeInterface() throw()
  214372. : lastFace (0),
  214373. lastBold (false),
  214374. lastItalic (false)
  214375. {
  214376. if (FT_Init_FreeType (&ftLib) != 0)
  214377. {
  214378. ftLib = 0;
  214379. DBG (T("Failed to initialize FreeType"));
  214380. }
  214381. StringArray fontDirs;
  214382. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  214383. fontDirs.removeEmptyStrings (true);
  214384. if (fontDirs.size() == 0)
  214385. {
  214386. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  214387. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  214388. if (fontsInfo != 0)
  214389. {
  214390. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  214391. {
  214392. fontDirs.add (e->getAllSubText().trim());
  214393. }
  214394. delete fontsInfo;
  214395. }
  214396. }
  214397. if (fontDirs.size() == 0)
  214398. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  214399. for (int i = 0; i < fontDirs.size(); ++i)
  214400. enumerateFaces (fontDirs[i]);
  214401. }
  214402. ~FreeTypeInterface() throw()
  214403. {
  214404. if (lastFace != 0)
  214405. FT_Done_Face (lastFace);
  214406. if (ftLib != 0)
  214407. FT_Done_FreeType (ftLib);
  214408. clearSingletonInstance();
  214409. }
  214410. FreeTypeFontFace* findOrCreate (const String& familyName,
  214411. const bool create = false) throw()
  214412. {
  214413. for (int i = 0; i < faces.size(); i++)
  214414. if (faces[i]->getFamilyName() == familyName)
  214415. return faces[i];
  214416. if (! create)
  214417. return NULL;
  214418. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  214419. faces.add (newFace);
  214420. return newFace;
  214421. }
  214422. // Enumerate all font faces available in a given directory
  214423. void enumerateFaces (const String& path) throw()
  214424. {
  214425. File dirPath (path);
  214426. if (path.isEmpty() || ! dirPath.isDirectory())
  214427. return;
  214428. DirectoryIterator di (dirPath, true);
  214429. while (di.next())
  214430. {
  214431. File possible (di.getFile());
  214432. if (possible.hasFileExtension (T("ttf"))
  214433. || possible.hasFileExtension (T("pfb"))
  214434. || possible.hasFileExtension (T("pcf")))
  214435. {
  214436. FT_Face face;
  214437. int faceIndex = 0;
  214438. int numFaces = 0;
  214439. do
  214440. {
  214441. if (FT_New_Face (ftLib,
  214442. possible.getFullPathName(),
  214443. faceIndex,
  214444. &face) == 0)
  214445. {
  214446. if (faceIndex == 0)
  214447. numFaces = face->num_faces;
  214448. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  214449. {
  214450. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  214451. int style = (int) FreeTypeFontFace::Plain;
  214452. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  214453. style |= (int) FreeTypeFontFace::Bold;
  214454. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  214455. style |= (int) FreeTypeFontFace::Italic;
  214456. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  214457. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  214458. newFace->setMonospaced (true);
  214459. else
  214460. newFace->setMonospaced (false);
  214461. // Surely there must be a better way to do this?
  214462. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  214463. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  214464. || String (face->family_name).containsIgnoreCase (T("Arial")))
  214465. {
  214466. newFace->setSerif (false);
  214467. }
  214468. else
  214469. {
  214470. newFace->setSerif (true);
  214471. }
  214472. }
  214473. FT_Done_Face (face);
  214474. }
  214475. ++faceIndex;
  214476. }
  214477. while (faceIndex < numFaces);
  214478. }
  214479. }
  214480. }
  214481. // Create a FreeType face object for a given font
  214482. FT_Face createFT_Face (const String& fontName,
  214483. const bool bold,
  214484. const bool italic) throw()
  214485. {
  214486. FT_Face face = NULL;
  214487. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  214488. {
  214489. face = lastFace;
  214490. }
  214491. else
  214492. {
  214493. if (lastFace)
  214494. {
  214495. FT_Done_Face (lastFace);
  214496. lastFace = NULL;
  214497. }
  214498. lastFontName = fontName;
  214499. lastBold = bold;
  214500. lastItalic = italic;
  214501. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  214502. if (ftFace != 0)
  214503. {
  214504. int style = (int) FreeTypeFontFace::Plain;
  214505. if (bold)
  214506. style |= (int) FreeTypeFontFace::Bold;
  214507. if (italic)
  214508. style |= (int) FreeTypeFontFace::Italic;
  214509. int faceIndex;
  214510. String fileName (ftFace->getFileName (style, &faceIndex));
  214511. if (fileName.isEmpty())
  214512. {
  214513. style ^= (int) FreeTypeFontFace::Bold;
  214514. fileName = ftFace->getFileName (style, &faceIndex);
  214515. if (fileName.isEmpty())
  214516. {
  214517. style ^= (int) FreeTypeFontFace::Bold;
  214518. style ^= (int) FreeTypeFontFace::Italic;
  214519. fileName = ftFace->getFileName (style, &faceIndex);
  214520. if (! fileName.length())
  214521. {
  214522. style ^= (int) FreeTypeFontFace::Bold;
  214523. fileName = ftFace->getFileName (style, &faceIndex);
  214524. }
  214525. }
  214526. }
  214527. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  214528. {
  214529. face = lastFace;
  214530. // If there isn't a unicode charmap then select the first one.
  214531. if (FT_Select_Charmap (face, ft_encoding_unicode))
  214532. FT_Set_Charmap (face, face->charmaps[0]);
  214533. }
  214534. }
  214535. }
  214536. return face;
  214537. }
  214538. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  214539. {
  214540. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  214541. const float height = (float) (face->ascender - face->descender);
  214542. const float scaleX = 1.0f / height;
  214543. const float scaleY = -1.0f / height;
  214544. Path destShape;
  214545. #define CONVERTX(val) (scaleX * (val).x)
  214546. #define CONVERTY(val) (scaleY * (val).y)
  214547. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  214548. | FT_LOAD_NO_BITMAP
  214549. | FT_LOAD_IGNORE_TRANSFORM) != 0
  214550. || face->glyph->format != ft_glyph_format_outline)
  214551. {
  214552. return false;
  214553. }
  214554. const FT_Outline* const outline = &face->glyph->outline;
  214555. const short* const contours = outline->contours;
  214556. const char* const tags = outline->tags;
  214557. FT_Vector* const points = outline->points;
  214558. for (int c = 0; c < outline->n_contours; c++)
  214559. {
  214560. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  214561. const int endPoint = contours[c];
  214562. for (int p = startPoint; p <= endPoint; p++)
  214563. {
  214564. const float x = CONVERTX (points[p]);
  214565. const float y = CONVERTY (points[p]);
  214566. if (p == startPoint)
  214567. {
  214568. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214569. {
  214570. float x2 = CONVERTX (points [endPoint]);
  214571. float y2 = CONVERTY (points [endPoint]);
  214572. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  214573. {
  214574. x2 = (x + x2) * 0.5f;
  214575. y2 = (y + y2) * 0.5f;
  214576. }
  214577. destShape.startNewSubPath (x2, y2);
  214578. }
  214579. else
  214580. {
  214581. destShape.startNewSubPath (x, y);
  214582. }
  214583. }
  214584. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  214585. {
  214586. if (p != startPoint)
  214587. destShape.lineTo (x, y);
  214588. }
  214589. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214590. {
  214591. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  214592. float x2 = CONVERTX (points [nextIndex]);
  214593. float y2 = CONVERTY (points [nextIndex]);
  214594. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  214595. {
  214596. x2 = (x + x2) * 0.5f;
  214597. y2 = (y + y2) * 0.5f;
  214598. }
  214599. else
  214600. {
  214601. ++p;
  214602. }
  214603. destShape.quadraticTo (x, y, x2, y2);
  214604. }
  214605. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  214606. {
  214607. if (p >= endPoint)
  214608. return false;
  214609. const int next1 = p + 1;
  214610. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  214611. const float x2 = CONVERTX (points [next1]);
  214612. const float y2 = CONVERTY (points [next1]);
  214613. const float x3 = CONVERTX (points [next2]);
  214614. const float y3 = CONVERTY (points [next2]);
  214615. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  214616. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  214617. return false;
  214618. destShape.cubicTo (x, y, x2, y2, x3, y3);
  214619. p += 2;
  214620. }
  214621. }
  214622. destShape.closeSubPath();
  214623. }
  214624. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  214625. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  214626. addKerning (face, dest, character, glyphIndex);
  214627. return true;
  214628. }
  214629. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  214630. {
  214631. const float height = (float) (face->ascender - face->descender);
  214632. uint32 rightGlyphIndex;
  214633. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  214634. while (rightGlyphIndex != 0)
  214635. {
  214636. FT_Vector kerning;
  214637. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  214638. {
  214639. if (kerning.x != 0)
  214640. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  214641. }
  214642. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  214643. }
  214644. }
  214645. // Add a glyph to a font
  214646. bool addGlyphToFont (const uint32 character,
  214647. const tchar* fontName, bool bold, bool italic,
  214648. Typeface& dest) throw()
  214649. {
  214650. FT_Face face = createFT_Face (fontName, bold, italic);
  214651. if (face != 0)
  214652. return addGlyph (face, dest, character);
  214653. return false;
  214654. }
  214655. // Create a Typeface object for given name/style
  214656. bool createTypeface (const String& fontName,
  214657. const bool bold, const bool italic,
  214658. Typeface& dest,
  214659. const bool addAllGlyphs) throw()
  214660. {
  214661. dest.clear();
  214662. dest.setName (fontName);
  214663. dest.setBold (bold);
  214664. dest.setItalic (italic);
  214665. FT_Face face = createFT_Face (fontName, bold, italic);
  214666. if (face == 0)
  214667. {
  214668. #ifdef JUCE_DEBUG
  214669. String msg (T("Failed to create typeface: "));
  214670. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  214671. DBG (msg);
  214672. #endif
  214673. return face;
  214674. }
  214675. const float height = (float) (face->ascender - face->descender);
  214676. dest.setAscent (face->ascender / height);
  214677. dest.setDefaultCharacter (L' ');
  214678. if (addAllGlyphs)
  214679. {
  214680. uint32 glyphIndex;
  214681. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  214682. while (glyphIndex != 0)
  214683. {
  214684. addGlyph (face, dest, charCode);
  214685. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  214686. }
  214687. }
  214688. return true;
  214689. }
  214690. void getFamilyNames (StringArray& familyNames) const throw()
  214691. {
  214692. for (int i = 0; i < faces.size(); i++)
  214693. familyNames.add (faces[i]->getFamilyName());
  214694. }
  214695. void getMonospacedNames (StringArray& monoSpaced) const throw()
  214696. {
  214697. for (int i = 0; i < faces.size(); i++)
  214698. if (faces[i]->getMonospaced())
  214699. monoSpaced.add (faces[i]->getFamilyName());
  214700. }
  214701. void getSerifNames (StringArray& serif) const throw()
  214702. {
  214703. for (int i = 0; i < faces.size(); i++)
  214704. if (faces[i]->getSerif())
  214705. serif.add (faces[i]->getFamilyName());
  214706. }
  214707. void getSansSerifNames (StringArray& sansSerif) const throw()
  214708. {
  214709. for (int i = 0; i < faces.size(); i++)
  214710. if (! faces[i]->getSerif())
  214711. sansSerif.add (faces[i]->getFamilyName());
  214712. }
  214713. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  214714. private:
  214715. FT_Library ftLib;
  214716. FT_Face lastFace;
  214717. String lastFontName;
  214718. bool lastBold, lastItalic;
  214719. OwnedArray<FreeTypeFontFace> faces;
  214720. };
  214721. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  214722. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  214723. bool bold, bool italic,
  214724. bool addAllGlyphsToFont) throw()
  214725. {
  214726. FreeTypeInterface::getInstance()
  214727. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  214728. }
  214729. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  214730. {
  214731. return FreeTypeInterface::getInstance()
  214732. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  214733. }
  214734. const StringArray Font::findAllTypefaceNames() throw()
  214735. {
  214736. StringArray s;
  214737. FreeTypeInterface::getInstance()->getFamilyNames (s);
  214738. s.sort (true);
  214739. return s;
  214740. }
  214741. static const String pickBestFont (const StringArray& names,
  214742. const char* const choicesString)
  214743. {
  214744. StringArray choices;
  214745. choices.addTokens (String (choicesString), T(","), 0);
  214746. choices.trim();
  214747. choices.removeEmptyStrings();
  214748. int i, j;
  214749. for (j = 0; j < choices.size(); ++j)
  214750. if (names.contains (choices[j], true))
  214751. return choices[j];
  214752. for (j = 0; j < choices.size(); ++j)
  214753. for (i = 0; i < names.size(); i++)
  214754. if (names[i].startsWithIgnoreCase (choices[j]))
  214755. return names[i];
  214756. for (j = 0; j < choices.size(); ++j)
  214757. for (i = 0; i < names.size(); i++)
  214758. if (names[i].containsIgnoreCase (choices[j]))
  214759. return names[i];
  214760. return names[0];
  214761. }
  214762. static const String linux_getDefaultSansSerifFontName()
  214763. {
  214764. StringArray allFonts;
  214765. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  214766. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  214767. }
  214768. static const String linux_getDefaultSerifFontName()
  214769. {
  214770. StringArray allFonts;
  214771. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  214772. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  214773. }
  214774. static const String linux_getDefaultMonospacedFontName()
  214775. {
  214776. StringArray allFonts;
  214777. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  214778. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  214779. }
  214780. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  214781. {
  214782. defaultSans = linux_getDefaultSansSerifFontName();
  214783. defaultSerif = linux_getDefaultSerifFontName();
  214784. defaultFixed = linux_getDefaultMonospacedFontName();
  214785. }
  214786. #endif
  214787. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  214788. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  214789. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214790. // compiled on its own).
  214791. #if JUCE_INCLUDED_FILE
  214792. #define TAKE_FOCUS 0
  214793. #define DELETE_WINDOW 1
  214794. #define SYSTEM_TRAY_REQUEST_DOCK 0
  214795. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  214796. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  214797. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  214798. static Atom wm_ChangeState = None;
  214799. static Atom wm_State = None;
  214800. static Atom wm_Protocols = None;
  214801. static Atom wm_ProtocolList [2] = { None, None };
  214802. static Atom wm_ActiveWin = None;
  214803. #define ourDndVersion 3
  214804. static Atom XA_XdndAware = None;
  214805. static Atom XA_XdndEnter = None;
  214806. static Atom XA_XdndLeave = None;
  214807. static Atom XA_XdndPosition = None;
  214808. static Atom XA_XdndStatus = None;
  214809. static Atom XA_XdndDrop = None;
  214810. static Atom XA_XdndFinished = None;
  214811. static Atom XA_XdndSelection = None;
  214812. static Atom XA_XdndProxy = None;
  214813. static Atom XA_XdndTypeList = None;
  214814. static Atom XA_XdndActionList = None;
  214815. static Atom XA_XdndActionDescription = None;
  214816. static Atom XA_XdndActionCopy = None;
  214817. static Atom XA_XdndActionMove = None;
  214818. static Atom XA_XdndActionLink = None;
  214819. static Atom XA_XdndActionAsk = None;
  214820. static Atom XA_XdndActionPrivate = None;
  214821. static Atom XA_JXSelectionWindowProperty = None;
  214822. static Atom XA_MimeTextPlain = None;
  214823. static Atom XA_MimeTextUriList = None;
  214824. static Atom XA_MimeRootDrop = None;
  214825. static XErrorHandler oldHandler = 0;
  214826. static int trappedErrorCode = 0;
  214827. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  214828. {
  214829. trappedErrorCode = err->error_code;
  214830. return 0;
  214831. }
  214832. static void trapErrors()
  214833. {
  214834. trappedErrorCode = 0;
  214835. oldHandler = XSetErrorHandler (errorTrapHandler);
  214836. }
  214837. static bool untrapErrors()
  214838. {
  214839. XSetErrorHandler (oldHandler);
  214840. return (trappedErrorCode == 0);
  214841. }
  214842. static bool isActiveApplication = false;
  214843. bool Process::isForegroundProcess() throw()
  214844. {
  214845. return isActiveApplication;
  214846. }
  214847. // (used in the messaging code, declared here for build reasons)
  214848. bool juce_isRunningAsApplication()
  214849. {
  214850. return JUCEApplication::getInstance() != 0;
  214851. }
  214852. // These are defined in juce_linux_Messaging.cpp
  214853. extern Display* display;
  214854. extern XContext improbableNumber;
  214855. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  214856. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  214857. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  214858. static int pointerMap[5];
  214859. static int lastMousePosX = 0, lastMousePosY = 0;
  214860. enum MouseButtons
  214861. {
  214862. NoButton = 0,
  214863. LeftButton = 1,
  214864. MiddleButton = 2,
  214865. RightButton = 3,
  214866. WheelUp = 4,
  214867. WheelDown = 5
  214868. };
  214869. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  214870. {
  214871. Window root, child;
  214872. int winx, winy;
  214873. unsigned int mask;
  214874. mouseMods = 0;
  214875. if (XQueryPointer (display,
  214876. RootWindow (display, DefaultScreen (display)),
  214877. &root, &child,
  214878. &x, &y, &winx, &winy, &mask) == False)
  214879. {
  214880. // Pointer not on the default screen
  214881. x = y = -1;
  214882. }
  214883. else
  214884. {
  214885. if ((mask & Button1Mask) != 0)
  214886. mouseMods |= ModifierKeys::leftButtonModifier;
  214887. if ((mask & Button2Mask) != 0)
  214888. mouseMods |= ModifierKeys::middleButtonModifier;
  214889. if ((mask & Button3Mask) != 0)
  214890. mouseMods |= ModifierKeys::rightButtonModifier;
  214891. }
  214892. }
  214893. static int AltMask = 0;
  214894. static int NumLockMask = 0;
  214895. static bool numLock = 0;
  214896. static bool capsLock = 0;
  214897. static char keyStates [32];
  214898. static void updateKeyStates (const int keycode, const bool press) throw()
  214899. {
  214900. const int keybyte = keycode >> 3;
  214901. const int keybit = (1 << (keycode & 7));
  214902. if (press)
  214903. keyStates [keybyte] |= keybit;
  214904. else
  214905. keyStates [keybyte] &= ~keybit;
  214906. }
  214907. static bool keyDown (const int keycode) throw()
  214908. {
  214909. const int keybyte = keycode >> 3;
  214910. const int keybit = (1 << (keycode & 7));
  214911. return (keyStates [keybyte] & keybit) != 0;
  214912. }
  214913. static const int extendedKeyModifier = 0x10000000;
  214914. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  214915. {
  214916. int keysym;
  214917. if (keyCode & extendedKeyModifier)
  214918. {
  214919. keysym = 0xff00 | (keyCode & 0xff);
  214920. }
  214921. else
  214922. {
  214923. keysym = keyCode;
  214924. if (keysym == (XK_Tab & 0xff)
  214925. || keysym == (XK_Return & 0xff)
  214926. || keysym == (XK_Escape & 0xff)
  214927. || keysym == (XK_BackSpace & 0xff))
  214928. {
  214929. keysym |= 0xff00;
  214930. }
  214931. }
  214932. return keyDown (XKeysymToKeycode (display, keysym));
  214933. }
  214934. // Alt and Num lock are not defined by standard X
  214935. // modifier constants: check what they're mapped to
  214936. static void getModifierMapping() throw()
  214937. {
  214938. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  214939. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  214940. AltMask = 0;
  214941. NumLockMask = 0;
  214942. XModifierKeymap* mapping = XGetModifierMapping (display);
  214943. if (mapping)
  214944. {
  214945. for (int i = 0; i < 8; i++)
  214946. {
  214947. if (mapping->modifiermap [i << 1] == altLeftCode)
  214948. AltMask = 1 << i;
  214949. else if (mapping->modifiermap [i << 1] == numLockCode)
  214950. NumLockMask = 1 << i;
  214951. }
  214952. XFreeModifiermap (mapping);
  214953. }
  214954. }
  214955. static int currentModifiers = 0;
  214956. void ModifierKeys::updateCurrentModifiers() throw()
  214957. {
  214958. currentModifierFlags = currentModifiers;
  214959. }
  214960. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  214961. {
  214962. int x, y, mouseMods;
  214963. getMousePos (x, y, mouseMods);
  214964. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  214965. currentModifiers |= mouseMods;
  214966. return ModifierKeys (currentModifiers);
  214967. }
  214968. static void updateKeyModifiers (const int status) throw()
  214969. {
  214970. currentModifiers &= ~(ModifierKeys::shiftModifier
  214971. | ModifierKeys::ctrlModifier
  214972. | ModifierKeys::altModifier);
  214973. if (status & ShiftMask)
  214974. currentModifiers |= ModifierKeys::shiftModifier;
  214975. if (status & ControlMask)
  214976. currentModifiers |= ModifierKeys::ctrlModifier;
  214977. if (status & AltMask)
  214978. currentModifiers |= ModifierKeys::altModifier;
  214979. numLock = ((status & NumLockMask) != 0);
  214980. capsLock = ((status & LockMask) != 0);
  214981. }
  214982. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  214983. {
  214984. int modifier = 0;
  214985. bool isModifier = true;
  214986. switch (sym)
  214987. {
  214988. case XK_Shift_L:
  214989. case XK_Shift_R:
  214990. modifier = ModifierKeys::shiftModifier;
  214991. break;
  214992. case XK_Control_L:
  214993. case XK_Control_R:
  214994. modifier = ModifierKeys::ctrlModifier;
  214995. break;
  214996. case XK_Alt_L:
  214997. case XK_Alt_R:
  214998. modifier = ModifierKeys::altModifier;
  214999. break;
  215000. case XK_Num_Lock:
  215001. if (press)
  215002. numLock = ! numLock;
  215003. break;
  215004. case XK_Caps_Lock:
  215005. if (press)
  215006. capsLock = ! capsLock;
  215007. break;
  215008. case XK_Scroll_Lock:
  215009. break;
  215010. default:
  215011. isModifier = false;
  215012. break;
  215013. }
  215014. if (modifier != 0)
  215015. {
  215016. if (press)
  215017. currentModifiers |= modifier;
  215018. else
  215019. currentModifiers &= ~modifier;
  215020. }
  215021. return isModifier;
  215022. }
  215023. #if JUCE_USE_XSHM
  215024. static bool isShmAvailable() throw()
  215025. {
  215026. static bool isChecked = false;
  215027. static bool isAvailable = false;
  215028. if (! isChecked)
  215029. {
  215030. isChecked = true;
  215031. int major, minor;
  215032. Bool pixmaps;
  215033. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  215034. {
  215035. trapErrors();
  215036. XShmSegmentInfo segmentInfo;
  215037. zerostruct (segmentInfo);
  215038. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  215039. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  215040. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  215041. xImage->bytes_per_line * xImage->height,
  215042. IPC_CREAT | 0777)) >= 0)
  215043. {
  215044. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215045. if (segmentInfo.shmaddr != (void*) -1)
  215046. {
  215047. segmentInfo.readOnly = False;
  215048. xImage->data = segmentInfo.shmaddr;
  215049. XSync (display, False);
  215050. if (XShmAttach (display, &segmentInfo) != 0)
  215051. {
  215052. XSync (display, False);
  215053. XShmDetach (display, &segmentInfo);
  215054. isAvailable = true;
  215055. }
  215056. }
  215057. XFlush (display);
  215058. XDestroyImage (xImage);
  215059. shmdt (segmentInfo.shmaddr);
  215060. }
  215061. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215062. isAvailable &= untrapErrors();
  215063. }
  215064. }
  215065. return isAvailable;
  215066. }
  215067. #endif
  215068. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  215069. {
  215070. const int width = image.getWidth();
  215071. const int height = image.getHeight();
  215072. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  215073. int index = 0;
  215074. for (int y = 0; y < height; ++y)
  215075. for (int x = 0; x < width; ++x)
  215076. colour[index++] = image.getPixelAt (x, y).getARGB();
  215077. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  215078. 0, (char*) colour, width, height, 32, 0);
  215079. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  215080. width, height, 24);
  215081. GC gc = XCreateGC (display, pixmap, 0, 0);
  215082. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  215083. XFreeGC (display, gc);
  215084. juce_free (colour);
  215085. return pixmap;
  215086. }
  215087. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  215088. {
  215089. const int width = image.getWidth();
  215090. const int height = image.getHeight();
  215091. const int stride = (width + 7) >> 3;
  215092. uint8* const mask = (uint8*) juce_calloc (stride * height);
  215093. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  215094. for (int y = 0; y < height; ++y)
  215095. {
  215096. for (int x = 0; x < width; ++x)
  215097. {
  215098. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  215099. const int offset = y * stride + (x >> 3);
  215100. if (image.getPixelAt (x, y).getAlpha() >= 128)
  215101. mask[offset] |= bit;
  215102. }
  215103. }
  215104. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  215105. (char*) mask, width, height, 1, 0, 1);
  215106. juce_free (mask);
  215107. return pixmap;
  215108. }
  215109. class XBitmapImage : public Image
  215110. {
  215111. public:
  215112. XBitmapImage (const PixelFormat format_, const int w, const int h,
  215113. const bool clearImage, const bool is16Bit_)
  215114. : Image (format_, w, h),
  215115. is16Bit (is16Bit_)
  215116. {
  215117. jassert (format_ == RGB || format_ == ARGB);
  215118. pixelStride = (format_ == RGB) ? 3 : 4;
  215119. lineStride = ((w * pixelStride + 3) & ~3);
  215120. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  215121. #if JUCE_USE_XSHM
  215122. usingXShm = false;
  215123. if ((! is16Bit) && isShmAvailable())
  215124. {
  215125. zerostruct (segmentInfo);
  215126. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  215127. if (xImage != 0)
  215128. {
  215129. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  215130. xImage->bytes_per_line * xImage->height,
  215131. IPC_CREAT | 0777)) >= 0)
  215132. {
  215133. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  215134. if (segmentInfo.shmaddr != (void*) -1)
  215135. {
  215136. segmentInfo.readOnly = False;
  215137. xImage->data = segmentInfo.shmaddr;
  215138. imageData = (uint8*) segmentInfo.shmaddr;
  215139. XSync (display, False);
  215140. if (XShmAttach (display, &segmentInfo) != 0)
  215141. {
  215142. XSync (display, False);
  215143. usingXShm = true;
  215144. }
  215145. else
  215146. {
  215147. jassertfalse
  215148. }
  215149. }
  215150. else
  215151. {
  215152. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215153. }
  215154. }
  215155. }
  215156. }
  215157. if (! usingXShm)
  215158. #endif
  215159. {
  215160. imageData = (uint8*) juce_malloc (lineStride * h);
  215161. if (format_ == ARGB && clearImage)
  215162. zeromem (imageData, h * lineStride);
  215163. xImage = (XImage*) juce_calloc (sizeof (XImage));
  215164. xImage->width = w;
  215165. xImage->height = h;
  215166. xImage->xoffset = 0;
  215167. xImage->format = ZPixmap;
  215168. xImage->data = (char*) imageData;
  215169. xImage->byte_order = ImageByteOrder (display);
  215170. xImage->bitmap_unit = BitmapUnit (display);
  215171. xImage->bitmap_bit_order = BitmapBitOrder (display);
  215172. xImage->bitmap_pad = 32;
  215173. xImage->depth = pixelStride * 8;
  215174. xImage->bytes_per_line = lineStride;
  215175. xImage->bits_per_pixel = pixelStride * 8;
  215176. xImage->red_mask = 0x00FF0000;
  215177. xImage->green_mask = 0x0000FF00;
  215178. xImage->blue_mask = 0x000000FF;
  215179. if (is16Bit)
  215180. {
  215181. const int pixelStride = 2;
  215182. const int lineStride = ((w * pixelStride + 3) & ~3);
  215183. xImage->data = (char*) juce_malloc (lineStride * h);
  215184. xImage->bitmap_pad = 16;
  215185. xImage->depth = pixelStride * 8;
  215186. xImage->bytes_per_line = lineStride;
  215187. xImage->bits_per_pixel = pixelStride * 8;
  215188. xImage->red_mask = visual->red_mask;
  215189. xImage->green_mask = visual->green_mask;
  215190. xImage->blue_mask = visual->blue_mask;
  215191. }
  215192. if (! XInitImage (xImage))
  215193. {
  215194. jassertfalse
  215195. }
  215196. }
  215197. }
  215198. ~XBitmapImage()
  215199. {
  215200. #if JUCE_USE_XSHM
  215201. if (usingXShm)
  215202. {
  215203. XShmDetach (display, &segmentInfo);
  215204. XFlush (display);
  215205. XDestroyImage (xImage);
  215206. shmdt (segmentInfo.shmaddr);
  215207. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215208. }
  215209. else
  215210. #endif
  215211. {
  215212. juce_free (xImage->data);
  215213. xImage->data = 0;
  215214. XDestroyImage (xImage);
  215215. }
  215216. if (! is16Bit)
  215217. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  215218. }
  215219. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  215220. {
  215221. static GC gc = 0;
  215222. if (gc == 0)
  215223. gc = DefaultGC (display, DefaultScreen (display));
  215224. if (is16Bit)
  215225. {
  215226. const uint32 rMask = xImage->red_mask;
  215227. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  215228. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  215229. const uint32 gMask = xImage->green_mask;
  215230. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  215231. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  215232. const uint32 bMask = xImage->blue_mask;
  215233. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  215234. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  215235. int ls, ps;
  215236. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  215237. for (int y = sy; y < sy + dh; ++y)
  215238. {
  215239. const uint8* p = pixels + y * ls + sx * ps;
  215240. for (int x = sx; x < sx + dw; ++x)
  215241. {
  215242. const PixelRGB* const pixel = (const PixelRGB*) p;
  215243. p += ps;
  215244. XPutPixel (xImage, x, y,
  215245. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  215246. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  215247. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  215248. }
  215249. }
  215250. releasePixelDataReadOnly (pixels);
  215251. }
  215252. // blit results to screen.
  215253. #if JUCE_USE_XSHM
  215254. if (usingXShm)
  215255. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  215256. else
  215257. #endif
  215258. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  215259. }
  215260. juce_UseDebuggingNewOperator
  215261. private:
  215262. XImage* xImage;
  215263. const bool is16Bit;
  215264. #if JUCE_USE_XSHM
  215265. XShmSegmentInfo segmentInfo;
  215266. bool usingXShm;
  215267. #endif
  215268. static int getShiftNeeded (const uint32 mask) throw()
  215269. {
  215270. for (int i = 32; --i >= 0;)
  215271. if (((mask >> i) & 1) != 0)
  215272. return i - 7;
  215273. jassertfalse
  215274. return 0;
  215275. }
  215276. };
  215277. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215278. class LinuxComponentPeer : public ComponentPeer
  215279. {
  215280. public:
  215281. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  215282. : ComponentPeer (component, windowStyleFlags),
  215283. windowH (0),
  215284. parentWindow (0),
  215285. wx (0),
  215286. wy (0),
  215287. ww (0),
  215288. wh (0),
  215289. taskbarImage (0),
  215290. fullScreen (false),
  215291. entered (false),
  215292. mapped (false)
  215293. {
  215294. // it's dangerous to create a window on a thread other than the message thread..
  215295. checkMessageManagerIsLocked
  215296. repainter = new LinuxRepaintManager (this);
  215297. createWindow();
  215298. setTitle (component->getName());
  215299. }
  215300. ~LinuxComponentPeer()
  215301. {
  215302. // it's dangerous to delete a window on a thread other than the message thread..
  215303. checkMessageManagerIsLocked
  215304. deleteTaskBarIcon();
  215305. deleteIconPixmaps();
  215306. destroyWindow();
  215307. windowH = 0;
  215308. delete repainter;
  215309. }
  215310. void* getNativeHandle() const
  215311. {
  215312. return (void*) windowH;
  215313. }
  215314. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  215315. {
  215316. XPointer peer = 0;
  215317. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  215318. {
  215319. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  215320. peer = 0;
  215321. }
  215322. return (LinuxComponentPeer*) peer;
  215323. }
  215324. void setVisible (bool shouldBeVisible)
  215325. {
  215326. if (shouldBeVisible)
  215327. XMapWindow (display, windowH);
  215328. else
  215329. XUnmapWindow (display, windowH);
  215330. }
  215331. void setTitle (const String& title)
  215332. {
  215333. setWindowTitle (windowH, title);
  215334. }
  215335. void setPosition (int x, int y)
  215336. {
  215337. setBounds (x, y, ww, wh, false);
  215338. }
  215339. void setSize (int w, int h)
  215340. {
  215341. setBounds (wx, wy, w, h, false);
  215342. }
  215343. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  215344. {
  215345. fullScreen = isNowFullScreen;
  215346. if (windowH != 0)
  215347. {
  215348. const ComponentDeletionWatcher deletionChecker (component);
  215349. wx = x;
  215350. wy = y;
  215351. ww = jmax (1, w);
  215352. wh = jmax (1, h);
  215353. // Make sure the Window manager does what we want
  215354. XSizeHints* hints = XAllocSizeHints();
  215355. hints->flags = USSize | USPosition;
  215356. hints->width = ww;
  215357. hints->height = wh;
  215358. hints->x = wx;
  215359. hints->y = wy;
  215360. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  215361. {
  215362. hints->min_width = hints->max_width = hints->width;
  215363. hints->min_height = hints->max_height = hints->height;
  215364. hints->flags |= PMinSize | PMaxSize;
  215365. }
  215366. XSetWMNormalHints (display, windowH, hints);
  215367. XFree (hints);
  215368. XMoveResizeWindow (display, windowH,
  215369. wx - windowBorder.getLeft(),
  215370. wy - windowBorder.getTop(), ww, wh);
  215371. if (! deletionChecker.hasBeenDeleted())
  215372. {
  215373. updateBorderSize();
  215374. handleMovedOrResized();
  215375. }
  215376. }
  215377. }
  215378. void getBounds (int& x, int& y, int& w, int& h) const
  215379. {
  215380. x = wx;
  215381. y = wy;
  215382. w = ww;
  215383. h = wh;
  215384. }
  215385. int getScreenX() const
  215386. {
  215387. return wx;
  215388. }
  215389. int getScreenY() const
  215390. {
  215391. return wy;
  215392. }
  215393. void relativePositionToGlobal (int& x, int& y)
  215394. {
  215395. x += wx;
  215396. y += wy;
  215397. }
  215398. void globalPositionToRelative (int& x, int& y)
  215399. {
  215400. x -= wx;
  215401. y -= wy;
  215402. }
  215403. void setMinimised (bool shouldBeMinimised)
  215404. {
  215405. if (shouldBeMinimised)
  215406. {
  215407. Window root = RootWindow (display, DefaultScreen (display));
  215408. XClientMessageEvent clientMsg;
  215409. clientMsg.display = display;
  215410. clientMsg.window = windowH;
  215411. clientMsg.type = ClientMessage;
  215412. clientMsg.format = 32;
  215413. clientMsg.message_type = wm_ChangeState;
  215414. clientMsg.data.l[0] = IconicState;
  215415. XSendEvent (display, root, false,
  215416. SubstructureRedirectMask | SubstructureNotifyMask,
  215417. (XEvent*) &clientMsg);
  215418. }
  215419. else
  215420. {
  215421. setVisible (true);
  215422. }
  215423. }
  215424. bool isMinimised() const
  215425. {
  215426. bool minimised = false;
  215427. unsigned char* stateProp;
  215428. unsigned long nitems, bytesLeft;
  215429. Atom actualType;
  215430. int actualFormat;
  215431. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  215432. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  215433. &stateProp) == Success
  215434. && actualType == wm_State
  215435. && actualFormat == 32
  215436. && nitems > 0)
  215437. {
  215438. if (((unsigned long*) stateProp)[0] == IconicState)
  215439. minimised = true;
  215440. XFree (stateProp);
  215441. }
  215442. return minimised;
  215443. }
  215444. void setFullScreen (const bool shouldBeFullScreen)
  215445. {
  215446. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  215447. setMinimised (false);
  215448. if (fullScreen != shouldBeFullScreen)
  215449. {
  215450. if (shouldBeFullScreen)
  215451. r = Desktop::getInstance().getMainMonitorArea();
  215452. if (! r.isEmpty())
  215453. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  215454. getComponent()->repaint();
  215455. }
  215456. }
  215457. bool isFullScreen() const
  215458. {
  215459. return fullScreen;
  215460. }
  215461. bool isChildWindowOf (Window possibleParent) const
  215462. {
  215463. Window* windowList = 0;
  215464. uint32 windowListSize = 0;
  215465. Window parent, root;
  215466. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  215467. {
  215468. if (windowList != 0)
  215469. XFree (windowList);
  215470. return parent == possibleParent;
  215471. }
  215472. return false;
  215473. }
  215474. bool isFrontWindow() const
  215475. {
  215476. Window* windowList = 0;
  215477. uint32 windowListSize = 0;
  215478. bool result = false;
  215479. Window parent, root = RootWindow (display, DefaultScreen (display));
  215480. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  215481. {
  215482. for (int i = windowListSize; --i >= 0;)
  215483. {
  215484. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  215485. if (peer != 0)
  215486. {
  215487. result = (peer == this);
  215488. break;
  215489. }
  215490. }
  215491. }
  215492. if (windowList != 0)
  215493. XFree (windowList);
  215494. return result;
  215495. }
  215496. bool contains (int x, int y, bool trueIfInAChildWindow) const
  215497. {
  215498. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  215499. if (((unsigned int) x) >= (unsigned int) ww
  215500. || ((unsigned int) y) >= (unsigned int) wh)
  215501. return false;
  215502. bool inFront = false;
  215503. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  215504. {
  215505. Component* const c = Desktop::getInstance().getComponent (i);
  215506. if (inFront)
  215507. {
  215508. if (c->contains (x + wx - c->getScreenX(),
  215509. y + wy - c->getScreenY()))
  215510. {
  215511. return false;
  215512. }
  215513. }
  215514. else if (c == getComponent())
  215515. {
  215516. inFront = true;
  215517. }
  215518. }
  215519. if (trueIfInAChildWindow)
  215520. return true;
  215521. ::Window root, child;
  215522. unsigned int bw, depth;
  215523. int wx, wy, w, h;
  215524. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  215525. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  215526. &bw, &depth))
  215527. {
  215528. return false;
  215529. }
  215530. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  215531. return false;
  215532. return child == None;
  215533. }
  215534. const BorderSize getFrameSize() const
  215535. {
  215536. return BorderSize();
  215537. }
  215538. bool setAlwaysOnTop (bool alwaysOnTop)
  215539. {
  215540. if (windowH != 0)
  215541. {
  215542. const bool wasVisible = component->isVisible();
  215543. if (wasVisible)
  215544. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  215545. XSetWindowAttributes swa;
  215546. swa.override_redirect = alwaysOnTop ? True : False;
  215547. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  215548. if (wasVisible)
  215549. setVisible (true);
  215550. }
  215551. return true;
  215552. }
  215553. void toFront (bool makeActive)
  215554. {
  215555. if (makeActive)
  215556. {
  215557. setVisible (true);
  215558. grabFocus();
  215559. }
  215560. XEvent ev;
  215561. ev.xclient.type = ClientMessage;
  215562. ev.xclient.serial = 0;
  215563. ev.xclient.send_event = True;
  215564. ev.xclient.message_type = wm_ActiveWin;
  215565. ev.xclient.window = windowH;
  215566. ev.xclient.format = 32;
  215567. ev.xclient.data.l[0] = 2;
  215568. ev.xclient.data.l[1] = CurrentTime;
  215569. ev.xclient.data.l[2] = 0;
  215570. ev.xclient.data.l[3] = 0;
  215571. ev.xclient.data.l[4] = 0;
  215572. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  215573. False,
  215574. SubstructureRedirectMask | SubstructureNotifyMask,
  215575. &ev);
  215576. XWindowAttributes attr;
  215577. XGetWindowAttributes (display, windowH, &attr);
  215578. if (attr.override_redirect)
  215579. XRaiseWindow (display, windowH);
  215580. XSync (display, False);
  215581. handleBroughtToFront();
  215582. }
  215583. void toBehind (ComponentPeer* other)
  215584. {
  215585. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  215586. jassert (otherPeer != 0); // wrong type of window?
  215587. if (otherPeer != 0)
  215588. {
  215589. setMinimised (false);
  215590. Window newStack[] = { otherPeer->windowH, windowH };
  215591. XRestackWindows (display, newStack, 2);
  215592. }
  215593. }
  215594. bool isFocused() const
  215595. {
  215596. int revert;
  215597. Window focusedWindow = 0;
  215598. XGetInputFocus (display, &focusedWindow, &revert);
  215599. return focusedWindow == windowH;
  215600. }
  215601. void grabFocus()
  215602. {
  215603. XWindowAttributes atts;
  215604. if (windowH != 0
  215605. && XGetWindowAttributes (display, windowH, &atts)
  215606. && atts.map_state == IsViewable
  215607. && ! isFocused())
  215608. {
  215609. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  215610. isActiveApplication = true;
  215611. }
  215612. }
  215613. void textInputRequired (int /*x*/, int /*y*/)
  215614. {
  215615. }
  215616. void repaint (int x, int y, int w, int h)
  215617. {
  215618. if (Rectangle::intersectRectangles (x, y, w, h,
  215619. 0, 0,
  215620. getComponent()->getWidth(),
  215621. getComponent()->getHeight()))
  215622. {
  215623. repainter->repaint (x, y, w, h);
  215624. }
  215625. }
  215626. void performAnyPendingRepaintsNow()
  215627. {
  215628. repainter->performAnyPendingRepaintsNow();
  215629. }
  215630. void setIcon (const Image& newIcon)
  215631. {
  215632. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  215633. unsigned long* const data = (unsigned long*) juce_malloc (dataSize * sizeof (uint32));
  215634. int index = 0;
  215635. data[index++] = newIcon.getWidth();
  215636. data[index++] = newIcon.getHeight();
  215637. for (int y = 0; y < newIcon.getHeight(); ++y)
  215638. for (int x = 0; x < newIcon.getWidth(); ++x)
  215639. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  215640. XChangeProperty (display, windowH,
  215641. XInternAtom (display, "_NET_WM_ICON", False),
  215642. XA_CARDINAL, 32, PropModeReplace,
  215643. (unsigned char*) data, dataSize);
  215644. juce_free (data);
  215645. deleteIconPixmaps();
  215646. XWMHints* wmHints = XGetWMHints (display, windowH);
  215647. if (wmHints == 0)
  215648. wmHints = XAllocWMHints();
  215649. wmHints->flags |= IconPixmapHint | IconMaskHint;
  215650. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  215651. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  215652. XSetWMHints (display, windowH, wmHints);
  215653. XFree (wmHints);
  215654. XSync (display, False);
  215655. }
  215656. void deleteIconPixmaps()
  215657. {
  215658. XWMHints* wmHints = XGetWMHints (display, windowH);
  215659. if (wmHints != 0)
  215660. {
  215661. if ((wmHints->flags & IconPixmapHint) != 0)
  215662. {
  215663. wmHints->flags &= ~IconPixmapHint;
  215664. XFreePixmap (display, wmHints->icon_pixmap);
  215665. }
  215666. if ((wmHints->flags & IconMaskHint) != 0)
  215667. {
  215668. wmHints->flags &= ~IconMaskHint;
  215669. XFreePixmap (display, wmHints->icon_mask);
  215670. }
  215671. XSetWMHints (display, windowH, wmHints);
  215672. XFree (wmHints);
  215673. }
  215674. }
  215675. void handleWindowMessage (XEvent* event)
  215676. {
  215677. switch (event->xany.type)
  215678. {
  215679. case 2: // 'KeyPress'
  215680. {
  215681. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  215682. updateKeyStates (keyEvent->keycode, true);
  215683. char utf8 [64];
  215684. zeromem (utf8, sizeof (utf8));
  215685. KeySym sym;
  215686. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  215687. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  215688. int keyCode = (int) unicodeChar;
  215689. if (keyCode < 0x20)
  215690. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  215691. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  215692. const int oldMods = currentModifiers;
  215693. bool keyPressed = false;
  215694. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  215695. if ((sym & 0xff00) == 0xff00)
  215696. {
  215697. // Translate keypad
  215698. if (sym == XK_KP_Divide)
  215699. keyCode = XK_slash;
  215700. else if (sym == XK_KP_Multiply)
  215701. keyCode = XK_asterisk;
  215702. else if (sym == XK_KP_Subtract)
  215703. keyCode = XK_hyphen;
  215704. else if (sym == XK_KP_Add)
  215705. keyCode = XK_plus;
  215706. else if (sym == XK_KP_Enter)
  215707. keyCode = XK_Return;
  215708. else if (sym == XK_KP_Decimal)
  215709. keyCode = numLock ? XK_period : XK_Delete;
  215710. else if (sym == XK_KP_0)
  215711. keyCode = numLock ? XK_0 : XK_Insert;
  215712. else if (sym == XK_KP_1)
  215713. keyCode = numLock ? XK_1 : XK_End;
  215714. else if (sym == XK_KP_2)
  215715. keyCode = numLock ? XK_2 : XK_Down;
  215716. else if (sym == XK_KP_3)
  215717. keyCode = numLock ? XK_3 : XK_Page_Down;
  215718. else if (sym == XK_KP_4)
  215719. keyCode = numLock ? XK_4 : XK_Left;
  215720. else if (sym == XK_KP_5)
  215721. keyCode = XK_5;
  215722. else if (sym == XK_KP_6)
  215723. keyCode = numLock ? XK_6 : XK_Right;
  215724. else if (sym == XK_KP_7)
  215725. keyCode = numLock ? XK_7 : XK_Home;
  215726. else if (sym == XK_KP_8)
  215727. keyCode = numLock ? XK_8 : XK_Up;
  215728. else if (sym == XK_KP_9)
  215729. keyCode = numLock ? XK_9 : XK_Page_Up;
  215730. switch (sym)
  215731. {
  215732. case XK_Left:
  215733. case XK_Right:
  215734. case XK_Up:
  215735. case XK_Down:
  215736. case XK_Page_Up:
  215737. case XK_Page_Down:
  215738. case XK_End:
  215739. case XK_Home:
  215740. case XK_Delete:
  215741. case XK_Insert:
  215742. keyPressed = true;
  215743. keyCode = (sym & 0xff) | extendedKeyModifier;
  215744. break;
  215745. case XK_Tab:
  215746. case XK_Return:
  215747. case XK_Escape:
  215748. case XK_BackSpace:
  215749. keyPressed = true;
  215750. keyCode &= 0xff;
  215751. break;
  215752. default:
  215753. {
  215754. if (sym >= XK_F1 && sym <= XK_F16)
  215755. {
  215756. keyPressed = true;
  215757. keyCode = (sym & 0xff) | extendedKeyModifier;
  215758. }
  215759. break;
  215760. }
  215761. }
  215762. }
  215763. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  215764. keyPressed = true;
  215765. if (oldMods != currentModifiers)
  215766. handleModifierKeysChange();
  215767. if (keyDownChange)
  215768. handleKeyUpOrDown (true);
  215769. if (keyPressed)
  215770. handleKeyPress (keyCode, unicodeChar);
  215771. break;
  215772. }
  215773. case KeyRelease:
  215774. {
  215775. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  215776. updateKeyStates (keyEvent->keycode, false);
  215777. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  215778. const int oldMods = currentModifiers;
  215779. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  215780. if (oldMods != currentModifiers)
  215781. handleModifierKeysChange();
  215782. if (keyDownChange)
  215783. handleKeyUpOrDown (false);
  215784. break;
  215785. }
  215786. case ButtonPress:
  215787. {
  215788. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  215789. bool buttonMsg = false;
  215790. bool wheelUpMsg = false;
  215791. bool wheelDownMsg = false;
  215792. const int map = pointerMap [buttonPressEvent->button - Button1];
  215793. if (map == LeftButton)
  215794. {
  215795. currentModifiers |= ModifierKeys::leftButtonModifier;
  215796. buttonMsg = true;
  215797. }
  215798. else if (map == RightButton)
  215799. {
  215800. currentModifiers |= ModifierKeys::rightButtonModifier;
  215801. buttonMsg = true;
  215802. }
  215803. else if (map == MiddleButton)
  215804. {
  215805. currentModifiers |= ModifierKeys::middleButtonModifier;
  215806. buttonMsg = true;
  215807. }
  215808. else if (map == WheelUp)
  215809. {
  215810. wheelUpMsg = true;
  215811. }
  215812. else if (map == WheelDown)
  215813. {
  215814. wheelDownMsg = true;
  215815. }
  215816. updateKeyModifiers (buttonPressEvent->state);
  215817. if (buttonMsg)
  215818. {
  215819. toFront (true);
  215820. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  215821. getEventTime (buttonPressEvent->time));
  215822. }
  215823. else if (wheelUpMsg || wheelDownMsg)
  215824. {
  215825. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  215826. getEventTime (buttonPressEvent->time));
  215827. }
  215828. lastMousePosX = lastMousePosY = 0x100000;
  215829. break;
  215830. }
  215831. case ButtonRelease:
  215832. {
  215833. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  215834. const int oldModifiers = currentModifiers;
  215835. const int map = pointerMap [buttonRelEvent->button - Button1];
  215836. if (map == LeftButton)
  215837. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  215838. else if (map == RightButton)
  215839. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  215840. else if (map == MiddleButton)
  215841. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  215842. updateKeyModifiers (buttonRelEvent->state);
  215843. handleMouseUp (oldModifiers,
  215844. buttonRelEvent->x, buttonRelEvent->y,
  215845. getEventTime (buttonRelEvent->time));
  215846. lastMousePosX = lastMousePosY = 0x100000;
  215847. break;
  215848. }
  215849. case MotionNotify:
  215850. {
  215851. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  215852. updateKeyModifiers (movedEvent->state);
  215853. int x, y, mouseMods;
  215854. getMousePos (x, y, mouseMods);
  215855. if (lastMousePosX != x || lastMousePosY != y)
  215856. {
  215857. lastMousePosX = x;
  215858. lastMousePosY = y;
  215859. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  215860. {
  215861. Window wRoot = 0, wParent = 0;
  215862. Window* wChild = 0;
  215863. unsigned int numChildren;
  215864. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  215865. if (wParent != 0
  215866. && wParent != windowH
  215867. && wParent != wRoot)
  215868. {
  215869. parentWindow = wParent;
  215870. updateBounds();
  215871. x -= getScreenX();
  215872. y -= getScreenY();
  215873. }
  215874. else
  215875. {
  215876. parentWindow = 0;
  215877. x -= getScreenX();
  215878. y -= getScreenY();
  215879. }
  215880. }
  215881. else
  215882. {
  215883. x -= getScreenX();
  215884. y -= getScreenY();
  215885. }
  215886. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  215887. handleMouseMove (x, y, getEventTime (movedEvent->time));
  215888. else
  215889. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  215890. }
  215891. break;
  215892. }
  215893. case EnterNotify:
  215894. {
  215895. lastMousePosX = lastMousePosY = 0x100000;
  215896. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  215897. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215898. && ! entered)
  215899. {
  215900. updateKeyModifiers (enterEvent->state);
  215901. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  215902. entered = true;
  215903. }
  215904. break;
  215905. }
  215906. case LeaveNotify:
  215907. {
  215908. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  215909. // Suppress the normal leave if we've got a pointer grab, or if
  215910. // it's a bogus one caused by clicking a mouse button when running
  215911. // in a Window manager
  215912. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215913. && leaveEvent->mode == NotifyNormal)
  215914. || leaveEvent->mode == NotifyUngrab)
  215915. {
  215916. updateKeyModifiers (leaveEvent->state);
  215917. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  215918. entered = false;
  215919. }
  215920. break;
  215921. }
  215922. case FocusIn:
  215923. {
  215924. isActiveApplication = true;
  215925. if (isFocused())
  215926. handleFocusGain();
  215927. break;
  215928. }
  215929. case FocusOut:
  215930. {
  215931. isActiveApplication = false;
  215932. if (! isFocused())
  215933. handleFocusLoss();
  215934. break;
  215935. }
  215936. case Expose:
  215937. {
  215938. // Batch together all pending expose events
  215939. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  215940. XEvent nextEvent;
  215941. if (exposeEvent->window != windowH)
  215942. {
  215943. Window child;
  215944. XTranslateCoordinates (display, exposeEvent->window, windowH,
  215945. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  215946. &child);
  215947. }
  215948. repaint (exposeEvent->x, exposeEvent->y,
  215949. exposeEvent->width, exposeEvent->height);
  215950. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  215951. {
  215952. XPeekEvent (display, (XEvent*) &nextEvent);
  215953. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  215954. break;
  215955. XNextEvent (display, (XEvent*) &nextEvent);
  215956. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  215957. repaint (nextExposeEvent->x, nextExposeEvent->y,
  215958. nextExposeEvent->width, nextExposeEvent->height);
  215959. }
  215960. break;
  215961. }
  215962. case CirculateNotify:
  215963. case CreateNotify:
  215964. case DestroyNotify:
  215965. // Think we can ignore these
  215966. break;
  215967. case ConfigureNotify:
  215968. {
  215969. updateBounds();
  215970. updateBorderSize();
  215971. handleMovedOrResized();
  215972. // if the native title bar is dragged, need to tell any active menus, etc.
  215973. if ((styleFlags & windowHasTitleBar) != 0
  215974. && component->isCurrentlyBlockedByAnotherModalComponent())
  215975. {
  215976. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  215977. if (currentModalComp != 0)
  215978. currentModalComp->inputAttemptWhenModal();
  215979. }
  215980. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  215981. if (confEvent->window == windowH
  215982. && confEvent->above != 0
  215983. && isFrontWindow())
  215984. {
  215985. handleBroughtToFront();
  215986. }
  215987. break;
  215988. }
  215989. case ReparentNotify:
  215990. case GravityNotify:
  215991. {
  215992. parentWindow = 0;
  215993. Window wRoot = 0;
  215994. Window* wChild = 0;
  215995. unsigned int numChildren;
  215996. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  215997. if (parentWindow == windowH || parentWindow == wRoot)
  215998. parentWindow = 0;
  215999. updateBounds();
  216000. updateBorderSize();
  216001. handleMovedOrResized();
  216002. break;
  216003. }
  216004. case MapNotify:
  216005. mapped = true;
  216006. handleBroughtToFront();
  216007. break;
  216008. case UnmapNotify:
  216009. mapped = false;
  216010. break;
  216011. case MappingNotify:
  216012. {
  216013. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  216014. if (mappingEvent->request != MappingPointer)
  216015. {
  216016. // Deal with modifier/keyboard mapping
  216017. XRefreshKeyboardMapping (mappingEvent);
  216018. getModifierMapping();
  216019. }
  216020. break;
  216021. }
  216022. case ClientMessage:
  216023. {
  216024. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  216025. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  216026. {
  216027. const Atom atom = (Atom) clientMsg->data.l[0];
  216028. if (atom == wm_ProtocolList [TAKE_FOCUS])
  216029. {
  216030. XWindowAttributes atts;
  216031. if (clientMsg->window != 0
  216032. && XGetWindowAttributes (display, clientMsg->window, &atts))
  216033. {
  216034. if (atts.map_state == IsViewable)
  216035. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  216036. }
  216037. }
  216038. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  216039. {
  216040. handleUserClosingWindow();
  216041. }
  216042. }
  216043. else if (clientMsg->message_type == XA_XdndEnter)
  216044. {
  216045. handleDragAndDropEnter (clientMsg);
  216046. }
  216047. else if (clientMsg->message_type == XA_XdndLeave)
  216048. {
  216049. resetDragAndDrop();
  216050. }
  216051. else if (clientMsg->message_type == XA_XdndPosition)
  216052. {
  216053. handleDragAndDropPosition (clientMsg);
  216054. }
  216055. else if (clientMsg->message_type == XA_XdndDrop)
  216056. {
  216057. handleDragAndDropDrop (clientMsg);
  216058. }
  216059. else if (clientMsg->message_type == XA_XdndStatus)
  216060. {
  216061. handleDragAndDropStatus (clientMsg);
  216062. }
  216063. else if (clientMsg->message_type == XA_XdndFinished)
  216064. {
  216065. resetDragAndDrop();
  216066. }
  216067. break;
  216068. }
  216069. case SelectionNotify:
  216070. handleDragAndDropSelection (event);
  216071. break;
  216072. case SelectionClear:
  216073. case SelectionRequest:
  216074. break;
  216075. default:
  216076. break;
  216077. }
  216078. }
  216079. void showMouseCursor (Cursor cursor) throw()
  216080. {
  216081. XDefineCursor (display, windowH, cursor);
  216082. }
  216083. void setTaskBarIcon (const Image& image)
  216084. {
  216085. deleteTaskBarIcon();
  216086. taskbarImage = image.createCopy();
  216087. Screen* const screen = XDefaultScreenOfDisplay (display);
  216088. const int screenNumber = XScreenNumberOfScreen (screen);
  216089. char screenAtom[32];
  216090. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  216091. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  216092. XGrabServer (display);
  216093. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  216094. if (managerWin != None)
  216095. XSelectInput (display, managerWin, StructureNotifyMask);
  216096. XUngrabServer (display);
  216097. XFlush (display);
  216098. if (managerWin != None)
  216099. {
  216100. XEvent ev;
  216101. zerostruct (ev);
  216102. ev.xclient.type = ClientMessage;
  216103. ev.xclient.window = managerWin;
  216104. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  216105. ev.xclient.format = 32;
  216106. ev.xclient.data.l[0] = CurrentTime;
  216107. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  216108. ev.xclient.data.l[2] = windowH;
  216109. ev.xclient.data.l[3] = 0;
  216110. ev.xclient.data.l[4] = 0;
  216111. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  216112. XSync (display, False);
  216113. }
  216114. // For older KDE's ...
  216115. long atomData = 1;
  216116. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  216117. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  216118. // For more recent KDE's...
  216119. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  216120. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  216121. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  216122. XSizeHints* hints = XAllocSizeHints();
  216123. hints->flags = PMinSize;
  216124. hints->min_width = 22;
  216125. hints->min_height = 22;
  216126. XSetWMNormalHints (display, windowH, hints);
  216127. XFree (hints);
  216128. }
  216129. void deleteTaskBarIcon()
  216130. {
  216131. deleteAndZero (taskbarImage);
  216132. }
  216133. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  216134. juce_UseDebuggingNewOperator
  216135. bool dontRepaint;
  216136. private:
  216137. class LinuxRepaintManager : public Timer
  216138. {
  216139. public:
  216140. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  216141. : peer (peer_),
  216142. image (0),
  216143. lastTimeImageUsed (0)
  216144. {
  216145. #if JUCE_USE_XSHM
  216146. useARGBImagesForRendering = isShmAvailable();
  216147. if (useARGBImagesForRendering)
  216148. {
  216149. XShmSegmentInfo segmentinfo;
  216150. XImage* const testImage
  216151. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  216152. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  216153. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  216154. XDestroyImage (testImage);
  216155. }
  216156. #endif
  216157. }
  216158. ~LinuxRepaintManager()
  216159. {
  216160. delete image;
  216161. }
  216162. void timerCallback()
  216163. {
  216164. if (! regionsNeedingRepaint.isEmpty())
  216165. {
  216166. stopTimer();
  216167. performAnyPendingRepaintsNow();
  216168. }
  216169. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  216170. {
  216171. stopTimer();
  216172. deleteAndZero (image);
  216173. }
  216174. }
  216175. void repaint (int x, int y, int w, int h)
  216176. {
  216177. if (! isTimerRunning())
  216178. startTimer (repaintTimerPeriod);
  216179. regionsNeedingRepaint.add (x, y, w, h);
  216180. }
  216181. void performAnyPendingRepaintsNow()
  216182. {
  216183. peer->clearMaskedRegion();
  216184. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  216185. if (! totalArea.isEmpty())
  216186. {
  216187. if (image == 0 || image->getWidth() < totalArea.getWidth()
  216188. || image->getHeight() < totalArea.getHeight())
  216189. {
  216190. delete image;
  216191. #if JUCE_USE_XSHM
  216192. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  216193. : Image::RGB,
  216194. #else
  216195. image = new XBitmapImage (Image::RGB,
  216196. #endif
  216197. (totalArea.getWidth() + 31) & ~31,
  216198. (totalArea.getHeight() + 31) & ~31,
  216199. false,
  216200. peer->depthIs16Bit);
  216201. }
  216202. startTimer (repaintTimerPeriod);
  216203. LowLevelGraphicsSoftwareRenderer context (*image);
  216204. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  216205. if (context.reduceClipRegion (regionsNeedingRepaint))
  216206. peer->handlePaint (context);
  216207. if (! peer->maskedRegion.isEmpty())
  216208. regionsNeedingRepaint.subtract (peer->maskedRegion);
  216209. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  216210. {
  216211. const Rectangle& r = *i.getRectangle();
  216212. image->blitToWindow (peer->windowH,
  216213. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  216214. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  216215. }
  216216. }
  216217. regionsNeedingRepaint.clear();
  216218. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  216219. startTimer (repaintTimerPeriod);
  216220. }
  216221. private:
  216222. LinuxComponentPeer* const peer;
  216223. XBitmapImage* image;
  216224. uint32 lastTimeImageUsed;
  216225. RectangleList regionsNeedingRepaint;
  216226. #if JUCE_USE_XSHM
  216227. bool useARGBImagesForRendering;
  216228. #endif
  216229. LinuxRepaintManager (const LinuxRepaintManager&);
  216230. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  216231. };
  216232. LinuxRepaintManager* repainter;
  216233. friend class LinuxRepaintManager;
  216234. Window windowH, parentWindow;
  216235. int wx, wy, ww, wh;
  216236. Image* taskbarImage;
  216237. bool fullScreen, entered, mapped, depthIs16Bit;
  216238. BorderSize windowBorder;
  216239. void removeWindowDecorations (Window wndH)
  216240. {
  216241. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216242. if (hints != None)
  216243. {
  216244. typedef struct
  216245. {
  216246. unsigned long flags;
  216247. unsigned long functions;
  216248. unsigned long decorations;
  216249. long input_mode;
  216250. unsigned long status;
  216251. } MotifWmHints;
  216252. MotifWmHints motifHints;
  216253. zerostruct (motifHints);
  216254. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  216255. motifHints.decorations = 0;
  216256. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216257. (unsigned char*) &motifHints, 4);
  216258. }
  216259. hints = XInternAtom (display, "_WIN_HINTS", True);
  216260. if (hints != None)
  216261. {
  216262. long gnomeHints = 0;
  216263. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216264. (unsigned char*) &gnomeHints, 1);
  216265. }
  216266. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  216267. if (hints != None)
  216268. {
  216269. long kwmHints = 2; /*KDE_tinyDecoration*/
  216270. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216271. (unsigned char*) &kwmHints, 1);
  216272. }
  216273. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  216274. if (hints != None)
  216275. {
  216276. int netHints [2];
  216277. int numHints = 0;
  216278. if ((styleFlags & windowIsTemporary) != 0)
  216279. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  216280. else
  216281. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  216282. if (netHints [numHints] != 0)
  216283. ++numHints;
  216284. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  216285. if (netHints [numHints] != 0)
  216286. ++numHints;
  216287. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216288. (unsigned char*) &netHints, numHints);
  216289. }
  216290. }
  216291. void addWindowButtons (Window wndH)
  216292. {
  216293. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216294. if (hints != None)
  216295. {
  216296. typedef struct
  216297. {
  216298. unsigned long flags;
  216299. unsigned long functions;
  216300. unsigned long decorations;
  216301. long input_mode;
  216302. unsigned long status;
  216303. } MotifWmHints;
  216304. MotifWmHints motifHints;
  216305. zerostruct (motifHints);
  216306. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  216307. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  216308. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  216309. if ((styleFlags & windowHasCloseButton) != 0)
  216310. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  216311. if ((styleFlags & windowHasMinimiseButton) != 0)
  216312. {
  216313. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  216314. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  216315. }
  216316. if ((styleFlags & windowHasMaximiseButton) != 0)
  216317. {
  216318. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  216319. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  216320. }
  216321. if ((styleFlags & windowIsResizable) != 0)
  216322. {
  216323. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  216324. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  216325. }
  216326. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  216327. }
  216328. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  216329. if (hints != None)
  216330. {
  216331. int netHints [6];
  216332. int num = 0;
  216333. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  216334. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  216335. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  216336. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  216337. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216338. (unsigned char*) &netHints, num);
  216339. }
  216340. }
  216341. void createWindow()
  216342. {
  216343. static bool atomsInitialised = false;
  216344. if (! atomsInitialised)
  216345. {
  216346. atomsInitialised = true;
  216347. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  216348. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  216349. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  216350. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  216351. wm_State = XInternAtom (display, "WM_STATE", 1);
  216352. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  216353. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  216354. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  216355. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  216356. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  216357. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  216358. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  216359. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  216360. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  216361. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  216362. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  216363. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  216364. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  216365. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  216366. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  216367. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  216368. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  216369. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  216370. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  216371. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  216372. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  216373. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  216374. }
  216375. resetDragAndDrop();
  216376. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  216377. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  216378. allowedMimeTypeAtoms [1] = XA_OtherMime;
  216379. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  216380. allowedActions [0] = XA_XdndActionMove;
  216381. allowedActions [1] = XA_XdndActionCopy;
  216382. allowedActions [2] = XA_XdndActionLink;
  216383. allowedActions [3] = XA_XdndActionAsk;
  216384. allowedActions [4] = XA_XdndActionPrivate;
  216385. // Get defaults for various properties
  216386. const int screen = DefaultScreen (display);
  216387. Window root = RootWindow (display, screen);
  216388. // Attempt to create a 24-bit window on the default screen. If this is not
  216389. // possible then exit
  216390. XVisualInfo desiredVisual;
  216391. desiredVisual.screen = screen;
  216392. desiredVisual.depth = 24;
  216393. depthIs16Bit = false;
  216394. int numVisuals;
  216395. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216396. &desiredVisual, &numVisuals);
  216397. if (numVisuals < 1 || visuals == 0)
  216398. {
  216399. XFree (visuals);
  216400. desiredVisual.depth = 16;
  216401. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216402. &desiredVisual, &numVisuals);
  216403. if (numVisuals < 1 || visuals == 0)
  216404. {
  216405. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  216406. Process::terminate();
  216407. }
  216408. depthIs16Bit = true;
  216409. }
  216410. XFree (visuals);
  216411. // Set up the window attributes
  216412. XSetWindowAttributes swa;
  216413. swa.border_pixel = 0;
  216414. swa.background_pixmap = None;
  216415. swa.colormap = DefaultColormap (display, screen);
  216416. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  216417. swa.event_mask = eventMask;
  216418. Window wndH = XCreateWindow (display, root,
  216419. 0, 0, 1, 1,
  216420. 0, 0, InputOutput, (Visual*) CopyFromParent,
  216421. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  216422. &swa);
  216423. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  216424. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  216425. GrabModeAsync, GrabModeAsync, None, None);
  216426. // Set the window context to identify the window handle object
  216427. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  216428. {
  216429. // Failed
  216430. jassertfalse
  216431. Logger::outputDebugString ("Failed to create context information for window.\n");
  216432. XDestroyWindow (display, wndH);
  216433. wndH = 0;
  216434. }
  216435. // Set window manager hints
  216436. XWMHints* wmHints = XAllocWMHints();
  216437. wmHints->flags = InputHint | StateHint;
  216438. wmHints->input = True; // Locally active input model
  216439. wmHints->initial_state = NormalState;
  216440. XSetWMHints (display, wndH, wmHints);
  216441. XFree (wmHints);
  216442. if ((styleFlags & windowIsSemiTransparent) != 0)
  216443. {
  216444. //xxx
  216445. }
  216446. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  216447. {
  216448. //xxx
  216449. }
  216450. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  216451. if ((styleFlags & windowHasTitleBar) == 0)
  216452. removeWindowDecorations (wndH);
  216453. else
  216454. addWindowButtons (wndH);
  216455. // Set window manager protocols
  216456. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  216457. (unsigned char*) wm_ProtocolList, 2);
  216458. // Set drag and drop flags
  216459. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  216460. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  216461. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  216462. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  216463. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  216464. (const unsigned char*) "", 0);
  216465. unsigned long dndVersion = ourDndVersion;
  216466. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  216467. (const unsigned char*) &dndVersion, 1);
  216468. // Set window name
  216469. setWindowTitle (wndH, getComponent()->getName());
  216470. // Initialise the pointer and keyboard mapping
  216471. // This is not the same as the logical pointer mapping the X server uses:
  216472. // we don't mess with this.
  216473. static bool mappingInitialised = false;
  216474. if (! mappingInitialised)
  216475. {
  216476. mappingInitialised = true;
  216477. const int numButtons = XGetPointerMapping (display, 0, 0);
  216478. if (numButtons == 2)
  216479. {
  216480. pointerMap[0] = LeftButton;
  216481. pointerMap[1] = RightButton;
  216482. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  216483. }
  216484. else if (numButtons >= 3)
  216485. {
  216486. pointerMap[0] = LeftButton;
  216487. pointerMap[1] = MiddleButton;
  216488. pointerMap[2] = RightButton;
  216489. if (numButtons >= 5)
  216490. {
  216491. pointerMap[3] = WheelUp;
  216492. pointerMap[4] = WheelDown;
  216493. }
  216494. }
  216495. getModifierMapping();
  216496. }
  216497. windowH = wndH;
  216498. }
  216499. void destroyWindow()
  216500. {
  216501. XPointer handlePointer;
  216502. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  216503. XDeleteContext (display, (XID) windowH, improbableNumber);
  216504. XDestroyWindow (display, windowH);
  216505. // Wait for it to complete and then remove any events for this
  216506. // window from the event queue.
  216507. XSync (display, false);
  216508. XEvent event;
  216509. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  216510. {}
  216511. }
  216512. static int64 getEventTime (::Time t) throw()
  216513. {
  216514. static int64 eventTimeOffset = 0x12345678;
  216515. const int64 thisMessageTime = t;
  216516. if (eventTimeOffset == 0x12345678)
  216517. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  216518. return eventTimeOffset + thisMessageTime;
  216519. }
  216520. static void setWindowTitle (Window xwin, const char* const title) throw()
  216521. {
  216522. XTextProperty nameProperty;
  216523. char* strings[] = { (char*) title };
  216524. if (XStringListToTextProperty (strings, 1, &nameProperty))
  216525. {
  216526. XSetWMName (display, xwin, &nameProperty);
  216527. XSetWMIconName (display, xwin, &nameProperty);
  216528. XFree (nameProperty.value);
  216529. }
  216530. }
  216531. void updateBorderSize()
  216532. {
  216533. if ((styleFlags & windowHasTitleBar) == 0)
  216534. {
  216535. windowBorder = BorderSize (0);
  216536. }
  216537. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  216538. {
  216539. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  216540. if (hints != None)
  216541. {
  216542. unsigned char* data = 0;
  216543. unsigned long nitems, bytesLeft;
  216544. Atom actualType;
  216545. int actualFormat;
  216546. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  216547. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216548. &data) == Success)
  216549. {
  216550. const unsigned long* const sizes = (const unsigned long*) data;
  216551. if (actualFormat == 32)
  216552. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  216553. (int) sizes[3], (int) sizes[1]);
  216554. XFree (data);
  216555. }
  216556. }
  216557. }
  216558. }
  216559. void updateBounds()
  216560. {
  216561. jassert (windowH != 0);
  216562. if (windowH != 0)
  216563. {
  216564. Window root, child;
  216565. unsigned int bw, depth;
  216566. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216567. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  216568. &bw, &depth))
  216569. {
  216570. wx = wy = ww = wh = 0;
  216571. }
  216572. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  216573. {
  216574. wx = wy = 0;
  216575. }
  216576. }
  216577. }
  216578. void resetDragAndDrop()
  216579. {
  216580. dragAndDropFiles.clear();
  216581. lastDropX = lastDropY = -1;
  216582. dragAndDropCurrentMimeType = 0;
  216583. dragAndDropSourceWindow = 0;
  216584. srcMimeTypeAtomList.clear();
  216585. }
  216586. void sendDragAndDropMessage (XClientMessageEvent& msg)
  216587. {
  216588. msg.type = ClientMessage;
  216589. msg.display = display;
  216590. msg.window = dragAndDropSourceWindow;
  216591. msg.format = 32;
  216592. msg.data.l[0] = windowH;
  216593. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  216594. }
  216595. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  216596. {
  216597. XClientMessageEvent msg;
  216598. zerostruct (msg);
  216599. msg.message_type = XA_XdndStatus;
  216600. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  216601. msg.data.l[4] = dropAction;
  216602. sendDragAndDropMessage (msg);
  216603. }
  216604. void sendDragAndDropLeave()
  216605. {
  216606. XClientMessageEvent msg;
  216607. zerostruct (msg);
  216608. msg.message_type = XA_XdndLeave;
  216609. sendDragAndDropMessage (msg);
  216610. }
  216611. void sendDragAndDropFinish()
  216612. {
  216613. XClientMessageEvent msg;
  216614. zerostruct (msg);
  216615. msg.message_type = XA_XdndFinished;
  216616. sendDragAndDropMessage (msg);
  216617. }
  216618. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  216619. {
  216620. if ((clientMsg->data.l[1] & 1) == 0)
  216621. {
  216622. sendDragAndDropLeave();
  216623. if (dragAndDropFiles.size() > 0)
  216624. handleFileDragExit (dragAndDropFiles);
  216625. dragAndDropFiles.clear();
  216626. }
  216627. }
  216628. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  216629. {
  216630. if (dragAndDropSourceWindow == 0)
  216631. return;
  216632. dragAndDropSourceWindow = clientMsg->data.l[0];
  216633. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  216634. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  216635. if (lastDropX != dropX || lastDropY != dropY)
  216636. {
  216637. lastDropX = dropX;
  216638. lastDropY = dropY;
  216639. dragAndDropTimestamp = clientMsg->data.l[3];
  216640. Atom targetAction = XA_XdndActionCopy;
  216641. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  216642. {
  216643. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  216644. {
  216645. targetAction = allowedActions[i];
  216646. break;
  216647. }
  216648. }
  216649. sendDragAndDropStatus (true, targetAction);
  216650. if (dragAndDropFiles.size() == 0)
  216651. updateDraggedFileList (clientMsg);
  216652. if (dragAndDropFiles.size() > 0)
  216653. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  216654. }
  216655. }
  216656. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  216657. {
  216658. if (dragAndDropFiles.size() == 0)
  216659. updateDraggedFileList (clientMsg);
  216660. const StringArray files (dragAndDropFiles);
  216661. const int lastX = lastDropX, lastY = lastDropY;
  216662. sendDragAndDropFinish();
  216663. resetDragAndDrop();
  216664. if (files.size() > 0)
  216665. handleFileDragDrop (files, lastX, lastY);
  216666. }
  216667. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  216668. {
  216669. dragAndDropFiles.clear();
  216670. srcMimeTypeAtomList.clear();
  216671. dragAndDropCurrentMimeType = 0;
  216672. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  216673. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  216674. {
  216675. dragAndDropSourceWindow = 0;
  216676. return;
  216677. }
  216678. dragAndDropSourceWindow = clientMsg->data.l[0];
  216679. if ((clientMsg->data.l[1] & 1) != 0)
  216680. {
  216681. Atom actual;
  216682. int format;
  216683. unsigned long count = 0, remaining = 0;
  216684. unsigned char* data = 0;
  216685. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  216686. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  216687. &count, &remaining, &data);
  216688. if (data != 0)
  216689. {
  216690. if (actual == XA_ATOM && format == 32 && count != 0)
  216691. {
  216692. const unsigned long* const types = (const unsigned long*) data;
  216693. for (unsigned int i = 0; i < count; ++i)
  216694. if (types[i] != None)
  216695. srcMimeTypeAtomList.add (types[i]);
  216696. }
  216697. XFree (data);
  216698. }
  216699. }
  216700. if (srcMimeTypeAtomList.size() == 0)
  216701. {
  216702. for (int i = 2; i < 5; ++i)
  216703. if (clientMsg->data.l[i] != None)
  216704. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  216705. if (srcMimeTypeAtomList.size() == 0)
  216706. {
  216707. dragAndDropSourceWindow = 0;
  216708. return;
  216709. }
  216710. }
  216711. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  216712. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  216713. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  216714. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  216715. handleDragAndDropPosition (clientMsg);
  216716. }
  216717. void handleDragAndDropSelection (const XEvent* const evt)
  216718. {
  216719. dragAndDropFiles.clear();
  216720. if (evt->xselection.property != 0)
  216721. {
  216722. StringArray lines;
  216723. {
  216724. MemoryBlock dropData;
  216725. for (;;)
  216726. {
  216727. Atom actual;
  216728. uint8* data = 0;
  216729. unsigned long count = 0, remaining = 0;
  216730. int format = 0;
  216731. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  216732. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  216733. &format, &count, &remaining, &data) == Success)
  216734. {
  216735. dropData.append (data, count * format / 8);
  216736. XFree (data);
  216737. if (remaining == 0)
  216738. break;
  216739. }
  216740. else
  216741. {
  216742. XFree (data);
  216743. break;
  216744. }
  216745. }
  216746. lines.addLines (dropData.toString());
  216747. }
  216748. for (int i = 0; i < lines.size(); ++i)
  216749. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  216750. dragAndDropFiles.trim();
  216751. dragAndDropFiles.removeEmptyStrings();
  216752. }
  216753. }
  216754. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  216755. {
  216756. dragAndDropFiles.clear();
  216757. if (dragAndDropSourceWindow != None
  216758. && dragAndDropCurrentMimeType != 0)
  216759. {
  216760. dragAndDropTimestamp = clientMsg->data.l[2];
  216761. XConvertSelection (display,
  216762. XA_XdndSelection,
  216763. dragAndDropCurrentMimeType,
  216764. XA_JXSelectionWindowProperty,
  216765. windowH,
  216766. dragAndDropTimestamp);
  216767. }
  216768. }
  216769. StringArray dragAndDropFiles;
  216770. int dragAndDropTimestamp, lastDropX, lastDropY;
  216771. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  216772. Window dragAndDropSourceWindow;
  216773. unsigned int allowedActions [5];
  216774. unsigned int allowedMimeTypeAtoms [3];
  216775. Array <Atom> srcMimeTypeAtomList;
  216776. };
  216777. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  216778. {
  216779. if (enableOrDisable)
  216780. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  216781. }
  216782. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  216783. {
  216784. return new LinuxComponentPeer (this, styleFlags);
  216785. }
  216786. // (this callback is hooked up in the messaging code)
  216787. void juce_windowMessageReceive (XEvent* event)
  216788. {
  216789. if (event->xany.window != None)
  216790. {
  216791. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  216792. if (ComponentPeer::isValidPeer (peer))
  216793. peer->handleWindowMessage (event);
  216794. }
  216795. else
  216796. {
  216797. switch (event->xany.type)
  216798. {
  216799. case KeymapNotify:
  216800. {
  216801. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  216802. memcpy (keyStates, keymapEvent->key_vector, 32);
  216803. break;
  216804. }
  216805. default:
  216806. break;
  216807. }
  216808. }
  216809. }
  216810. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  216811. {
  216812. #if JUCE_USE_XINERAMA
  216813. int major_opcode, first_event, first_error;
  216814. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  216815. && XineramaIsActive (display))
  216816. {
  216817. int numMonitors = 0;
  216818. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  216819. if (screens != 0)
  216820. {
  216821. for (int i = numMonitors; --i >= 0;)
  216822. {
  216823. int index = screens[i].screen_number;
  216824. if (index >= 0)
  216825. {
  216826. while (monitorCoords.size() < index)
  216827. monitorCoords.add (Rectangle (0, 0, 0, 0));
  216828. monitorCoords.set (index, Rectangle (screens[i].x_org,
  216829. screens[i].y_org,
  216830. screens[i].width,
  216831. screens[i].height));
  216832. }
  216833. }
  216834. XFree (screens);
  216835. }
  216836. }
  216837. if (monitorCoords.size() == 0)
  216838. #endif
  216839. {
  216840. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  216841. if (hints != None)
  216842. {
  216843. const int numMonitors = ScreenCount (display);
  216844. for (int i = 0; i < numMonitors; ++i)
  216845. {
  216846. Window root = RootWindow (display, i);
  216847. unsigned long nitems, bytesLeft;
  216848. Atom actualType;
  216849. int actualFormat;
  216850. unsigned char* data = 0;
  216851. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  216852. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216853. &data) == Success)
  216854. {
  216855. const long* const position = (const long*) data;
  216856. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  216857. monitorCoords.add (Rectangle (position[0], position[1],
  216858. position[2], position[3]));
  216859. XFree (data);
  216860. }
  216861. }
  216862. }
  216863. if (monitorCoords.size() == 0)
  216864. {
  216865. monitorCoords.add (Rectangle (0, 0,
  216866. DisplayWidth (display, DefaultScreen (display)),
  216867. DisplayHeight (display, DefaultScreen (display))));
  216868. }
  216869. }
  216870. }
  216871. bool Desktop::canUseSemiTransparentWindows() throw()
  216872. {
  216873. return false;
  216874. }
  216875. void Desktop::getMousePosition (int& x, int& y) throw()
  216876. {
  216877. int mouseMods;
  216878. getMousePos (x, y, mouseMods);
  216879. }
  216880. void Desktop::setMousePosition (int x, int y) throw()
  216881. {
  216882. Window root = RootWindow (display, DefaultScreen (display));
  216883. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  216884. }
  216885. static bool screenSaverAllowed = true;
  216886. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  216887. {
  216888. if (screenSaverAllowed != isEnabled)
  216889. {
  216890. screenSaverAllowed = isEnabled;
  216891. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  216892. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  216893. if (xScreenSaverSuspend == 0)
  216894. {
  216895. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  216896. if (h != 0)
  216897. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  216898. }
  216899. if (xScreenSaverSuspend != 0)
  216900. xScreenSaverSuspend (display, ! isEnabled);
  216901. }
  216902. }
  216903. bool Desktop::isScreenSaverEnabled() throw()
  216904. {
  216905. return screenSaverAllowed;
  216906. }
  216907. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  216908. {
  216909. Window root = RootWindow (display, DefaultScreen (display));
  216910. const unsigned int imageW = image.getWidth();
  216911. const unsigned int imageH = image.getHeight();
  216912. unsigned int cursorW, cursorH;
  216913. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  216914. return 0;
  216915. Image im (Image::ARGB, cursorW, cursorH, true);
  216916. Graphics g (im);
  216917. if (imageW > cursorW || imageH > cursorH)
  216918. {
  216919. hotspotX = (hotspotX * cursorW) / imageW;
  216920. hotspotY = (hotspotY * cursorH) / imageH;
  216921. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  216922. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  216923. false);
  216924. }
  216925. else
  216926. {
  216927. g.drawImageAt (&image, 0, 0);
  216928. }
  216929. const int stride = (cursorW + 7) >> 3;
  216930. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  216931. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  216932. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216933. for (int y = cursorH; --y >= 0;)
  216934. {
  216935. for (int x = cursorW; --x >= 0;)
  216936. {
  216937. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216938. const int offset = y * stride + (x >> 3);
  216939. const Colour c (im.getPixelAt (x, y));
  216940. if (c.getAlpha() >= 128)
  216941. maskPlane[offset] |= mask;
  216942. if (c.getBrightness() >= 0.5f)
  216943. sourcePlane[offset] |= mask;
  216944. }
  216945. }
  216946. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  216947. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  216948. juce_free (maskPlane);
  216949. juce_free (sourcePlane);
  216950. XColor white, black;
  216951. black.red = black.green = black.blue = 0;
  216952. white.red = white.green = white.blue = 0xffff;
  216953. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  216954. XFreePixmap (display, sourcePixmap);
  216955. XFreePixmap (display, maskPixmap);
  216956. return result;
  216957. }
  216958. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  216959. {
  216960. if (cursorHandle != None)
  216961. XFreeCursor (display, (Cursor) cursorHandle);
  216962. }
  216963. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  216964. {
  216965. unsigned int shape;
  216966. switch (type)
  216967. {
  216968. case MouseCursor::NoCursor:
  216969. {
  216970. const Image im (Image::ARGB, 16, 16, true);
  216971. return juce_createMouseCursorFromImage (im, 0, 0);
  216972. }
  216973. case MouseCursor::NormalCursor:
  216974. return (void*) None; // Use parent cursor
  216975. case MouseCursor::DraggingHandCursor:
  216976. {
  216977. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  216978. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  216979. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  216980. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  216981. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  216982. const int dragHandDataSize = 99;
  216983. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  216984. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  216985. delete im;
  216986. return dragHandCursor;
  216987. }
  216988. case MouseCursor::CopyingCursor:
  216989. {
  216990. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  216991. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  216992. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  216993. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  216994. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  216995. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  216996. const int copyCursorSize = 119;
  216997. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  216998. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  216999. delete im;
  217000. return copyCursor;
  217001. }
  217002. case MouseCursor::WaitCursor:
  217003. shape = XC_watch;
  217004. break;
  217005. case MouseCursor::IBeamCursor:
  217006. shape = XC_xterm;
  217007. break;
  217008. case MouseCursor::PointingHandCursor:
  217009. shape = XC_hand2;
  217010. break;
  217011. case MouseCursor::LeftRightResizeCursor:
  217012. shape = XC_sb_h_double_arrow;
  217013. break;
  217014. case MouseCursor::UpDownResizeCursor:
  217015. shape = XC_sb_v_double_arrow;
  217016. break;
  217017. case MouseCursor::UpDownLeftRightResizeCursor:
  217018. shape = XC_fleur;
  217019. break;
  217020. case MouseCursor::TopEdgeResizeCursor:
  217021. shape = XC_top_side;
  217022. break;
  217023. case MouseCursor::BottomEdgeResizeCursor:
  217024. shape = XC_bottom_side;
  217025. break;
  217026. case MouseCursor::LeftEdgeResizeCursor:
  217027. shape = XC_left_side;
  217028. break;
  217029. case MouseCursor::RightEdgeResizeCursor:
  217030. shape = XC_right_side;
  217031. break;
  217032. case MouseCursor::TopLeftCornerResizeCursor:
  217033. shape = XC_top_left_corner;
  217034. break;
  217035. case MouseCursor::TopRightCornerResizeCursor:
  217036. shape = XC_top_right_corner;
  217037. break;
  217038. case MouseCursor::BottomLeftCornerResizeCursor:
  217039. shape = XC_bottom_left_corner;
  217040. break;
  217041. case MouseCursor::BottomRightCornerResizeCursor:
  217042. shape = XC_bottom_right_corner;
  217043. break;
  217044. case MouseCursor::CrosshairCursor:
  217045. shape = XC_crosshair;
  217046. break;
  217047. default:
  217048. return (void*) None; // Use parent cursor
  217049. }
  217050. return (void*) XCreateFontCursor (display, shape);
  217051. }
  217052. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  217053. {
  217054. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  217055. if (lp != 0)
  217056. lp->showMouseCursor ((Cursor) getHandle());
  217057. }
  217058. void MouseCursor::showInAllWindows() const throw()
  217059. {
  217060. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  217061. showInWindow (ComponentPeer::getPeer (i));
  217062. }
  217063. Image* juce_createIconForFile (const File& file)
  217064. {
  217065. return 0;
  217066. }
  217067. #if JUCE_OPENGL
  217068. class WindowedGLContext : public OpenGLContext
  217069. {
  217070. public:
  217071. WindowedGLContext (Component* const component,
  217072. const OpenGLPixelFormat& pixelFormat_,
  217073. GLXContext sharedContext)
  217074. : renderContext (0),
  217075. embeddedWindow (0),
  217076. pixelFormat (pixelFormat_)
  217077. {
  217078. jassert (component != 0);
  217079. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  217080. if (peer == 0)
  217081. return;
  217082. XSync (display, False);
  217083. GLint attribs [64];
  217084. int n = 0;
  217085. attribs[n++] = GLX_RGBA;
  217086. attribs[n++] = GLX_DOUBLEBUFFER;
  217087. attribs[n++] = GLX_RED_SIZE;
  217088. attribs[n++] = pixelFormat.redBits;
  217089. attribs[n++] = GLX_GREEN_SIZE;
  217090. attribs[n++] = pixelFormat.greenBits;
  217091. attribs[n++] = GLX_BLUE_SIZE;
  217092. attribs[n++] = pixelFormat.blueBits;
  217093. attribs[n++] = GLX_ALPHA_SIZE;
  217094. attribs[n++] = pixelFormat.alphaBits;
  217095. attribs[n++] = GLX_DEPTH_SIZE;
  217096. attribs[n++] = pixelFormat.depthBufferBits;
  217097. attribs[n++] = GLX_STENCIL_SIZE;
  217098. attribs[n++] = pixelFormat.stencilBufferBits;
  217099. attribs[n++] = GLX_ACCUM_RED_SIZE;
  217100. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  217101. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  217102. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  217103. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  217104. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  217105. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  217106. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  217107. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  217108. attribs[n++] = None;
  217109. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  217110. if (bestVisual == 0)
  217111. return;
  217112. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  217113. Window windowH = (Window) peer->getNativeHandle();
  217114. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  217115. XSetWindowAttributes swa;
  217116. swa.colormap = colourMap;
  217117. swa.border_pixel = 0;
  217118. swa.event_mask = ExposureMask | StructureNotifyMask;
  217119. embeddedWindow = XCreateWindow (display, windowH,
  217120. 0, 0, 1, 1, 0,
  217121. bestVisual->depth,
  217122. InputOutput,
  217123. bestVisual->visual,
  217124. CWBorderPixel | CWColormap | CWEventMask,
  217125. &swa);
  217126. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  217127. XMapWindow (display, embeddedWindow);
  217128. XFreeColormap (display, colourMap);
  217129. XFree (bestVisual);
  217130. XSync (display, False);
  217131. }
  217132. ~WindowedGLContext()
  217133. {
  217134. makeInactive();
  217135. glXDestroyContext (display, renderContext);
  217136. XUnmapWindow (display, embeddedWindow);
  217137. XDestroyWindow (display, embeddedWindow);
  217138. }
  217139. bool makeActive() const throw()
  217140. {
  217141. jassert (renderContext != 0);
  217142. return glXMakeCurrent (display, embeddedWindow, renderContext)
  217143. && XSync (display, False);
  217144. }
  217145. bool makeInactive() const throw()
  217146. {
  217147. return (! isActive()) || glXMakeCurrent (display, None, 0);
  217148. }
  217149. bool isActive() const throw()
  217150. {
  217151. return glXGetCurrentContext() == renderContext;
  217152. }
  217153. const OpenGLPixelFormat getPixelFormat() const
  217154. {
  217155. return pixelFormat;
  217156. }
  217157. void* getRawContext() const throw()
  217158. {
  217159. return renderContext;
  217160. }
  217161. void updateWindowPosition (int x, int y, int w, int h, int)
  217162. {
  217163. XMoveResizeWindow (display, embeddedWindow,
  217164. x, y, jmax (1, w), jmax (1, h));
  217165. }
  217166. void swapBuffers()
  217167. {
  217168. glXSwapBuffers (display, embeddedWindow);
  217169. }
  217170. bool setSwapInterval (const int numFramesPerSwap)
  217171. {
  217172. // xxx needs doing..
  217173. return false;
  217174. }
  217175. int getSwapInterval() const
  217176. {
  217177. // xxx needs doing..
  217178. return 0;
  217179. }
  217180. void repaint()
  217181. {
  217182. }
  217183. juce_UseDebuggingNewOperator
  217184. GLXContext renderContext;
  217185. private:
  217186. Window embeddedWindow;
  217187. OpenGLPixelFormat pixelFormat;
  217188. WindowedGLContext (const WindowedGLContext&);
  217189. const WindowedGLContext& operator= (const WindowedGLContext&);
  217190. };
  217191. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  217192. const OpenGLPixelFormat& pixelFormat,
  217193. const OpenGLContext* const contextToShareWith)
  217194. {
  217195. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  217196. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  217197. if (c->renderContext == 0)
  217198. deleteAndZero (c);
  217199. return c;
  217200. }
  217201. void juce_glViewport (const int w, const int h)
  217202. {
  217203. glViewport (0, 0, w, h);
  217204. }
  217205. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  217206. OwnedArray <OpenGLPixelFormat>& results)
  217207. {
  217208. results.add (new OpenGLPixelFormat()); // xxx
  217209. }
  217210. #endif
  217211. static void initClipboard (Window root, Atom* cutBuffers) throw()
  217212. {
  217213. static bool init = false;
  217214. if (! init)
  217215. {
  217216. init = true;
  217217. // Make sure all cut buffers exist before use
  217218. for (int i = 0; i < 8; i++)
  217219. {
  217220. XChangeProperty (display, root, cutBuffers[i],
  217221. XA_STRING, 8, PropModeAppend, NULL, 0);
  217222. }
  217223. }
  217224. }
  217225. // Clipboard implemented currently using cut buffers
  217226. // rather than the more powerful selection method
  217227. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  217228. {
  217229. Window root = RootWindow (display, DefaultScreen (display));
  217230. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217231. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217232. initClipboard (root, cutBuffers);
  217233. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  217234. XChangeProperty (display, root, cutBuffers[0],
  217235. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  217236. clipText.length());
  217237. }
  217238. const String SystemClipboard::getTextFromClipboard() throw()
  217239. {
  217240. const int bufSize = 64; // in words
  217241. String returnData;
  217242. int byteOffset = 0;
  217243. Window root = RootWindow (display, DefaultScreen (display));
  217244. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217245. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217246. initClipboard (root, cutBuffers);
  217247. for (;;)
  217248. {
  217249. unsigned long bytesLeft = 0, nitems = 0;
  217250. unsigned char* clipData = 0;
  217251. int actualFormat = 0;
  217252. Atom actualType;
  217253. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  217254. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  217255. &clipData) == Success)
  217256. {
  217257. if (actualType == XA_STRING && actualFormat == 8)
  217258. {
  217259. byteOffset += nitems;
  217260. returnData += String ((const char*) clipData, nitems);
  217261. }
  217262. else
  217263. {
  217264. bytesLeft = 0;
  217265. }
  217266. if (clipData != 0)
  217267. XFree (clipData);
  217268. }
  217269. if (bytesLeft == 0)
  217270. break;
  217271. }
  217272. return returnData;
  217273. }
  217274. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  217275. {
  217276. jassertfalse // not implemented!
  217277. return false;
  217278. }
  217279. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  217280. {
  217281. jassertfalse // not implemented!
  217282. return false;
  217283. }
  217284. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  217285. {
  217286. if (! isOnDesktop ())
  217287. addToDesktop (0);
  217288. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217289. if (wp != 0)
  217290. {
  217291. wp->setTaskBarIcon (newImage);
  217292. setVisible (true);
  217293. toFront (false);
  217294. repaint();
  217295. }
  217296. }
  217297. void SystemTrayIconComponent::paint (Graphics& g)
  217298. {
  217299. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217300. if (wp != 0)
  217301. {
  217302. const Image* const image = wp->getTaskbarIcon();
  217303. if (image != 0)
  217304. {
  217305. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  217306. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  217307. false);
  217308. }
  217309. }
  217310. }
  217311. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  217312. {
  217313. // xxx not yet implemented!
  217314. }
  217315. void PlatformUtilities::beep()
  217316. {
  217317. fprintf (stdout, "\a");
  217318. fflush (stdout);
  217319. }
  217320. bool AlertWindow::showNativeDialogBox (const String& title,
  217321. const String& bodyText,
  217322. bool isOkCancel)
  217323. {
  217324. // xxx this is supposed to pop up an alert!
  217325. Logger::outputDebugString (title + ": " + bodyText);
  217326. // use a non-native one for the time being..
  217327. if (isOkCancel)
  217328. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  217329. else
  217330. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  217331. return true;
  217332. }
  217333. const int KeyPress::spaceKey = XK_space & 0xff;
  217334. const int KeyPress::returnKey = XK_Return & 0xff;
  217335. const int KeyPress::escapeKey = XK_Escape & 0xff;
  217336. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  217337. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  217338. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  217339. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  217340. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  217341. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  217342. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  217343. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  217344. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  217345. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  217346. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  217347. const int KeyPress::tabKey = XK_Tab & 0xff;
  217348. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  217349. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  217350. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  217351. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  217352. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  217353. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  217354. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  217355. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  217356. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  217357. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  217358. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  217359. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  217360. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  217361. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  217362. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  217363. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  217364. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  217365. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  217366. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  217367. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  217368. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  217369. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  217370. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  217371. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  217372. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  217373. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  217374. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  217375. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  217376. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  217377. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  217378. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  217379. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  217380. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  217381. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  217382. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  217383. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  217384. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  217385. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  217386. #endif
  217387. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  217388. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  217389. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217390. // compiled on its own).
  217391. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  217392. static const int maxNumChans = 64;
  217393. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  217394. {
  217395. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  217396. snd_pcm_hw_params_t* hwParams;
  217397. snd_pcm_hw_params_alloca (&hwParams);
  217398. for (int i = 0; ratesToTry[i] != 0; ++i)
  217399. {
  217400. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  217401. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  217402. {
  217403. rates.addIfNotAlreadyThere (ratesToTry[i]);
  217404. }
  217405. }
  217406. }
  217407. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  217408. {
  217409. snd_pcm_hw_params_t *params;
  217410. snd_pcm_hw_params_alloca (&params);
  217411. if (snd_pcm_hw_params_any (handle, params) >= 0)
  217412. {
  217413. snd_pcm_hw_params_get_channels_min (params, minChans);
  217414. snd_pcm_hw_params_get_channels_max (params, maxChans);
  217415. }
  217416. }
  217417. static void getDeviceProperties (const String& id,
  217418. unsigned int& minChansOut,
  217419. unsigned int& maxChansOut,
  217420. unsigned int& minChansIn,
  217421. unsigned int& maxChansIn,
  217422. Array <int>& rates)
  217423. {
  217424. if (id.isEmpty())
  217425. return;
  217426. snd_ctl_t* handle;
  217427. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  217428. {
  217429. snd_pcm_info_t* info;
  217430. snd_pcm_info_alloca (&info);
  217431. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  217432. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  217433. snd_pcm_info_set_subdevice (info, 0);
  217434. if (snd_ctl_pcm_info (handle, info) >= 0)
  217435. {
  217436. snd_pcm_t* pcmHandle;
  217437. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217438. {
  217439. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  217440. getDeviceSampleRates (pcmHandle, rates);
  217441. snd_pcm_close (pcmHandle);
  217442. }
  217443. }
  217444. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  217445. if (snd_ctl_pcm_info (handle, info) >= 0)
  217446. {
  217447. snd_pcm_t* pcmHandle;
  217448. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217449. {
  217450. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  217451. if (rates.size() == 0)
  217452. getDeviceSampleRates (pcmHandle, rates);
  217453. snd_pcm_close (pcmHandle);
  217454. }
  217455. }
  217456. snd_ctl_close (handle);
  217457. }
  217458. }
  217459. class ALSADevice
  217460. {
  217461. public:
  217462. ALSADevice (const String& id,
  217463. const bool forInput)
  217464. : handle (0),
  217465. bitDepth (16),
  217466. numChannelsRunning (0),
  217467. isInput (forInput),
  217468. sampleFormat (AudioDataConverters::int16LE)
  217469. {
  217470. failed (snd_pcm_open (&handle, id,
  217471. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  217472. SND_PCM_ASYNC));
  217473. }
  217474. ~ALSADevice()
  217475. {
  217476. if (handle != 0)
  217477. snd_pcm_close (handle);
  217478. }
  217479. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  217480. {
  217481. if (handle == 0)
  217482. return false;
  217483. snd_pcm_hw_params_t* hwParams;
  217484. snd_pcm_hw_params_alloca (&hwParams);
  217485. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  217486. return false;
  217487. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  217488. isInterleaved = false;
  217489. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  217490. isInterleaved = true;
  217491. else
  217492. {
  217493. jassertfalse
  217494. return false;
  217495. }
  217496. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  217497. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  217498. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  217499. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  217500. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  217501. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  217502. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  217503. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  217504. bitDepth = 0;
  217505. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  217506. {
  217507. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  217508. {
  217509. bitDepth = formatsToTry [i + 1];
  217510. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  217511. break;
  217512. }
  217513. }
  217514. if (bitDepth == 0)
  217515. {
  217516. error = "device doesn't support a compatible PCM format";
  217517. DBG (T("ALSA error: ") + error + T("\n"));
  217518. return false;
  217519. }
  217520. int dir = 0;
  217521. unsigned int periods = 4;
  217522. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  217523. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  217524. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  217525. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  217526. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  217527. || failed (snd_pcm_hw_params (handle, hwParams)))
  217528. {
  217529. return false;
  217530. }
  217531. snd_pcm_sw_params_t* swParams;
  217532. snd_pcm_sw_params_alloca (&swParams);
  217533. snd_pcm_uframes_t boundary;
  217534. if (failed (snd_pcm_sw_params_current (handle, swParams))
  217535. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  217536. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  217537. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  217538. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  217539. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  217540. || failed (snd_pcm_sw_params (handle, swParams)))
  217541. {
  217542. return false;
  217543. }
  217544. /*
  217545. #ifdef JUCE_DEBUG
  217546. // enable this to dump the config of the devices that get opened
  217547. snd_output_t* out;
  217548. snd_output_stdio_attach (&out, stderr, 0);
  217549. snd_pcm_hw_params_dump (hwParams, out);
  217550. snd_pcm_sw_params_dump (swParams, out);
  217551. #endif
  217552. */
  217553. numChannelsRunning = numChannels;
  217554. return true;
  217555. }
  217556. bool write (float** const data, const int numSamples)
  217557. {
  217558. if (isInterleaved)
  217559. {
  217560. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217561. float* interleaved = (float*) scratch;
  217562. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  217563. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217564. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  217565. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217566. return false;
  217567. }
  217568. else
  217569. {
  217570. for (int i = 0; i < numChannelsRunning; ++i)
  217571. if (data[i] != 0)
  217572. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  217573. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  217574. if (failed (num))
  217575. {
  217576. if (num == -EPIPE)
  217577. {
  217578. if (failed (snd_pcm_prepare (handle)))
  217579. return false;
  217580. }
  217581. else if (num != -ESTRPIPE)
  217582. return false;
  217583. }
  217584. }
  217585. return true;
  217586. }
  217587. bool read (float** const data, const int numSamples)
  217588. {
  217589. if (isInterleaved)
  217590. {
  217591. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217592. float* interleaved = (float*) scratch;
  217593. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  217594. if (failed (num))
  217595. {
  217596. if (num == -EPIPE)
  217597. {
  217598. if (failed (snd_pcm_prepare (handle)))
  217599. return false;
  217600. }
  217601. else if (num != -ESTRPIPE)
  217602. return false;
  217603. }
  217604. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217605. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  217606. }
  217607. else
  217608. {
  217609. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  217610. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217611. return false;
  217612. for (int i = 0; i < numChannelsRunning; ++i)
  217613. if (data[i] != 0)
  217614. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  217615. }
  217616. return true;
  217617. }
  217618. juce_UseDebuggingNewOperator
  217619. snd_pcm_t* handle;
  217620. String error;
  217621. int bitDepth, numChannelsRunning;
  217622. private:
  217623. const bool isInput;
  217624. bool isInterleaved;
  217625. MemoryBlock scratch;
  217626. AudioDataConverters::DataFormat sampleFormat;
  217627. bool failed (const int errorNum)
  217628. {
  217629. if (errorNum >= 0)
  217630. return false;
  217631. error = snd_strerror (errorNum);
  217632. DBG (T("ALSA error: ") + error + T("\n"));
  217633. return true;
  217634. }
  217635. };
  217636. class ALSAThread : public Thread
  217637. {
  217638. public:
  217639. ALSAThread (const String& inputId_,
  217640. const String& outputId_)
  217641. : Thread ("Juce ALSA"),
  217642. sampleRate (0),
  217643. bufferSize (0),
  217644. callback (0),
  217645. inputId (inputId_),
  217646. outputId (outputId_),
  217647. outputDevice (0),
  217648. inputDevice (0),
  217649. numCallbacks (0),
  217650. totalNumInputChannels (0),
  217651. totalNumOutputChannels (0)
  217652. {
  217653. zeromem (outputChannelData, sizeof (outputChannelData));
  217654. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217655. zeromem (inputChannelData, sizeof (inputChannelData));
  217656. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217657. initialiseRatesAndChannels();
  217658. }
  217659. ~ALSAThread()
  217660. {
  217661. close();
  217662. }
  217663. void open (BitArray inputChannels,
  217664. BitArray outputChannels,
  217665. const double sampleRate_,
  217666. const int bufferSize_)
  217667. {
  217668. close();
  217669. error = String::empty;
  217670. sampleRate = sampleRate_;
  217671. bufferSize = bufferSize_;
  217672. currentInputChans.clear();
  217673. currentOutputChans.clear();
  217674. if (inputChannels.getHighestBit() >= 0)
  217675. {
  217676. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), minChansIn); ++i)
  217677. {
  217678. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217679. if (inputChannels[i])
  217680. {
  217681. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  217682. currentInputChans.setBit (i);
  217683. }
  217684. }
  217685. }
  217686. if (outputChannels.getHighestBit() >= 0)
  217687. {
  217688. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), minChansOut); ++i)
  217689. {
  217690. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217691. if (outputChannels[i])
  217692. {
  217693. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  217694. currentOutputChans.setBit (i);
  217695. }
  217696. }
  217697. }
  217698. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  217699. {
  217700. outputDevice = new ALSADevice (outputId, false);
  217701. if (outputDevice->error.isNotEmpty())
  217702. {
  217703. error = outputDevice->error;
  217704. deleteAndZero (outputDevice);
  217705. return;
  217706. }
  217707. currentOutputChans.setRange (0, minChansOut, true);
  217708. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  217709. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  217710. bufferSize))
  217711. {
  217712. error = outputDevice->error;
  217713. deleteAndZero (outputDevice);
  217714. return;
  217715. }
  217716. }
  217717. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  217718. {
  217719. inputDevice = new ALSADevice (inputId, true);
  217720. if (inputDevice->error.isNotEmpty())
  217721. {
  217722. error = inputDevice->error;
  217723. deleteAndZero (inputDevice);
  217724. return;
  217725. }
  217726. currentInputChans.setRange (0, minChansIn, true);
  217727. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  217728. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  217729. bufferSize))
  217730. {
  217731. error = inputDevice->error;
  217732. deleteAndZero (inputDevice);
  217733. return;
  217734. }
  217735. }
  217736. if (outputDevice == 0 && inputDevice == 0)
  217737. {
  217738. error = "no channels";
  217739. return;
  217740. }
  217741. if (outputDevice != 0 && inputDevice != 0)
  217742. {
  217743. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  217744. }
  217745. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  217746. return;
  217747. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  217748. return;
  217749. startThread (9);
  217750. int count = 1000;
  217751. while (numCallbacks == 0)
  217752. {
  217753. sleep (5);
  217754. if (--count < 0 || ! isThreadRunning())
  217755. {
  217756. error = "device didn't start";
  217757. break;
  217758. }
  217759. }
  217760. }
  217761. void close()
  217762. {
  217763. stopThread (6000);
  217764. deleteAndZero (inputDevice);
  217765. deleteAndZero (outputDevice);
  217766. for (int i = 0; i < maxNumChans; ++i)
  217767. {
  217768. juce_free (inputChannelData [i]);
  217769. juce_free (outputChannelData [i]);
  217770. }
  217771. zeromem (outputChannelData, sizeof (outputChannelData));
  217772. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217773. zeromem (inputChannelData, sizeof (inputChannelData));
  217774. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217775. totalNumOutputChannels = 0;
  217776. totalNumInputChannels = 0;
  217777. numCallbacks = 0;
  217778. }
  217779. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  217780. {
  217781. const ScopedLock sl (callbackLock);
  217782. callback = newCallback;
  217783. }
  217784. void run()
  217785. {
  217786. while (! threadShouldExit())
  217787. {
  217788. if (inputDevice != 0)
  217789. {
  217790. if (! inputDevice->read (inputChannelData, bufferSize))
  217791. {
  217792. DBG ("ALSA: read failure");
  217793. break;
  217794. }
  217795. }
  217796. if (threadShouldExit())
  217797. break;
  217798. {
  217799. const ScopedLock sl (callbackLock);
  217800. ++numCallbacks;
  217801. if (callback != 0)
  217802. {
  217803. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  217804. totalNumInputChannels,
  217805. outputChannelDataForCallback,
  217806. totalNumOutputChannels,
  217807. bufferSize);
  217808. }
  217809. else
  217810. {
  217811. for (int i = 0; i < totalNumOutputChannels; ++i)
  217812. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  217813. }
  217814. }
  217815. if (outputDevice != 0)
  217816. {
  217817. failed (snd_pcm_wait (outputDevice->handle, 2000));
  217818. if (threadShouldExit())
  217819. break;
  217820. failed (snd_pcm_avail_update (outputDevice->handle));
  217821. if (! outputDevice->write (outputChannelData, bufferSize))
  217822. {
  217823. DBG ("ALSA: write failure");
  217824. break;
  217825. }
  217826. }
  217827. }
  217828. }
  217829. int getBitDepth() const throw()
  217830. {
  217831. if (outputDevice != 0)
  217832. return outputDevice->bitDepth;
  217833. if (inputDevice != 0)
  217834. return inputDevice->bitDepth;
  217835. return 16;
  217836. }
  217837. juce_UseDebuggingNewOperator
  217838. String error;
  217839. double sampleRate;
  217840. int bufferSize;
  217841. BitArray currentInputChans, currentOutputChans;
  217842. Array <int> sampleRates;
  217843. StringArray channelNamesOut, channelNamesIn;
  217844. AudioIODeviceCallback* callback;
  217845. private:
  217846. const String inputId, outputId;
  217847. ALSADevice* outputDevice;
  217848. ALSADevice* inputDevice;
  217849. int numCallbacks;
  217850. CriticalSection callbackLock;
  217851. float* outputChannelData [maxNumChans];
  217852. float* outputChannelDataForCallback [maxNumChans];
  217853. int totalNumInputChannels;
  217854. float* inputChannelData [maxNumChans];
  217855. float* inputChannelDataForCallback [maxNumChans];
  217856. int totalNumOutputChannels;
  217857. unsigned int minChansOut, maxChansOut;
  217858. unsigned int minChansIn, maxChansIn;
  217859. bool failed (const int errorNum) throw()
  217860. {
  217861. if (errorNum >= 0)
  217862. return false;
  217863. error = snd_strerror (errorNum);
  217864. DBG (T("ALSA error: ") + error + T("\n"));
  217865. return true;
  217866. }
  217867. void initialiseRatesAndChannels() throw()
  217868. {
  217869. sampleRates.clear();
  217870. channelNamesOut.clear();
  217871. channelNamesIn.clear();
  217872. minChansOut = 0;
  217873. maxChansOut = 0;
  217874. minChansIn = 0;
  217875. maxChansIn = 0;
  217876. unsigned int dummy = 0;
  217877. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  217878. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  217879. unsigned int i;
  217880. for (i = 0; i < maxChansOut; ++i)
  217881. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  217882. for (i = 0; i < maxChansIn; ++i)
  217883. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  217884. }
  217885. };
  217886. class ALSAAudioIODevice : public AudioIODevice
  217887. {
  217888. public:
  217889. ALSAAudioIODevice (const String& deviceName,
  217890. const String& inputId_,
  217891. const String& outputId_)
  217892. : AudioIODevice (deviceName, T("ALSA")),
  217893. inputId (inputId_),
  217894. outputId (outputId_),
  217895. isOpen_ (false),
  217896. isStarted (false),
  217897. internal (0)
  217898. {
  217899. internal = new ALSAThread (inputId, outputId);
  217900. }
  217901. ~ALSAAudioIODevice()
  217902. {
  217903. delete internal;
  217904. }
  217905. const StringArray getOutputChannelNames()
  217906. {
  217907. return internal->channelNamesOut;
  217908. }
  217909. const StringArray getInputChannelNames()
  217910. {
  217911. return internal->channelNamesIn;
  217912. }
  217913. int getNumSampleRates()
  217914. {
  217915. return internal->sampleRates.size();
  217916. }
  217917. double getSampleRate (int index)
  217918. {
  217919. return internal->sampleRates [index];
  217920. }
  217921. int getNumBufferSizesAvailable()
  217922. {
  217923. return 50;
  217924. }
  217925. int getBufferSizeSamples (int index)
  217926. {
  217927. int n = 16;
  217928. for (int i = 0; i < index; ++i)
  217929. n += n < 64 ? 16
  217930. : (n < 512 ? 32
  217931. : (n < 1024 ? 64
  217932. : (n < 2048 ? 128 : 256)));
  217933. return n;
  217934. }
  217935. int getDefaultBufferSize()
  217936. {
  217937. return 512;
  217938. }
  217939. const String open (const BitArray& inputChannels,
  217940. const BitArray& outputChannels,
  217941. double sampleRate,
  217942. int bufferSizeSamples)
  217943. {
  217944. close();
  217945. if (bufferSizeSamples <= 0)
  217946. bufferSizeSamples = getDefaultBufferSize();
  217947. if (sampleRate <= 0)
  217948. {
  217949. for (int i = 0; i < getNumSampleRates(); ++i)
  217950. {
  217951. if (getSampleRate (i) >= 44100)
  217952. {
  217953. sampleRate = getSampleRate (i);
  217954. break;
  217955. }
  217956. }
  217957. }
  217958. internal->open (inputChannels, outputChannels,
  217959. sampleRate, bufferSizeSamples);
  217960. isOpen_ = internal->error.isEmpty();
  217961. return internal->error;
  217962. }
  217963. void close()
  217964. {
  217965. stop();
  217966. internal->close();
  217967. isOpen_ = false;
  217968. }
  217969. bool isOpen()
  217970. {
  217971. return isOpen_;
  217972. }
  217973. int getCurrentBufferSizeSamples()
  217974. {
  217975. return internal->bufferSize;
  217976. }
  217977. double getCurrentSampleRate()
  217978. {
  217979. return internal->sampleRate;
  217980. }
  217981. int getCurrentBitDepth()
  217982. {
  217983. return internal->getBitDepth();
  217984. }
  217985. const BitArray getActiveOutputChannels() const
  217986. {
  217987. return internal->currentOutputChans;
  217988. }
  217989. const BitArray getActiveInputChannels() const
  217990. {
  217991. return internal->currentInputChans;
  217992. }
  217993. int getOutputLatencyInSamples()
  217994. {
  217995. return 0;
  217996. }
  217997. int getInputLatencyInSamples()
  217998. {
  217999. return 0;
  218000. }
  218001. void start (AudioIODeviceCallback* callback)
  218002. {
  218003. if (! isOpen_)
  218004. callback = 0;
  218005. internal->setCallback (callback);
  218006. if (callback != 0)
  218007. callback->audioDeviceAboutToStart (this);
  218008. isStarted = (callback != 0);
  218009. }
  218010. void stop()
  218011. {
  218012. AudioIODeviceCallback* const oldCallback = internal->callback;
  218013. start (0);
  218014. if (oldCallback != 0)
  218015. oldCallback->audioDeviceStopped();
  218016. }
  218017. bool isPlaying()
  218018. {
  218019. return isStarted && internal->error.isEmpty();
  218020. }
  218021. const String getLastError()
  218022. {
  218023. return internal->error;
  218024. }
  218025. String inputId, outputId;
  218026. private:
  218027. bool isOpen_, isStarted;
  218028. ALSAThread* internal;
  218029. };
  218030. class ALSAAudioIODeviceType : public AudioIODeviceType
  218031. {
  218032. public:
  218033. ALSAAudioIODeviceType()
  218034. : AudioIODeviceType (T("ALSA")),
  218035. hasScanned (false)
  218036. {
  218037. }
  218038. ~ALSAAudioIODeviceType()
  218039. {
  218040. }
  218041. void scanForDevices()
  218042. {
  218043. if (hasScanned)
  218044. return;
  218045. hasScanned = true;
  218046. inputNames.clear();
  218047. inputIds.clear();
  218048. outputNames.clear();
  218049. outputIds.clear();
  218050. snd_ctl_t* handle;
  218051. snd_ctl_card_info_t* info;
  218052. snd_ctl_card_info_alloca (&info);
  218053. int cardNum = -1;
  218054. while (outputIds.size() + inputIds.size() <= 32)
  218055. {
  218056. snd_card_next (&cardNum);
  218057. if (cardNum < 0)
  218058. break;
  218059. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  218060. {
  218061. if (snd_ctl_card_info (handle, info) >= 0)
  218062. {
  218063. String cardId (snd_ctl_card_info_get_id (info));
  218064. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  218065. cardId = String (cardNum);
  218066. int device = -1;
  218067. for (;;)
  218068. {
  218069. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  218070. break;
  218071. String id, name;
  218072. id << "hw:" << cardId << ',' << device;
  218073. bool isInput, isOutput;
  218074. if (testDevice (id, isInput, isOutput))
  218075. {
  218076. name << snd_ctl_card_info_get_name (info);
  218077. if (name.isEmpty())
  218078. name = id;
  218079. if (isInput)
  218080. {
  218081. inputNames.add (name);
  218082. inputIds.add (id);
  218083. }
  218084. if (isOutput)
  218085. {
  218086. outputNames.add (name);
  218087. outputIds.add (id);
  218088. }
  218089. }
  218090. }
  218091. }
  218092. snd_ctl_close (handle);
  218093. }
  218094. }
  218095. inputNames.appendNumbersToDuplicates (false, true);
  218096. outputNames.appendNumbersToDuplicates (false, true);
  218097. }
  218098. const StringArray getDeviceNames (const bool wantInputNames) const
  218099. {
  218100. jassert (hasScanned); // need to call scanForDevices() before doing this
  218101. return wantInputNames ? inputNames : outputNames;
  218102. }
  218103. int getDefaultDeviceIndex (const bool forInput) const
  218104. {
  218105. jassert (hasScanned); // need to call scanForDevices() before doing this
  218106. return 0;
  218107. }
  218108. bool hasSeparateInputsAndOutputs() const { return true; }
  218109. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  218110. {
  218111. jassert (hasScanned); // need to call scanForDevices() before doing this
  218112. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  218113. if (d == 0)
  218114. return -1;
  218115. return asInput ? inputIds.indexOf (d->inputId)
  218116. : outputIds.indexOf (d->outputId);
  218117. }
  218118. AudioIODevice* createDevice (const String& outputDeviceName,
  218119. const String& inputDeviceName)
  218120. {
  218121. jassert (hasScanned); // need to call scanForDevices() before doing this
  218122. const int inputIndex = inputNames.indexOf (inputDeviceName);
  218123. const int outputIndex = outputNames.indexOf (outputDeviceName);
  218124. String deviceName (outputDeviceName);
  218125. if (deviceName.isEmpty())
  218126. deviceName = inputDeviceName;
  218127. if (index >= 0)
  218128. return new ALSAAudioIODevice (deviceName,
  218129. inputIds [inputIndex],
  218130. outputIds [outputIndex]);
  218131. return 0;
  218132. }
  218133. juce_UseDebuggingNewOperator
  218134. private:
  218135. StringArray inputNames, outputNames, inputIds, outputIds;
  218136. bool hasScanned;
  218137. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  218138. {
  218139. unsigned int minChansOut = 0, maxChansOut = 0;
  218140. unsigned int minChansIn = 0, maxChansIn = 0;
  218141. Array <int> rates;
  218142. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  218143. DBG (T("ALSA device: ") + id
  218144. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  218145. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  218146. + T(" rates=") + String (rates.size()));
  218147. isInput = maxChansIn > 0;
  218148. isOutput = maxChansOut > 0;
  218149. return (isInput || isOutput) && rates.size() > 0;
  218150. }
  218151. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  218152. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  218153. };
  218154. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  218155. {
  218156. return new ALSAAudioIODeviceType();
  218157. }
  218158. #endif
  218159. /********* End of inlined file: juce_linux_Audio.cpp *********/
  218160. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  218161. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218162. // compiled on its own).
  218163. #if JUCE_INCLUDED_FILE
  218164. #if JUCE_ALSA
  218165. static snd_seq_t* iterateDevices (const bool forInput,
  218166. StringArray& deviceNamesFound,
  218167. const int deviceIndexToOpen)
  218168. {
  218169. snd_seq_t* returnedHandle = 0;
  218170. snd_seq_t* seqHandle;
  218171. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  218172. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  218173. {
  218174. snd_seq_system_info_t* systemInfo;
  218175. snd_seq_client_info_t* clientInfo;
  218176. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  218177. {
  218178. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  218179. && snd_seq_client_info_malloc (&clientInfo) == 0)
  218180. {
  218181. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  218182. while (--numClients >= 0 && returnedHandle == 0)
  218183. {
  218184. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  218185. {
  218186. snd_seq_port_info_t* portInfo;
  218187. if (snd_seq_port_info_malloc (&portInfo) == 0)
  218188. {
  218189. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  218190. const int client = snd_seq_client_info_get_client (clientInfo);
  218191. snd_seq_port_info_set_client (portInfo, client);
  218192. snd_seq_port_info_set_port (portInfo, -1);
  218193. while (--numPorts >= 0)
  218194. {
  218195. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  218196. && (snd_seq_port_info_get_capability (portInfo)
  218197. & (forInput ? SND_SEQ_PORT_CAP_READ
  218198. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  218199. {
  218200. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  218201. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  218202. {
  218203. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  218204. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  218205. if (sourcePort != -1)
  218206. {
  218207. snd_seq_set_client_name (seqHandle,
  218208. forInput ? "Juce Midi Input"
  218209. : "Juce Midi Output");
  218210. const int portId
  218211. = snd_seq_create_simple_port (seqHandle,
  218212. forInput ? "Juce Midi In Port"
  218213. : "Juce Midi Out Port",
  218214. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218215. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218216. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218217. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  218218. returnedHandle = seqHandle;
  218219. }
  218220. }
  218221. }
  218222. }
  218223. snd_seq_port_info_free (portInfo);
  218224. }
  218225. }
  218226. }
  218227. snd_seq_client_info_free (clientInfo);
  218228. }
  218229. snd_seq_system_info_free (systemInfo);
  218230. }
  218231. if (returnedHandle == 0)
  218232. snd_seq_close (seqHandle);
  218233. }
  218234. deviceNamesFound.appendNumbersToDuplicates (true, true);
  218235. return returnedHandle;
  218236. }
  218237. static snd_seq_t* createDevice (const bool forInput,
  218238. const String& deviceNameToOpen)
  218239. {
  218240. snd_seq_t* seqHandle = 0;
  218241. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  218242. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  218243. {
  218244. snd_seq_set_client_name (seqHandle,
  218245. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  218246. : (deviceNameToOpen + T(" Output"))));
  218247. const int portId
  218248. = snd_seq_create_simple_port (seqHandle,
  218249. forInput ? "in"
  218250. : "out",
  218251. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218252. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218253. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  218254. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218255. if (portId < 0)
  218256. {
  218257. snd_seq_close (seqHandle);
  218258. seqHandle = 0;
  218259. }
  218260. }
  218261. return seqHandle;
  218262. }
  218263. class MidiOutputDevice
  218264. {
  218265. public:
  218266. MidiOutputDevice (MidiOutput* const midiOutput_,
  218267. snd_seq_t* const seqHandle_)
  218268. :
  218269. midiOutput (midiOutput_),
  218270. seqHandle (seqHandle_),
  218271. maxEventSize (16 * 1024)
  218272. {
  218273. jassert (seqHandle != 0 && midiOutput != 0);
  218274. snd_midi_event_new (maxEventSize, &midiParser);
  218275. }
  218276. ~MidiOutputDevice()
  218277. {
  218278. snd_midi_event_free (midiParser);
  218279. snd_seq_close (seqHandle);
  218280. }
  218281. void sendMessageNow (const MidiMessage& message)
  218282. {
  218283. if (message.getRawDataSize() > maxEventSize)
  218284. {
  218285. maxEventSize = message.getRawDataSize();
  218286. snd_midi_event_free (midiParser);
  218287. snd_midi_event_new (maxEventSize, &midiParser);
  218288. }
  218289. snd_seq_event_t event;
  218290. snd_seq_ev_clear (&event);
  218291. snd_midi_event_encode (midiParser,
  218292. message.getRawData(),
  218293. message.getRawDataSize(),
  218294. &event);
  218295. snd_midi_event_reset_encode (midiParser);
  218296. snd_seq_ev_set_source (&event, 0);
  218297. snd_seq_ev_set_subs (&event);
  218298. snd_seq_ev_set_direct (&event);
  218299. snd_seq_event_output (seqHandle, &event);
  218300. snd_seq_drain_output (seqHandle);
  218301. }
  218302. juce_UseDebuggingNewOperator
  218303. private:
  218304. MidiOutput* const midiOutput;
  218305. snd_seq_t* const seqHandle;
  218306. snd_midi_event_t* midiParser;
  218307. int maxEventSize;
  218308. };
  218309. const StringArray MidiOutput::getDevices()
  218310. {
  218311. StringArray devices;
  218312. iterateDevices (false, devices, -1);
  218313. return devices;
  218314. }
  218315. int MidiOutput::getDefaultDeviceIndex()
  218316. {
  218317. return 0;
  218318. }
  218319. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  218320. {
  218321. MidiOutput* newDevice = 0;
  218322. StringArray devices;
  218323. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  218324. if (handle != 0)
  218325. {
  218326. newDevice = new MidiOutput();
  218327. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218328. }
  218329. return newDevice;
  218330. }
  218331. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  218332. {
  218333. MidiOutput* newDevice = 0;
  218334. snd_seq_t* const handle = createDevice (false, deviceName);
  218335. if (handle != 0)
  218336. {
  218337. newDevice = new MidiOutput();
  218338. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218339. }
  218340. return newDevice;
  218341. }
  218342. MidiOutput::~MidiOutput()
  218343. {
  218344. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  218345. delete device;
  218346. }
  218347. void MidiOutput::reset()
  218348. {
  218349. }
  218350. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  218351. {
  218352. return false;
  218353. }
  218354. void MidiOutput::setVolume (float leftVol, float rightVol)
  218355. {
  218356. }
  218357. void MidiOutput::sendMessageNow (const MidiMessage& message)
  218358. {
  218359. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  218360. }
  218361. class MidiInputThread : public Thread
  218362. {
  218363. public:
  218364. MidiInputThread (MidiInput* const midiInput_,
  218365. snd_seq_t* const seqHandle_,
  218366. MidiInputCallback* const callback_)
  218367. : Thread (T("Juce MIDI Input")),
  218368. midiInput (midiInput_),
  218369. seqHandle (seqHandle_),
  218370. callback (callback_)
  218371. {
  218372. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  218373. }
  218374. ~MidiInputThread()
  218375. {
  218376. snd_seq_close (seqHandle);
  218377. }
  218378. void run()
  218379. {
  218380. const int maxEventSize = 16 * 1024;
  218381. snd_midi_event_t* midiParser;
  218382. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  218383. {
  218384. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  218385. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  218386. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  218387. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  218388. while (! threadShouldExit())
  218389. {
  218390. if (poll (pfd, numPfds, 500) > 0)
  218391. {
  218392. snd_seq_event_t* inputEvent = 0;
  218393. snd_seq_nonblock (seqHandle, 1);
  218394. do
  218395. {
  218396. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  218397. {
  218398. // xxx what about SYSEXes that are too big for the buffer?
  218399. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  218400. snd_midi_event_reset_decode (midiParser);
  218401. if (numBytes > 0)
  218402. {
  218403. const MidiMessage message ((const uint8*) buffer,
  218404. numBytes,
  218405. Time::getMillisecondCounter() * 0.001);
  218406. callback->handleIncomingMidiMessage (midiInput, message);
  218407. }
  218408. snd_seq_free_event (inputEvent);
  218409. }
  218410. }
  218411. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  218412. snd_seq_free_event (inputEvent);
  218413. }
  218414. }
  218415. snd_midi_event_free (midiParser);
  218416. juce_free (buffer);
  218417. }
  218418. };
  218419. juce_UseDebuggingNewOperator
  218420. private:
  218421. MidiInput* const midiInput;
  218422. snd_seq_t* const seqHandle;
  218423. MidiInputCallback* const callback;
  218424. };
  218425. MidiInput::MidiInput (const String& name_)
  218426. : name (name_),
  218427. internal (0)
  218428. {
  218429. }
  218430. MidiInput::~MidiInput()
  218431. {
  218432. stop();
  218433. MidiInputThread* const thread = (MidiInputThread*) internal;
  218434. delete thread;
  218435. }
  218436. void MidiInput::start()
  218437. {
  218438. ((MidiInputThread*) internal)->startThread();
  218439. }
  218440. void MidiInput::stop()
  218441. {
  218442. ((MidiInputThread*) internal)->stopThread (3000);
  218443. }
  218444. int MidiInput::getDefaultDeviceIndex()
  218445. {
  218446. return 0;
  218447. }
  218448. const StringArray MidiInput::getDevices()
  218449. {
  218450. StringArray devices;
  218451. iterateDevices (true, devices, -1);
  218452. return devices;
  218453. }
  218454. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  218455. {
  218456. MidiInput* newDevice = 0;
  218457. StringArray devices;
  218458. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  218459. if (handle != 0)
  218460. {
  218461. newDevice = new MidiInput (devices [deviceIndex]);
  218462. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218463. }
  218464. return newDevice;
  218465. }
  218466. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  218467. {
  218468. MidiInput* newDevice = 0;
  218469. snd_seq_t* const handle = createDevice (true, deviceName);
  218470. if (handle != 0)
  218471. {
  218472. newDevice = new MidiInput (deviceName);
  218473. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218474. }
  218475. return newDevice;
  218476. }
  218477. #else
  218478. // (These are just stub functions if ALSA is unavailable...)
  218479. const StringArray MidiOutput::getDevices() { return StringArray(); }
  218480. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  218481. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  218482. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  218483. MidiOutput::~MidiOutput() {}
  218484. void MidiOutput::reset() {}
  218485. bool MidiOutput::getVolume (float&, float&) { return false; }
  218486. void MidiOutput::setVolume (float, float) {}
  218487. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  218488. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  218489. MidiInput::~MidiInput() {}
  218490. void MidiInput::start() {}
  218491. void MidiInput::stop() {}
  218492. int MidiInput::getDefaultDeviceIndex() { return 0; }
  218493. const StringArray MidiInput::getDevices() { return StringArray(); }
  218494. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  218495. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  218496. #endif
  218497. #endif
  218498. /********* End of inlined file: juce_linux_Midi.cpp *********/
  218499. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  218500. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218501. // compiled on its own).
  218502. #if JUCE_INCLUDED_FILE
  218503. AudioCDReader::AudioCDReader()
  218504. : AudioFormatReader (0, T("CD Audio"))
  218505. {
  218506. }
  218507. const StringArray AudioCDReader::getAvailableCDNames()
  218508. {
  218509. StringArray names;
  218510. return names;
  218511. }
  218512. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  218513. {
  218514. return 0;
  218515. }
  218516. AudioCDReader::~AudioCDReader()
  218517. {
  218518. }
  218519. void AudioCDReader::refreshTrackLengths()
  218520. {
  218521. }
  218522. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  218523. int64 startSampleInFile, int numSamples)
  218524. {
  218525. return false;
  218526. }
  218527. bool AudioCDReader::isCDStillPresent() const
  218528. {
  218529. return false;
  218530. }
  218531. int AudioCDReader::getNumTracks() const
  218532. {
  218533. return 0;
  218534. }
  218535. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  218536. {
  218537. return 0;
  218538. }
  218539. bool AudioCDReader::isTrackAudio (int trackNum) const
  218540. {
  218541. return false;
  218542. }
  218543. void AudioCDReader::enableIndexScanning (bool b)
  218544. {
  218545. }
  218546. int AudioCDReader::getLastIndex() const
  218547. {
  218548. return 0;
  218549. }
  218550. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  218551. {
  218552. return Array<int>();
  218553. }
  218554. int AudioCDReader::getCDDBId()
  218555. {
  218556. return 0;
  218557. }
  218558. #endif
  218559. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  218560. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  218561. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218562. // compiled on its own).
  218563. #if JUCE_INCLUDED_FILE
  218564. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218565. const String& title,
  218566. const File& file,
  218567. const String& filters,
  218568. bool isDirectory,
  218569. bool isSave,
  218570. bool warnAboutOverwritingExistingFiles,
  218571. bool selectMultipleFiles,
  218572. FilePreviewComponent* previewComponent)
  218573. {
  218574. //xxx ain't got one!
  218575. jassertfalse
  218576. }
  218577. #endif
  218578. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  218579. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218580. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218581. // compiled on its own).
  218582. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  218583. /*
  218584. Sorry.. This class isn't implemented on Linux!
  218585. */
  218586. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  218587. : browser (0),
  218588. blankPageShown (false),
  218589. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  218590. {
  218591. setOpaque (true);
  218592. }
  218593. WebBrowserComponent::~WebBrowserComponent()
  218594. {
  218595. }
  218596. void WebBrowserComponent::goToURL (const String& url,
  218597. const StringArray* headers,
  218598. const MemoryBlock* postData)
  218599. {
  218600. lastURL = url;
  218601. lastHeaders.clear();
  218602. if (headers != 0)
  218603. lastHeaders = *headers;
  218604. lastPostData.setSize (0);
  218605. if (postData != 0)
  218606. lastPostData = *postData;
  218607. blankPageShown = false;
  218608. }
  218609. void WebBrowserComponent::stop()
  218610. {
  218611. }
  218612. void WebBrowserComponent::goBack()
  218613. {
  218614. lastURL = String::empty;
  218615. blankPageShown = false;
  218616. }
  218617. void WebBrowserComponent::goForward()
  218618. {
  218619. lastURL = String::empty;
  218620. }
  218621. void WebBrowserComponent::refresh()
  218622. {
  218623. }
  218624. void WebBrowserComponent::paint (Graphics& g)
  218625. {
  218626. g.fillAll (Colours::white);
  218627. }
  218628. void WebBrowserComponent::checkWindowAssociation()
  218629. {
  218630. }
  218631. void WebBrowserComponent::reloadLastURL()
  218632. {
  218633. if (lastURL.isNotEmpty())
  218634. {
  218635. goToURL (lastURL, &lastHeaders, &lastPostData);
  218636. lastURL = String::empty;
  218637. }
  218638. }
  218639. void WebBrowserComponent::parentHierarchyChanged()
  218640. {
  218641. checkWindowAssociation();
  218642. }
  218643. void WebBrowserComponent::resized()
  218644. {
  218645. }
  218646. void WebBrowserComponent::visibilityChanged()
  218647. {
  218648. checkWindowAssociation();
  218649. }
  218650. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  218651. {
  218652. return true;
  218653. }
  218654. #endif
  218655. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218656. #endif
  218657. END_JUCE_NAMESPACE
  218658. /********* End of inlined file: juce_linux_NativeCode.cpp *********/
  218659. #endif
  218660. #if JUCE_MAC || JUCE_IPHONE
  218661. /********* Start of inlined file: juce_mac_NativeCode.mm *********/
  218662. /*
  218663. This file wraps together all the mac-specific code, so that
  218664. we can include all the native headers just once, and compile all our
  218665. platform-specific stuff in one big lump, keeping it out of the way of
  218666. the rest of the codebase.
  218667. */
  218668. BEGIN_JUCE_NAMESPACE
  218669. #undef Point
  218670. #define JUCE_INCLUDED_FILE 1
  218671. // Now include the actual code files..
  218672. /********* Start of inlined file: juce_mac_ObjCSuffix.h *********/
  218673. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  218674. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  218675. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  218676. cross-linked so that when you make a call to a class that you thought was private, it ends up
  218677. actually calling into a similarly named class in the other module's address space.
  218678. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  218679. have unique names, and should avoid this problem.
  218680. If you're using the amalgamated version, you can just set this macro to something unique before
  218681. you include juce_amalgamated.cpp.
  218682. */
  218683. #ifndef JUCE_ObjCExtraSuffix
  218684. #define JUCE_ObjCExtraSuffix 3
  218685. #endif
  218686. #define appendMacro1(a, b, c, d) a ## _ ## b ## _ ## c ## _ ## d
  218687. #define appendMacro2(a, b, c, d) appendMacro1(a, b, c, d)
  218688. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_ObjCExtraSuffix)
  218689. /********* End of inlined file: juce_mac_ObjCSuffix.h *********/
  218690. /********* Start of inlined file: juce_mac_Strings.mm *********/
  218691. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218692. // compiled on its own).
  218693. #if JUCE_INCLUDED_FILE
  218694. static const String nsStringToJuce (NSString* s)
  218695. {
  218696. return String::fromUTF8 ((uint8*) [s UTF8String]);
  218697. }
  218698. static NSString* juceStringToNS (const String& s)
  218699. {
  218700. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  218701. }
  218702. static const String convertUTF16ToString (const UniChar* utf16)
  218703. {
  218704. String s;
  218705. while (*utf16 != 0)
  218706. s += (juce_wchar) *utf16++;
  218707. return s;
  218708. }
  218709. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  218710. {
  218711. String result;
  218712. if (cfString != 0)
  218713. {
  218714. #if JUCE_STRINGS_ARE_UNICODE
  218715. CFRange range = { 0, CFStringGetLength (cfString) };
  218716. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  218717. CFStringGetCharacters (cfString, range, u);
  218718. u[range.length] = 0;
  218719. result = convertUTF16ToString (u);
  218720. juce_free (u);
  218721. #else
  218722. const int len = CFStringGetLength (cfString);
  218723. char* buffer = (char*) juce_malloc (len + 1);
  218724. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  218725. result = buffer;
  218726. juce_free (buffer);
  218727. #endif
  218728. }
  218729. return result;
  218730. }
  218731. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  218732. {
  218733. #if JUCE_STRINGS_ARE_UNICODE
  218734. const int len = s.length();
  218735. const juce_wchar* t = (const juce_wchar*) s;
  218736. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  218737. for (int i = 0; i <= len; ++i)
  218738. temp[i] = t[i];
  218739. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  218740. juce_free (temp);
  218741. return result;
  218742. #else
  218743. return CFStringCreateWithCString (kCFAllocatorDefault,
  218744. (const char*) s,
  218745. CFStringGetSystemEncoding());
  218746. #endif
  218747. }
  218748. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  218749. {
  218750. #if JUCE_IPHONE
  218751. const ScopedAutoReleasePool pool;
  218752. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  218753. #else
  218754. UnicodeMapping map;
  218755. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218756. kUnicodeNoSubset,
  218757. kTextEncodingDefaultFormat);
  218758. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218759. kUnicodeCanonicalCompVariant,
  218760. kTextEncodingDefaultFormat);
  218761. map.mappingVersion = kUnicodeUseLatestMapping;
  218762. UnicodeToTextInfo conversionInfo = 0;
  218763. String result;
  218764. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  218765. {
  218766. const int len = s.length();
  218767. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218768. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218769. for (int i = 0; i <= len; ++i)
  218770. tempIn[i] = s[i];
  218771. ByteCount bytesRead = 0;
  218772. ByteCount outputBufferSize = 0;
  218773. if (ConvertFromUnicodeToText (conversionInfo,
  218774. len * sizeof (UniChar), tempIn,
  218775. kUnicodeDefaultDirectionMask,
  218776. 0, 0, 0, 0,
  218777. len * sizeof (UniChar), &bytesRead,
  218778. &outputBufferSize, tempOut) == noErr)
  218779. {
  218780. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  218781. tchar* t = const_cast <tchar*> ((const tchar*) result);
  218782. unsigned int i;
  218783. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  218784. t[i] = (tchar) tempOut[i];
  218785. t[i] = 0;
  218786. }
  218787. juce_free (tempIn);
  218788. juce_free (tempOut);
  218789. DisposeUnicodeToTextInfo (&conversionInfo);
  218790. }
  218791. return result;
  218792. #endif
  218793. }
  218794. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218795. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  218796. {
  218797. #if JUCE_IPHONE
  218798. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  218799. forPasteboardType: @"public.text"];
  218800. #else
  218801. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  218802. owner: nil];
  218803. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  218804. forType: NSStringPboardType];
  218805. #endif
  218806. }
  218807. const String SystemClipboard::getTextFromClipboard() throw()
  218808. {
  218809. #if JUCE_IPHONE
  218810. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  218811. #else
  218812. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  218813. #endif
  218814. return text == 0 ? String::empty
  218815. : nsStringToJuce (text);
  218816. }
  218817. #endif
  218818. #endif
  218819. /********* End of inlined file: juce_mac_Strings.mm *********/
  218820. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  218821. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218822. // compiled on its own).
  218823. #if JUCE_INCLUDED_FILE
  218824. static int64 highResTimerFrequency = 0;
  218825. static double highResTimerToMillisecRatio = 0;
  218826. #if JUCE_INTEL
  218827. static void juce_getCpuVendor (char* const v) throw()
  218828. {
  218829. int vendor[4];
  218830. zerostruct (vendor);
  218831. int dummy = 0;
  218832. asm ("mov %%ebx, %%esi \n\t"
  218833. "cpuid \n\t"
  218834. "xchg %%esi, %%ebx"
  218835. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  218836. memcpy (v, vendor, 16);
  218837. }
  218838. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  218839. {
  218840. unsigned int cpu = 0;
  218841. unsigned int ext = 0;
  218842. unsigned int family = 0;
  218843. unsigned int dummy = 0;
  218844. asm ("mov %%ebx, %%esi \n\t"
  218845. "cpuid \n\t"
  218846. "xchg %%esi, %%ebx"
  218847. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  218848. familyModel = family;
  218849. extFeatures = ext;
  218850. return cpu;
  218851. }
  218852. struct CPUFlags
  218853. {
  218854. bool hasMMX : 1;
  218855. bool hasSSE : 1;
  218856. bool hasSSE2 : 1;
  218857. bool has3DNow : 1;
  218858. };
  218859. static CPUFlags cpuFlags;
  218860. #endif
  218861. void SystemStats::initialiseStats() throw()
  218862. {
  218863. static bool initialised = false;
  218864. if (! initialised)
  218865. {
  218866. initialised = true;
  218867. #if JUCE_MAC
  218868. // extremely annoying: adding this line stops the apple menu items from working. Of
  218869. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  218870. // any events.
  218871. //NSApplicationLoad();
  218872. [NSApplication sharedApplication];
  218873. #endif
  218874. #if JUCE_INTEL
  218875. {
  218876. unsigned int familyModel, extFeatures;
  218877. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  218878. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  218879. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  218880. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  218881. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  218882. }
  218883. #endif
  218884. mach_timebase_info_data_t timebase;
  218885. (void) mach_timebase_info (&timebase);
  218886. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  218887. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  218888. String s (SystemStats::getJUCEVersion());
  218889. rlimit lim;
  218890. getrlimit (RLIMIT_NOFILE, &lim);
  218891. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  218892. setrlimit (RLIMIT_NOFILE, &lim);
  218893. }
  218894. }
  218895. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  218896. {
  218897. return MacOSX;
  218898. }
  218899. const String SystemStats::getOperatingSystemName() throw()
  218900. {
  218901. return T("Mac OS X");
  218902. }
  218903. bool SystemStats::isOperatingSystem64Bit() throw()
  218904. {
  218905. #if JUCE_64BIT
  218906. return true;
  218907. #else
  218908. //xxx not sure how to find this out?..
  218909. return false;
  218910. #endif
  218911. }
  218912. int SystemStats::getMemorySizeInMegabytes() throw()
  218913. {
  218914. uint64 mem = 0;
  218915. size_t memSize = sizeof (mem);
  218916. int mib[] = { CTL_HW, HW_MEMSIZE };
  218917. sysctl (mib, 2, &mem, &memSize, 0, 0);
  218918. return mem / (1024 * 1024);
  218919. }
  218920. bool SystemStats::hasMMX() throw()
  218921. {
  218922. #if JUCE_INTEL
  218923. return cpuFlags.hasMMX;
  218924. #else
  218925. return false;
  218926. #endif
  218927. }
  218928. bool SystemStats::hasSSE() throw()
  218929. {
  218930. #if JUCE_INTEL
  218931. return cpuFlags.hasSSE;
  218932. #else
  218933. return false;
  218934. #endif
  218935. }
  218936. bool SystemStats::hasSSE2() throw()
  218937. {
  218938. #if JUCE_INTEL
  218939. return cpuFlags.hasSSE2;
  218940. #else
  218941. return false;
  218942. #endif
  218943. }
  218944. bool SystemStats::has3DNow() throw()
  218945. {
  218946. #if JUCE_INTEL
  218947. return cpuFlags.has3DNow;
  218948. #else
  218949. return false;
  218950. #endif
  218951. }
  218952. const String SystemStats::getCpuVendor() throw()
  218953. {
  218954. #if JUCE_INTEL
  218955. char v [16];
  218956. juce_getCpuVendor (v);
  218957. return String (v, 16);
  218958. #else
  218959. return String::empty;
  218960. #endif
  218961. }
  218962. int SystemStats::getCpuSpeedInMegaherz() throw()
  218963. {
  218964. uint64 speedHz = 0;
  218965. size_t speedSize = sizeof (speedHz);
  218966. int mib[] = { CTL_HW, HW_CPU_FREQ };
  218967. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  218968. #if JUCE_BIG_ENDIAN
  218969. if (speedSize == 4)
  218970. speedHz >>= 32;
  218971. #endif
  218972. return speedHz / 1000000;
  218973. }
  218974. int SystemStats::getNumCpus() throw()
  218975. {
  218976. #if MACOS_10_4_OR_EARLIER
  218977. return MPProcessors();
  218978. #else
  218979. return [[NSProcessInfo processInfo] activeProcessorCount];
  218980. #endif
  218981. }
  218982. uint32 juce_millisecondsSinceStartup() throw()
  218983. {
  218984. return (uint32) (mach_absolute_time() * highResTimerToMillisecRatio);
  218985. }
  218986. double Time::getMillisecondCounterHiRes() throw()
  218987. {
  218988. return mach_absolute_time() * highResTimerToMillisecRatio;
  218989. }
  218990. int64 Time::getHighResolutionTicks() throw()
  218991. {
  218992. return (int64) mach_absolute_time();
  218993. }
  218994. int64 Time::getHighResolutionTicksPerSecond() throw()
  218995. {
  218996. return highResTimerFrequency;
  218997. }
  218998. int64 SystemStats::getClockCycleCounter() throw()
  218999. {
  219000. return (int64) mach_absolute_time();
  219001. }
  219002. bool Time::setSystemTimeToThisTime() const throw()
  219003. {
  219004. jassertfalse
  219005. return false;
  219006. }
  219007. int SystemStats::getPageSize() throw()
  219008. {
  219009. return NSPageSize();
  219010. }
  219011. void PlatformUtilities::fpuReset()
  219012. {
  219013. }
  219014. #endif
  219015. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  219016. /********* Start of inlined file: juce_mac_Network.mm *********/
  219017. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219018. // compiled on its own).
  219019. #if JUCE_INCLUDED_FILE
  219020. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  219021. {
  219022. #ifndef IFT_ETHER
  219023. #define IFT_ETHER 6
  219024. #endif
  219025. ifaddrs* addrs = 0;
  219026. int numResults = 0;
  219027. if (getifaddrs (&addrs) == 0)
  219028. {
  219029. const ifaddrs* cursor = addrs;
  219030. while (cursor != 0 && numResults < maxNum)
  219031. {
  219032. if (cursor->ifa_addr->sa_family == AF_LINK)
  219033. {
  219034. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  219035. if (sadd->sdl_type == IFT_ETHER)
  219036. {
  219037. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  219038. uint64 a = 0;
  219039. for (int i = 6; --i >= 0;)
  219040. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  219041. *addresses++ = (int64) a;
  219042. ++numResults;
  219043. }
  219044. }
  219045. cursor = cursor->ifa_next;
  219046. }
  219047. freeifaddrs (addrs);
  219048. }
  219049. return numResults;
  219050. }
  219051. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  219052. const String& emailSubject,
  219053. const String& bodyText,
  219054. const StringArray& filesToAttach)
  219055. {
  219056. #if JUCE_IPHONE
  219057. //xxx probably need to use MFMailComposeViewController
  219058. jassertfalse
  219059. return false;
  219060. #else
  219061. const ScopedAutoReleasePool pool;
  219062. String script;
  219063. script << "tell application \"Mail\"\r\n"
  219064. "set newMessage to make new outgoing message with properties {subject:\""
  219065. << emailSubject.replace (T("\""), T("\\\""))
  219066. << "\", content:\""
  219067. << bodyText.replace (T("\""), T("\\\""))
  219068. << "\" & return & return}\r\n"
  219069. "tell newMessage\r\n"
  219070. "set visible to true\r\n"
  219071. "set sender to \"sdfsdfsdfewf\"\r\n"
  219072. "make new to recipient at end of to recipients with properties {address:\""
  219073. << targetEmailAddress
  219074. << "\"}\r\n";
  219075. for (int i = 0; i < filesToAttach.size(); ++i)
  219076. {
  219077. script << "tell content\r\n"
  219078. "make new attachment with properties {file name:\""
  219079. << filesToAttach[i].replace (T("\""), T("\\\""))
  219080. << "\"} at after the last paragraph\r\n"
  219081. "end tell\r\n";
  219082. }
  219083. script << "end tell\r\n"
  219084. "end tell\r\n";
  219085. NSAppleScript* s = [[NSAppleScript alloc]
  219086. initWithSource: juceStringToNS (script)];
  219087. NSDictionary* error = 0;
  219088. const bool ok = [s executeAndReturnError: &error] != nil;
  219089. [s release];
  219090. return ok;
  219091. #endif
  219092. }
  219093. END_JUCE_NAMESPACE
  219094. using namespace JUCE_NAMESPACE;
  219095. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  219096. @interface JuceURLConnection : NSObject
  219097. {
  219098. @public
  219099. NSURLRequest* request;
  219100. NSURLConnection* connection;
  219101. NSMutableData* data;
  219102. Thread* runLoopThread;
  219103. bool initialised, hasFailed, hasFinished;
  219104. int position;
  219105. int64 contentLength;
  219106. NSLock* dataLock;
  219107. }
  219108. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  219109. - (void) dealloc;
  219110. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  219111. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  219112. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  219113. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  219114. - (BOOL) isOpen;
  219115. - (int) read: (char*) dest numBytes: (int) num;
  219116. - (int) readPosition;
  219117. - (void) stop;
  219118. - (void) createConnection;
  219119. @end
  219120. class JuceURLConnectionMessageThread : public Thread
  219121. {
  219122. JuceURLConnection* owner;
  219123. public:
  219124. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  219125. : Thread (T("http connection")),
  219126. owner (owner_)
  219127. {
  219128. }
  219129. ~JuceURLConnectionMessageThread()
  219130. {
  219131. stopThread (10000);
  219132. }
  219133. void run()
  219134. {
  219135. [owner createConnection];
  219136. while (! threadShouldExit())
  219137. {
  219138. const ScopedAutoReleasePool pool;
  219139. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  219140. }
  219141. }
  219142. };
  219143. @implementation JuceURLConnection
  219144. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  219145. withCallback: (URL::OpenStreamProgressCallback*) callback
  219146. withContext: (void*) context;
  219147. {
  219148. [super init];
  219149. request = req;
  219150. [request retain];
  219151. data = [[NSMutableData data] retain];
  219152. dataLock = [[NSLock alloc] init];
  219153. connection = 0;
  219154. initialised = false;
  219155. hasFailed = false;
  219156. hasFinished = false;
  219157. contentLength = -1;
  219158. runLoopThread = new JuceURLConnectionMessageThread (self);
  219159. runLoopThread->startThread();
  219160. while (runLoopThread->isThreadRunning() && ! initialised)
  219161. {
  219162. if (callback != 0)
  219163. callback (context, -1, [[request HTTPBody] length]);
  219164. Thread::sleep (1);
  219165. }
  219166. return self;
  219167. }
  219168. - (void) dealloc
  219169. {
  219170. [self stop];
  219171. delete runLoopThread;
  219172. [connection release];
  219173. [data release];
  219174. [dataLock release];
  219175. [request release];
  219176. [super dealloc];
  219177. }
  219178. - (void) createConnection
  219179. {
  219180. connection = [[NSURLConnection alloc] initWithRequest: request
  219181. delegate: [self retain]];
  219182. if (connection == nil)
  219183. runLoopThread->signalThreadShouldExit();
  219184. }
  219185. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  219186. {
  219187. [dataLock lock];
  219188. [data setLength: 0];
  219189. [dataLock unlock];
  219190. initialised = true;
  219191. contentLength = [response expectedContentLength];
  219192. }
  219193. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  219194. {
  219195. DBG (nsStringToJuce ([error description]));
  219196. hasFailed = true;
  219197. initialised = true;
  219198. runLoopThread->signalThreadShouldExit();
  219199. }
  219200. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  219201. {
  219202. [dataLock lock];
  219203. [data appendData: newData];
  219204. [dataLock unlock];
  219205. initialised = true;
  219206. }
  219207. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  219208. {
  219209. hasFinished = true;
  219210. initialised = true;
  219211. runLoopThread->signalThreadShouldExit();
  219212. }
  219213. - (BOOL) isOpen
  219214. {
  219215. return connection != 0 && ! hasFailed;
  219216. }
  219217. - (int) readPosition
  219218. {
  219219. return position;
  219220. }
  219221. - (int) read: (char*) dest numBytes: (int) numNeeded
  219222. {
  219223. int numDone = 0;
  219224. while (numNeeded > 0)
  219225. {
  219226. int available = jmin (numNeeded, [data length]);
  219227. if (available > 0)
  219228. {
  219229. [dataLock lock];
  219230. [data getBytes: dest length: available];
  219231. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  219232. [dataLock unlock];
  219233. numDone += available;
  219234. numNeeded -= available;
  219235. dest += available;
  219236. }
  219237. else
  219238. {
  219239. if (hasFailed || hasFinished)
  219240. break;
  219241. Thread::sleep (1);
  219242. }
  219243. }
  219244. position += numDone;
  219245. return numDone;
  219246. }
  219247. - (void) stop
  219248. {
  219249. [connection cancel];
  219250. runLoopThread->stopThread (10000);
  219251. }
  219252. @end
  219253. BEGIN_JUCE_NAMESPACE
  219254. bool juce_isOnLine()
  219255. {
  219256. return true;
  219257. }
  219258. void* juce_openInternetFile (const String& url,
  219259. const String& headers,
  219260. const MemoryBlock& postData,
  219261. const bool isPost,
  219262. URL::OpenStreamProgressCallback* callback,
  219263. void* callbackContext,
  219264. int timeOutMs)
  219265. {
  219266. const ScopedAutoReleasePool pool;
  219267. NSMutableURLRequest* req = [NSMutableURLRequest
  219268. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  219269. cachePolicy: NSURLRequestUseProtocolCachePolicy
  219270. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  219271. if (req == nil)
  219272. return 0;
  219273. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  219274. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  219275. StringArray headerLines;
  219276. headerLines.addLines (headers);
  219277. headerLines.removeEmptyStrings (true);
  219278. for (int i = 0; i < headerLines.size(); ++i)
  219279. {
  219280. const String key (headerLines[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  219281. const String value (headerLines[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  219282. if (key.isNotEmpty() && value.isNotEmpty())
  219283. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  219284. }
  219285. if (isPost && postData.getSize() > 0)
  219286. {
  219287. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  219288. length: postData.getSize()]];
  219289. }
  219290. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  219291. withCallback: callback
  219292. withContext: callbackContext];
  219293. if ([s isOpen])
  219294. return s;
  219295. [s release];
  219296. return 0;
  219297. }
  219298. void juce_closeInternetFile (void* handle)
  219299. {
  219300. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219301. if (s != 0)
  219302. {
  219303. const ScopedAutoReleasePool pool;
  219304. [s stop];
  219305. [s release];
  219306. }
  219307. }
  219308. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  219309. {
  219310. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219311. if (s != 0)
  219312. {
  219313. const ScopedAutoReleasePool pool;
  219314. return [s read: (char*) buffer numBytes: bytesToRead];
  219315. }
  219316. return 0;
  219317. }
  219318. int64 juce_getInternetFileContentLength (void* handle)
  219319. {
  219320. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219321. if (s != 0)
  219322. return s->contentLength;
  219323. return -1;
  219324. }
  219325. int juce_seekInInternetFile (void* handle, int newPosition)
  219326. {
  219327. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219328. if (s != 0)
  219329. return [s readPosition];
  219330. return 0;
  219331. }
  219332. #endif
  219333. /********* End of inlined file: juce_mac_Network.mm *********/
  219334. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  219335. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219336. // compiled on its own).
  219337. #if JUCE_INCLUDED_FILE
  219338. struct NamedPipeInternal
  219339. {
  219340. String pipeInName, pipeOutName;
  219341. int pipeIn, pipeOut;
  219342. bool volatile createdPipe, blocked, stopReadOperation;
  219343. static void signalHandler (int) {}
  219344. };
  219345. void NamedPipe::cancelPendingReads()
  219346. {
  219347. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  219348. {
  219349. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219350. intern->stopReadOperation = true;
  219351. char buffer [1] = { 0 };
  219352. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  219353. (void) bytesWritten;
  219354. int timeout = 2000;
  219355. while (intern->blocked && --timeout >= 0)
  219356. Thread::sleep (2);
  219357. intern->stopReadOperation = false;
  219358. }
  219359. }
  219360. void NamedPipe::close()
  219361. {
  219362. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219363. if (intern != 0)
  219364. {
  219365. internal = 0;
  219366. if (intern->pipeIn != -1)
  219367. ::close (intern->pipeIn);
  219368. if (intern->pipeOut != -1)
  219369. ::close (intern->pipeOut);
  219370. if (intern->createdPipe)
  219371. {
  219372. unlink (intern->pipeInName);
  219373. unlink (intern->pipeOutName);
  219374. }
  219375. delete intern;
  219376. }
  219377. }
  219378. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  219379. {
  219380. close();
  219381. NamedPipeInternal* const intern = new NamedPipeInternal();
  219382. internal = intern;
  219383. intern->createdPipe = createPipe;
  219384. intern->blocked = false;
  219385. intern->stopReadOperation = false;
  219386. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  219387. siginterrupt (SIGPIPE, 1);
  219388. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  219389. intern->pipeInName = pipePath + T("_in");
  219390. intern->pipeOutName = pipePath + T("_out");
  219391. intern->pipeIn = -1;
  219392. intern->pipeOut = -1;
  219393. if (createPipe)
  219394. {
  219395. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  219396. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  219397. {
  219398. delete intern;
  219399. internal = 0;
  219400. return false;
  219401. }
  219402. }
  219403. return true;
  219404. }
  219405. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  219406. {
  219407. int bytesRead = -1;
  219408. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219409. if (intern != 0)
  219410. {
  219411. intern->blocked = true;
  219412. if (intern->pipeIn == -1)
  219413. {
  219414. if (intern->createdPipe)
  219415. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  219416. else
  219417. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  219418. if (intern->pipeIn == -1)
  219419. {
  219420. intern->blocked = false;
  219421. return -1;
  219422. }
  219423. }
  219424. bytesRead = 0;
  219425. char* p = (char*) destBuffer;
  219426. while (bytesRead < maxBytesToRead)
  219427. {
  219428. const int bytesThisTime = maxBytesToRead - bytesRead;
  219429. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  219430. if (numRead <= 0 || intern->stopReadOperation)
  219431. {
  219432. bytesRead = -1;
  219433. break;
  219434. }
  219435. bytesRead += numRead;
  219436. p += bytesRead;
  219437. }
  219438. intern->blocked = false;
  219439. }
  219440. return bytesRead;
  219441. }
  219442. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  219443. {
  219444. int bytesWritten = -1;
  219445. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219446. if (intern != 0)
  219447. {
  219448. if (intern->pipeOut == -1)
  219449. {
  219450. if (intern->createdPipe)
  219451. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  219452. else
  219453. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  219454. if (intern->pipeOut == -1)
  219455. {
  219456. return -1;
  219457. }
  219458. }
  219459. const char* p = (const char*) sourceBuffer;
  219460. bytesWritten = 0;
  219461. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  219462. while (bytesWritten < numBytesToWrite
  219463. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  219464. {
  219465. const int bytesThisTime = numBytesToWrite - bytesWritten;
  219466. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  219467. if (numWritten <= 0)
  219468. {
  219469. bytesWritten = -1;
  219470. break;
  219471. }
  219472. bytesWritten += numWritten;
  219473. p += bytesWritten;
  219474. }
  219475. }
  219476. return bytesWritten;
  219477. }
  219478. #endif
  219479. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  219480. /********* Start of inlined file: juce_mac_Threads.mm *********/
  219481. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219482. // compiled on its own).
  219483. #if JUCE_INCLUDED_FILE
  219484. /*
  219485. Note that a lot of methods that you'd expect to find in this file actually
  219486. live in juce_posix_SharedCode.h!
  219487. */
  219488. void JUCE_API juce_threadEntryPoint (void*);
  219489. void* threadEntryProc (void* userData) throw()
  219490. {
  219491. const ScopedAutoReleasePool pool;
  219492. juce_threadEntryPoint (userData);
  219493. return 0;
  219494. }
  219495. void* juce_createThread (void* userData) throw()
  219496. {
  219497. pthread_t handle = 0;
  219498. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  219499. {
  219500. pthread_detach (handle);
  219501. return (void*) handle;
  219502. }
  219503. return 0;
  219504. }
  219505. void juce_killThread (void* handle) throw()
  219506. {
  219507. if (handle != 0)
  219508. pthread_cancel ((pthread_t) handle);
  219509. }
  219510. void juce_setCurrentThreadName (const String& /*name*/) throw()
  219511. {
  219512. }
  219513. Thread::ThreadID Thread::getCurrentThreadId() throw()
  219514. {
  219515. return (ThreadID) pthread_self();
  219516. }
  219517. bool juce_setThreadPriority (void* handle, int priority) throw()
  219518. {
  219519. if (handle == 0)
  219520. handle = (void*) pthread_self();
  219521. struct sched_param param;
  219522. int policy;
  219523. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  219524. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  219525. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  219526. }
  219527. void Thread::yield() throw()
  219528. {
  219529. sched_yield();
  219530. }
  219531. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  219532. {
  219533. // xxx
  219534. jassertfalse
  219535. }
  219536. bool Process::isForegroundProcess() throw()
  219537. {
  219538. #if JUCE_MAC
  219539. return [NSApp isActive];
  219540. #else
  219541. return true; // xxx change this if more than one app is ever possible on the iPhone!
  219542. #endif
  219543. }
  219544. void Process::raisePrivilege()
  219545. {
  219546. jassertfalse
  219547. }
  219548. void Process::lowerPrivilege()
  219549. {
  219550. jassertfalse
  219551. }
  219552. void Process::terminate()
  219553. {
  219554. exit (0);
  219555. }
  219556. void Process::setPriority (ProcessPriority p)
  219557. {
  219558. // xxx
  219559. }
  219560. #endif
  219561. /********* End of inlined file: juce_mac_Threads.mm *********/
  219562. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  219563. /*
  219564. This file contains posix routines that are common to both the Linux and Mac builds.
  219565. It gets included directly in the cpp files for these platforms.
  219566. */
  219567. CriticalSection::CriticalSection() throw()
  219568. {
  219569. pthread_mutexattr_t atts;
  219570. pthread_mutexattr_init (&atts);
  219571. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  219572. pthread_mutex_init (&internal, &atts);
  219573. }
  219574. CriticalSection::~CriticalSection() throw()
  219575. {
  219576. pthread_mutex_destroy (&internal);
  219577. }
  219578. void CriticalSection::enter() const throw()
  219579. {
  219580. pthread_mutex_lock (&internal);
  219581. }
  219582. bool CriticalSection::tryEnter() const throw()
  219583. {
  219584. return pthread_mutex_trylock (&internal) == 0;
  219585. }
  219586. void CriticalSection::exit() const throw()
  219587. {
  219588. pthread_mutex_unlock (&internal);
  219589. }
  219590. struct EventStruct
  219591. {
  219592. pthread_cond_t condition;
  219593. pthread_mutex_t mutex;
  219594. bool triggered;
  219595. };
  219596. WaitableEvent::WaitableEvent() throw()
  219597. {
  219598. EventStruct* const es = new EventStruct();
  219599. es->triggered = false;
  219600. pthread_cond_init (&es->condition, 0);
  219601. pthread_mutex_init (&es->mutex, 0);
  219602. internal = es;
  219603. }
  219604. WaitableEvent::~WaitableEvent() throw()
  219605. {
  219606. EventStruct* const es = (EventStruct*) internal;
  219607. pthread_cond_destroy (&es->condition);
  219608. pthread_mutex_destroy (&es->mutex);
  219609. delete es;
  219610. }
  219611. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  219612. {
  219613. EventStruct* const es = (EventStruct*) internal;
  219614. bool ok = true;
  219615. pthread_mutex_lock (&es->mutex);
  219616. if (timeOutMillisecs < 0)
  219617. {
  219618. while (! es->triggered)
  219619. pthread_cond_wait (&es->condition, &es->mutex);
  219620. }
  219621. else
  219622. {
  219623. while (! es->triggered)
  219624. {
  219625. struct timeval t;
  219626. gettimeofday (&t, 0);
  219627. struct timespec time;
  219628. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  219629. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  219630. if (time.tv_nsec >= 1000000000)
  219631. {
  219632. time.tv_nsec -= 1000000000;
  219633. time.tv_sec++;
  219634. }
  219635. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  219636. {
  219637. ok = false;
  219638. break;
  219639. }
  219640. }
  219641. }
  219642. es->triggered = false;
  219643. pthread_mutex_unlock (&es->mutex);
  219644. return ok;
  219645. }
  219646. void WaitableEvent::signal() const throw()
  219647. {
  219648. EventStruct* const es = (EventStruct*) internal;
  219649. pthread_mutex_lock (&es->mutex);
  219650. es->triggered = true;
  219651. pthread_cond_broadcast (&es->condition);
  219652. pthread_mutex_unlock (&es->mutex);
  219653. }
  219654. void WaitableEvent::reset() const throw()
  219655. {
  219656. EventStruct* const es = (EventStruct*) internal;
  219657. pthread_mutex_lock (&es->mutex);
  219658. es->triggered = false;
  219659. pthread_mutex_unlock (&es->mutex);
  219660. }
  219661. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  219662. {
  219663. struct timespec time;
  219664. time.tv_sec = millisecs / 1000;
  219665. time.tv_nsec = (millisecs % 1000) * 1000000;
  219666. nanosleep (&time, 0);
  219667. }
  219668. const tchar File::separator = T('/');
  219669. const tchar* File::separatorString = T("/");
  219670. bool juce_copyFile (const String& s, const String& d) throw();
  219671. static bool juce_stat (const String& fileName, struct stat& info) throw()
  219672. {
  219673. return fileName.isNotEmpty()
  219674. && (stat (fileName.toUTF8(), &info) == 0);
  219675. }
  219676. bool juce_isDirectory (const String& fileName) throw()
  219677. {
  219678. struct stat info;
  219679. return fileName.isEmpty()
  219680. || (juce_stat (fileName, info)
  219681. && ((info.st_mode & S_IFDIR) != 0));
  219682. }
  219683. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  219684. {
  219685. if (fileName.isEmpty())
  219686. return false;
  219687. const char* const fileNameUTF8 = fileName.toUTF8();
  219688. bool exists = access (fileNameUTF8, F_OK) == 0;
  219689. if (exists && dontCountDirectories)
  219690. {
  219691. struct stat info;
  219692. const int res = stat (fileNameUTF8, &info);
  219693. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  219694. exists = false;
  219695. }
  219696. return exists;
  219697. }
  219698. int64 juce_getFileSize (const String& fileName) throw()
  219699. {
  219700. struct stat info;
  219701. return juce_stat (fileName, info) ? info.st_size : 0;
  219702. }
  219703. bool juce_canWriteToFile (const String& fileName) throw()
  219704. {
  219705. return access (fileName.toUTF8(), W_OK) == 0;
  219706. }
  219707. bool juce_deleteFile (const String& fileName) throw()
  219708. {
  219709. if (juce_isDirectory (fileName))
  219710. return rmdir ((const char*) fileName.toUTF8()) == 0;
  219711. else
  219712. return remove ((const char*) fileName.toUTF8()) == 0;
  219713. }
  219714. bool juce_moveFile (const String& source, const String& dest) throw()
  219715. {
  219716. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  219717. return true;
  219718. if (juce_canWriteToFile (source)
  219719. && juce_copyFile (source, dest))
  219720. {
  219721. if (juce_deleteFile (source))
  219722. return true;
  219723. juce_deleteFile (dest);
  219724. }
  219725. return false;
  219726. }
  219727. void juce_createDirectory (const String& fileName) throw()
  219728. {
  219729. mkdir (fileName.toUTF8(), 0777);
  219730. }
  219731. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  219732. {
  219733. int flags = O_RDONLY;
  219734. if (forWriting)
  219735. {
  219736. if (juce_fileExists (fileName, false))
  219737. {
  219738. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  219739. if (f != -1)
  219740. lseek (f, 0, SEEK_END);
  219741. return (void*) f;
  219742. }
  219743. else
  219744. {
  219745. flags = O_RDWR + O_CREAT;
  219746. }
  219747. }
  219748. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  219749. }
  219750. void juce_fileClose (void* handle) throw()
  219751. {
  219752. if (handle != 0)
  219753. close ((int) (pointer_sized_int) handle);
  219754. }
  219755. int juce_fileRead (void* handle, void* buffer, int size) throw()
  219756. {
  219757. if (handle != 0)
  219758. return read ((int) (pointer_sized_int) handle, buffer, size);
  219759. return 0;
  219760. }
  219761. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  219762. {
  219763. if (handle != 0)
  219764. return write ((int) (pointer_sized_int) handle, buffer, size);
  219765. return 0;
  219766. }
  219767. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  219768. {
  219769. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  219770. return pos;
  219771. return -1;
  219772. }
  219773. int64 juce_fileGetPosition (void* handle) throw()
  219774. {
  219775. if (handle != 0)
  219776. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  219777. else
  219778. return -1;
  219779. }
  219780. void juce_fileFlush (void* handle) throw()
  219781. {
  219782. if (handle != 0)
  219783. fsync ((int) (pointer_sized_int) handle);
  219784. }
  219785. const File juce_getExecutableFile()
  219786. {
  219787. Dl_info exeInfo;
  219788. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  219789. return File (exeInfo.dli_fname);
  219790. }
  219791. // if this file doesn't exist, find a parent of it that does..
  219792. static bool doStatFS (const File* file, struct statfs& result) throw()
  219793. {
  219794. File f (*file);
  219795. for (int i = 5; --i >= 0;)
  219796. {
  219797. if (f.exists())
  219798. break;
  219799. f = f.getParentDirectory();
  219800. }
  219801. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  219802. }
  219803. int64 File::getBytesFreeOnVolume() const throw()
  219804. {
  219805. struct statfs buf;
  219806. if (doStatFS (this, buf))
  219807. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  219808. return 0;
  219809. }
  219810. int64 File::getVolumeTotalSize() const throw()
  219811. {
  219812. struct statfs buf;
  219813. if (doStatFS (this, buf))
  219814. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  219815. return 0;
  219816. }
  219817. const String juce_getVolumeLabel (const String& filenameOnVolume,
  219818. int& volumeSerialNumber) throw()
  219819. {
  219820. volumeSerialNumber = 0;
  219821. #if JUCE_MAC
  219822. struct VolAttrBuf
  219823. {
  219824. u_int32_t length;
  219825. attrreference_t mountPointRef;
  219826. char mountPointSpace [MAXPATHLEN];
  219827. } attrBuf;
  219828. struct attrlist attrList;
  219829. zerostruct (attrList);
  219830. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  219831. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  219832. File f (filenameOnVolume);
  219833. for (;;)
  219834. {
  219835. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  219836. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  219837. {
  219838. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  219839. (int) attrBuf.mountPointRef.attr_length);
  219840. }
  219841. const File parent (f.getParentDirectory());
  219842. if (f == parent)
  219843. break;
  219844. f = parent;
  219845. }
  219846. #endif
  219847. return String::empty;
  219848. }
  219849. void juce_runSystemCommand (const String& command)
  219850. {
  219851. int result = system ((const char*) command.toUTF8());
  219852. (void) result;
  219853. }
  219854. const String juce_getOutputFromCommand (const String& command)
  219855. {
  219856. // slight bodge here, as we just pipe the output into a temp file and read it...
  219857. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  219858. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  219859. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  219860. String result (tempFile.loadFileAsString());
  219861. tempFile.deleteFile();
  219862. return result;
  219863. }
  219864. #if JUCE_64BIT
  219865. #define filedesc ((long long) internal)
  219866. #else
  219867. #define filedesc ((int) internal)
  219868. #endif
  219869. InterProcessLock::InterProcessLock (const String& name_) throw()
  219870. : internal (0),
  219871. name (name_),
  219872. reentrancyLevel (0)
  219873. {
  219874. #if JUCE_MAC
  219875. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  219876. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  219877. #else
  219878. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  219879. #endif
  219880. temp.create();
  219881. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  219882. }
  219883. InterProcessLock::~InterProcessLock() throw()
  219884. {
  219885. while (reentrancyLevel > 0)
  219886. this->exit();
  219887. close (filedesc);
  219888. }
  219889. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  219890. {
  219891. if (internal == 0)
  219892. return false;
  219893. if (reentrancyLevel != 0)
  219894. return true;
  219895. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  219896. struct flock fl;
  219897. zerostruct (fl);
  219898. fl.l_whence = SEEK_SET;
  219899. fl.l_type = F_WRLCK;
  219900. for (;;)
  219901. {
  219902. const int result = fcntl (filedesc, F_SETLK, &fl);
  219903. if (result >= 0)
  219904. {
  219905. ++reentrancyLevel;
  219906. return true;
  219907. }
  219908. if (errno != EINTR)
  219909. {
  219910. if (timeOutMillisecs == 0
  219911. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  219912. break;
  219913. Thread::sleep (10);
  219914. }
  219915. }
  219916. return false;
  219917. }
  219918. void InterProcessLock::exit() throw()
  219919. {
  219920. if (reentrancyLevel > 0 && internal != 0)
  219921. {
  219922. --reentrancyLevel;
  219923. struct flock fl;
  219924. zerostruct (fl);
  219925. fl.l_whence = SEEK_SET;
  219926. fl.l_type = F_UNLCK;
  219927. for (;;)
  219928. {
  219929. const int result = fcntl (filedesc, F_SETLKW, &fl);
  219930. if (result >= 0 || errno != EINTR)
  219931. break;
  219932. }
  219933. }
  219934. }
  219935. /********* End of inlined file: juce_posix_SharedCode.h *********/
  219936. /********* Start of inlined file: juce_mac_Files.mm *********/
  219937. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219938. // compiled on its own).
  219939. #if JUCE_INCLUDED_FILE
  219940. /*
  219941. Note that a lot of methods that you'd expect to find in this file actually
  219942. live in juce_posix_SharedCode.h!
  219943. */
  219944. void juce_getFileTimes (const String& fileName,
  219945. int64& modificationTime,
  219946. int64& accessTime,
  219947. int64& creationTime) throw()
  219948. {
  219949. modificationTime = 0;
  219950. accessTime = 0;
  219951. creationTime = 0;
  219952. struct stat info;
  219953. const int res = stat (fileName.toUTF8(), &info);
  219954. if (res == 0)
  219955. {
  219956. modificationTime = (int64) info.st_mtime * 1000;
  219957. accessTime = (int64) info.st_atime * 1000;
  219958. creationTime = (int64) info.st_ctime * 1000;
  219959. }
  219960. }
  219961. bool juce_setFileTimes (const String& fileName,
  219962. int64 modificationTime,
  219963. int64 accessTime,
  219964. int64 creationTime) throw()
  219965. {
  219966. struct utimbuf times;
  219967. times.actime = (time_t) (accessTime / 1000);
  219968. times.modtime = (time_t) (modificationTime / 1000);
  219969. return utime (fileName.toUTF8(), &times) == 0;
  219970. }
  219971. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  219972. {
  219973. struct stat info;
  219974. const int res = stat (fileName.toUTF8(), &info);
  219975. if (res != 0)
  219976. return false;
  219977. info.st_mode &= 0777; // Just permissions
  219978. if (isReadOnly)
  219979. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  219980. else
  219981. // Give everybody write permission?
  219982. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  219983. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  219984. }
  219985. bool juce_copyFile (const String& src, const String& dst) throw()
  219986. {
  219987. const ScopedAutoReleasePool pool;
  219988. NSFileManager* fm = [NSFileManager defaultManager];
  219989. return [fm fileExistsAtPath: juceStringToNS (src)]
  219990. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  219991. && [fm copyItemAtPath: juceStringToNS (src)
  219992. toPath: juceStringToNS (dst)
  219993. error: nil];
  219994. #else
  219995. && [fm copyPath: juceStringToNS (src)
  219996. toPath: juceStringToNS (dst)
  219997. handler: nil];
  219998. #endif
  219999. }
  220000. const StringArray juce_getFileSystemRoots() throw()
  220001. {
  220002. StringArray s;
  220003. s.add (T("/"));
  220004. return s;
  220005. }
  220006. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  220007. {
  220008. struct statfs buf;
  220009. if (doStatFS (f, buf))
  220010. {
  220011. const String type (buf.f_fstypename);
  220012. while (*types != 0)
  220013. if (type.equalsIgnoreCase (*types++))
  220014. return true;
  220015. }
  220016. return false;
  220017. }
  220018. bool File::isOnCDRomDrive() const throw()
  220019. {
  220020. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  220021. return isFileOnDriveType (this, (const char**) cdTypes);
  220022. }
  220023. bool File::isOnHardDisk() const throw()
  220024. {
  220025. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  220026. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  220027. }
  220028. bool File::isOnRemovableDrive() const throw()
  220029. {
  220030. #if JUCE_IPHONE
  220031. return false; // xxx is this possible?
  220032. #else
  220033. const ScopedAutoReleasePool pool;
  220034. BOOL removable = false;
  220035. [[NSWorkspace sharedWorkspace]
  220036. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  220037. isRemovable: &removable
  220038. isWritable: nil
  220039. isUnmountable: nil
  220040. description: nil
  220041. type: nil];
  220042. return removable;
  220043. #endif
  220044. }
  220045. static bool juce_isHiddenFile (const String& path) throw()
  220046. {
  220047. #if JUCE_IPHONE
  220048. return File (path).getFileName().startsWithChar (T('.'));
  220049. #else
  220050. FSRef ref;
  220051. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  220052. return false;
  220053. FSCatalogInfo info;
  220054. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  220055. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  220056. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  220057. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  220058. #endif
  220059. }
  220060. bool File::isHidden() const throw()
  220061. {
  220062. return juce_isHiddenFile (getFullPathName());
  220063. }
  220064. const File File::getSpecialLocation (const SpecialLocationType type)
  220065. {
  220066. const ScopedAutoReleasePool pool;
  220067. String resultPath;
  220068. switch (type)
  220069. {
  220070. case userHomeDirectory:
  220071. resultPath = nsStringToJuce (NSHomeDirectory());
  220072. break;
  220073. case userDocumentsDirectory:
  220074. resultPath = "~/Documents";
  220075. break;
  220076. case userDesktopDirectory:
  220077. resultPath = "~/Desktop";
  220078. break;
  220079. case userApplicationDataDirectory:
  220080. resultPath = "~/Library";
  220081. break;
  220082. case commonApplicationDataDirectory:
  220083. resultPath = "/Library";
  220084. break;
  220085. case globalApplicationsDirectory:
  220086. resultPath = "/Applications";
  220087. break;
  220088. case userMusicDirectory:
  220089. resultPath = "~/Music";
  220090. break;
  220091. case userMoviesDirectory:
  220092. resultPath = "~/Movies";
  220093. break;
  220094. case tempDirectory:
  220095. {
  220096. File tmp (T("~/Library/Caches/") + juce_getExecutableFile().getFileNameWithoutExtension());
  220097. tmp.createDirectory();
  220098. return tmp.getFullPathName();
  220099. }
  220100. case currentExecutableFile:
  220101. return juce_getExecutableFile();
  220102. case currentApplicationFile:
  220103. {
  220104. const File exe (juce_getExecutableFile());
  220105. const File parent (exe.getParentDirectory());
  220106. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  220107. ? parent.getParentDirectory().getParentDirectory()
  220108. : exe;
  220109. }
  220110. default:
  220111. jassertfalse // unknown type?
  220112. break;
  220113. }
  220114. if (resultPath != 0)
  220115. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  220116. return File::nonexistent;
  220117. }
  220118. const File File::getCurrentWorkingDirectory() throw()
  220119. {
  220120. char buf [2048];
  220121. getcwd (buf, sizeof(buf));
  220122. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  220123. }
  220124. bool File::setAsCurrentWorkingDirectory() const throw()
  220125. {
  220126. return chdir (getFullPathName().toUTF8()) == 0;
  220127. }
  220128. const String File::getVersion() const throw()
  220129. {
  220130. const ScopedAutoReleasePool pool;
  220131. String result;
  220132. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  220133. if (bundle != 0)
  220134. {
  220135. NSDictionary* info = [bundle infoDictionary];
  220136. if (info != 0)
  220137. {
  220138. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  220139. if (name != nil)
  220140. result = nsStringToJuce (name);
  220141. }
  220142. }
  220143. return result;
  220144. }
  220145. const File File::getLinkedTarget() const throw()
  220146. {
  220147. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  220148. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  220149. #else
  220150. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  220151. #endif
  220152. if (dest != nil)
  220153. return File (nsStringToJuce (dest));
  220154. return *this;
  220155. }
  220156. bool File::moveToTrash() const throw()
  220157. {
  220158. if (! exists())
  220159. return true;
  220160. #if JUCE_IPHONE
  220161. return deleteFile(); //xxx is there a trashcan on the iPhone?
  220162. #else
  220163. const ScopedAutoReleasePool pool;
  220164. NSString* p = juceStringToNS (getFullPathName());
  220165. return [[NSWorkspace sharedWorkspace]
  220166. performFileOperation: NSWorkspaceRecycleOperation
  220167. source: [p stringByDeletingLastPathComponent]
  220168. destination: @""
  220169. files: [NSArray arrayWithObject: [p lastPathComponent]]
  220170. tag: nil ];
  220171. #endif
  220172. }
  220173. struct FindFileStruct
  220174. {
  220175. NSDirectoryEnumerator* enumerator;
  220176. String parentDir, wildCard;
  220177. };
  220178. bool juce_findFileNext (void* handle, String& resultFile,
  220179. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  220180. {
  220181. FindFileStruct* ff = (FindFileStruct*) handle;
  220182. NSString* file;
  220183. const char* const wildcardUTF8 = ff->wildCard.toUTF8();
  220184. for (;;)
  220185. {
  220186. if (ff == 0 || (file = [ff->enumerator nextObject]) == 0)
  220187. return false;
  220188. [ff->enumerator skipDescendents];
  220189. resultFile = nsStringToJuce (file);
  220190. if (fnmatch (wildcardUTF8, resultFile.toUTF8(), FNM_CASEFOLD) != 0)
  220191. continue;
  220192. const String path (ff->parentDir + resultFile);
  220193. if (isDir != 0 || fileSize != 0)
  220194. {
  220195. struct stat info;
  220196. const bool statOk = juce_stat (path, info);
  220197. if (isDir != 0)
  220198. *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  220199. if (isHidden != 0)
  220200. *isHidden = juce_isHiddenFile (path);
  220201. if (fileSize != 0)
  220202. *fileSize = statOk ? info.st_size : 0;
  220203. }
  220204. if (modTime != 0 || creationTime != 0)
  220205. {
  220206. int64 m, a, c;
  220207. juce_getFileTimes (path, m, a, c);
  220208. if (modTime != 0)
  220209. *modTime = m;
  220210. if (creationTime != 0)
  220211. *creationTime = c;
  220212. }
  220213. if (isReadOnly != 0)
  220214. *isReadOnly = ! juce_canWriteToFile (path);
  220215. return true;
  220216. }
  220217. }
  220218. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  220219. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  220220. Time* creationTime, bool* isReadOnly) throw()
  220221. {
  220222. NSDirectoryEnumerator* e = [[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory)];
  220223. if (e != 0)
  220224. {
  220225. FindFileStruct* ff = new FindFileStruct();
  220226. ff->enumerator = [e retain];
  220227. ff->parentDir = directory;
  220228. ff->wildCard = wildCard;
  220229. if (! ff->parentDir.endsWithChar (File::separator))
  220230. ff->parentDir += File::separator;
  220231. if (juce_findFileNext (ff, firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  220232. return ff;
  220233. [e release];
  220234. delete ff;
  220235. }
  220236. return 0;
  220237. }
  220238. void juce_findFileClose (void* handle) throw()
  220239. {
  220240. FindFileStruct* ff = (FindFileStruct*) handle;
  220241. [ff->enumerator release];
  220242. delete ff;
  220243. }
  220244. bool juce_launchExecutable (const String& pathAndArguments) throw()
  220245. {
  220246. const char* const argv[4] = { "/bin/sh", "-c", (const char*) pathAndArguments, 0 };
  220247. const int cpid = fork();
  220248. if (cpid == 0)
  220249. {
  220250. // Child process
  220251. if (execve (argv[0], (char**) argv, 0) < 0)
  220252. exit (0);
  220253. }
  220254. else
  220255. {
  220256. if (cpid < 0)
  220257. return false;
  220258. }
  220259. return true;
  220260. }
  220261. bool juce_launchFile (const String& fileName,
  220262. const String& parameters) throw()
  220263. {
  220264. #if JUCE_IPHONE
  220265. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  220266. #else
  220267. const ScopedAutoReleasePool pool;
  220268. if (parameters.isEmpty())
  220269. {
  220270. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  220271. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  220272. }
  220273. bool ok = false;
  220274. FSRef ref;
  220275. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  220276. {
  220277. if (PlatformUtilities::isBundle (fileName))
  220278. {
  220279. NSMutableArray* urls = [NSMutableArray array];
  220280. StringArray docs;
  220281. docs.addTokens (parameters, true);
  220282. for (int i = 0; i < docs.size(); ++i)
  220283. [urls addObject: juceStringToNS (docs[i])];
  220284. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  220285. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  220286. options: nil
  220287. additionalEventParamDescriptor: nil
  220288. launchIdentifiers: nil];
  220289. }
  220290. else
  220291. {
  220292. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  220293. }
  220294. }
  220295. return ok;
  220296. #endif
  220297. }
  220298. #if ! JUCE_IPHONE
  220299. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  220300. {
  220301. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  220302. }
  220303. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  220304. {
  220305. uint8 path [2048];
  220306. zeromem (path, sizeof (path));
  220307. String result;
  220308. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  220309. result = String::fromUTF8 (path);
  220310. return PlatformUtilities::convertToPrecomposedUnicode (result);
  220311. }
  220312. #endif
  220313. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  220314. {
  220315. const ScopedAutoReleasePool pool;
  220316. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  220317. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  220318. #else
  220319. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  220320. #endif
  220321. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  220322. return [fileDict fileHFSTypeCode];
  220323. }
  220324. bool PlatformUtilities::isBundle (const String& filename)
  220325. {
  220326. #if JUCE_IPHONE
  220327. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  220328. #else
  220329. const ScopedAutoReleasePool pool;
  220330. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  220331. #endif
  220332. }
  220333. #endif
  220334. /********* End of inlined file: juce_mac_Files.mm *********/
  220335. #if JUCE_IPHONE
  220336. /********* Start of inlined file: juce_iphone_MiscUtilities.mm *********/
  220337. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220338. // compiled on its own).
  220339. #if JUCE_INCLUDED_FILE
  220340. static JUCEApplication* juce_intialisingApp;
  220341. END_JUCE_NAMESPACE
  220342. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  220343. {
  220344. }
  220345. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  220346. - (void) applicationWillResignActive: (UIApplication*) application;
  220347. @end
  220348. @implementation JuceAppStartupDelegate
  220349. - (void) applicationDidFinishLaunching: (UIApplication*) application
  220350. {
  220351. String dummy;
  220352. if (! juce_intialisingApp->initialiseApp (dummy))
  220353. {
  220354. // (should quit)
  220355. }
  220356. }
  220357. - (void) applicationWillResignActive: (UIApplication*) application
  220358. {
  220359. JUCEApplication::shutdownAppAndClearUp();
  220360. }
  220361. @end
  220362. BEGIN_JUCE_NAMESPACE
  220363. int juce_IPhoneMain (int argc, char* argv[], JUCEApplication* app)
  220364. {
  220365. juce_intialisingApp = app;
  220366. return UIApplicationMain (argc, argv, nil, @"JuceAppStartupDelegate");
  220367. }
  220368. ScopedAutoReleasePool::ScopedAutoReleasePool()
  220369. {
  220370. pool = [[NSAutoreleasePool alloc] init];
  220371. }
  220372. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  220373. {
  220374. [((NSAutoreleasePool*) pool) release];
  220375. }
  220376. void PlatformUtilities::beep()
  220377. {
  220378. //xxx
  220379. //AudioServicesPlaySystemSound ();
  220380. }
  220381. void PlatformUtilities::addItemToDock (const File& file)
  220382. {
  220383. }
  220384. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220385. END_JUCE_NAMESPACE
  220386. @interface JuceAlertBoxDelegate : NSObject
  220387. {
  220388. @public
  220389. bool clickedOk;
  220390. }
  220391. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  220392. @end
  220393. @implementation JuceAlertBoxDelegate
  220394. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  220395. {
  220396. clickedOk = (buttonIndex == 0);
  220397. alertView.hidden = true;
  220398. }
  220399. @end
  220400. BEGIN_JUCE_NAMESPACE
  220401. // (This function is used directly by other bits of code)
  220402. bool juce_iPhoneShowModalAlert (const String& title,
  220403. const String& bodyText,
  220404. NSString* okButtonText,
  220405. NSString* cancelButtonText)
  220406. {
  220407. const ScopedAutoReleasePool pool;
  220408. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  220409. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  220410. message: juceStringToNS (bodyText)
  220411. delegate: callback
  220412. cancelButtonTitle: okButtonText
  220413. otherButtonTitles: cancelButtonText, nil];
  220414. [alert retain];
  220415. [alert show];
  220416. while (! alert.hidden && alert.superview != nil)
  220417. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  220418. const bool result = callback->clickedOk;
  220419. [alert release];
  220420. [callback release];
  220421. return result;
  220422. }
  220423. bool AlertWindow::showNativeDialogBox (const String& title,
  220424. const String& bodyText,
  220425. bool isOkCancel)
  220426. {
  220427. return juce_iPhoneShowModalAlert (title, bodyText,
  220428. @"OK",
  220429. isOkCancel ? @"Cancel" : nil);
  220430. }
  220431. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220432. {
  220433. jassertfalse // no such thing on the iphone!
  220434. return false;
  220435. }
  220436. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220437. {
  220438. jassertfalse // no such thing on the iphone!
  220439. return false;
  220440. }
  220441. bool Desktop::canUseSemiTransparentWindows() throw()
  220442. {
  220443. return true;
  220444. }
  220445. void Desktop::getMousePosition (int& x, int& y) throw()
  220446. {
  220447. x = 0;
  220448. y = 0;
  220449. }
  220450. void Desktop::setMousePosition (int x, int y) throw()
  220451. {
  220452. }
  220453. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220454. {
  220455. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  220456. }
  220457. bool Desktop::isScreenSaverEnabled() throw()
  220458. {
  220459. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  220460. }
  220461. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220462. {
  220463. const ScopedAutoReleasePool pool;
  220464. monitorCoords.clear();
  220465. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  220466. : [[UIScreen mainScreen] bounds];
  220467. monitorCoords.add (Rectangle ((int) r.origin.x,
  220468. (int) r.origin.y,
  220469. (int) r.size.width,
  220470. (int) r.size.height));
  220471. }
  220472. #endif
  220473. #endif
  220474. /********* End of inlined file: juce_iphone_MiscUtilities.mm *********/
  220475. #else
  220476. /********* Start of inlined file: juce_mac_MiscUtilities.mm *********/
  220477. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220478. // compiled on its own).
  220479. #if JUCE_INCLUDED_FILE
  220480. ScopedAutoReleasePool::ScopedAutoReleasePool()
  220481. {
  220482. pool = [[NSAutoreleasePool alloc] init];
  220483. }
  220484. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  220485. {
  220486. [((NSAutoreleasePool*) pool) release];
  220487. }
  220488. void PlatformUtilities::beep()
  220489. {
  220490. NSBeep();
  220491. }
  220492. void PlatformUtilities::addItemToDock (const File& file)
  220493. {
  220494. // check that it's not already there...
  220495. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  220496. .containsIgnoreCase (file.getFullPathName()))
  220497. {
  220498. 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>"
  220499. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  220500. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  220501. }
  220502. }
  220503. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220504. bool AlertWindow::showNativeDialogBox (const String& title,
  220505. const String& bodyText,
  220506. bool isOkCancel)
  220507. {
  220508. const ScopedAutoReleasePool pool;
  220509. return NSRunAlertPanel (juceStringToNS (title),
  220510. juceStringToNS (bodyText),
  220511. @"Ok",
  220512. isOkCancel ? @"Cancel" : nil,
  220513. nil) == NSAlertDefaultReturn;
  220514. }
  220515. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220516. {
  220517. if (files.size() == 0)
  220518. return false;
  220519. Component* sourceComp = Component::getComponentUnderMouse();
  220520. if (sourceComp == 0)
  220521. {
  220522. jassertfalse // this method must be called in response to a
  220523. // component's mouseDrag event!
  220524. return false;
  220525. }
  220526. const ScopedAutoReleasePool pool;
  220527. NSView* view = (NSView*) sourceComp->getWindowHandle();
  220528. if (view == 0)
  220529. return false;
  220530. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  220531. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  220532. owner: nil];
  220533. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  220534. for (int i = 0; i < files.size(); ++i)
  220535. [filesArray addObject: juceStringToNS (files[i])];
  220536. [pboard setPropertyList: filesArray
  220537. forType: NSFilenamesPboardType];
  220538. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  220539. fromView: nil];
  220540. dragPosition.x -= 16;
  220541. dragPosition.y -= 16;
  220542. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  220543. at: dragPosition
  220544. offset: NSMakeSize (0, 0)
  220545. event: [[view window] currentEvent]
  220546. pasteboard: pboard
  220547. source: view
  220548. slideBack: YES];
  220549. return true;
  220550. }
  220551. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220552. {
  220553. jassertfalse // not implemented!
  220554. return false;
  220555. }
  220556. bool Desktop::canUseSemiTransparentWindows() throw()
  220557. {
  220558. return true;
  220559. }
  220560. void Desktop::getMousePosition (int& x, int& y) throw()
  220561. {
  220562. const ScopedAutoReleasePool pool;
  220563. const NSPoint p ([NSEvent mouseLocation]);
  220564. x = roundFloatToInt (p.x);
  220565. y = roundFloatToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y);
  220566. }
  220567. void Desktop::setMousePosition (int x, int y) throw()
  220568. {
  220569. // this rubbish needs to be done around the warp call, to avoid causing a
  220570. // bizarre glitch..
  220571. CGAssociateMouseAndMouseCursorPosition (false);
  220572. #if (! defined (MAC_OS_X_VERSION_10_6)) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
  220573. CGSetLocalEventsSuppressionInterval (0);
  220574. #endif
  220575. CGPoint pos = { x, y };
  220576. CGWarpMouseCursorPosition (pos);
  220577. CGAssociateMouseAndMouseCursorPosition (true);
  220578. }
  220579. #if MACOS_10_4_OR_EARLIER
  220580. class ScreenSaverDefeater : public Timer,
  220581. public DeletedAtShutdown
  220582. {
  220583. public:
  220584. ScreenSaverDefeater() throw()
  220585. {
  220586. startTimer (10000);
  220587. timerCallback();
  220588. }
  220589. ~ScreenSaverDefeater() {}
  220590. void timerCallback()
  220591. {
  220592. if (Process::isForegroundProcess())
  220593. UpdateSystemActivity (UsrActivity);
  220594. }
  220595. };
  220596. static ScreenSaverDefeater* screenSaverDefeater = 0;
  220597. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220598. {
  220599. if (isEnabled)
  220600. {
  220601. deleteAndZero (screenSaverDefeater);
  220602. }
  220603. else if (screenSaverDefeater == 0)
  220604. {
  220605. screenSaverDefeater = new ScreenSaverDefeater();
  220606. }
  220607. }
  220608. bool Desktop::isScreenSaverEnabled() throw()
  220609. {
  220610. return screenSaverDefeater == 0;
  220611. }
  220612. #else
  220613. static IOPMAssertionID screenSaverDisablerID = 0;
  220614. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220615. {
  220616. if (isEnabled)
  220617. {
  220618. if (screenSaverDisablerID != 0)
  220619. {
  220620. IOPMAssertionRelease (screenSaverDisablerID);
  220621. screenSaverDisablerID = 0;
  220622. }
  220623. }
  220624. else
  220625. {
  220626. if (screenSaverDisablerID == 0)
  220627. {
  220628. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  220629. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220630. CFSTR ("Juce"), &screenSaverDisablerID);
  220631. #else
  220632. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220633. &screenSaverDisablerID);
  220634. #endif
  220635. }
  220636. }
  220637. }
  220638. bool Desktop::isScreenSaverEnabled() throw()
  220639. {
  220640. return screenSaverDisablerID == 0;
  220641. }
  220642. #endif
  220643. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220644. {
  220645. const ScopedAutoReleasePool pool;
  220646. monitorCoords.clear();
  220647. NSArray* screens = [NSScreen screens];
  220648. const float mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  220649. for (unsigned int i = 0; i < [screens count]; ++i)
  220650. {
  220651. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  220652. NSRect r = clipToWorkArea ? [s visibleFrame]
  220653. : [s frame];
  220654. monitorCoords.add (Rectangle ((int) r.origin.x,
  220655. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  220656. (int) r.size.width,
  220657. (int) r.size.height));
  220658. }
  220659. jassert (monitorCoords.size() > 0);
  220660. }
  220661. #endif
  220662. #endif
  220663. /********* End of inlined file: juce_mac_MiscUtilities.mm *********/
  220664. #endif
  220665. /********* Start of inlined file: juce_mac_Debugging.mm *********/
  220666. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220667. // compiled on its own).
  220668. #if JUCE_INCLUDED_FILE
  220669. void Logger::outputDebugString (const String& text) throw()
  220670. {
  220671. fputs (text.toUTF8(), stderr);
  220672. fputs ("\n", stderr);
  220673. }
  220674. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  220675. {
  220676. String text;
  220677. va_list args;
  220678. va_start (args, format);
  220679. text.vprintf (format, args);
  220680. outputDebugString (text);
  220681. }
  220682. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  220683. {
  220684. static char testResult = 0;
  220685. if (testResult == 0)
  220686. {
  220687. struct kinfo_proc info;
  220688. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  220689. size_t sz = sizeof (info);
  220690. sysctl (m, 4, &info, &sz, 0, 0);
  220691. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  220692. }
  220693. return testResult > 0;
  220694. }
  220695. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  220696. {
  220697. return juce_isRunningUnderDebugger();
  220698. }
  220699. #endif
  220700. /********* End of inlined file: juce_mac_Debugging.mm *********/
  220701. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220702. #if JUCE_IPHONE
  220703. /********* Start of inlined file: juce_iphone_UIViewComponentPeer.mm *********/
  220704. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220705. // compiled on its own).
  220706. #if JUCE_INCLUDED_FILE
  220707. class UIViewComponentPeer;
  220708. END_JUCE_NAMESPACE
  220709. #define JuceUIView MakeObjCClassName(JuceUIView)
  220710. @interface JuceUIView : UIView
  220711. {
  220712. @public
  220713. UIViewComponentPeer* owner;
  220714. }
  220715. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  220716. - (void) dealloc;
  220717. - (void) drawRect: (CGRect) r;
  220718. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  220719. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  220720. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  220721. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  220722. - (BOOL) becomeFirstResponder;
  220723. - (BOOL) resignFirstResponder;
  220724. - (BOOL) canBecomeFirstResponder;
  220725. @end
  220726. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  220727. @interface JuceUIWindow : UIWindow
  220728. {
  220729. @private
  220730. UIViewComponentPeer* owner;
  220731. bool isZooming;
  220732. }
  220733. - (void) setOwner: (UIViewComponentPeer*) owner;
  220734. - (void) becomeKeyWindow;
  220735. @end
  220736. BEGIN_JUCE_NAMESPACE
  220737. class UIViewComponentPeer : public ComponentPeer
  220738. {
  220739. public:
  220740. UIViewComponentPeer (Component* const component,
  220741. const int windowStyleFlags,
  220742. UIView* viewToAttachTo);
  220743. ~UIViewComponentPeer();
  220744. void* getNativeHandle() const;
  220745. void setVisible (bool shouldBeVisible);
  220746. void setTitle (const String& title);
  220747. void setPosition (int x, int y);
  220748. void setSize (int w, int h);
  220749. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  220750. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  220751. void getBounds (int& x, int& y, int& w, int& h) const;
  220752. int getScreenX() const;
  220753. int getScreenY() const;
  220754. void relativePositionToGlobal (int& x, int& y);
  220755. void globalPositionToRelative (int& x, int& y);
  220756. void setMinimised (bool shouldBeMinimised);
  220757. bool isMinimised() const;
  220758. void setFullScreen (bool shouldBeFullScreen);
  220759. bool isFullScreen() const;
  220760. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  220761. const BorderSize getFrameSize() const;
  220762. bool setAlwaysOnTop (bool alwaysOnTop);
  220763. void toFront (bool makeActiveWindow);
  220764. void toBehind (ComponentPeer* other);
  220765. void setIcon (const Image& newIcon);
  220766. virtual void drawRect (CGRect r);
  220767. virtual bool canBecomeKeyWindow();
  220768. virtual bool windowShouldClose();
  220769. virtual void redirectMovedOrResized();
  220770. virtual CGRect constrainRect (CGRect r);
  220771. virtual void viewFocusGain();
  220772. virtual void viewFocusLoss();
  220773. bool isFocused() const;
  220774. void grabFocus();
  220775. void textInputRequired (int x, int y);
  220776. void repaint (int x, int y, int w, int h);
  220777. void performAnyPendingRepaintsNow();
  220778. juce_UseDebuggingNewOperator
  220779. UIWindow* window;
  220780. JuceUIView* view;
  220781. bool isSharedWindow, fullScreen;
  220782. };
  220783. END_JUCE_NAMESPACE
  220784. @implementation JuceUIView
  220785. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  220786. withFrame: (CGRect) frame
  220787. {
  220788. [super initWithFrame: frame];
  220789. owner = owner_;
  220790. return self;
  220791. }
  220792. - (void) dealloc
  220793. {
  220794. [super dealloc];
  220795. }
  220796. - (void) drawRect: (CGRect) r
  220797. {
  220798. if (owner != 0)
  220799. owner->drawRect (r);
  220800. }
  220801. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  220802. {
  220803. return false;
  220804. }
  220805. static int currentModifiers = 0;
  220806. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220807. {
  220808. return ModifierKeys (currentModifiers);
  220809. }
  220810. void ModifierKeys::updateCurrentModifiers() throw()
  220811. {
  220812. currentModifierFlags = currentModifiers;
  220813. }
  220814. static int getModifierForButtonNumber (const int num) throw()
  220815. {
  220816. return num == 0 ? ModifierKeys::leftButtonModifier
  220817. : (num == 1 ? ModifierKeys::rightButtonModifier
  220818. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  220819. }
  220820. static int64 getMouseTime (UIEvent* e) { return (int64) [e timestamp] * 1000.0; }
  220821. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  220822. {
  220823. NSArray* const t = [[event touchesForView: self] allObjects];
  220824. switch ([t count])
  220825. {
  220826. case 1: // One finger..
  220827. {
  220828. CGPoint p = [[t objectAtIndex: 0] locationInView: self];
  220829. currentModifiers |= getModifierForButtonNumber (0);
  220830. owner->handleMouseDown (p.x, p.y, getMouseTime (event));
  220831. }
  220832. default:
  220833. //xxx multi-touch..
  220834. break;
  220835. }
  220836. }
  220837. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  220838. {
  220839. NSArray* const t = [[event touchesForView: self] allObjects];
  220840. switch ([t count])
  220841. {
  220842. case 1: // One finger..
  220843. {
  220844. CGPoint p = [[t objectAtIndex: 0] locationInView: self];
  220845. owner->handleMouseDrag (p.x, p.y, getMouseTime (event));
  220846. }
  220847. default:
  220848. //xxx multi-touch..
  220849. break;
  220850. }
  220851. }
  220852. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  220853. {
  220854. NSArray* const t = [[event touchesForView: self] allObjects];
  220855. switch ([t count])
  220856. {
  220857. case 1: // One finger..
  220858. {
  220859. CGPoint p = [[t objectAtIndex: 0] locationInView: self];
  220860. const int oldMods = currentModifiers;
  220861. currentModifiers &= ~getModifierForButtonNumber (0);
  220862. owner->handleMouseUp (oldMods, p.x, p.y, getMouseTime (event));
  220863. }
  220864. default:
  220865. //xxx multi-touch..
  220866. break;
  220867. }
  220868. }
  220869. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  220870. {
  220871. [self touchesEnded: touches withEvent: event];
  220872. }
  220873. - (BOOL) becomeFirstResponder
  220874. {
  220875. if (owner != 0)
  220876. owner->viewFocusGain();
  220877. return true;
  220878. }
  220879. - (BOOL) resignFirstResponder
  220880. {
  220881. if (owner != 0)
  220882. owner->viewFocusLoss();
  220883. return true;
  220884. }
  220885. - (BOOL) canBecomeFirstResponder
  220886. {
  220887. return owner != 0 && owner->canBecomeKeyWindow();
  220888. }
  220889. @end
  220890. @implementation JuceUIWindow
  220891. - (void) setOwner: (UIViewComponentPeer*) owner_
  220892. {
  220893. owner = owner_;
  220894. isZooming = false;
  220895. }
  220896. - (void) becomeKeyWindow
  220897. {
  220898. [super becomeKeyWindow];
  220899. if (owner != 0)
  220900. owner->grabFocus();
  220901. }
  220902. @end
  220903. BEGIN_JUCE_NAMESPACE
  220904. class JuceUIImage
  220905. {
  220906. public:
  220907. JuceUIImage (const int width, const int height, const bool hasAlpha)
  220908. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  220909. width, height, hasAlpha)
  220910. {
  220911. lineStride = 0;
  220912. pixelStride = 0;
  220913. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  220914. lineStride, pixelStride);
  220915. CGDataProviderRef provider = CGDataProviderCreateWithData (0, imageData, lineStride * pixelStride, 0);
  220916. imageRef = CGImageCreate (width, height,
  220917. 8, pixelStride * 8, lineStride,
  220918. CGColorSpaceCreateDeviceRGB(),
  220919. hasAlpha ? (kCGImageAlphaFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault,
  220920. provider,
  220921. 0,
  220922. true, kCGRenderingIntentDefault);
  220923. juceImage.releasePixelDataReadWrite (imageData);
  220924. uiImage = [[UIImage imageWithCGImage: imageRef] retain];
  220925. }
  220926. ~JuceUIImage()
  220927. {
  220928. [uiImage release];
  220929. CFRelease (imageRef);
  220930. }
  220931. Image& getJuceImage() throw() { return juceImage; }
  220932. void draw (const float x, const float y) const
  220933. {
  220934. [uiImage drawAtPoint: CGPointMake (x, y)
  220935. blendMode: kCGBlendModeCopy
  220936. alpha: 1.0f];
  220937. }
  220938. void drawUIImage (UIImage* imageToDraw)
  220939. {
  220940. const ScopedAutoReleasePool pool;
  220941. jassertfalse
  220942. /*[NSGraphicsContext saveGraphicsState];
  220943. [NSGraphicsContext setCurrentContext:
  220944. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  220945. [imageToDraw drawAtPoint: NSZeroPoint
  220946. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  220947. operation: NSCompositeSourceOver
  220948. fraction: 1.0f];
  220949. [[NSGraphicsContext currentContext] flushGraphics];
  220950. [NSGraphicsContext restoreGraphicsState];
  220951. if (juceImage.hasAlphaChannel())
  220952. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());*/
  220953. }
  220954. private:
  220955. Image juceImage;
  220956. CGImageRef imageRef;
  220957. CGDataProviderRef provider;
  220958. UIImage* uiImage;
  220959. uint8* imageData;
  220960. int pixelStride, lineStride;
  220961. /* void swapRGBOrder (const int x, const int y, const int w, int h) const
  220962. {
  220963. #if JUCE_BIG_ENDIAN
  220964. jassert (pixelStride == 4);
  220965. #endif
  220966. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  220967. .contains (Rectangle (x, y, w, h)));
  220968. uint8* start = imageData + x * pixelStride + y * lineStride;
  220969. while (--h >= 0)
  220970. {
  220971. uint8* p = start;
  220972. start += lineStride;
  220973. for (int i = w; --i >= 0;)
  220974. {
  220975. #if JUCE_BIG_ENDIAN
  220976. const uint8 oldp3 = p[3];
  220977. const uint8 oldp1 = p[1];
  220978. p[3] = p[0];
  220979. p[0] = oldp1;
  220980. p[1] = p[2];
  220981. p[2] = oldp3;
  220982. #else
  220983. const uint8 oldp0 = p[0];
  220984. p[0] = p[2];
  220985. p[2] = oldp0;
  220986. #endif
  220987. p += pixelStride;
  220988. }
  220989. }
  220990. }*/
  220991. };
  220992. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  220993. const int windowStyleFlags,
  220994. UIView* viewToAttachTo)
  220995. : ComponentPeer (component, windowStyleFlags),
  220996. window (0),
  220997. view (0),
  220998. isSharedWindow (viewToAttachTo != 0),
  220999. fullScreen (false)
  221000. {
  221001. CGRect r;
  221002. r.origin.x = 0;
  221003. r.origin.y = 0;
  221004. r.size.width = (float) component->getWidth();
  221005. r.size.height = (float) component->getHeight();
  221006. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  221007. if (isSharedWindow)
  221008. {
  221009. window = [viewToAttachTo window];
  221010. [viewToAttachTo addSubview: view];
  221011. setVisible (component->isVisible());
  221012. }
  221013. else
  221014. {
  221015. r.origin.x = (float) component->getX();
  221016. r.origin.y = (float) component->getY();
  221017. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  221018. window = [[JuceUIWindow alloc] init];
  221019. window.frame = r;
  221020. [((JuceUIWindow*) window) setOwner: this];
  221021. if (component->isAlwaysOnTop())
  221022. window.windowLevel = UIWindowLevelAlert;
  221023. [window addSubview: view];
  221024. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  221025. }
  221026. setTitle (component->getName());
  221027. }
  221028. UIViewComponentPeer::~UIViewComponentPeer()
  221029. {
  221030. view->owner = 0;
  221031. [view removeFromSuperview];
  221032. [view release];
  221033. if (! isSharedWindow)
  221034. {
  221035. [((JuceUIWindow*) window) setOwner: 0];
  221036. [window release];
  221037. }
  221038. }
  221039. void* UIViewComponentPeer::getNativeHandle() const
  221040. {
  221041. return view;
  221042. }
  221043. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  221044. {
  221045. view.hidden = ! shouldBeVisible;
  221046. }
  221047. void UIViewComponentPeer::setTitle (const String& title)
  221048. {
  221049. // xxx is this possible?
  221050. }
  221051. void UIViewComponentPeer::setPosition (int x, int y)
  221052. {
  221053. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  221054. }
  221055. void UIViewComponentPeer::setSize (int w, int h)
  221056. {
  221057. setBounds (component->getX(), component->getY(), w, h, false);
  221058. }
  221059. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  221060. {
  221061. fullScreen = isNowFullScreen;
  221062. w = jmax (0, w);
  221063. h = jmax (0, h);
  221064. CGRect r;
  221065. r.origin.x = (float) x;
  221066. r.origin.y = (float) y;
  221067. r.size.width = (float) w;
  221068. r.size.height = (float) h;
  221069. if (isSharedWindow)
  221070. {
  221071. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  221072. if ([view frame].size.width != r.size.width
  221073. || [view frame].size.height != r.size.height)
  221074. [view setNeedsDisplay];
  221075. view.frame = r;
  221076. }
  221077. else
  221078. {
  221079. //r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  221080. window.frame = r;
  221081. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  221082. }
  221083. }
  221084. void UIViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  221085. {
  221086. CGRect r = [view frame];
  221087. if (global && [view window] != 0)
  221088. {
  221089. r = [view convertRect: r toView: nil];
  221090. CGRect wr = [[view window] frame];
  221091. r.origin.x += wr.origin.x;
  221092. r.origin.y += wr.origin.y;
  221093. y = (int) ([[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height);
  221094. }
  221095. else
  221096. {
  221097. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  221098. }
  221099. x = (int) r.origin.x;
  221100. w = (int) r.size.width;
  221101. h = (int) r.size.height;
  221102. }
  221103. void UIViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  221104. {
  221105. getBounds (x, y, w, h, ! isSharedWindow);
  221106. }
  221107. int UIViewComponentPeer::getScreenX() const
  221108. {
  221109. int x, y, w, h;
  221110. getBounds (x, y, w, h, true);
  221111. return x;
  221112. }
  221113. int UIViewComponentPeer::getScreenY() const
  221114. {
  221115. int x, y, w, h;
  221116. getBounds (x, y, w, h, true);
  221117. return y;
  221118. }
  221119. void UIViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  221120. {
  221121. int wx, wy, ww, wh;
  221122. getBounds (wx, wy, ww, wh, true);
  221123. x += wx;
  221124. y += wy;
  221125. }
  221126. void UIViewComponentPeer::globalPositionToRelative (int& x, int& y)
  221127. {
  221128. int wx, wy, ww, wh;
  221129. getBounds (wx, wy, ww, wh, true);
  221130. x -= wx;
  221131. y -= wy;
  221132. }
  221133. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  221134. {
  221135. if (constrainer != 0)
  221136. {
  221137. CGRect current = [window frame];
  221138. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  221139. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  221140. int x = (int) r.origin.x;
  221141. int y = (int) r.origin.y;
  221142. int w = (int) r.size.width;
  221143. int h = (int) r.size.height;
  221144. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  221145. (int) current.size.width, (int) current.size.height);
  221146. constrainer->checkBounds (x, y, w, h,
  221147. original,
  221148. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  221149. y != original.getY() && y + h == original.getBottom(),
  221150. x != original.getX() && x + w == original.getRight(),
  221151. y == original.getY() && y + h != original.getBottom(),
  221152. x == original.getX() && x + w != original.getRight());
  221153. r.origin.x = x;
  221154. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - y;
  221155. r.size.width = w;
  221156. r.size.height = h;
  221157. }
  221158. return r;
  221159. }
  221160. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  221161. {
  221162. // xxx
  221163. }
  221164. bool UIViewComponentPeer::isMinimised() const
  221165. {
  221166. return false;
  221167. }
  221168. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  221169. {
  221170. if (! isSharedWindow)
  221171. {
  221172. Rectangle r (lastNonFullscreenBounds);
  221173. setMinimised (false);
  221174. if (fullScreen != shouldBeFullScreen)
  221175. {
  221176. if (shouldBeFullScreen)
  221177. r = Desktop::getInstance().getMainMonitorArea();
  221178. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  221179. if (r != getComponent()->getBounds() && ! r.isEmpty())
  221180. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  221181. }
  221182. }
  221183. }
  221184. bool UIViewComponentPeer::isFullScreen() const
  221185. {
  221186. return fullScreen;
  221187. }
  221188. bool UIViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  221189. {
  221190. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  221191. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  221192. return false;
  221193. CGPoint p;
  221194. p.x = (float) x;
  221195. p.y = (float) y;
  221196. UIView* v = [view hitTest: p withEvent: nil];
  221197. if (trueIfInAChildWindow)
  221198. return v != nil;
  221199. return v == view;
  221200. }
  221201. const BorderSize UIViewComponentPeer::getFrameSize() const
  221202. {
  221203. BorderSize b;
  221204. if (! isSharedWindow)
  221205. {
  221206. CGRect v = [view convertRect: [view frame] toView: nil];
  221207. CGRect w = [window frame];
  221208. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  221209. b.setBottom ((int) v.origin.y);
  221210. b.setLeft ((int) v.origin.x);
  221211. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  221212. }
  221213. return b;
  221214. }
  221215. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  221216. {
  221217. if (! isSharedWindow)
  221218. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  221219. return true;
  221220. }
  221221. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  221222. {
  221223. if (isSharedWindow)
  221224. [[view superview] bringSubviewToFront: view];
  221225. if (window != 0 && component->isVisible())
  221226. [window makeKeyAndVisible];
  221227. }
  221228. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  221229. {
  221230. UIViewComponentPeer* o = (UIViewComponentPeer*) other;
  221231. if (isSharedWindow)
  221232. {
  221233. [[view superview] insertSubview: view belowSubview: o->view];
  221234. }
  221235. else
  221236. {
  221237. jassertfalse // don't know how to do this
  221238. }
  221239. }
  221240. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  221241. {
  221242. // to do..
  221243. }
  221244. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  221245. void UIViewComponentPeer::viewFocusGain()
  221246. {
  221247. if (currentlyFocusedPeer != this)
  221248. {
  221249. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  221250. currentlyFocusedPeer->handleFocusLoss();
  221251. currentlyFocusedPeer = this;
  221252. handleFocusGain();
  221253. }
  221254. }
  221255. void UIViewComponentPeer::viewFocusLoss()
  221256. {
  221257. if (currentlyFocusedPeer == this)
  221258. {
  221259. currentlyFocusedPeer = 0;
  221260. handleFocusLoss();
  221261. }
  221262. }
  221263. void juce_HandleProcessFocusChange()
  221264. {
  221265. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  221266. {
  221267. if (Process::isForegroundProcess())
  221268. {
  221269. currentlyFocusedPeer->handleFocusGain();
  221270. ComponentPeer::bringModalComponentToFront();
  221271. }
  221272. else
  221273. {
  221274. currentlyFocusedPeer->handleFocusLoss();
  221275. // turn kiosk mode off if we lose focus..
  221276. Desktop::getInstance().setKioskModeComponent (0);
  221277. }
  221278. }
  221279. }
  221280. bool UIViewComponentPeer::isFocused() const
  221281. {
  221282. return isSharedWindow ? this == currentlyFocusedPeer
  221283. : (window != 0 && [window isKeyWindow]);
  221284. }
  221285. void UIViewComponentPeer::grabFocus()
  221286. {
  221287. if (window != 0)
  221288. {
  221289. [window makeKeyWindow];
  221290. viewFocusGain();
  221291. }
  221292. }
  221293. void UIViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  221294. {
  221295. }
  221296. void UIViewComponentPeer::drawRect (CGRect r)
  221297. {
  221298. if (r.size.width < 1.0f || r.size.height < 1.0f)
  221299. return;
  221300. DBG (Rectangle (r.origin.x, r.origin.y, r.size.width, r.size.height).toString());
  221301. const float y = r.origin.y;//[view frame].size.height - (r.origin.y + r.size.height);
  221302. JuceUIImage temp ((int) (r.size.width + 0.5f),
  221303. (int) (r.size.height + 0.5f),
  221304. true);//! getComponent()->isOpaque());
  221305. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  221306. const int originX = -roundFloatToInt (r.origin.x);
  221307. const int originY = -roundFloatToInt (y);
  221308. context.setOrigin (originX, originY);
  221309. handlePaint (context);
  221310. //CGContextClipToRect (UIGraphicsGetCurrentContext(), r);
  221311. temp.draw (r.origin.x, r.origin.y);
  221312. }
  221313. bool UIViewComponentPeer::canBecomeKeyWindow()
  221314. {
  221315. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  221316. }
  221317. bool UIViewComponentPeer::windowShouldClose()
  221318. {
  221319. if (! isValidPeer (this))
  221320. return YES;
  221321. handleUserClosingWindow();
  221322. return NO;
  221323. }
  221324. void UIViewComponentPeer::redirectMovedOrResized()
  221325. {
  221326. handleMovedOrResized();
  221327. }
  221328. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221329. {
  221330. }
  221331. void UIViewComponentPeer::repaint (int x, int y, int w, int h)
  221332. {
  221333. [view setNeedsDisplayInRect:
  221334. CGRectMake ((float) x, (float) y,//([view frame].size.height - (y + h)),
  221335. (float) w, (float) h)];
  221336. }
  221337. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  221338. {
  221339. }
  221340. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221341. {
  221342. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  221343. }
  221344. static Image* UIImageToJuceImage (UIImage* image)
  221345. {
  221346. JuceUIImage juceIm ((int) [image size].width,
  221347. (int) [image size].height,
  221348. true);
  221349. juceIm.drawUIImage (image);
  221350. return juceIm.getJuceImage().createCopy();
  221351. }
  221352. Image* juce_createIconForFile (const File& file)
  221353. {
  221354. return 0;
  221355. }
  221356. const int KeyPress::spaceKey = ' ';
  221357. const int KeyPress::returnKey = 0x0d;
  221358. const int KeyPress::escapeKey = 0x1b;
  221359. const int KeyPress::backspaceKey = 0x7f;
  221360. const int KeyPress::leftKey = 0x1000;
  221361. const int KeyPress::rightKey = 0x1001;
  221362. const int KeyPress::upKey = 0x1002;
  221363. const int KeyPress::downKey = 0x1003;
  221364. const int KeyPress::pageUpKey = 0x1004;
  221365. const int KeyPress::pageDownKey = 0x1005;
  221366. const int KeyPress::endKey = 0x1006;
  221367. const int KeyPress::homeKey = 0x1007;
  221368. const int KeyPress::deleteKey = 0x1008;
  221369. const int KeyPress::insertKey = -1;
  221370. const int KeyPress::tabKey = 9;
  221371. const int KeyPress::F1Key = 0x2001;
  221372. const int KeyPress::F2Key = 0x2002;
  221373. const int KeyPress::F3Key = 0x2003;
  221374. const int KeyPress::F4Key = 0x2004;
  221375. const int KeyPress::F5Key = 0x2005;
  221376. const int KeyPress::F6Key = 0x2006;
  221377. const int KeyPress::F7Key = 0x2007;
  221378. const int KeyPress::F8Key = 0x2008;
  221379. const int KeyPress::F9Key = 0x2009;
  221380. const int KeyPress::F10Key = 0x200a;
  221381. const int KeyPress::F11Key = 0x200b;
  221382. const int KeyPress::F12Key = 0x200c;
  221383. const int KeyPress::F13Key = 0x200d;
  221384. const int KeyPress::F14Key = 0x200e;
  221385. const int KeyPress::F15Key = 0x200f;
  221386. const int KeyPress::F16Key = 0x2010;
  221387. const int KeyPress::numberPad0 = 0x30020;
  221388. const int KeyPress::numberPad1 = 0x30021;
  221389. const int KeyPress::numberPad2 = 0x30022;
  221390. const int KeyPress::numberPad3 = 0x30023;
  221391. const int KeyPress::numberPad4 = 0x30024;
  221392. const int KeyPress::numberPad5 = 0x30025;
  221393. const int KeyPress::numberPad6 = 0x30026;
  221394. const int KeyPress::numberPad7 = 0x30027;
  221395. const int KeyPress::numberPad8 = 0x30028;
  221396. const int KeyPress::numberPad9 = 0x30029;
  221397. const int KeyPress::numberPadAdd = 0x3002a;
  221398. const int KeyPress::numberPadSubtract = 0x3002b;
  221399. const int KeyPress::numberPadMultiply = 0x3002c;
  221400. const int KeyPress::numberPadDivide = 0x3002d;
  221401. const int KeyPress::numberPadSeparator = 0x3002e;
  221402. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  221403. const int KeyPress::numberPadEquals = 0x30030;
  221404. const int KeyPress::numberPadDelete = 0x30031;
  221405. const int KeyPress::playKey = 0x30000;
  221406. const int KeyPress::stopKey = 0x30001;
  221407. const int KeyPress::fastForwardKey = 0x30002;
  221408. const int KeyPress::rewindKey = 0x30003;
  221409. #endif
  221410. /********* End of inlined file: juce_iphone_UIViewComponentPeer.mm *********/
  221411. /********* Start of inlined file: juce_iphone_Fonts.mm *********/
  221412. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221413. // compiled on its own).
  221414. #if JUCE_INCLUDED_FILE
  221415. class FontHelper
  221416. {
  221417. UIFont* font;
  221418. public:
  221419. String name;
  221420. bool isBold, isItalic, needsItalicTransform;
  221421. float fontSize, totalSize, ascent;
  221422. int refCount;
  221423. FontHelper (const String& name_,
  221424. const bool bold_,
  221425. const bool italic_,
  221426. const float size_)
  221427. : font (0),
  221428. name (name_),
  221429. isBold (bold_),
  221430. isItalic (italic_),
  221431. needsItalicTransform (false),
  221432. fontSize (size_),
  221433. refCount (1)
  221434. {
  221435. //attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  221436. // forKey: NSLigatureAttributeName] retain];
  221437. font = [UIFont fontWithName: juceStringToNS (name_) size: size_];
  221438. if (italic_)
  221439. {
  221440. /* NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  221441. if (newFont == font)
  221442. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  221443. font = newFont;*/
  221444. }
  221445. // if (bold_)
  221446. // font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  221447. [font retain];
  221448. ascent = fabsf (font.ascender);
  221449. totalSize = ascent + fabsf (font.descender);
  221450. }
  221451. ~FontHelper()
  221452. {
  221453. [font release];
  221454. }
  221455. bool getPathAndKerning (const juce_wchar char1,
  221456. const juce_wchar char2,
  221457. Path* path,
  221458. float& kerning,
  221459. float* ascent,
  221460. float* descent)
  221461. {
  221462. const ScopedAutoReleasePool pool;
  221463. return false;
  221464. /* if (font == 0
  221465. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  221466. return false;
  221467. String chars;
  221468. chars << ' ' << char1 << char2;
  221469. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  221470. attributes: attributes] autorelease];
  221471. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  221472. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  221473. [layoutManager addTextContainer: textContainer];
  221474. [textStorage addLayoutManager: layoutManager];
  221475. [textStorage setFont: font];
  221476. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  221477. actualCharacterRange: 0].location;
  221478. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  221479. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  221480. kerning = p2.x - p1.x;
  221481. if (ascent != 0)
  221482. *ascent = this->ascent;
  221483. if (descent != 0)
  221484. *descent = fabsf ([font descender]);
  221485. if (path != 0)
  221486. {
  221487. NSBezierPath* bez = [NSBezierPath bezierPath];
  221488. [bez moveToPoint: NSMakePoint (0, 0)];
  221489. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  221490. inFont: font];
  221491. for (int i = 0; i < [bez elementCount]; ++i)
  221492. {
  221493. NSPoint p[3];
  221494. switch ([bez elementAtIndex: i associatedPoints: p])
  221495. {
  221496. case NSMoveToBezierPathElement:
  221497. path->startNewSubPath (p[0].x, -p[0].y);
  221498. break;
  221499. case NSLineToBezierPathElement:
  221500. path->lineTo (p[0].x, -p[0].y);
  221501. break;
  221502. case NSCurveToBezierPathElement:
  221503. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  221504. break;
  221505. case NSClosePathBezierPathElement:
  221506. path->closeSubPath();
  221507. break;
  221508. default:
  221509. jassertfalse
  221510. break;
  221511. }
  221512. }
  221513. if (needsItalicTransform)
  221514. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  221515. }
  221516. return kerning != 0;*/
  221517. }
  221518. juce_wchar getDefaultChar()
  221519. {
  221520. return 0;
  221521. }
  221522. };
  221523. class FontHelperCache : public Timer,
  221524. public DeletedAtShutdown
  221525. {
  221526. VoidArray cache;
  221527. public:
  221528. FontHelperCache()
  221529. {
  221530. }
  221531. ~FontHelperCache()
  221532. {
  221533. for (int i = cache.size(); --i >= 0;)
  221534. {
  221535. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221536. delete f;
  221537. }
  221538. clearSingletonInstance();
  221539. }
  221540. FontHelper* getFont (const String& name,
  221541. const bool bold,
  221542. const bool italic,
  221543. const float size = 1024)
  221544. {
  221545. for (int i = cache.size(); --i >= 0;)
  221546. {
  221547. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221548. if (f->name == name
  221549. && f->isBold == bold
  221550. && f->isItalic == italic
  221551. && f->fontSize == size)
  221552. {
  221553. f->refCount++;
  221554. return f;
  221555. }
  221556. }
  221557. FontHelper* const f = new FontHelper (name, bold, italic, size);
  221558. cache.add (f);
  221559. return f;
  221560. }
  221561. void releaseFont (FontHelper* f)
  221562. {
  221563. for (int i = cache.size(); --i >= 0;)
  221564. {
  221565. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  221566. if (f == f2)
  221567. {
  221568. f->refCount--;
  221569. if (f->refCount == 0)
  221570. startTimer (5000);
  221571. break;
  221572. }
  221573. }
  221574. }
  221575. void timerCallback()
  221576. {
  221577. stopTimer();
  221578. for (int i = cache.size(); --i >= 0;)
  221579. {
  221580. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221581. if (f->refCount == 0)
  221582. {
  221583. cache.remove (i);
  221584. delete f;
  221585. }
  221586. }
  221587. if (cache.size() == 0)
  221588. delete this;
  221589. }
  221590. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  221591. };
  221592. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  221593. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  221594. bool bold,
  221595. bool italic,
  221596. bool addAllGlyphsToFont) throw()
  221597. {
  221598. // This method is only safe to be called from the normal UI thread..
  221599. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  221600. FontHelper* const helper = FontHelperCache::getInstance()
  221601. ->getFont (fontName, bold, italic);
  221602. clear();
  221603. setAscent (helper->ascent / helper->totalSize);
  221604. setName (fontName);
  221605. setDefaultCharacter (helper->getDefaultChar());
  221606. setBold (bold);
  221607. setItalic (italic);
  221608. if (addAllGlyphsToFont)
  221609. {
  221610. //xxx
  221611. jassertfalse
  221612. }
  221613. FontHelperCache::getInstance()->releaseFont (helper);
  221614. }
  221615. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  221616. {
  221617. // This method is only safe to be called from the normal UI thread..
  221618. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  221619. if (character == 0)
  221620. return false;
  221621. FontHelper* const helper = FontHelperCache::getInstance()
  221622. ->getFont (getName(), isBold(), isItalic());
  221623. Path path;
  221624. float width;
  221625. bool foundOne = false;
  221626. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  221627. {
  221628. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  221629. 1.0f / helper->totalSize));
  221630. addGlyph (character, path, width / helper->totalSize);
  221631. for (int i = 0; i < glyphs.size(); ++i)
  221632. {
  221633. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  221634. float kerning;
  221635. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  221636. {
  221637. kerning = (kerning - width) / helper->totalSize;
  221638. if (kerning != 0)
  221639. addKerningPair (character, g->getCharacter(), kerning);
  221640. }
  221641. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  221642. {
  221643. kerning = kerning / helper->totalSize - g->width;
  221644. if (kerning != 0)
  221645. addKerningPair (g->getCharacter(), character, kerning);
  221646. }
  221647. }
  221648. foundOne = true;
  221649. }
  221650. FontHelperCache::getInstance()->releaseFont (helper);
  221651. return foundOne;
  221652. }
  221653. const StringArray Font::findAllTypefaceNames() throw()
  221654. {
  221655. StringArray names;
  221656. const ScopedAutoReleasePool pool;
  221657. NSArray* fonts = [UIFont familyNames];
  221658. for (unsigned int i = 0; i < [fonts count]; ++i)
  221659. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  221660. names.sort (true);
  221661. return names;
  221662. }
  221663. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  221664. {
  221665. defaultSans = "Lucida Grande";
  221666. defaultSerif = "Times New Roman";
  221667. defaultFixed = "Monaco";
  221668. }
  221669. #endif
  221670. /********* End of inlined file: juce_iphone_Fonts.mm *********/
  221671. /********* Start of inlined file: juce_iphone_MessageManager.mm *********/
  221672. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221673. // compiled on its own).
  221674. #if JUCE_INCLUDED_FILE
  221675. struct CallbackMessagePayload
  221676. {
  221677. MessageCallbackFunction* function;
  221678. void* parameter;
  221679. void* volatile result;
  221680. bool volatile hasBeenExecuted;
  221681. };
  221682. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  221683. for example having more than one juce plugin loaded into a host, then when a
  221684. method is called, the actual code that runs might actually be in a different module
  221685. than the one you expect... So any calls to library functions or statics that are
  221686. made inside obj-c methods will probably end up getting executed in a different DLL's
  221687. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  221688. To work around this insanity, I'm only allowing obj-c methods to make calls to
  221689. virtual methods of an object that's known to live inside the right module's space.
  221690. */
  221691. class AppDelegateRedirector
  221692. {
  221693. public:
  221694. AppDelegateRedirector() {}
  221695. virtual ~AppDelegateRedirector() {}
  221696. virtual BOOL openFile (const NSString* filename)
  221697. {
  221698. if (JUCEApplication::getInstance() != 0)
  221699. {
  221700. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  221701. return YES;
  221702. }
  221703. return NO;
  221704. }
  221705. virtual void openFiles (NSArray* filenames)
  221706. {
  221707. StringArray files;
  221708. for (unsigned int i = 0; i < [filenames count]; ++i)
  221709. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  221710. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  221711. {
  221712. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  221713. }
  221714. }
  221715. virtual void focusChanged()
  221716. {
  221717. juce_HandleProcessFocusChange();
  221718. }
  221719. virtual void deliverMessage (void* message)
  221720. {
  221721. // no need for an mm lock here - deliverMessage locks it
  221722. MessageManager::getInstance()->deliverMessage (message);
  221723. }
  221724. virtual void performCallback (CallbackMessagePayload* pl)
  221725. {
  221726. pl->result = (*pl->function) (pl->parameter);
  221727. pl->hasBeenExecuted = true;
  221728. }
  221729. virtual void deleteSelf()
  221730. {
  221731. delete this;
  221732. }
  221733. };
  221734. END_JUCE_NAMESPACE
  221735. using namespace JUCE_NAMESPACE;
  221736. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  221737. static int numPendingMessages = 0;
  221738. @interface JuceAppDelegate : NSObject <UIApplicationDelegate>
  221739. {
  221740. @private
  221741. id oldDelegate;
  221742. AppDelegateRedirector* redirector;
  221743. @public
  221744. bool flushingMessages;
  221745. }
  221746. - (JuceAppDelegate*) init;
  221747. - (void) dealloc;
  221748. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url;
  221749. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  221750. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  221751. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  221752. - (void) customEvent: (id) data;
  221753. - (void) performCallback: (id) info;
  221754. - (void) dummyMethod;
  221755. @end
  221756. @implementation JuceAppDelegate
  221757. - (JuceAppDelegate*) init
  221758. {
  221759. [super init];
  221760. redirector = new AppDelegateRedirector();
  221761. numPendingMessages = 0;
  221762. flushingMessages = false;
  221763. oldDelegate = [[UIApplication sharedApplication] delegate];
  221764. [[UIApplication sharedApplication] setDelegate: self];
  221765. return self;
  221766. }
  221767. - (void) dealloc
  221768. {
  221769. if (oldDelegate != 0)
  221770. [[UIApplication sharedApplication] setDelegate: oldDelegate];
  221771. redirector->deleteSelf();
  221772. [super dealloc];
  221773. }
  221774. - (BOOL) application: (UIApplication*) application handleOpenURL: (NSURL*) url
  221775. {
  221776. return redirector->openFile ([url absoluteString]);
  221777. }
  221778. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  221779. {
  221780. redirector->focusChanged();
  221781. }
  221782. - (void) applicationDidResignActive: (NSNotification*) aNotification
  221783. {
  221784. redirector->focusChanged();
  221785. }
  221786. - (void) applicationWillUnhide: (NSNotification*) aNotification
  221787. {
  221788. redirector->focusChanged();
  221789. }
  221790. - (void) customEvent: (id) n
  221791. {
  221792. atomicDecrement (numPendingMessages);
  221793. NSData* data = (NSData*) n;
  221794. void* message = 0;
  221795. [data getBytes: &message length: sizeof (message)];
  221796. [data release];
  221797. if (message != 0 && ! flushingMessages)
  221798. redirector->deliverMessage (message);
  221799. }
  221800. - (void) performCallback: (id) info
  221801. {
  221802. if ([info isKindOfClass: [NSData class]])
  221803. {
  221804. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  221805. if (pl != 0)
  221806. redirector->performCallback (pl);
  221807. }
  221808. else
  221809. {
  221810. jassertfalse // should never get here!
  221811. }
  221812. }
  221813. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  221814. @end
  221815. BEGIN_JUCE_NAMESPACE
  221816. static JuceAppDelegate* juceAppDelegate = 0;
  221817. void MessageManager::runDispatchLoop()
  221818. {
  221819. jassert (isThisTheMessageThread()); // must only be called by the message thread
  221820. runDispatchLoopUntil (-1);
  221821. }
  221822. static const int quitMessageId = 0xfffff321;
  221823. void MessageManager::stopDispatchLoop()
  221824. {
  221825. Message* const m = new Message (quitMessageId, 0, 0, 0);
  221826. m->messageRecipient = 0;
  221827. postMessageToQueue (m);
  221828. quitMessagePosted = true;
  221829. }
  221830. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  221831. {
  221832. const ScopedAutoReleasePool pool;
  221833. jassert (isThisTheMessageThread()); // must only be called by the message thread
  221834. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  221835. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  221836. while (! quitMessagePosted)
  221837. {
  221838. const ScopedAutoReleasePool pool;
  221839. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  221840. beforeDate: endDate];
  221841. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  221842. break;
  221843. }
  221844. return ! quitMessagePosted;
  221845. }
  221846. void MessageManager::doPlatformSpecificInitialisation()
  221847. {
  221848. if (juceAppDelegate == 0)
  221849. juceAppDelegate = [[JuceAppDelegate alloc] init];
  221850. }
  221851. void MessageManager::doPlatformSpecificShutdown()
  221852. {
  221853. if (juceAppDelegate != 0)
  221854. {
  221855. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  221856. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  221857. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  221858. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  221859. juceAppDelegate->flushingMessages = true;
  221860. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  221861. {
  221862. const ScopedAutoReleasePool pool;
  221863. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  221864. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  221865. }
  221866. [juceAppDelegate release];
  221867. juceAppDelegate = 0;
  221868. }
  221869. }
  221870. bool juce_postMessageToSystemQueue (void* message)
  221871. {
  221872. atomicIncrement (numPendingMessages);
  221873. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  221874. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  221875. waitUntilDone: NO];
  221876. return true;
  221877. }
  221878. void MessageManager::broadcastMessage (const String& value) throw()
  221879. {
  221880. }
  221881. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  221882. void* data)
  221883. {
  221884. if (isThisTheMessageThread())
  221885. {
  221886. return (*callback) (data);
  221887. }
  221888. else
  221889. {
  221890. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  221891. // deadlock because the message manager is blocked from running, so can never
  221892. // call your function..
  221893. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  221894. const ScopedAutoReleasePool pool;
  221895. CallbackMessagePayload cmp;
  221896. cmp.function = callback;
  221897. cmp.parameter = data;
  221898. cmp.result = 0;
  221899. cmp.hasBeenExecuted = false;
  221900. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  221901. withObject: [NSData dataWithBytesNoCopy: &cmp
  221902. length: sizeof (cmp)
  221903. freeWhenDone: NO]
  221904. waitUntilDone: YES];
  221905. return cmp.result;
  221906. }
  221907. }
  221908. #endif
  221909. /********* End of inlined file: juce_iphone_MessageManager.mm *********/
  221910. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  221911. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221912. // compiled on its own).
  221913. #if JUCE_INCLUDED_FILE
  221914. #if JUCE_MAC
  221915. END_JUCE_NAMESPACE
  221916. using namespace JUCE_NAMESPACE;
  221917. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  221918. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  221919. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  221920. #else
  221921. @interface JuceFileChooserDelegate : NSObject
  221922. #endif
  221923. {
  221924. StringArray* filters;
  221925. }
  221926. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  221927. - (void) dealloc;
  221928. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  221929. @end
  221930. @implementation JuceFileChooserDelegate
  221931. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  221932. {
  221933. [super init];
  221934. filters = filters_;
  221935. return self;
  221936. }
  221937. - (void) dealloc
  221938. {
  221939. delete filters;
  221940. [super dealloc];
  221941. }
  221942. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  221943. {
  221944. const String fname (nsStringToJuce (filename));
  221945. for (int i = filters->size(); --i >= 0;)
  221946. if (fname.matchesWildcard ((*filters)[i], true))
  221947. return true;
  221948. return File (fname).isDirectory();
  221949. }
  221950. @end
  221951. BEGIN_JUCE_NAMESPACE
  221952. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  221953. const String& title,
  221954. const File& currentFileOrDirectory,
  221955. const String& filter,
  221956. bool selectsDirectory,
  221957. bool isSaveDialogue,
  221958. bool warnAboutOverwritingExistingFiles,
  221959. bool selectMultipleFiles,
  221960. FilePreviewComponent* extraInfoComponent)
  221961. {
  221962. const ScopedAutoReleasePool pool;
  221963. StringArray* filters = new StringArray();
  221964. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  221965. filters->trim();
  221966. filters->removeEmptyStrings();
  221967. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  221968. [delegate autorelease];
  221969. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  221970. : [NSOpenPanel openPanel];
  221971. [panel setTitle: juceStringToNS (title)];
  221972. if (! isSaveDialogue)
  221973. {
  221974. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  221975. [openPanel setCanChooseDirectories: selectsDirectory];
  221976. [openPanel setCanChooseFiles: ! selectsDirectory];
  221977. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  221978. }
  221979. [panel setDelegate: delegate];
  221980. String directory, filename;
  221981. if (currentFileOrDirectory.isDirectory())
  221982. {
  221983. directory = currentFileOrDirectory.getFullPathName();
  221984. }
  221985. else
  221986. {
  221987. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  221988. filename = currentFileOrDirectory.getFileName();
  221989. }
  221990. if ([panel runModalForDirectory: juceStringToNS (directory)
  221991. file: juceStringToNS (filename)]
  221992. == NSOKButton)
  221993. {
  221994. if (isSaveDialogue)
  221995. {
  221996. results.add (new File (nsStringToJuce ([panel filename])));
  221997. }
  221998. else
  221999. {
  222000. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  222001. NSArray* urls = [openPanel filenames];
  222002. for (unsigned int i = 0; i < [urls count]; ++i)
  222003. {
  222004. NSString* f = [urls objectAtIndex: i];
  222005. results.add (new File (nsStringToJuce (f)));
  222006. }
  222007. }
  222008. }
  222009. [panel setDelegate: nil];
  222010. }
  222011. #else
  222012. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  222013. const String& title,
  222014. const File& currentFileOrDirectory,
  222015. const String& filter,
  222016. bool selectsDirectory,
  222017. bool isSaveDialogue,
  222018. bool warnAboutOverwritingExistingFiles,
  222019. bool selectMultipleFiles,
  222020. FilePreviewComponent* extraInfoComponent)
  222021. {
  222022. const ScopedAutoReleasePool pool;
  222023. jassertfalse //xxx to do
  222024. }
  222025. #endif
  222026. #endif
  222027. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  222028. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  222029. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222030. // compiled on its own).
  222031. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  222032. #if JUCE_MAC
  222033. END_JUCE_NAMESPACE
  222034. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  222035. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  222036. {
  222037. CriticalSection* contextLock;
  222038. bool needsUpdate;
  222039. }
  222040. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  222041. - (bool) makeActive;
  222042. - (void) makeInactive;
  222043. - (void) reshape;
  222044. @end
  222045. @implementation ThreadSafeNSOpenGLView
  222046. - (id) initWithFrame: (NSRect) frameRect
  222047. pixelFormat: (NSOpenGLPixelFormat*) format
  222048. {
  222049. contextLock = new CriticalSection();
  222050. self = [super initWithFrame: frameRect pixelFormat: format];
  222051. if (self != nil)
  222052. [[NSNotificationCenter defaultCenter] addObserver: self
  222053. selector: @selector (_surfaceNeedsUpdate:)
  222054. name: NSViewGlobalFrameDidChangeNotification
  222055. object: self];
  222056. return self;
  222057. }
  222058. - (void) dealloc
  222059. {
  222060. [[NSNotificationCenter defaultCenter] removeObserver: self];
  222061. delete contextLock;
  222062. [super dealloc];
  222063. }
  222064. - (bool) makeActive
  222065. {
  222066. const ScopedLock sl (*contextLock);
  222067. if ([self openGLContext] == 0)
  222068. return false;
  222069. [[self openGLContext] makeCurrentContext];
  222070. if (needsUpdate)
  222071. {
  222072. [super update];
  222073. needsUpdate = false;
  222074. }
  222075. return true;
  222076. }
  222077. - (void) makeInactive
  222078. {
  222079. const ScopedLock sl (*contextLock);
  222080. [NSOpenGLContext clearCurrentContext];
  222081. }
  222082. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  222083. {
  222084. const ScopedLock sl (*contextLock);
  222085. needsUpdate = true;
  222086. }
  222087. - (void) update
  222088. {
  222089. const ScopedLock sl (*contextLock);
  222090. needsUpdate = true;
  222091. }
  222092. - (void) reshape
  222093. {
  222094. const ScopedLock sl (*contextLock);
  222095. needsUpdate = true;
  222096. }
  222097. @end
  222098. BEGIN_JUCE_NAMESPACE
  222099. class WindowedGLContext : public OpenGLContext
  222100. {
  222101. public:
  222102. WindowedGLContext (Component* const component,
  222103. const OpenGLPixelFormat& pixelFormat_,
  222104. NSOpenGLContext* sharedContext)
  222105. : renderContext (0),
  222106. pixelFormat (pixelFormat_)
  222107. {
  222108. jassert (component != 0);
  222109. NSOpenGLPixelFormatAttribute attribs [64];
  222110. int n = 0;
  222111. attribs[n++] = NSOpenGLPFADoubleBuffer;
  222112. attribs[n++] = NSOpenGLPFAAccelerated;
  222113. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  222114. attribs[n++] = NSOpenGLPFAColorSize;
  222115. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  222116. pixelFormat.greenBits,
  222117. pixelFormat.blueBits);
  222118. attribs[n++] = NSOpenGLPFAAlphaSize;
  222119. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  222120. attribs[n++] = NSOpenGLPFADepthSize;
  222121. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  222122. attribs[n++] = NSOpenGLPFAStencilSize;
  222123. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  222124. attribs[n++] = NSOpenGLPFAAccumSize;
  222125. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  222126. pixelFormat.accumulationBufferGreenBits,
  222127. pixelFormat.accumulationBufferBlueBits,
  222128. pixelFormat.accumulationBufferAlphaBits);
  222129. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  222130. attribs[n++] = NSOpenGLPFASampleBuffers;
  222131. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  222132. attribs[n++] = NSOpenGLPFAClosestPolicy;
  222133. attribs[n++] = NSOpenGLPFANoRecovery;
  222134. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  222135. NSOpenGLPixelFormat* format
  222136. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  222137. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  222138. pixelFormat: format];
  222139. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  222140. shareContext: sharedContext] autorelease];
  222141. const GLint swapInterval = 1;
  222142. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  222143. [view setOpenGLContext: renderContext];
  222144. [renderContext setView: view];
  222145. [format release];
  222146. viewHolder = new NSViewComponentInternal (view, component);
  222147. }
  222148. ~WindowedGLContext()
  222149. {
  222150. makeInactive();
  222151. [renderContext setView: nil];
  222152. delete viewHolder;
  222153. }
  222154. bool makeActive() const throw()
  222155. {
  222156. jassert (renderContext != 0);
  222157. [view makeActive];
  222158. return isActive();
  222159. }
  222160. bool makeInactive() const throw()
  222161. {
  222162. [view makeInactive];
  222163. return true;
  222164. }
  222165. bool isActive() const throw()
  222166. {
  222167. return [NSOpenGLContext currentContext] == renderContext;
  222168. }
  222169. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  222170. void* getRawContext() const throw() { return renderContext; }
  222171. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  222172. {
  222173. }
  222174. void swapBuffers()
  222175. {
  222176. [renderContext flushBuffer];
  222177. }
  222178. bool setSwapInterval (const int numFramesPerSwap)
  222179. {
  222180. [renderContext setValues: (const GLint*) &numFramesPerSwap
  222181. forParameter: NSOpenGLCPSwapInterval];
  222182. return true;
  222183. }
  222184. int getSwapInterval() const
  222185. {
  222186. GLint numFrames = 0;
  222187. [renderContext getValues: &numFrames
  222188. forParameter: NSOpenGLCPSwapInterval];
  222189. return numFrames;
  222190. }
  222191. void repaint()
  222192. {
  222193. // we need to invalidate the juce view that holds this gl view, to make it
  222194. // cause a repaint callback
  222195. NSView* v = (NSView*) viewHolder->view;
  222196. NSRect r = [v frame];
  222197. // bit of a bodge here.. if we only invalidate the area of the gl component,
  222198. // it's completely covered by the NSOpenGLView, so the OS throws away the
  222199. // repaint message, thus never causing our paint() callback, and never repainting
  222200. // the comp. So invalidating just a little bit around the edge helps..
  222201. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  222202. }
  222203. void* getNativeWindowHandle() const { return viewHolder->view; }
  222204. juce_UseDebuggingNewOperator
  222205. NSOpenGLContext* renderContext;
  222206. ThreadSafeNSOpenGLView* view;
  222207. private:
  222208. OpenGLPixelFormat pixelFormat;
  222209. NSViewComponentInternal* viewHolder;
  222210. WindowedGLContext (const WindowedGLContext&);
  222211. const WindowedGLContext& operator= (const WindowedGLContext&);
  222212. };
  222213. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222214. const OpenGLPixelFormat& pixelFormat,
  222215. const OpenGLContext* const contextToShareWith)
  222216. {
  222217. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  222218. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  222219. if (c->renderContext == 0)
  222220. deleteAndZero (c);
  222221. return c;
  222222. }
  222223. void* OpenGLComponent::getNativeWindowHandle() const
  222224. {
  222225. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  222226. : 0;
  222227. }
  222228. void juce_glViewport (const int w, const int h)
  222229. {
  222230. glViewport (0, 0, w, h);
  222231. }
  222232. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  222233. OwnedArray <OpenGLPixelFormat>& results)
  222234. {
  222235. /* GLint attribs [64];
  222236. int n = 0;
  222237. attribs[n++] = AGL_RGBA;
  222238. attribs[n++] = AGL_DOUBLEBUFFER;
  222239. attribs[n++] = AGL_ACCELERATED;
  222240. attribs[n++] = AGL_NO_RECOVERY;
  222241. attribs[n++] = AGL_NONE;
  222242. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  222243. while (p != 0)
  222244. {
  222245. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  222246. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  222247. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  222248. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  222249. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  222250. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  222251. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  222252. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  222253. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  222254. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  222255. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  222256. results.add (pf);
  222257. p = aglNextPixelFormat (p);
  222258. }*/
  222259. //jassertfalse //xxx can't see how you do this in cocoa!
  222260. }
  222261. #else
  222262. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222263. const OpenGLPixelFormat& pixelFormat,
  222264. const OpenGLContext* const contextToShareWith)
  222265. {
  222266. return 0;
  222267. }
  222268. void juce_glViewport (const int w, const int h)
  222269. {
  222270. //glViewport (0, 0, w, h);
  222271. }
  222272. #endif
  222273. #endif
  222274. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  222275. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  222276. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222277. // compiled on its own).
  222278. #if JUCE_INCLUDED_FILE
  222279. #if JUCE_MAC
  222280. static NSImage* juceImageToNSImage (const Image& image)
  222281. {
  222282. const ScopedAutoReleasePool pool;
  222283. int lineStride, pixelStride;
  222284. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  222285. lineStride, pixelStride);
  222286. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  222287. initWithBitmapDataPlanes: NULL
  222288. pixelsWide: image.getWidth()
  222289. pixelsHigh: image.getHeight()
  222290. bitsPerSample: 8
  222291. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  222292. hasAlpha: image.hasAlphaChannel()
  222293. isPlanar: NO
  222294. colorSpaceName: NSCalibratedRGBColorSpace
  222295. bitmapFormat: (NSBitmapFormat) 0
  222296. bytesPerRow: lineStride
  222297. bitsPerPixel: pixelStride * 8];
  222298. unsigned char* newData = [rep bitmapData];
  222299. memcpy (newData, pixels, lineStride * image.getHeight());
  222300. image.releasePixelDataReadOnly (pixels);
  222301. NSImage* im = [[NSImage alloc] init];
  222302. [im addRepresentation: rep];
  222303. [rep release];
  222304. return im;
  222305. }
  222306. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  222307. {
  222308. NSImage* im = juceImageToNSImage (image);
  222309. NSCursor* c = [[NSCursor alloc] initWithImage: im
  222310. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  222311. [im release];
  222312. return (void*) c;
  222313. }
  222314. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  222315. {
  222316. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  222317. jassert (im != 0);
  222318. if (im == 0)
  222319. return 0;
  222320. void* const curs = juce_createMouseCursorFromImage (*im,
  222321. (int) (hx * im->getWidth()),
  222322. (int) (hy * im->getHeight()));
  222323. delete im;
  222324. return curs;
  222325. }
  222326. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  222327. {
  222328. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  222329. MemoryBlock mb;
  222330. if (f.getChildFile (filename).loadFileAsData (mb))
  222331. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  222332. return 0;
  222333. }
  222334. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  222335. {
  222336. const ScopedAutoReleasePool pool;
  222337. NSCursor* c = 0;
  222338. switch (type)
  222339. {
  222340. case MouseCursor::NormalCursor:
  222341. c = [NSCursor arrowCursor];
  222342. break;
  222343. case MouseCursor::NoCursor:
  222344. {
  222345. Image blank (Image::ARGB, 8, 8, true);
  222346. return juce_createMouseCursorFromImage (blank, 0, 0);
  222347. }
  222348. case MouseCursor::DraggingHandCursor:
  222349. c = [NSCursor openHandCursor];
  222350. break;
  222351. case MouseCursor::CopyingCursor:
  222352. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  222353. case MouseCursor::WaitCursor:
  222354. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  222355. break;
  222356. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  222357. case MouseCursor::IBeamCursor:
  222358. c = [NSCursor IBeamCursor];
  222359. break;
  222360. case MouseCursor::PointingHandCursor:
  222361. c = [NSCursor pointingHandCursor];
  222362. break;
  222363. case MouseCursor::LeftRightResizeCursor:
  222364. c = [NSCursor resizeLeftRightCursor];
  222365. break;
  222366. case MouseCursor::LeftEdgeResizeCursor:
  222367. c = [NSCursor resizeLeftCursor];
  222368. break;
  222369. case MouseCursor::RightEdgeResizeCursor:
  222370. c = [NSCursor resizeRightCursor];
  222371. break;
  222372. case MouseCursor::UpDownResizeCursor:
  222373. case MouseCursor::TopEdgeResizeCursor:
  222374. case MouseCursor::BottomEdgeResizeCursor:
  222375. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  222376. case MouseCursor::TopLeftCornerResizeCursor:
  222377. case MouseCursor::BottomRightCornerResizeCursor:
  222378. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  222379. case MouseCursor::TopRightCornerResizeCursor:
  222380. case MouseCursor::BottomLeftCornerResizeCursor:
  222381. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  222382. case MouseCursor::UpDownLeftRightResizeCursor:
  222383. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  222384. case MouseCursor::CrosshairCursor:
  222385. c = [NSCursor crosshairCursor];
  222386. break;
  222387. }
  222388. [c retain];
  222389. return (void*) c;
  222390. }
  222391. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  222392. {
  222393. NSCursor* c = (NSCursor*) cursorHandle;
  222394. [c release];
  222395. }
  222396. void MouseCursor::showInAllWindows() const throw()
  222397. {
  222398. showInWindow (0);
  222399. }
  222400. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  222401. {
  222402. NSCursor* const c = (NSCursor*) getHandle();
  222403. [c set];
  222404. }
  222405. #else
  222406. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw() { return 0; }
  222407. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw() { return 0; }
  222408. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw() {}
  222409. void MouseCursor::showInAllWindows() const throw() {}
  222410. void MouseCursor::showInWindow (ComponentPeer*) const throw() {}
  222411. #endif
  222412. #endif
  222413. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  222414. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  222415. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222416. // compiled on its own).
  222417. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222418. #if JUCE_MAC
  222419. END_JUCE_NAMESPACE
  222420. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  222421. @interface DownloadClickDetector : NSObject
  222422. {
  222423. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  222424. }
  222425. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  222426. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  222427. request: (NSURLRequest*) request
  222428. frame: (WebFrame*) frame
  222429. decisionListener: (id<WebPolicyDecisionListener>) listener;
  222430. @end
  222431. @implementation DownloadClickDetector
  222432. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  222433. {
  222434. [super init];
  222435. ownerComponent = ownerComponent_;
  222436. return self;
  222437. }
  222438. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  222439. request: (NSURLRequest*) request
  222440. frame: (WebFrame*) frame
  222441. decisionListener: (id <WebPolicyDecisionListener>) listener
  222442. {
  222443. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  222444. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  222445. [listener use];
  222446. else
  222447. [listener ignore];
  222448. }
  222449. @end
  222450. BEGIN_JUCE_NAMESPACE
  222451. class WebBrowserComponentInternal : public NSViewComponent
  222452. {
  222453. public:
  222454. WebBrowserComponentInternal (WebBrowserComponent* owner)
  222455. {
  222456. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  222457. frameName: @""
  222458. groupName: @""];
  222459. setView (webView);
  222460. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  222461. [webView setPolicyDelegate: clickListener];
  222462. }
  222463. ~WebBrowserComponentInternal()
  222464. {
  222465. [webView setPolicyDelegate: nil];
  222466. [clickListener release];
  222467. setView (0);
  222468. }
  222469. void goToURL (const String& url,
  222470. const StringArray* headers,
  222471. const MemoryBlock* postData)
  222472. {
  222473. NSMutableURLRequest* r
  222474. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  222475. cachePolicy: NSURLRequestUseProtocolCachePolicy
  222476. timeoutInterval: 30.0];
  222477. if (postData != 0 && postData->getSize() > 0)
  222478. {
  222479. [r setHTTPMethod: @"POST"];
  222480. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  222481. length: postData->getSize()]];
  222482. }
  222483. if (headers != 0)
  222484. {
  222485. for (int i = 0; i < headers->size(); ++i)
  222486. {
  222487. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  222488. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  222489. [r setValue: juceStringToNS (headerValue)
  222490. forHTTPHeaderField: juceStringToNS (headerName)];
  222491. }
  222492. }
  222493. stop();
  222494. [[webView mainFrame] loadRequest: r];
  222495. }
  222496. void goBack()
  222497. {
  222498. [webView goBack];
  222499. }
  222500. void goForward()
  222501. {
  222502. [webView goForward];
  222503. }
  222504. void stop()
  222505. {
  222506. [webView stopLoading: nil];
  222507. }
  222508. void refresh()
  222509. {
  222510. [webView reload: nil];
  222511. }
  222512. private:
  222513. WebView* webView;
  222514. DownloadClickDetector* clickListener;
  222515. };
  222516. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222517. : browser (0),
  222518. blankPageShown (false),
  222519. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222520. {
  222521. setOpaque (true);
  222522. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  222523. }
  222524. WebBrowserComponent::~WebBrowserComponent()
  222525. {
  222526. deleteAndZero (browser);
  222527. }
  222528. void WebBrowserComponent::goToURL (const String& url,
  222529. const StringArray* headers,
  222530. const MemoryBlock* postData)
  222531. {
  222532. lastURL = url;
  222533. lastHeaders.clear();
  222534. if (headers != 0)
  222535. lastHeaders = *headers;
  222536. lastPostData.setSize (0);
  222537. if (postData != 0)
  222538. lastPostData = *postData;
  222539. blankPageShown = false;
  222540. browser->goToURL (url, headers, postData);
  222541. }
  222542. void WebBrowserComponent::stop()
  222543. {
  222544. browser->stop();
  222545. }
  222546. void WebBrowserComponent::goBack()
  222547. {
  222548. lastURL = String::empty;
  222549. blankPageShown = false;
  222550. browser->goBack();
  222551. }
  222552. void WebBrowserComponent::goForward()
  222553. {
  222554. lastURL = String::empty;
  222555. browser->goForward();
  222556. }
  222557. void WebBrowserComponent::refresh()
  222558. {
  222559. browser->refresh();
  222560. }
  222561. void WebBrowserComponent::paint (Graphics& g)
  222562. {
  222563. }
  222564. void WebBrowserComponent::checkWindowAssociation()
  222565. {
  222566. if (isShowing())
  222567. {
  222568. if (blankPageShown)
  222569. goBack();
  222570. }
  222571. else
  222572. {
  222573. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  222574. {
  222575. // when the component becomes invisible, some stuff like flash
  222576. // carries on playing audio, so we need to force it onto a blank
  222577. // page to avoid this, (and send it back when it's made visible again).
  222578. blankPageShown = true;
  222579. browser->goToURL ("about:blank", 0, 0);
  222580. }
  222581. }
  222582. }
  222583. void WebBrowserComponent::reloadLastURL()
  222584. {
  222585. if (lastURL.isNotEmpty())
  222586. {
  222587. goToURL (lastURL, &lastHeaders, &lastPostData);
  222588. lastURL = String::empty;
  222589. }
  222590. }
  222591. void WebBrowserComponent::parentHierarchyChanged()
  222592. {
  222593. checkWindowAssociation();
  222594. }
  222595. void WebBrowserComponent::resized()
  222596. {
  222597. browser->setSize (getWidth(), getHeight());
  222598. }
  222599. void WebBrowserComponent::visibilityChanged()
  222600. {
  222601. checkWindowAssociation();
  222602. }
  222603. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222604. {
  222605. return true;
  222606. }
  222607. #else
  222608. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222609. {
  222610. }
  222611. WebBrowserComponent::~WebBrowserComponent()
  222612. {
  222613. }
  222614. void WebBrowserComponent::goToURL (const String& url,
  222615. const StringArray* headers,
  222616. const MemoryBlock* postData)
  222617. {
  222618. }
  222619. void WebBrowserComponent::stop()
  222620. {
  222621. }
  222622. void WebBrowserComponent::goBack()
  222623. {
  222624. }
  222625. void WebBrowserComponent::goForward()
  222626. {
  222627. }
  222628. void WebBrowserComponent::refresh()
  222629. {
  222630. }
  222631. void WebBrowserComponent::paint (Graphics& g)
  222632. {
  222633. }
  222634. void WebBrowserComponent::checkWindowAssociation()
  222635. {
  222636. }
  222637. void WebBrowserComponent::reloadLastURL()
  222638. {
  222639. }
  222640. void WebBrowserComponent::parentHierarchyChanged()
  222641. {
  222642. }
  222643. void WebBrowserComponent::resized()
  222644. {
  222645. }
  222646. void WebBrowserComponent::visibilityChanged()
  222647. {
  222648. }
  222649. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222650. {
  222651. return true;
  222652. }
  222653. #endif
  222654. #endif
  222655. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  222656. /********* Start of inlined file: juce_iphone_Audio.cpp *********/
  222657. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222658. // compiled on its own).
  222659. #if JUCE_INCLUDED_FILE
  222660. class IPhoneAudioIODevice : public AudioIODevice
  222661. {
  222662. public:
  222663. IPhoneAudioIODevice (const String& deviceName)
  222664. : AudioIODevice (deviceName, T("Audio")),
  222665. audioUnit (0),
  222666. isRunning (false),
  222667. callback (0),
  222668. actualBufferSize (0),
  222669. floatData (1, 2)
  222670. {
  222671. numInputChannels = 2;
  222672. numOutputChannels = 2;
  222673. preferredBufferSize = 0;
  222674. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  222675. updateDeviceInfo();
  222676. }
  222677. ~IPhoneAudioIODevice()
  222678. {
  222679. close();
  222680. }
  222681. const StringArray getOutputChannelNames()
  222682. {
  222683. StringArray s;
  222684. s.add ("Left");
  222685. s.add ("Right");
  222686. return s;
  222687. }
  222688. const StringArray getInputChannelNames()
  222689. {
  222690. StringArray s;
  222691. if (audioInputIsAvailable)
  222692. {
  222693. s.add ("Left");
  222694. s.add ("Right");
  222695. }
  222696. return s;
  222697. }
  222698. int getNumSampleRates()
  222699. {
  222700. return 1;
  222701. }
  222702. double getSampleRate (int index)
  222703. {
  222704. return sampleRate;
  222705. }
  222706. int getNumBufferSizesAvailable()
  222707. {
  222708. return 1;
  222709. }
  222710. int getBufferSizeSamples (int index)
  222711. {
  222712. return getDefaultBufferSize();
  222713. }
  222714. int getDefaultBufferSize()
  222715. {
  222716. return 1024;
  222717. }
  222718. const String open (const BitArray& inputChannels,
  222719. const BitArray& outputChannels,
  222720. double sampleRate,
  222721. int bufferSize)
  222722. {
  222723. close();
  222724. lastError = String::empty;
  222725. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  222726. // xxx set up channel mapping
  222727. activeOutputChans = outputChannels;
  222728. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  222729. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  222730. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  222731. activeInputChans = inputChannels;
  222732. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  222733. numInputChannels = activeInputChans.countNumberOfSetBits();
  222734. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  222735. AudioSessionSetActive (true);
  222736. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  222737. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  222738. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  222739. fixAudioRouteIfSetToReceiver();
  222740. updateDeviceInfo();
  222741. Float32 bufferDuration = preferredBufferSize / sampleRate;
  222742. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  222743. actualBufferSize = preferredBufferSize;
  222744. prepareFloatBuffers();
  222745. isRunning = true;
  222746. propertyChanged (0, 0, 0); // creates and starts the AU
  222747. lastError = audioUnit != 0 ? String::empty
  222748. : T("Couldn't open the device");
  222749. return lastError;
  222750. }
  222751. void close()
  222752. {
  222753. if (isRunning)
  222754. {
  222755. isRunning = false;
  222756. AudioSessionSetActive (false);
  222757. if (audioUnit != 0)
  222758. {
  222759. AudioComponentInstanceDispose (audioUnit);
  222760. audioUnit = 0;
  222761. }
  222762. }
  222763. }
  222764. bool isOpen()
  222765. {
  222766. return isRunning;
  222767. }
  222768. int getCurrentBufferSizeSamples()
  222769. {
  222770. return actualBufferSize;
  222771. }
  222772. double getCurrentSampleRate()
  222773. {
  222774. return sampleRate;
  222775. }
  222776. int getCurrentBitDepth()
  222777. {
  222778. return 16;
  222779. }
  222780. const BitArray getActiveOutputChannels() const
  222781. {
  222782. return activeOutputChans;
  222783. }
  222784. const BitArray getActiveInputChannels() const
  222785. {
  222786. return activeInputChans;
  222787. }
  222788. int getOutputLatencyInSamples()
  222789. {
  222790. return 0; //xxx
  222791. }
  222792. int getInputLatencyInSamples()
  222793. {
  222794. return 0; //xxx
  222795. }
  222796. void start (AudioIODeviceCallback* callback_)
  222797. {
  222798. if (isRunning && callback != callback_)
  222799. {
  222800. if (callback_ != 0)
  222801. callback_->audioDeviceAboutToStart (this);
  222802. callbackLock.enter();
  222803. callback = callback_;
  222804. callbackLock.exit();
  222805. }
  222806. }
  222807. void stop()
  222808. {
  222809. if (isRunning)
  222810. {
  222811. callbackLock.enter();
  222812. AudioIODeviceCallback* const lastCallback = callback;
  222813. callback = 0;
  222814. callbackLock.exit();
  222815. if (lastCallback != 0)
  222816. lastCallback->audioDeviceStopped();
  222817. }
  222818. }
  222819. bool isPlaying()
  222820. {
  222821. return isRunning && callback != 0;
  222822. }
  222823. const String getLastError()
  222824. {
  222825. return lastError;
  222826. }
  222827. private:
  222828. CriticalSection callbackLock;
  222829. Float64 sampleRate;
  222830. int numInputChannels, numOutputChannels;
  222831. int preferredBufferSize;
  222832. int actualBufferSize;
  222833. bool isRunning;
  222834. String lastError;
  222835. AudioStreamBasicDescription format;
  222836. AudioUnit audioUnit;
  222837. UInt32 audioInputIsAvailable;
  222838. AudioIODeviceCallback* callback;
  222839. BitArray activeOutputChans, activeInputChans;
  222840. AudioSampleBuffer floatData;
  222841. float* inputChannels[3];
  222842. float* outputChannels[3];
  222843. bool monoInputChannelNumber, monoOutputChannelNumber;
  222844. void prepareFloatBuffers()
  222845. {
  222846. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  222847. zerostruct (inputChannels);
  222848. zerostruct (outputChannels);
  222849. for (int i = 0; i < numInputChannels; ++i)
  222850. inputChannels[i] = floatData.getSampleData (i);
  222851. for (int i = 0; i < numOutputChannels; ++i)
  222852. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  222853. }
  222854. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  222855. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData) throw()
  222856. {
  222857. OSStatus err = noErr;
  222858. if (audioInputIsAvailable)
  222859. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  222860. const ScopedLock sl (callbackLock);
  222861. if (callback != 0)
  222862. {
  222863. if (audioInputIsAvailable && numInputChannels > 0)
  222864. {
  222865. short* shortData = (short*) ioData->mBuffers[0].mData;
  222866. if (numInputChannels >= 2)
  222867. {
  222868. for (UInt32 i = 0; i < inNumberFrames; ++i)
  222869. {
  222870. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  222871. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  222872. }
  222873. }
  222874. else
  222875. {
  222876. if (monoInputChannelNumber > 0)
  222877. ++shortData;
  222878. for (UInt32 i = 0; i < inNumberFrames; ++i)
  222879. {
  222880. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  222881. ++shortData;
  222882. }
  222883. }
  222884. }
  222885. else
  222886. {
  222887. zeromem (inputChannels[0], sizeof (float) * inNumberFrames);
  222888. zeromem (inputChannels[1], sizeof (float) * inNumberFrames);
  222889. }
  222890. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  222891. outputChannels, numOutputChannels,
  222892. (int) inNumberFrames);
  222893. short* shortData = (short*) ioData->mBuffers[0].mData;
  222894. int n = 0;
  222895. if (numOutputChannels >= 2)
  222896. {
  222897. for (UInt32 i = 0; i < inNumberFrames; ++i)
  222898. {
  222899. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  222900. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  222901. }
  222902. }
  222903. else if (numOutputChannels == 1)
  222904. {
  222905. for (UInt32 i = 0; i < inNumberFrames; ++i)
  222906. {
  222907. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  222908. shortData [n++] = s;
  222909. shortData [n++] = s;
  222910. }
  222911. }
  222912. else
  222913. {
  222914. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  222915. }
  222916. }
  222917. else
  222918. {
  222919. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  222920. }
  222921. return err;
  222922. }
  222923. void updateDeviceInfo() throw()
  222924. {
  222925. UInt32 size = sizeof (sampleRate);
  222926. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  222927. size = sizeof (audioInputIsAvailable);
  222928. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  222929. }
  222930. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  222931. {
  222932. if (! isRunning)
  222933. return;
  222934. if (inPropertyValue != 0)
  222935. {
  222936. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  222937. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  222938. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  222939. SInt32 routeChangeReason;
  222940. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  222941. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  222942. fixAudioRouteIfSetToReceiver();
  222943. }
  222944. updateDeviceInfo();
  222945. createAudioUnit();
  222946. AudioSessionSetActive (true);
  222947. if (audioUnit != 0)
  222948. {
  222949. UInt32 formatSize = sizeof (format);
  222950. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  222951. Float32 bufferDuration = preferredBufferSize / sampleRate;
  222952. UInt32 bufferDurationSize = sizeof (bufferDuration);
  222953. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  222954. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  222955. AudioOutputUnitStart (audioUnit);
  222956. }
  222957. }
  222958. void interruptionListener (UInt32 inInterruption)
  222959. {
  222960. if (inInterruption == kAudioSessionBeginInterruption)
  222961. {
  222962. isRunning = false;
  222963. AudioOutputUnitStop (audioUnit);
  222964. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  222965. "This could have been interrupted by another application or by unplugging a headset",
  222966. @"Resume",
  222967. @"Cancel"))
  222968. {
  222969. isRunning = true;
  222970. propertyChanged (0, 0, 0);
  222971. }
  222972. }
  222973. if (inInterruption == kAudioSessionEndInterruption)
  222974. {
  222975. isRunning = true;
  222976. AudioSessionSetActive (true);
  222977. AudioOutputUnitStart (audioUnit);
  222978. }
  222979. }
  222980. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  222981. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  222982. {
  222983. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  222984. }
  222985. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  222986. {
  222987. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  222988. }
  222989. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  222990. {
  222991. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  222992. }
  222993. void resetFormat (const int numChannels)
  222994. {
  222995. memset (&format, 0, sizeof (format));
  222996. format.mFormatID = kAudioFormatLinearPCM;
  222997. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  222998. format.mBitsPerChannel = 8 * sizeof (short);
  222999. format.mChannelsPerFrame = 2;
  223000. format.mFramesPerPacket = 1;
  223001. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  223002. }
  223003. bool createAudioUnit()
  223004. {
  223005. if (audioUnit != 0)
  223006. {
  223007. AudioComponentInstanceDispose (audioUnit);
  223008. audioUnit = 0;
  223009. }
  223010. resetFormat (2);
  223011. AudioComponentDescription desc;
  223012. desc.componentType = kAudioUnitType_Output;
  223013. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  223014. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  223015. desc.componentFlags = 0;
  223016. desc.componentFlagsMask = 0;
  223017. AudioComponent comp = AudioComponentFindNext (0, &desc);
  223018. AudioComponentInstanceNew (comp, &audioUnit);
  223019. if (audioUnit == 0)
  223020. return false;
  223021. const UInt32 one = 1;
  223022. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  223023. AudioChannelLayout layout;
  223024. layout.mChannelBitmap = 0;
  223025. layout.mNumberChannelDescriptions = 0;
  223026. layout.mChannelLayoutTag = kAudioChannelLayoutTag_StereoHeadphones;
  223027. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  223028. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  223029. AURenderCallbackStruct inputProc;
  223030. inputProc.inputProc = processStatic;
  223031. inputProc.inputProcRefCon = this;
  223032. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  223033. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  223034. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  223035. AudioUnitInitialize (audioUnit);
  223036. return true;
  223037. }
  223038. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  223039. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  223040. static void fixAudioRouteIfSetToReceiver() throw()
  223041. {
  223042. CFStringRef audioRoute = 0;
  223043. UInt32 propertySize = sizeof (audioRoute);
  223044. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  223045. {
  223046. NSString* route = (NSString*) audioRoute;
  223047. //printf ("audio route: %s\n", [route cString]);
  223048. if ([route hasPrefix: @"Receiver"])
  223049. {
  223050. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  223051. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  223052. }
  223053. CFRelease (audioRoute);
  223054. }
  223055. }
  223056. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  223057. const IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  223058. };
  223059. class IPhoneAudioIODeviceType : public AudioIODeviceType
  223060. {
  223061. public:
  223062. IPhoneAudioIODeviceType()
  223063. : AudioIODeviceType (T("iPhone Audio"))
  223064. {
  223065. }
  223066. ~IPhoneAudioIODeviceType()
  223067. {
  223068. }
  223069. void scanForDevices()
  223070. {
  223071. }
  223072. const StringArray getDeviceNames (const bool wantInputNames) const
  223073. {
  223074. StringArray s;
  223075. s.add (wantInputNames ? "Microphone" : "Speaker");
  223076. return s;
  223077. }
  223078. int getDefaultDeviceIndex (const bool forInput) const
  223079. {
  223080. return 0;
  223081. }
  223082. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  223083. {
  223084. return device != 0 ? 0 : -1;
  223085. }
  223086. bool hasSeparateInputsAndOutputs() const { return false; }
  223087. AudioIODevice* createDevice (const String& outputDeviceName,
  223088. const String& inputDeviceName)
  223089. {
  223090. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  223091. {
  223092. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  223093. : inputDeviceName);
  223094. }
  223095. return 0;
  223096. }
  223097. juce_UseDebuggingNewOperator
  223098. private:
  223099. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  223100. const IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  223101. };
  223102. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  223103. {
  223104. return new IPhoneAudioIODeviceType();
  223105. }
  223106. #endif
  223107. /********* End of inlined file: juce_iphone_Audio.cpp *********/
  223108. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  223109. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223110. // compiled on its own).
  223111. #if JUCE_INCLUDED_FILE
  223112. #if JUCE_MAC
  223113. #undef log
  223114. #define log(a) Logger::writeToLog(a)
  223115. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  223116. {
  223117. if (err == noErr)
  223118. return true;
  223119. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  223120. jassertfalse
  223121. return false;
  223122. }
  223123. #undef OK
  223124. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  223125. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  223126. {
  223127. String result;
  223128. CFStringRef str = 0;
  223129. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  223130. if (str != 0)
  223131. {
  223132. result = PlatformUtilities::cfStringToJuceString (str);
  223133. CFRelease (str);
  223134. str = 0;
  223135. }
  223136. MIDIEntityRef entity = 0;
  223137. MIDIEndpointGetEntity (endpoint, &entity);
  223138. if (entity == 0)
  223139. return result; // probably virtual
  223140. if (result.isEmpty())
  223141. {
  223142. // endpoint name has zero length - try the entity
  223143. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  223144. if (str != 0)
  223145. {
  223146. result += PlatformUtilities::cfStringToJuceString (str);
  223147. CFRelease (str);
  223148. str = 0;
  223149. }
  223150. }
  223151. // now consider the device's name
  223152. MIDIDeviceRef device = 0;
  223153. MIDIEntityGetDevice (entity, &device);
  223154. if (device == 0)
  223155. return result;
  223156. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  223157. if (str != 0)
  223158. {
  223159. const String s (PlatformUtilities::cfStringToJuceString (str));
  223160. CFRelease (str);
  223161. // if an external device has only one entity, throw away
  223162. // the endpoint name and just use the device name
  223163. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  223164. {
  223165. result = s;
  223166. }
  223167. else if (! result.startsWithIgnoreCase (s))
  223168. {
  223169. // prepend the device name to the entity name
  223170. result = (s + T(" ") + result).trimEnd();
  223171. }
  223172. }
  223173. return result;
  223174. }
  223175. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  223176. {
  223177. String result;
  223178. // Does the endpoint have connections?
  223179. CFDataRef connections = 0;
  223180. int numConnections = 0;
  223181. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  223182. if (connections != 0)
  223183. {
  223184. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  223185. if (numConnections > 0)
  223186. {
  223187. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  223188. for (int i = 0; i < numConnections; ++i, ++pid)
  223189. {
  223190. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  223191. MIDIObjectRef connObject;
  223192. MIDIObjectType connObjectType;
  223193. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  223194. if (err == noErr)
  223195. {
  223196. String s;
  223197. if (connObjectType == kMIDIObjectType_ExternalSource
  223198. || connObjectType == kMIDIObjectType_ExternalDestination)
  223199. {
  223200. // Connected to an external device's endpoint (10.3 and later).
  223201. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  223202. }
  223203. else
  223204. {
  223205. // Connected to an external device (10.2) (or something else, catch-all)
  223206. CFStringRef str = 0;
  223207. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  223208. if (str != 0)
  223209. {
  223210. s = PlatformUtilities::cfStringToJuceString (str);
  223211. CFRelease (str);
  223212. }
  223213. }
  223214. if (s.isNotEmpty())
  223215. {
  223216. if (result.isNotEmpty())
  223217. result += (", ");
  223218. result += s;
  223219. }
  223220. }
  223221. }
  223222. }
  223223. CFRelease (connections);
  223224. }
  223225. if (result.isNotEmpty())
  223226. return result;
  223227. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  223228. return getEndpointName (endpoint, false);
  223229. }
  223230. const StringArray MidiOutput::getDevices()
  223231. {
  223232. StringArray s;
  223233. const ItemCount num = MIDIGetNumberOfDestinations();
  223234. for (ItemCount i = 0; i < num; ++i)
  223235. {
  223236. MIDIEndpointRef dest = MIDIGetDestination (i);
  223237. if (dest != 0)
  223238. {
  223239. String name (getConnectedEndpointName (dest));
  223240. if (name.isEmpty())
  223241. name = "<error>";
  223242. s.add (name);
  223243. }
  223244. else
  223245. {
  223246. s.add ("<error>");
  223247. }
  223248. }
  223249. return s;
  223250. }
  223251. int MidiOutput::getDefaultDeviceIndex()
  223252. {
  223253. return 0;
  223254. }
  223255. static MIDIClientRef globalMidiClient;
  223256. static bool hasGlobalClientBeenCreated = false;
  223257. static bool makeSureClientExists()
  223258. {
  223259. if (! hasGlobalClientBeenCreated)
  223260. {
  223261. String name (T("JUCE"));
  223262. if (JUCEApplication::getInstance() != 0)
  223263. name = JUCEApplication::getInstance()->getApplicationName();
  223264. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  223265. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  223266. CFRelease (appName);
  223267. }
  223268. return hasGlobalClientBeenCreated;
  223269. }
  223270. struct MidiPortAndEndpoint
  223271. {
  223272. MIDIPortRef port;
  223273. MIDIEndpointRef endPoint;
  223274. };
  223275. MidiOutput* MidiOutput::openDevice (int index)
  223276. {
  223277. MidiOutput* mo = 0;
  223278. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  223279. {
  223280. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  223281. CFStringRef pname;
  223282. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  223283. {
  223284. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  223285. if (makeSureClientExists())
  223286. {
  223287. MIDIPortRef port;
  223288. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  223289. {
  223290. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  223291. mpe->port = port;
  223292. mpe->endPoint = endPoint;
  223293. mo = new MidiOutput();
  223294. mo->internal = (void*)mpe;
  223295. }
  223296. }
  223297. CFRelease (pname);
  223298. }
  223299. }
  223300. return mo;
  223301. }
  223302. MidiOutput::~MidiOutput()
  223303. {
  223304. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  223305. MIDIPortDispose (mpe->port);
  223306. delete mpe;
  223307. }
  223308. void MidiOutput::reset()
  223309. {
  223310. }
  223311. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223312. {
  223313. return false;
  223314. }
  223315. void MidiOutput::setVolume (float leftVol, float rightVol)
  223316. {
  223317. }
  223318. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223319. {
  223320. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  223321. if (message.isSysEx())
  223322. {
  223323. const int maxPacketSize = 256;
  223324. int pos = 0, bytesLeft = message.getRawDataSize();
  223325. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  223326. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  223327. packets->numPackets = numPackets;
  223328. MIDIPacket* p = packets->packet;
  223329. for (int i = 0; i < numPackets; ++i)
  223330. {
  223331. p->timeStamp = 0;
  223332. p->length = jmin (maxPacketSize, bytesLeft);
  223333. memcpy (p->data, message.getRawData() + pos, p->length);
  223334. pos += p->length;
  223335. bytesLeft -= p->length;
  223336. p = MIDIPacketNext (p);
  223337. }
  223338. MIDISend (mpe->port, mpe->endPoint, packets);
  223339. juce_free (packets);
  223340. }
  223341. else
  223342. {
  223343. MIDIPacketList packets;
  223344. packets.numPackets = 1;
  223345. packets.packet[0].timeStamp = 0;
  223346. packets.packet[0].length = message.getRawDataSize();
  223347. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  223348. MIDISend (mpe->port, mpe->endPoint, &packets);
  223349. }
  223350. }
  223351. const StringArray MidiInput::getDevices()
  223352. {
  223353. StringArray s;
  223354. const ItemCount num = MIDIGetNumberOfSources();
  223355. for (ItemCount i = 0; i < num; ++i)
  223356. {
  223357. MIDIEndpointRef source = MIDIGetSource (i);
  223358. if (source != 0)
  223359. {
  223360. String name (getConnectedEndpointName (source));
  223361. if (name.isEmpty())
  223362. name = "<error>";
  223363. s.add (name);
  223364. }
  223365. else
  223366. {
  223367. s.add ("<error>");
  223368. }
  223369. }
  223370. return s;
  223371. }
  223372. int MidiInput::getDefaultDeviceIndex()
  223373. {
  223374. return 0;
  223375. }
  223376. struct MidiPortAndCallback
  223377. {
  223378. MidiInput* input;
  223379. MIDIPortRef port;
  223380. MIDIEndpointRef endPoint;
  223381. MidiInputCallback* callback;
  223382. MemoryBlock pendingData;
  223383. int pendingBytes;
  223384. double pendingDataTime;
  223385. bool active;
  223386. };
  223387. static CriticalSection callbackLock;
  223388. static VoidArray activeCallbacks;
  223389. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  223390. {
  223391. if (*d == 0xf0)
  223392. {
  223393. mpe->pendingBytes = 0;
  223394. mpe->pendingDataTime = time;
  223395. }
  223396. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  223397. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  223398. uint8* dest = totalMessage + mpe->pendingBytes;
  223399. while (size > 0)
  223400. {
  223401. if (mpe->pendingBytes > 0 && *d >= 0x80)
  223402. {
  223403. if (*d >= 0xfa || *d == 0xf8)
  223404. {
  223405. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  223406. ++d;
  223407. --size;
  223408. }
  223409. else
  223410. {
  223411. if (*d == 0xf7)
  223412. {
  223413. *dest++ = *d++;
  223414. mpe->pendingBytes++;
  223415. --size;
  223416. }
  223417. break;
  223418. }
  223419. }
  223420. else
  223421. {
  223422. *dest++ = *d++;
  223423. mpe->pendingBytes++;
  223424. --size;
  223425. }
  223426. }
  223427. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  223428. {
  223429. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  223430. mpe->pendingBytes,
  223431. mpe->pendingDataTime));
  223432. mpe->pendingBytes = 0;
  223433. }
  223434. else
  223435. {
  223436. mpe->callback->handlePartialSysexMessage (mpe->input,
  223437. totalMessage,
  223438. mpe->pendingBytes,
  223439. mpe->pendingDataTime);
  223440. }
  223441. }
  223442. static void midiInputProc (const MIDIPacketList* pktlist,
  223443. void* readProcRefCon,
  223444. void* srcConnRefCon)
  223445. {
  223446. double time = Time::getMillisecondCounterHiRes() * 0.001;
  223447. const double originalTime = time;
  223448. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  223449. const ScopedLock sl (callbackLock);
  223450. if (activeCallbacks.contains (mpe) && mpe->active)
  223451. {
  223452. const MIDIPacket* packet = &pktlist->packet[0];
  223453. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  223454. {
  223455. const uint8* d = (const uint8*) (packet->data);
  223456. int size = packet->length;
  223457. while (size > 0)
  223458. {
  223459. time = originalTime;
  223460. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  223461. {
  223462. processSysex (mpe, d, size, time);
  223463. }
  223464. else
  223465. {
  223466. int used = 0;
  223467. const MidiMessage m (d, size, used, 0, time);
  223468. if (used <= 0)
  223469. {
  223470. jassertfalse // malformed midi message
  223471. break;
  223472. }
  223473. else
  223474. {
  223475. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  223476. }
  223477. size -= used;
  223478. d += used;
  223479. }
  223480. }
  223481. packet = MIDIPacketNext (packet);
  223482. }
  223483. }
  223484. }
  223485. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  223486. {
  223487. MidiInput* mi = 0;
  223488. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  223489. {
  223490. MIDIEndpointRef endPoint = MIDIGetSource (index);
  223491. if (endPoint != 0)
  223492. {
  223493. CFStringRef pname;
  223494. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  223495. {
  223496. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  223497. if (makeSureClientExists())
  223498. {
  223499. MIDIPortRef port;
  223500. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  223501. mpe->active = false;
  223502. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  223503. {
  223504. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  223505. {
  223506. mpe->port = port;
  223507. mpe->endPoint = endPoint;
  223508. mpe->callback = callback;
  223509. mpe->pendingBytes = 0;
  223510. mpe->pendingData.ensureSize (128);
  223511. mi = new MidiInput (getDevices() [index]);
  223512. mpe->input = mi;
  223513. mi->internal = (void*) mpe;
  223514. const ScopedLock sl (callbackLock);
  223515. activeCallbacks.add (mpe);
  223516. }
  223517. else
  223518. {
  223519. OK (MIDIPortDispose (port));
  223520. delete mpe;
  223521. }
  223522. }
  223523. else
  223524. {
  223525. delete mpe;
  223526. }
  223527. }
  223528. }
  223529. CFRelease (pname);
  223530. }
  223531. }
  223532. return mi;
  223533. }
  223534. MidiInput::MidiInput (const String& name_)
  223535. : name (name_)
  223536. {
  223537. }
  223538. MidiInput::~MidiInput()
  223539. {
  223540. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  223541. mpe->active = false;
  223542. callbackLock.enter();
  223543. activeCallbacks.removeValue (mpe);
  223544. callbackLock.exit();
  223545. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  223546. OK (MIDIPortDispose (mpe->port));
  223547. delete mpe;
  223548. }
  223549. void MidiInput::start()
  223550. {
  223551. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  223552. const ScopedLock sl (callbackLock);
  223553. mpe->active = true;
  223554. }
  223555. void MidiInput::stop()
  223556. {
  223557. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  223558. const ScopedLock sl (callbackLock);
  223559. mpe->active = false;
  223560. }
  223561. #undef log
  223562. #else
  223563. MidiOutput::~MidiOutput()
  223564. {
  223565. }
  223566. void MidiOutput::reset()
  223567. {
  223568. }
  223569. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223570. {
  223571. return false;
  223572. }
  223573. void MidiOutput::setVolume (float leftVol, float rightVol)
  223574. {
  223575. }
  223576. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223577. {
  223578. }
  223579. const StringArray MidiOutput::getDevices()
  223580. {
  223581. return StringArray();
  223582. }
  223583. MidiOutput* MidiOutput::openDevice (int index)
  223584. {
  223585. return 0;
  223586. }
  223587. const StringArray MidiInput::getDevices()
  223588. {
  223589. return StringArray();
  223590. }
  223591. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  223592. {
  223593. return 0;
  223594. }
  223595. #endif
  223596. #endif
  223597. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  223598. #else
  223599. /********* Start of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  223600. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223601. // compiled on its own).
  223602. #if JUCE_INCLUDED_FILE
  223603. class NSViewComponentPeer;
  223604. END_JUCE_NAMESPACE
  223605. #define JuceNSView MakeObjCClassName(JuceNSView)
  223606. @interface JuceNSView : NSView
  223607. {
  223608. @public
  223609. NSViewComponentPeer* owner;
  223610. NSNotificationCenter* notificationCenter;
  223611. }
  223612. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  223613. - (void) dealloc;
  223614. - (BOOL) isOpaque;
  223615. - (void) drawRect: (NSRect) r;
  223616. - (void) mouseDown: (NSEvent*) ev;
  223617. - (void) asyncMouseDown: (NSEvent*) ev;
  223618. - (void) mouseUp: (NSEvent*) ev;
  223619. - (void) asyncMouseUp: (NSEvent*) ev;
  223620. - (void) mouseDragged: (NSEvent*) ev;
  223621. - (void) mouseMoved: (NSEvent*) ev;
  223622. - (void) mouseEntered: (NSEvent*) ev;
  223623. - (void) mouseExited: (NSEvent*) ev;
  223624. - (void) rightMouseDown: (NSEvent*) ev;
  223625. - (void) rightMouseDragged: (NSEvent*) ev;
  223626. - (void) rightMouseUp: (NSEvent*) ev;
  223627. - (void) otherMouseDown: (NSEvent*) ev;
  223628. - (void) otherMouseDragged: (NSEvent*) ev;
  223629. - (void) otherMouseUp: (NSEvent*) ev;
  223630. - (void) scrollWheel: (NSEvent*) ev;
  223631. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  223632. - (void) frameChanged: (NSNotification*) n;
  223633. - (void) keyDown: (NSEvent*) ev;
  223634. - (void) keyUp: (NSEvent*) ev;
  223635. - (void) flagsChanged: (NSEvent*) ev;
  223636. #if MACOS_10_4_OR_EARLIER
  223637. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  223638. #endif
  223639. - (BOOL) becomeFirstResponder;
  223640. - (BOOL) resignFirstResponder;
  223641. - (BOOL) acceptsFirstResponder;
  223642. - (void) asyncRepaint: (id) rect;
  223643. - (NSArray*) getSupportedDragTypes;
  223644. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  223645. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  223646. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  223647. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  223648. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  223649. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  223650. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  223651. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  223652. @end
  223653. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  223654. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223655. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  223656. #else
  223657. @interface JuceNSWindow : NSWindow
  223658. #endif
  223659. {
  223660. @private
  223661. NSViewComponentPeer* owner;
  223662. bool isZooming;
  223663. }
  223664. - (void) setOwner: (NSViewComponentPeer*) owner;
  223665. - (BOOL) canBecomeKeyWindow;
  223666. - (void) becomeKeyWindow;
  223667. - (BOOL) windowShouldClose: (id) window;
  223668. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  223669. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  223670. - (void) zoom: (id) sender;
  223671. @end
  223672. BEGIN_JUCE_NAMESPACE
  223673. class NSViewComponentPeer : public ComponentPeer
  223674. {
  223675. public:
  223676. NSViewComponentPeer (Component* const component,
  223677. const int windowStyleFlags,
  223678. NSView* viewToAttachTo);
  223679. ~NSViewComponentPeer();
  223680. void* getNativeHandle() const;
  223681. void setVisible (bool shouldBeVisible);
  223682. void setTitle (const String& title);
  223683. void setPosition (int x, int y);
  223684. void setSize (int w, int h);
  223685. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  223686. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  223687. void getBounds (int& x, int& y, int& w, int& h) const;
  223688. int getScreenX() const;
  223689. int getScreenY() const;
  223690. void relativePositionToGlobal (int& x, int& y);
  223691. void globalPositionToRelative (int& x, int& y);
  223692. void setMinimised (bool shouldBeMinimised);
  223693. bool isMinimised() const;
  223694. void setFullScreen (bool shouldBeFullScreen);
  223695. bool isFullScreen() const;
  223696. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  223697. const BorderSize getFrameSize() const;
  223698. bool setAlwaysOnTop (bool alwaysOnTop);
  223699. void toFront (bool makeActiveWindow);
  223700. void toBehind (ComponentPeer* other);
  223701. void setIcon (const Image& newIcon);
  223702. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  223703. for example having more than one juce plugin loaded into a host, then when a
  223704. method is called, the actual code that runs might actually be in a different module
  223705. than the one you expect... So any calls to library functions or statics that are
  223706. made inside obj-c methods will probably end up getting executed in a different DLL's
  223707. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  223708. To work around this insanity, I'm only allowing obj-c methods to make calls to
  223709. virtual methods of an object that's known to live inside the right module's space.
  223710. */
  223711. virtual void redirectMouseDown (NSEvent* ev);
  223712. virtual void redirectMouseUp (NSEvent* ev);
  223713. virtual void redirectMouseDrag (NSEvent* ev);
  223714. virtual void redirectMouseMove (NSEvent* ev);
  223715. virtual void redirectMouseEnter (NSEvent* ev);
  223716. virtual void redirectMouseExit (NSEvent* ev);
  223717. virtual void redirectMouseWheel (NSEvent* ev);
  223718. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  223719. virtual bool redirectKeyDown (NSEvent* ev);
  223720. virtual bool redirectKeyUp (NSEvent* ev);
  223721. virtual void redirectModKeyChange (NSEvent* ev);
  223722. #if MACOS_10_4_OR_EARLIER
  223723. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  223724. #endif
  223725. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  223726. virtual bool isOpaque();
  223727. virtual void drawRect (NSRect r);
  223728. virtual bool canBecomeKeyWindow();
  223729. virtual bool windowShouldClose();
  223730. virtual void redirectMovedOrResized();
  223731. virtual NSRect constrainRect (NSRect r);
  223732. static void showArrowCursorIfNeeded();
  223733. virtual void viewFocusGain();
  223734. virtual void viewFocusLoss();
  223735. bool isFocused() const;
  223736. void grabFocus();
  223737. void textInputRequired (int x, int y);
  223738. void repaint (int x, int y, int w, int h);
  223739. void performAnyPendingRepaintsNow();
  223740. juce_UseDebuggingNewOperator
  223741. NSWindow* window;
  223742. JuceNSView* view;
  223743. bool isSharedWindow, fullScreen, insideDrawRect;
  223744. };
  223745. END_JUCE_NAMESPACE
  223746. @implementation JuceNSView
  223747. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  223748. withFrame: (NSRect) frame
  223749. {
  223750. [super initWithFrame: frame];
  223751. owner = owner_;
  223752. notificationCenter = [NSNotificationCenter defaultCenter];
  223753. [notificationCenter addObserver: self
  223754. selector: @selector (frameChanged:)
  223755. name: NSViewFrameDidChangeNotification
  223756. object: self];
  223757. if (! owner_->isSharedWindow)
  223758. {
  223759. [notificationCenter addObserver: self
  223760. selector: @selector (frameChanged:)
  223761. name: NSWindowDidMoveNotification
  223762. object: owner_->window];
  223763. }
  223764. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  223765. return self;
  223766. }
  223767. - (void) dealloc
  223768. {
  223769. [notificationCenter removeObserver: self];
  223770. [super dealloc];
  223771. }
  223772. - (void) drawRect: (NSRect) r
  223773. {
  223774. if (owner != 0)
  223775. owner->drawRect (r);
  223776. }
  223777. - (BOOL) isOpaque
  223778. {
  223779. return owner == 0 || owner->isOpaque();
  223780. }
  223781. - (void) mouseDown: (NSEvent*) ev
  223782. {
  223783. // In some host situations, the host will stop modal loops from working
  223784. // correctly if they're called from a mouse event, so we'll trigger
  223785. // the event asynchronously..
  223786. if (JUCEApplication::getInstance() == 0)
  223787. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  223788. withObject: ev
  223789. waitUntilDone: NO];
  223790. else
  223791. [self asyncMouseDown: ev];
  223792. }
  223793. - (void) asyncMouseDown: (NSEvent*) ev
  223794. {
  223795. if (owner != 0)
  223796. owner->redirectMouseDown (ev);
  223797. }
  223798. - (void) mouseUp: (NSEvent*) ev
  223799. {
  223800. // In some host situations, the host will stop modal loops from working
  223801. // correctly if they're called from a mouse event, so we'll trigger
  223802. // the event asynchronously..
  223803. if (JUCEApplication::getInstance() == 0)
  223804. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  223805. withObject: ev
  223806. waitUntilDone: NO];
  223807. else
  223808. [self asyncMouseUp: ev];
  223809. }
  223810. - (void) asyncMouseUp: (NSEvent*) ev
  223811. {
  223812. if (owner != 0)
  223813. owner->redirectMouseUp (ev);
  223814. }
  223815. - (void) mouseDragged: (NSEvent*) ev
  223816. {
  223817. if (owner != 0)
  223818. owner->redirectMouseDrag (ev);
  223819. }
  223820. - (void) mouseMoved: (NSEvent*) ev
  223821. {
  223822. if (owner != 0)
  223823. owner->redirectMouseMove (ev);
  223824. }
  223825. - (void) mouseEntered: (NSEvent*) ev
  223826. {
  223827. if (owner != 0)
  223828. owner->redirectMouseEnter (ev);
  223829. }
  223830. - (void) mouseExited: (NSEvent*) ev
  223831. {
  223832. if (owner != 0)
  223833. owner->redirectMouseExit (ev);
  223834. }
  223835. - (void) rightMouseDown: (NSEvent*) ev
  223836. {
  223837. [self mouseDown: ev];
  223838. }
  223839. - (void) rightMouseDragged: (NSEvent*) ev
  223840. {
  223841. [self mouseDragged: ev];
  223842. }
  223843. - (void) rightMouseUp: (NSEvent*) ev
  223844. {
  223845. [self mouseUp: ev];
  223846. }
  223847. - (void) otherMouseDown: (NSEvent*) ev
  223848. {
  223849. [self mouseDown: ev];
  223850. }
  223851. - (void) otherMouseDragged: (NSEvent*) ev
  223852. {
  223853. [self mouseDragged: ev];
  223854. }
  223855. - (void) otherMouseUp: (NSEvent*) ev
  223856. {
  223857. [self mouseUp: ev];
  223858. }
  223859. - (void) scrollWheel: (NSEvent*) ev
  223860. {
  223861. if (owner != 0)
  223862. owner->redirectMouseWheel (ev);
  223863. }
  223864. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  223865. {
  223866. return YES;
  223867. }
  223868. - (void) frameChanged: (NSNotification*) n
  223869. {
  223870. if (owner != 0)
  223871. owner->redirectMovedOrResized();
  223872. }
  223873. - (void) asyncRepaint: (id) rect
  223874. {
  223875. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  223876. [self setNeedsDisplayInRect: *r];
  223877. }
  223878. - (void) keyDown: (NSEvent*) ev
  223879. {
  223880. if (owner == 0 || ! owner->redirectKeyDown (ev))
  223881. [super keyDown: ev];
  223882. }
  223883. - (void) keyUp: (NSEvent*) ev
  223884. {
  223885. if (owner == 0 || ! owner->redirectKeyUp (ev))
  223886. [super keyUp: ev];
  223887. }
  223888. - (void) flagsChanged: (NSEvent*) ev
  223889. {
  223890. if (owner != 0)
  223891. owner->redirectModKeyChange (ev);
  223892. }
  223893. #if MACOS_10_4_OR_EARLIER
  223894. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  223895. {
  223896. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  223897. return true;
  223898. return [super performKeyEquivalent: ev];
  223899. }
  223900. #endif
  223901. - (BOOL) becomeFirstResponder
  223902. {
  223903. if (owner != 0)
  223904. owner->viewFocusGain();
  223905. return true;
  223906. }
  223907. - (BOOL) resignFirstResponder
  223908. {
  223909. if (owner != 0)
  223910. owner->viewFocusLoss();
  223911. return true;
  223912. }
  223913. - (BOOL) acceptsFirstResponder
  223914. {
  223915. return owner != 0 && owner->canBecomeKeyWindow();
  223916. }
  223917. - (NSArray*) getSupportedDragTypes
  223918. {
  223919. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  223920. }
  223921. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  223922. {
  223923. return owner != 0 && owner->sendDragCallback (type, sender);
  223924. }
  223925. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  223926. {
  223927. if ([self sendDragCallback: 0 sender: sender])
  223928. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  223929. else
  223930. return NSDragOperationNone;
  223931. }
  223932. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  223933. {
  223934. if ([self sendDragCallback: 0 sender: sender])
  223935. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  223936. else
  223937. return NSDragOperationNone;
  223938. }
  223939. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  223940. {
  223941. [self sendDragCallback: 1 sender: sender];
  223942. }
  223943. - (void) draggingExited: (id <NSDraggingInfo>) sender
  223944. {
  223945. [self sendDragCallback: 1 sender: sender];
  223946. }
  223947. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  223948. {
  223949. return YES;
  223950. }
  223951. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  223952. {
  223953. return [self sendDragCallback: 2 sender: sender];
  223954. }
  223955. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  223956. {
  223957. }
  223958. @end
  223959. @implementation JuceNSWindow
  223960. - (void) setOwner: (NSViewComponentPeer*) owner_
  223961. {
  223962. owner = owner_;
  223963. isZooming = false;
  223964. }
  223965. - (BOOL) canBecomeKeyWindow
  223966. {
  223967. return owner != 0 && owner->canBecomeKeyWindow();
  223968. }
  223969. - (void) becomeKeyWindow
  223970. {
  223971. [super becomeKeyWindow];
  223972. if (owner != 0)
  223973. owner->grabFocus();
  223974. }
  223975. - (BOOL) windowShouldClose: (id) window
  223976. {
  223977. return owner == 0 || owner->windowShouldClose();
  223978. }
  223979. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  223980. {
  223981. if (owner != 0)
  223982. frameRect = owner->constrainRect (frameRect);
  223983. return frameRect;
  223984. }
  223985. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  223986. {
  223987. if (isZooming)
  223988. return proposedFrameSize;
  223989. NSRect frameRect = [self frame];
  223990. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  223991. frameRect.size = proposedFrameSize;
  223992. if (owner != 0)
  223993. frameRect = owner->constrainRect (frameRect);
  223994. return frameRect.size;
  223995. }
  223996. - (void) zoom: (id) sender
  223997. {
  223998. isZooming = true;
  223999. [super zoom: sender];
  224000. isZooming = false;
  224001. }
  224002. - (void) windowWillMove: (NSNotification*) notification
  224003. {
  224004. if (juce::Component::getCurrentlyModalComponent() != 0
  224005. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  224006. && (owner->getStyleFlags() & juce::ComponentPeer::windowHasTitleBar) != 0)
  224007. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  224008. }
  224009. @end
  224010. BEGIN_JUCE_NAMESPACE
  224011. class JuceNSImage
  224012. {
  224013. public:
  224014. JuceNSImage (const int width, const int height, const bool hasAlpha)
  224015. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  224016. width, height, hasAlpha)
  224017. {
  224018. lineStride = 0;
  224019. pixelStride = 0;
  224020. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  224021. lineStride, pixelStride);
  224022. imageRep = [[NSBitmapImageRep alloc]
  224023. initWithBitmapDataPlanes: &imageData
  224024. pixelsWide: width
  224025. pixelsHigh: height
  224026. bitsPerSample: 8
  224027. samplesPerPixel: pixelStride
  224028. hasAlpha: hasAlpha
  224029. isPlanar: NO
  224030. colorSpaceName: NSCalibratedRGBColorSpace
  224031. bitmapFormat: /*NSAlphaFirstBitmapFormat*/ (NSBitmapFormat) 0
  224032. bytesPerRow: lineStride
  224033. bitsPerPixel: 8 * pixelStride ];
  224034. juceImage.releasePixelDataReadWrite (imageData);
  224035. }
  224036. ~JuceNSImage()
  224037. {
  224038. [imageRep release];
  224039. }
  224040. Image& getJuceImage() throw() { return juceImage; }
  224041. void draw (const float x, const float y,
  224042. const RectangleList& clip,
  224043. const int originX, const int originY) const
  224044. {
  224045. // Our data is BGRA and the damned image rep only takes RGBA, so
  224046. // we need to byte-swap the active areas if there's an alpha channel...
  224047. if (juceImage.hasAlphaChannel())
  224048. {
  224049. RectangleList::Iterator iter (clip);
  224050. while (iter.next())
  224051. {
  224052. const Rectangle* const r = iter.getRectangle();
  224053. swapRGBOrder (r->getX() + originX,
  224054. r->getY() + originY,
  224055. r->getWidth(),
  224056. r->getHeight());
  224057. }
  224058. }
  224059. NSPoint p;
  224060. p.x = x;
  224061. p.y = y;
  224062. [imageRep drawAtPoint: p];
  224063. }
  224064. void drawNSImage (NSImage* imageToDraw)
  224065. {
  224066. const ScopedAutoReleasePool pool;
  224067. [NSGraphicsContext saveGraphicsState];
  224068. [NSGraphicsContext setCurrentContext:
  224069. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  224070. [imageToDraw drawAtPoint: NSZeroPoint
  224071. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  224072. operation: NSCompositeSourceOver
  224073. fraction: 1.0f];
  224074. [[NSGraphicsContext currentContext] flushGraphics];
  224075. [NSGraphicsContext restoreGraphicsState];
  224076. if (juceImage.hasAlphaChannel())
  224077. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());
  224078. }
  224079. private:
  224080. Image juceImage;
  224081. NSBitmapImageRep* imageRep;
  224082. uint8* imageData;
  224083. int pixelStride, lineStride;
  224084. void swapRGBOrder (const int x, const int y, const int w, int h) const
  224085. {
  224086. #if JUCE_BIG_ENDIAN
  224087. jassert (pixelStride == 4);
  224088. #endif
  224089. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  224090. .contains (Rectangle (x, y, w, h)));
  224091. uint8* start = imageData + x * pixelStride + y * lineStride;
  224092. while (--h >= 0)
  224093. {
  224094. uint8* p = start;
  224095. start += lineStride;
  224096. for (int i = w; --i >= 0;)
  224097. {
  224098. #if JUCE_BIG_ENDIAN
  224099. const uint8 oldp3 = p[3];
  224100. const uint8 oldp1 = p[1];
  224101. p[3] = p[0];
  224102. p[0] = oldp1;
  224103. p[1] = p[2];
  224104. p[2] = oldp3;
  224105. #else
  224106. const uint8 oldp0 = p[0];
  224107. p[0] = p[2];
  224108. p[2] = oldp0;
  224109. #endif
  224110. p += pixelStride;
  224111. }
  224112. }
  224113. }
  224114. };
  224115. static ComponentPeer* currentlyFocusedPeer = 0;
  224116. static VoidArray keysCurrentlyDown;
  224117. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  224118. {
  224119. if (keysCurrentlyDown.contains ((void*) keyCode))
  224120. return true;
  224121. if (keyCode >= 'A' && keyCode <= 'Z'
  224122. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  224123. return true;
  224124. if (keyCode >= 'a' && keyCode <= 'z'
  224125. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  224126. return true;
  224127. return false;
  224128. }
  224129. static int getKeyCodeFromEvent (NSEvent* ev)
  224130. {
  224131. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  224132. int keyCode = unmodified[0];
  224133. if (keyCode == 0x19) // (backwards-tab)
  224134. keyCode = '\t';
  224135. else if (keyCode == 0x03) // (enter)
  224136. keyCode = '\r';
  224137. return keyCode;
  224138. }
  224139. static int currentModifiers = 0;
  224140. static void updateModifiers (NSEvent* e)
  224141. {
  224142. int m = currentModifiers & ~(ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  224143. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  224144. if (([e modifierFlags] & NSShiftKeyMask) != 0)
  224145. m |= ModifierKeys::shiftModifier;
  224146. if (([e modifierFlags] & NSControlKeyMask) != 0)
  224147. m |= ModifierKeys::ctrlModifier;
  224148. if (([e modifierFlags] & NSAlternateKeyMask) != 0)
  224149. m |= ModifierKeys::altModifier;
  224150. if (([e modifierFlags] & NSCommandKeyMask) != 0)
  224151. m |= ModifierKeys::commandModifier;
  224152. currentModifiers = m;
  224153. }
  224154. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  224155. {
  224156. updateModifiers (ev);
  224157. int keyCode = getKeyCodeFromEvent (ev);
  224158. if (keyCode != 0)
  224159. {
  224160. if (isKeyDown)
  224161. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  224162. else
  224163. keysCurrentlyDown.removeValue ((void*) keyCode);
  224164. }
  224165. }
  224166. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  224167. {
  224168. return ModifierKeys (currentModifiers);
  224169. }
  224170. void ModifierKeys::updateCurrentModifiers() throw()
  224171. {
  224172. currentModifierFlags = currentModifiers;
  224173. }
  224174. static int64 getMouseTime (NSEvent* e) { return (int64) [e timestamp] * 1000.0; }
  224175. static void getMousePos (NSEvent* e, NSView* view, int& x, int& y)
  224176. {
  224177. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  224178. x = roundFloatToInt (p.x);
  224179. y = roundFloatToInt ([view frame].size.height - p.y);
  224180. }
  224181. static int getModifierForButtonNumber (const int num) throw()
  224182. {
  224183. return num == 0 ? ModifierKeys::leftButtonModifier
  224184. : (num == 1 ? ModifierKeys::rightButtonModifier
  224185. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  224186. }
  224187. NSViewComponentPeer::NSViewComponentPeer (Component* const component,
  224188. const int windowStyleFlags,
  224189. NSView* viewToAttachTo)
  224190. : ComponentPeer (component, windowStyleFlags),
  224191. window (0),
  224192. view (0),
  224193. isSharedWindow (viewToAttachTo != 0),
  224194. fullScreen (false),
  224195. insideDrawRect (false)
  224196. {
  224197. NSRect r;
  224198. r.origin.x = 0;
  224199. r.origin.y = 0;
  224200. r.size.width = (float) component->getWidth();
  224201. r.size.height = (float) component->getHeight();
  224202. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  224203. [view setPostsFrameChangedNotifications: YES];
  224204. if (isSharedWindow)
  224205. {
  224206. window = [viewToAttachTo window];
  224207. [viewToAttachTo addSubview: view];
  224208. setVisible (component->isVisible());
  224209. }
  224210. else
  224211. {
  224212. r.origin.x = (float) component->getX();
  224213. r.origin.y = (float) component->getY();
  224214. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  224215. unsigned int style = 0;
  224216. if ((windowStyleFlags & windowHasTitleBar) == 0)
  224217. style = NSBorderlessWindowMask;
  224218. else
  224219. style = NSTitledWindowMask;
  224220. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  224221. style |= NSMiniaturizableWindowMask;
  224222. if ((windowStyleFlags & windowHasCloseButton) != 0)
  224223. style |= NSClosableWindowMask;
  224224. if ((windowStyleFlags & windowIsResizable) != 0)
  224225. style |= NSResizableWindowMask;
  224226. window = [[JuceNSWindow alloc] initWithContentRect: r
  224227. styleMask: style
  224228. backing: NSBackingStoreBuffered
  224229. defer: YES];
  224230. [((JuceNSWindow*) window) setOwner: this];
  224231. [window orderOut: nil];
  224232. [window setDelegate: (JuceNSWindow*) window];
  224233. [window setOpaque: component->isOpaque()];
  224234. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  224235. if (component->isAlwaysOnTop())
  224236. [window setLevel: NSFloatingWindowLevel];
  224237. [window setContentView: view];
  224238. [window setAutodisplay: YES];
  224239. [window setAcceptsMouseMovedEvents: YES];
  224240. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  224241. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  224242. [window setReleasedWhenClosed: YES];
  224243. [window retain];
  224244. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  224245. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  224246. }
  224247. setTitle (component->getName());
  224248. }
  224249. NSViewComponentPeer::~NSViewComponentPeer()
  224250. {
  224251. view->owner = 0;
  224252. [view removeFromSuperview];
  224253. [view release];
  224254. if (! isSharedWindow)
  224255. {
  224256. [((JuceNSWindow*) window) setOwner: 0];
  224257. [window close];
  224258. [window release];
  224259. }
  224260. }
  224261. void* NSViewComponentPeer::getNativeHandle() const
  224262. {
  224263. return view;
  224264. }
  224265. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  224266. {
  224267. if (isSharedWindow)
  224268. {
  224269. [view setHidden: ! shouldBeVisible];
  224270. }
  224271. else
  224272. {
  224273. if (shouldBeVisible)
  224274. [window orderFront: nil];
  224275. else
  224276. [window orderOut: nil];
  224277. }
  224278. }
  224279. void NSViewComponentPeer::setTitle (const String& title)
  224280. {
  224281. const ScopedAutoReleasePool pool;
  224282. if (! isSharedWindow)
  224283. [window setTitle: juceStringToNS (title)];
  224284. }
  224285. void NSViewComponentPeer::setPosition (int x, int y)
  224286. {
  224287. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  224288. }
  224289. void NSViewComponentPeer::setSize (int w, int h)
  224290. {
  224291. setBounds (component->getX(), component->getY(), w, h, false);
  224292. }
  224293. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  224294. {
  224295. fullScreen = isNowFullScreen;
  224296. w = jmax (0, w);
  224297. h = jmax (0, h);
  224298. NSRect r;
  224299. r.origin.x = (float) x;
  224300. r.origin.y = (float) y;
  224301. r.size.width = (float) w;
  224302. r.size.height = (float) h;
  224303. if (isSharedWindow)
  224304. {
  224305. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  224306. if ([view frame].size.width != r.size.width
  224307. || [view frame].size.height != r.size.height)
  224308. [view setNeedsDisplay: true];
  224309. [view setFrame: r];
  224310. }
  224311. else
  224312. {
  224313. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  224314. [window setFrame: [window frameRectForContentRect: r]
  224315. display: true];
  224316. }
  224317. }
  224318. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  224319. {
  224320. NSRect r = [view frame];
  224321. if (global && [view window] != 0)
  224322. {
  224323. r = [view convertRect: r toView: nil];
  224324. NSRect wr = [[view window] frame];
  224325. r.origin.x += wr.origin.x;
  224326. r.origin.y += wr.origin.y;
  224327. y = (int) ([[[NSScreen screens] objectAtIndex:0] frame].size.height - r.origin.y - r.size.height);
  224328. }
  224329. else
  224330. {
  224331. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  224332. }
  224333. x = (int) r.origin.x;
  224334. w = (int) r.size.width;
  224335. h = (int) r.size.height;
  224336. }
  224337. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  224338. {
  224339. getBounds (x, y, w, h, ! isSharedWindow);
  224340. }
  224341. int NSViewComponentPeer::getScreenX() const
  224342. {
  224343. int x, y, w, h;
  224344. getBounds (x, y, w, h, true);
  224345. return x;
  224346. }
  224347. int NSViewComponentPeer::getScreenY() const
  224348. {
  224349. int x, y, w, h;
  224350. getBounds (x, y, w, h, true);
  224351. return y;
  224352. }
  224353. void NSViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  224354. {
  224355. int wx, wy, ww, wh;
  224356. getBounds (wx, wy, ww, wh, true);
  224357. x += wx;
  224358. y += wy;
  224359. }
  224360. void NSViewComponentPeer::globalPositionToRelative (int& x, int& y)
  224361. {
  224362. int wx, wy, ww, wh;
  224363. getBounds (wx, wy, ww, wh, true);
  224364. x -= wx;
  224365. y -= wy;
  224366. }
  224367. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  224368. {
  224369. if (constrainer != 0)
  224370. {
  224371. NSRect current = [window frame];
  224372. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  224373. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  224374. int x = (int) r.origin.x;
  224375. int y = (int) r.origin.y;
  224376. int w = (int) r.size.width;
  224377. int h = (int) r.size.height;
  224378. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  224379. (int) current.size.width, (int) current.size.height);
  224380. constrainer->checkBounds (x, y, w, h,
  224381. original,
  224382. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  224383. y != original.getY() && y + h == original.getBottom(),
  224384. x != original.getX() && x + w == original.getRight(),
  224385. y == original.getY() && y + h != original.getBottom(),
  224386. x == original.getX() && x + w != original.getRight());
  224387. r.origin.x = x;
  224388. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - y;
  224389. r.size.width = w;
  224390. r.size.height = h;
  224391. }
  224392. return r;
  224393. }
  224394. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  224395. {
  224396. if (! isSharedWindow)
  224397. {
  224398. if (shouldBeMinimised)
  224399. [window miniaturize: nil];
  224400. else
  224401. [window deminiaturize: nil];
  224402. }
  224403. }
  224404. bool NSViewComponentPeer::isMinimised() const
  224405. {
  224406. return window != 0 && [window isMiniaturized];
  224407. }
  224408. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  224409. {
  224410. if (! isSharedWindow)
  224411. {
  224412. Rectangle r (lastNonFullscreenBounds);
  224413. setMinimised (false);
  224414. if (fullScreen != shouldBeFullScreen)
  224415. {
  224416. if (shouldBeFullScreen)
  224417. r = Desktop::getInstance().getMainMonitorArea();
  224418. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  224419. if (r != getComponent()->getBounds() && ! r.isEmpty())
  224420. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  224421. }
  224422. }
  224423. }
  224424. bool NSViewComponentPeer::isFullScreen() const
  224425. {
  224426. return fullScreen;
  224427. }
  224428. bool NSViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  224429. {
  224430. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  224431. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  224432. return false;
  224433. NSPoint p;
  224434. p.x = (float) x;
  224435. p.y = (float) y;
  224436. NSView* v = [view hitTest: p];
  224437. if (trueIfInAChildWindow)
  224438. return v != nil;
  224439. return v == view;
  224440. }
  224441. const BorderSize NSViewComponentPeer::getFrameSize() const
  224442. {
  224443. BorderSize b;
  224444. if (! isSharedWindow)
  224445. {
  224446. NSRect v = [view convertRect: [view frame] toView: nil];
  224447. NSRect w = [window frame];
  224448. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  224449. b.setBottom ((int) v.origin.y);
  224450. b.setLeft ((int) v.origin.x);
  224451. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  224452. }
  224453. return b;
  224454. }
  224455. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  224456. {
  224457. if (! isSharedWindow)
  224458. {
  224459. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  224460. : NSNormalWindowLevel];
  224461. }
  224462. return true;
  224463. }
  224464. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  224465. {
  224466. if (isSharedWindow)
  224467. {
  224468. [[view superview] addSubview: view
  224469. positioned: NSWindowAbove
  224470. relativeTo: nil];
  224471. }
  224472. if (window != 0 && component->isVisible())
  224473. {
  224474. if (makeActiveWindow)
  224475. [window makeKeyAndOrderFront: nil];
  224476. else
  224477. [window orderFront: nil];
  224478. }
  224479. }
  224480. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  224481. {
  224482. NSViewComponentPeer* o = (NSViewComponentPeer*) other;
  224483. if (isSharedWindow)
  224484. {
  224485. [[view superview] addSubview: view
  224486. positioned: NSWindowBelow
  224487. relativeTo: o->view];
  224488. }
  224489. else
  224490. {
  224491. [window orderWindow: NSWindowBelow
  224492. relativeTo: o->window != 0 ? [o->window windowNumber]
  224493. : nil ];
  224494. }
  224495. }
  224496. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  224497. {
  224498. // to do..
  224499. }
  224500. void NSViewComponentPeer::viewFocusGain()
  224501. {
  224502. if (currentlyFocusedPeer != this)
  224503. {
  224504. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  224505. currentlyFocusedPeer->handleFocusLoss();
  224506. currentlyFocusedPeer = this;
  224507. handleFocusGain();
  224508. }
  224509. }
  224510. void NSViewComponentPeer::viewFocusLoss()
  224511. {
  224512. if (currentlyFocusedPeer == this)
  224513. {
  224514. currentlyFocusedPeer = 0;
  224515. handleFocusLoss();
  224516. }
  224517. }
  224518. void juce_HandleProcessFocusChange()
  224519. {
  224520. keysCurrentlyDown.clear();
  224521. if (NSViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  224522. {
  224523. if (Process::isForegroundProcess())
  224524. {
  224525. currentlyFocusedPeer->handleFocusGain();
  224526. ComponentPeer::bringModalComponentToFront();
  224527. }
  224528. else
  224529. {
  224530. currentlyFocusedPeer->handleFocusLoss();
  224531. // turn kiosk mode off if we lose focus..
  224532. Desktop::getInstance().setKioskModeComponent (0);
  224533. }
  224534. }
  224535. }
  224536. bool NSViewComponentPeer::isFocused() const
  224537. {
  224538. return isSharedWindow ? this == currentlyFocusedPeer
  224539. : (window != 0 && [window isKeyWindow]);
  224540. }
  224541. void NSViewComponentPeer::grabFocus()
  224542. {
  224543. if (window != 0)
  224544. {
  224545. [window makeKeyWindow];
  224546. [window makeFirstResponder: view];
  224547. viewFocusGain();
  224548. }
  224549. }
  224550. void NSViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  224551. {
  224552. }
  224553. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  224554. {
  224555. String unicode (nsStringToJuce ([ev characters]));
  224556. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  224557. int keyCode = getKeyCodeFromEvent (ev);
  224558. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  224559. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  224560. if (unicode.isNotEmpty() || keyCode != 0)
  224561. {
  224562. if (isKeyDown)
  224563. {
  224564. bool used = false;
  224565. while (unicode.length() > 0)
  224566. {
  224567. juce_wchar textCharacter = unicode[0];
  224568. unicode = unicode.substring (1);
  224569. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  224570. textCharacter = 0;
  224571. used = handleKeyUpOrDown (true) || used;
  224572. used = handleKeyPress (keyCode, textCharacter) || used;
  224573. }
  224574. return used;
  224575. }
  224576. else
  224577. {
  224578. if (handleKeyUpOrDown (false))
  224579. return true;
  224580. }
  224581. }
  224582. return false;
  224583. }
  224584. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  224585. {
  224586. updateKeysDown (ev, true);
  224587. bool used = handleKeyEvent (ev, true);
  224588. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  224589. {
  224590. // for command keys, the key-up event is thrown away, so simulate one..
  224591. updateKeysDown (ev, false);
  224592. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  224593. }
  224594. // (If we're running modally, don't allow unused keystrokes to be passed
  224595. // along to other blocked views..)
  224596. if (Component::getCurrentlyModalComponent() != 0)
  224597. used = true;
  224598. return used;
  224599. }
  224600. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  224601. {
  224602. updateKeysDown (ev, false);
  224603. return handleKeyEvent (ev, false)
  224604. || Component::getCurrentlyModalComponent() != 0;
  224605. }
  224606. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  224607. {
  224608. updateModifiers (ev);
  224609. handleModifierKeysChange();
  224610. }
  224611. #if MACOS_10_4_OR_EARLIER
  224612. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  224613. {
  224614. if ([ev type] == NSKeyDown)
  224615. return redirectKeyDown (ev);
  224616. else if ([ev type] == NSKeyUp)
  224617. return redirectKeyUp (ev);
  224618. return false;
  224619. }
  224620. #endif
  224621. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  224622. {
  224623. updateModifiers (ev);
  224624. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  224625. int x, y;
  224626. getMousePos (ev, view, x, y);
  224627. handleMouseDown (x, y, getMouseTime (ev));
  224628. }
  224629. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  224630. {
  224631. const int oldMods = currentModifiers;
  224632. updateModifiers (ev);
  224633. currentModifiers &= ~getModifierForButtonNumber ([ev buttonNumber]);
  224634. int x, y;
  224635. getMousePos (ev, view, x, y);
  224636. handleMouseUp (oldMods, x, y, getMouseTime (ev));
  224637. showArrowCursorIfNeeded();
  224638. }
  224639. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  224640. {
  224641. updateModifiers (ev);
  224642. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  224643. int x, y;
  224644. getMousePos (ev, view, x, y);
  224645. handleMouseDrag (x, y, getMouseTime (ev));
  224646. }
  224647. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  224648. {
  224649. updateModifiers (ev);
  224650. int x, y;
  224651. getMousePos (ev, view, x, y);
  224652. handleMouseMove (x, y, getMouseTime (ev));
  224653. showArrowCursorIfNeeded();
  224654. }
  224655. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  224656. {
  224657. updateModifiers (ev);
  224658. int x, y;
  224659. getMousePos (ev, view, x, y);
  224660. handleMouseEnter (x, y, getMouseTime (ev));
  224661. }
  224662. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  224663. {
  224664. updateModifiers (ev);
  224665. int x, y;
  224666. getMousePos (ev, view, x, y);
  224667. handleMouseExit (x, y, getMouseTime (ev));
  224668. }
  224669. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  224670. {
  224671. updateModifiers (ev);
  224672. handleMouseWheel (roundFloatToInt ([ev deltaX] * 10.0f),
  224673. roundFloatToInt ([ev deltaY] * 10.0f),
  224674. getMouseTime (ev));
  224675. }
  224676. void NSViewComponentPeer::showArrowCursorIfNeeded()
  224677. {
  224678. if (Component::getComponentUnderMouse() == 0)
  224679. {
  224680. int mx, my;
  224681. Desktop::getInstance().getMousePosition (mx, my);
  224682. if (Desktop::getInstance().findComponentAt (mx, my) == 0)
  224683. [[NSCursor arrowCursor] set];
  224684. }
  224685. }
  224686. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  224687. {
  224688. NSString* bestType
  224689. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  224690. if (bestType == nil)
  224691. return false;
  224692. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  224693. int x = (int) p.x;
  224694. int y = (int) ([view frame].size.height - p.y);
  224695. StringArray files;
  224696. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  224697. if (list == nil)
  224698. return false;
  224699. if ([list isKindOfClass: [NSArray class]])
  224700. {
  224701. NSArray* items = (NSArray*) list;
  224702. for (unsigned int i = 0; i < [items count]; ++i)
  224703. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  224704. }
  224705. if (files.size() == 0)
  224706. return false;
  224707. if (type == 0)
  224708. handleFileDragMove (files, x, y);
  224709. else if (type == 1)
  224710. handleFileDragExit (files);
  224711. else if (type == 2)
  224712. handleFileDragDrop (files, x, y);
  224713. return true;
  224714. }
  224715. bool NSViewComponentPeer::isOpaque()
  224716. {
  224717. if (! getComponent()->isValidComponent())
  224718. return true;
  224719. return getComponent()->isOpaque();
  224720. }
  224721. void NSViewComponentPeer::drawRect (NSRect r)
  224722. {
  224723. if (r.size.width < 1.0f || r.size.height < 1.0f)
  224724. return;
  224725. const float y = [view frame].size.height - (r.origin.y + r.size.height);
  224726. JuceNSImage temp ((int) (r.size.width + 0.5f),
  224727. (int) (r.size.height + 0.5f),
  224728. ! getComponent()->isOpaque());
  224729. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  224730. const int originX = -roundFloatToInt (r.origin.x);
  224731. const int originY = -roundFloatToInt (y);
  224732. context.setOrigin (originX, originY);
  224733. const NSRect* rects = 0;
  224734. NSInteger numRects = 0;
  224735. [view getRectsBeingDrawn: &rects count: &numRects];
  224736. RectangleList clip;
  224737. for (int i = 0; i < numRects; ++i)
  224738. {
  224739. clip.addWithoutMerging (Rectangle (roundFloatToInt (rects[i].origin.x),
  224740. roundFloatToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  224741. roundFloatToInt (rects[i].size.width),
  224742. roundFloatToInt (rects[i].size.height)));
  224743. }
  224744. if (context.reduceClipRegion (clip))
  224745. {
  224746. insideDrawRect = true;
  224747. handlePaint (context);
  224748. insideDrawRect = false;
  224749. temp.draw (r.origin.x, r.origin.y, clip, originX, originY);
  224750. }
  224751. }
  224752. bool NSViewComponentPeer::canBecomeKeyWindow()
  224753. {
  224754. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  224755. }
  224756. bool NSViewComponentPeer::windowShouldClose()
  224757. {
  224758. if (! isValidPeer (this))
  224759. return YES;
  224760. handleUserClosingWindow();
  224761. return NO;
  224762. }
  224763. void NSViewComponentPeer::redirectMovedOrResized()
  224764. {
  224765. handleMovedOrResized();
  224766. }
  224767. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  224768. {
  224769. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  224770. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  224771. // is apparently still available in 64-bit apps..
  224772. if (enableOrDisable)
  224773. {
  224774. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  224775. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  224776. }
  224777. else
  224778. {
  224779. SetSystemUIMode (kUIModeNormal, 0);
  224780. }
  224781. }
  224782. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  224783. {
  224784. NSRect r = NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  224785. (float) w, (float) h);
  224786. if (insideDrawRect)
  224787. {
  224788. [view performSelectorOnMainThread: @selector (asyncRepaint:)
  224789. withObject: [NSData dataWithBytes: &r length: sizeof (r)]
  224790. waitUntilDone: NO];
  224791. }
  224792. else
  224793. {
  224794. [view setNeedsDisplayInRect: r];
  224795. }
  224796. }
  224797. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  224798. {
  224799. [view displayIfNeeded];
  224800. }
  224801. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  224802. {
  224803. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  224804. }
  224805. static Image* NSImageToJuceImage (NSImage* image)
  224806. {
  224807. JuceNSImage juceIm ((int) [image size].width,
  224808. (int) [image size].height,
  224809. true);
  224810. juceIm.drawNSImage (image);
  224811. return juceIm.getJuceImage().createCopy();
  224812. }
  224813. Image* juce_createIconForFile (const File& file)
  224814. {
  224815. const ScopedAutoReleasePool pool;
  224816. NSImage* im = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  224817. return NSImageToJuceImage (im);
  224818. }
  224819. const int KeyPress::spaceKey = ' ';
  224820. const int KeyPress::returnKey = 0x0d;
  224821. const int KeyPress::escapeKey = 0x1b;
  224822. const int KeyPress::backspaceKey = 0x7f;
  224823. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  224824. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  224825. const int KeyPress::upKey = NSUpArrowFunctionKey;
  224826. const int KeyPress::downKey = NSDownArrowFunctionKey;
  224827. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  224828. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  224829. const int KeyPress::endKey = NSEndFunctionKey;
  224830. const int KeyPress::homeKey = NSHomeFunctionKey;
  224831. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  224832. const int KeyPress::insertKey = -1;
  224833. const int KeyPress::tabKey = 9;
  224834. const int KeyPress::F1Key = NSF1FunctionKey;
  224835. const int KeyPress::F2Key = NSF2FunctionKey;
  224836. const int KeyPress::F3Key = NSF3FunctionKey;
  224837. const int KeyPress::F4Key = NSF4FunctionKey;
  224838. const int KeyPress::F5Key = NSF5FunctionKey;
  224839. const int KeyPress::F6Key = NSF6FunctionKey;
  224840. const int KeyPress::F7Key = NSF7FunctionKey;
  224841. const int KeyPress::F8Key = NSF8FunctionKey;
  224842. const int KeyPress::F9Key = NSF9FunctionKey;
  224843. const int KeyPress::F10Key = NSF10FunctionKey;
  224844. const int KeyPress::F11Key = NSF1FunctionKey;
  224845. const int KeyPress::F12Key = NSF12FunctionKey;
  224846. const int KeyPress::F13Key = NSF13FunctionKey;
  224847. const int KeyPress::F14Key = NSF14FunctionKey;
  224848. const int KeyPress::F15Key = NSF15FunctionKey;
  224849. const int KeyPress::F16Key = NSF16FunctionKey;
  224850. const int KeyPress::numberPad0 = 0x30020;
  224851. const int KeyPress::numberPad1 = 0x30021;
  224852. const int KeyPress::numberPad2 = 0x30022;
  224853. const int KeyPress::numberPad3 = 0x30023;
  224854. const int KeyPress::numberPad4 = 0x30024;
  224855. const int KeyPress::numberPad5 = 0x30025;
  224856. const int KeyPress::numberPad6 = 0x30026;
  224857. const int KeyPress::numberPad7 = 0x30027;
  224858. const int KeyPress::numberPad8 = 0x30028;
  224859. const int KeyPress::numberPad9 = 0x30029;
  224860. const int KeyPress::numberPadAdd = 0x3002a;
  224861. const int KeyPress::numberPadSubtract = 0x3002b;
  224862. const int KeyPress::numberPadMultiply = 0x3002c;
  224863. const int KeyPress::numberPadDivide = 0x3002d;
  224864. const int KeyPress::numberPadSeparator = 0x3002e;
  224865. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  224866. const int KeyPress::numberPadEquals = 0x30030;
  224867. const int KeyPress::numberPadDelete = 0x30031;
  224868. const int KeyPress::playKey = 0x30000;
  224869. const int KeyPress::stopKey = 0x30001;
  224870. const int KeyPress::fastForwardKey = 0x30002;
  224871. const int KeyPress::rewindKey = 0x30003;
  224872. #endif
  224873. /********* End of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  224874. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  224875. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224876. // compiled on its own).
  224877. #if JUCE_INCLUDED_FILE
  224878. #if JUCE_MAC
  224879. static NSImage* juceImageToNSImage (const Image& image)
  224880. {
  224881. const ScopedAutoReleasePool pool;
  224882. int lineStride, pixelStride;
  224883. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  224884. lineStride, pixelStride);
  224885. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  224886. initWithBitmapDataPlanes: NULL
  224887. pixelsWide: image.getWidth()
  224888. pixelsHigh: image.getHeight()
  224889. bitsPerSample: 8
  224890. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  224891. hasAlpha: image.hasAlphaChannel()
  224892. isPlanar: NO
  224893. colorSpaceName: NSCalibratedRGBColorSpace
  224894. bitmapFormat: (NSBitmapFormat) 0
  224895. bytesPerRow: lineStride
  224896. bitsPerPixel: pixelStride * 8];
  224897. unsigned char* newData = [rep bitmapData];
  224898. memcpy (newData, pixels, lineStride * image.getHeight());
  224899. image.releasePixelDataReadOnly (pixels);
  224900. NSImage* im = [[NSImage alloc] init];
  224901. [im addRepresentation: rep];
  224902. [rep release];
  224903. return im;
  224904. }
  224905. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  224906. {
  224907. NSImage* im = juceImageToNSImage (image);
  224908. NSCursor* c = [[NSCursor alloc] initWithImage: im
  224909. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  224910. [im release];
  224911. return (void*) c;
  224912. }
  224913. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  224914. {
  224915. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  224916. jassert (im != 0);
  224917. if (im == 0)
  224918. return 0;
  224919. void* const curs = juce_createMouseCursorFromImage (*im,
  224920. (int) (hx * im->getWidth()),
  224921. (int) (hy * im->getHeight()));
  224922. delete im;
  224923. return curs;
  224924. }
  224925. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  224926. {
  224927. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  224928. MemoryBlock mb;
  224929. if (f.getChildFile (filename).loadFileAsData (mb))
  224930. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  224931. return 0;
  224932. }
  224933. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  224934. {
  224935. const ScopedAutoReleasePool pool;
  224936. NSCursor* c = 0;
  224937. switch (type)
  224938. {
  224939. case MouseCursor::NormalCursor:
  224940. c = [NSCursor arrowCursor];
  224941. break;
  224942. case MouseCursor::NoCursor:
  224943. {
  224944. Image blank (Image::ARGB, 8, 8, true);
  224945. return juce_createMouseCursorFromImage (blank, 0, 0);
  224946. }
  224947. case MouseCursor::DraggingHandCursor:
  224948. c = [NSCursor openHandCursor];
  224949. break;
  224950. case MouseCursor::CopyingCursor:
  224951. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  224952. case MouseCursor::WaitCursor:
  224953. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  224954. break;
  224955. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  224956. case MouseCursor::IBeamCursor:
  224957. c = [NSCursor IBeamCursor];
  224958. break;
  224959. case MouseCursor::PointingHandCursor:
  224960. c = [NSCursor pointingHandCursor];
  224961. break;
  224962. case MouseCursor::LeftRightResizeCursor:
  224963. c = [NSCursor resizeLeftRightCursor];
  224964. break;
  224965. case MouseCursor::LeftEdgeResizeCursor:
  224966. c = [NSCursor resizeLeftCursor];
  224967. break;
  224968. case MouseCursor::RightEdgeResizeCursor:
  224969. c = [NSCursor resizeRightCursor];
  224970. break;
  224971. case MouseCursor::UpDownResizeCursor:
  224972. case MouseCursor::TopEdgeResizeCursor:
  224973. case MouseCursor::BottomEdgeResizeCursor:
  224974. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  224975. case MouseCursor::TopLeftCornerResizeCursor:
  224976. case MouseCursor::BottomRightCornerResizeCursor:
  224977. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  224978. case MouseCursor::TopRightCornerResizeCursor:
  224979. case MouseCursor::BottomLeftCornerResizeCursor:
  224980. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  224981. case MouseCursor::UpDownLeftRightResizeCursor:
  224982. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  224983. case MouseCursor::CrosshairCursor:
  224984. c = [NSCursor crosshairCursor];
  224985. break;
  224986. }
  224987. [c retain];
  224988. return (void*) c;
  224989. }
  224990. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  224991. {
  224992. NSCursor* c = (NSCursor*) cursorHandle;
  224993. [c release];
  224994. }
  224995. void MouseCursor::showInAllWindows() const throw()
  224996. {
  224997. showInWindow (0);
  224998. }
  224999. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  225000. {
  225001. NSCursor* const c = (NSCursor*) getHandle();
  225002. [c set];
  225003. }
  225004. #else
  225005. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw() { return 0; }
  225006. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw() { return 0; }
  225007. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw() {}
  225008. void MouseCursor::showInAllWindows() const throw() {}
  225009. void MouseCursor::showInWindow (ComponentPeer*) const throw() {}
  225010. #endif
  225011. #endif
  225012. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  225013. /********* Start of inlined file: juce_mac_NSViewComponent.mm *********/
  225014. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225015. // compiled on its own).
  225016. #if JUCE_INCLUDED_FILE
  225017. class NSViewComponentInternal : public ComponentMovementWatcher
  225018. {
  225019. Component* const owner;
  225020. NSViewComponentPeer* currentPeer;
  225021. bool wasShowing;
  225022. public:
  225023. NSView* const view;
  225024. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  225025. : ComponentMovementWatcher (owner_),
  225026. owner (owner_),
  225027. currentPeer (0),
  225028. wasShowing (false),
  225029. view (view_)
  225030. {
  225031. [view_ retain];
  225032. if (owner_->isShowing())
  225033. componentPeerChanged();
  225034. }
  225035. ~NSViewComponentInternal()
  225036. {
  225037. [view removeFromSuperview];
  225038. [view release];
  225039. }
  225040. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  225041. {
  225042. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  225043. // The ComponentMovementWatcher version of this method avoids calling
  225044. // us when the top-level comp is resized, but for an NSView we need to know this
  225045. // because with inverted co-ords, we need to update the position even if the
  225046. // top-left pos hasn't changed
  225047. if (comp.isOnDesktop() && wasResized)
  225048. componentMovedOrResized (wasMoved, wasResized);
  225049. }
  225050. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  225051. {
  225052. Component* const topComp = owner->getTopLevelComponent();
  225053. if (topComp->getPeer() != 0)
  225054. {
  225055. int x = 0, y = 0;
  225056. owner->relativePositionToOtherComponent (topComp, x, y);
  225057. NSRect r;
  225058. r.origin.x = (float) x;
  225059. r.origin.y = (float) y;
  225060. r.size.width = (float) owner->getWidth();
  225061. r.size.height = (float) owner->getHeight();
  225062. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  225063. [view setFrame: r];
  225064. }
  225065. }
  225066. void componentPeerChanged()
  225067. {
  225068. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  225069. if (currentPeer != peer)
  225070. {
  225071. [view removeFromSuperview];
  225072. currentPeer = peer;
  225073. if (peer != 0)
  225074. {
  225075. [peer->view addSubview: view];
  225076. componentMovedOrResized (false, false);
  225077. }
  225078. }
  225079. [view setHidden: ! owner->isShowing()];
  225080. }
  225081. void componentVisibilityChanged (Component&)
  225082. {
  225083. componentPeerChanged();
  225084. }
  225085. juce_UseDebuggingNewOperator
  225086. private:
  225087. NSViewComponentInternal (const NSViewComponentInternal&);
  225088. const NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  225089. };
  225090. NSViewComponent::NSViewComponent()
  225091. : info (0)
  225092. {
  225093. }
  225094. NSViewComponent::~NSViewComponent()
  225095. {
  225096. delete info;
  225097. }
  225098. void NSViewComponent::setView (void* view)
  225099. {
  225100. if (view != getView())
  225101. {
  225102. deleteAndZero (info);
  225103. if (view != 0)
  225104. info = new NSViewComponentInternal ((NSView*) view, this);
  225105. }
  225106. }
  225107. void* NSViewComponent::getView() const
  225108. {
  225109. return info == 0 ? 0 : info->view;
  225110. }
  225111. void NSViewComponent::paint (Graphics& g)
  225112. {
  225113. }
  225114. #endif
  225115. /********* End of inlined file: juce_mac_NSViewComponent.mm *********/
  225116. /********* Start of inlined file: juce_mac_AppleRemote.mm *********/
  225117. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225118. // compiled on its own).
  225119. #if JUCE_INCLUDED_FILE
  225120. AppleRemoteDevice::AppleRemoteDevice()
  225121. : device (0),
  225122. queue (0),
  225123. remoteId (0)
  225124. {
  225125. }
  225126. AppleRemoteDevice::~AppleRemoteDevice()
  225127. {
  225128. stop();
  225129. }
  225130. static io_object_t getAppleRemoteDevice() throw()
  225131. {
  225132. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  225133. io_iterator_t iter = 0;
  225134. io_object_t iod = 0;
  225135. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  225136. && iter != 0)
  225137. {
  225138. iod = IOIteratorNext (iter);
  225139. }
  225140. IOObjectRelease (iter);
  225141. return iod;
  225142. }
  225143. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  225144. {
  225145. jassert (*device == 0);
  225146. io_name_t classname;
  225147. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  225148. {
  225149. IOCFPlugInInterface** cfPlugInInterface = 0;
  225150. SInt32 score = 0;
  225151. if (IOCreatePlugInInterfaceForService (iod,
  225152. kIOHIDDeviceUserClientTypeID,
  225153. kIOCFPlugInInterfaceID,
  225154. &cfPlugInInterface,
  225155. &score) == kIOReturnSuccess)
  225156. {
  225157. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  225158. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  225159. device);
  225160. (void) hr;
  225161. (*cfPlugInInterface)->Release (cfPlugInInterface);
  225162. }
  225163. }
  225164. return *device != 0;
  225165. }
  225166. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  225167. {
  225168. if (queue != 0)
  225169. return true;
  225170. stop();
  225171. bool result = false;
  225172. io_object_t iod = getAppleRemoteDevice();
  225173. if (iod != 0)
  225174. {
  225175. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  225176. result = true;
  225177. else
  225178. stop();
  225179. IOObjectRelease (iod);
  225180. }
  225181. return result;
  225182. }
  225183. void AppleRemoteDevice::stop() throw()
  225184. {
  225185. if (queue != 0)
  225186. {
  225187. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  225188. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  225189. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  225190. queue = 0;
  225191. }
  225192. if (device != 0)
  225193. {
  225194. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  225195. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  225196. device = 0;
  225197. }
  225198. }
  225199. bool AppleRemoteDevice::isActive() const throw()
  225200. {
  225201. return queue != 0;
  225202. }
  225203. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  225204. {
  225205. if (result == kIOReturnSuccess)
  225206. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  225207. }
  225208. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  225209. {
  225210. Array <int> cookies;
  225211. CFArrayRef elements;
  225212. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  225213. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  225214. return false;
  225215. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  225216. {
  225217. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  225218. // get the cookie
  225219. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  225220. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  225221. continue;
  225222. long number;
  225223. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  225224. continue;
  225225. cookies.add ((int) number);
  225226. }
  225227. CFRelease (elements);
  225228. if ((*(IOHIDDeviceInterface**) device)
  225229. ->open ((IOHIDDeviceInterface**) device,
  225230. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  225231. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  225232. {
  225233. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  225234. if (queue != 0)
  225235. {
  225236. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  225237. for (int i = 0; i < cookies.size(); ++i)
  225238. {
  225239. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  225240. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  225241. }
  225242. CFRunLoopSourceRef eventSource;
  225243. if ((*(IOHIDQueueInterface**) queue)
  225244. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  225245. {
  225246. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  225247. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  225248. {
  225249. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  225250. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  225251. return true;
  225252. }
  225253. }
  225254. }
  225255. }
  225256. return false;
  225257. }
  225258. void AppleRemoteDevice::handleCallbackInternal()
  225259. {
  225260. int totalValues = 0;
  225261. AbsoluteTime nullTime = { 0, 0 };
  225262. char cookies [12];
  225263. int numCookies = 0;
  225264. while (numCookies < numElementsInArray (cookies))
  225265. {
  225266. IOHIDEventStruct e;
  225267. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  225268. break;
  225269. if ((int) e.elementCookie == 19)
  225270. {
  225271. remoteId = e.value;
  225272. buttonPressed (switched, false);
  225273. }
  225274. else
  225275. {
  225276. totalValues += e.value;
  225277. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  225278. }
  225279. }
  225280. cookies [numCookies++] = 0;
  225281. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  225282. static const char buttonPatterns[] =
  225283. {
  225284. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  225285. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  225286. 0x1f, 0x1d, 0x1c, 0x12, 0,
  225287. 0x1f, 0x1e, 0x1c, 0x12, 0,
  225288. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  225289. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  225290. 0x1f, 0x12, 0x04, 0x02, 0,
  225291. 0x1f, 0x12, 0x03, 0x02, 0,
  225292. 0x1f, 0x12, 0x1f, 0x12, 0,
  225293. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  225294. 19, 0
  225295. };
  225296. int buttonNum = (int) menuButton;
  225297. int i = 0;
  225298. while (i < numElementsInArray (buttonPatterns))
  225299. {
  225300. if (strcmp (cookies, buttonPatterns + i) == 0)
  225301. {
  225302. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  225303. break;
  225304. }
  225305. i += strlen (buttonPatterns + i) + 1;
  225306. ++buttonNum;
  225307. }
  225308. }
  225309. #endif
  225310. /********* End of inlined file: juce_mac_AppleRemote.mm *********/
  225311. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  225312. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225313. // compiled on its own).
  225314. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  225315. #if JUCE_MAC
  225316. END_JUCE_NAMESPACE
  225317. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  225318. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  225319. {
  225320. CriticalSection* contextLock;
  225321. bool needsUpdate;
  225322. }
  225323. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  225324. - (bool) makeActive;
  225325. - (void) makeInactive;
  225326. - (void) reshape;
  225327. @end
  225328. @implementation ThreadSafeNSOpenGLView
  225329. - (id) initWithFrame: (NSRect) frameRect
  225330. pixelFormat: (NSOpenGLPixelFormat*) format
  225331. {
  225332. contextLock = new CriticalSection();
  225333. self = [super initWithFrame: frameRect pixelFormat: format];
  225334. if (self != nil)
  225335. [[NSNotificationCenter defaultCenter] addObserver: self
  225336. selector: @selector (_surfaceNeedsUpdate:)
  225337. name: NSViewGlobalFrameDidChangeNotification
  225338. object: self];
  225339. return self;
  225340. }
  225341. - (void) dealloc
  225342. {
  225343. [[NSNotificationCenter defaultCenter] removeObserver: self];
  225344. delete contextLock;
  225345. [super dealloc];
  225346. }
  225347. - (bool) makeActive
  225348. {
  225349. const ScopedLock sl (*contextLock);
  225350. if ([self openGLContext] == 0)
  225351. return false;
  225352. [[self openGLContext] makeCurrentContext];
  225353. if (needsUpdate)
  225354. {
  225355. [super update];
  225356. needsUpdate = false;
  225357. }
  225358. return true;
  225359. }
  225360. - (void) makeInactive
  225361. {
  225362. const ScopedLock sl (*contextLock);
  225363. [NSOpenGLContext clearCurrentContext];
  225364. }
  225365. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  225366. {
  225367. const ScopedLock sl (*contextLock);
  225368. needsUpdate = true;
  225369. }
  225370. - (void) update
  225371. {
  225372. const ScopedLock sl (*contextLock);
  225373. needsUpdate = true;
  225374. }
  225375. - (void) reshape
  225376. {
  225377. const ScopedLock sl (*contextLock);
  225378. needsUpdate = true;
  225379. }
  225380. @end
  225381. BEGIN_JUCE_NAMESPACE
  225382. class WindowedGLContext : public OpenGLContext
  225383. {
  225384. public:
  225385. WindowedGLContext (Component* const component,
  225386. const OpenGLPixelFormat& pixelFormat_,
  225387. NSOpenGLContext* sharedContext)
  225388. : renderContext (0),
  225389. pixelFormat (pixelFormat_)
  225390. {
  225391. jassert (component != 0);
  225392. NSOpenGLPixelFormatAttribute attribs [64];
  225393. int n = 0;
  225394. attribs[n++] = NSOpenGLPFADoubleBuffer;
  225395. attribs[n++] = NSOpenGLPFAAccelerated;
  225396. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  225397. attribs[n++] = NSOpenGLPFAColorSize;
  225398. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  225399. pixelFormat.greenBits,
  225400. pixelFormat.blueBits);
  225401. attribs[n++] = NSOpenGLPFAAlphaSize;
  225402. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  225403. attribs[n++] = NSOpenGLPFADepthSize;
  225404. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  225405. attribs[n++] = NSOpenGLPFAStencilSize;
  225406. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  225407. attribs[n++] = NSOpenGLPFAAccumSize;
  225408. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  225409. pixelFormat.accumulationBufferGreenBits,
  225410. pixelFormat.accumulationBufferBlueBits,
  225411. pixelFormat.accumulationBufferAlphaBits);
  225412. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  225413. attribs[n++] = NSOpenGLPFASampleBuffers;
  225414. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  225415. attribs[n++] = NSOpenGLPFAClosestPolicy;
  225416. attribs[n++] = NSOpenGLPFANoRecovery;
  225417. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  225418. NSOpenGLPixelFormat* format
  225419. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  225420. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  225421. pixelFormat: format];
  225422. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  225423. shareContext: sharedContext] autorelease];
  225424. const GLint swapInterval = 1;
  225425. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  225426. [view setOpenGLContext: renderContext];
  225427. [renderContext setView: view];
  225428. [format release];
  225429. viewHolder = new NSViewComponentInternal (view, component);
  225430. }
  225431. ~WindowedGLContext()
  225432. {
  225433. makeInactive();
  225434. [renderContext setView: nil];
  225435. delete viewHolder;
  225436. }
  225437. bool makeActive() const throw()
  225438. {
  225439. jassert (renderContext != 0);
  225440. [view makeActive];
  225441. return isActive();
  225442. }
  225443. bool makeInactive() const throw()
  225444. {
  225445. [view makeInactive];
  225446. return true;
  225447. }
  225448. bool isActive() const throw()
  225449. {
  225450. return [NSOpenGLContext currentContext] == renderContext;
  225451. }
  225452. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  225453. void* getRawContext() const throw() { return renderContext; }
  225454. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  225455. {
  225456. }
  225457. void swapBuffers()
  225458. {
  225459. [renderContext flushBuffer];
  225460. }
  225461. bool setSwapInterval (const int numFramesPerSwap)
  225462. {
  225463. [renderContext setValues: (const GLint*) &numFramesPerSwap
  225464. forParameter: NSOpenGLCPSwapInterval];
  225465. return true;
  225466. }
  225467. int getSwapInterval() const
  225468. {
  225469. GLint numFrames = 0;
  225470. [renderContext getValues: &numFrames
  225471. forParameter: NSOpenGLCPSwapInterval];
  225472. return numFrames;
  225473. }
  225474. void repaint()
  225475. {
  225476. // we need to invalidate the juce view that holds this gl view, to make it
  225477. // cause a repaint callback
  225478. NSView* v = (NSView*) viewHolder->view;
  225479. NSRect r = [v frame];
  225480. // bit of a bodge here.. if we only invalidate the area of the gl component,
  225481. // it's completely covered by the NSOpenGLView, so the OS throws away the
  225482. // repaint message, thus never causing our paint() callback, and never repainting
  225483. // the comp. So invalidating just a little bit around the edge helps..
  225484. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  225485. }
  225486. void* getNativeWindowHandle() const { return viewHolder->view; }
  225487. juce_UseDebuggingNewOperator
  225488. NSOpenGLContext* renderContext;
  225489. ThreadSafeNSOpenGLView* view;
  225490. private:
  225491. OpenGLPixelFormat pixelFormat;
  225492. NSViewComponentInternal* viewHolder;
  225493. WindowedGLContext (const WindowedGLContext&);
  225494. const WindowedGLContext& operator= (const WindowedGLContext&);
  225495. };
  225496. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  225497. const OpenGLPixelFormat& pixelFormat,
  225498. const OpenGLContext* const contextToShareWith)
  225499. {
  225500. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  225501. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  225502. if (c->renderContext == 0)
  225503. deleteAndZero (c);
  225504. return c;
  225505. }
  225506. void* OpenGLComponent::getNativeWindowHandle() const
  225507. {
  225508. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  225509. : 0;
  225510. }
  225511. void juce_glViewport (const int w, const int h)
  225512. {
  225513. glViewport (0, 0, w, h);
  225514. }
  225515. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  225516. OwnedArray <OpenGLPixelFormat>& results)
  225517. {
  225518. /* GLint attribs [64];
  225519. int n = 0;
  225520. attribs[n++] = AGL_RGBA;
  225521. attribs[n++] = AGL_DOUBLEBUFFER;
  225522. attribs[n++] = AGL_ACCELERATED;
  225523. attribs[n++] = AGL_NO_RECOVERY;
  225524. attribs[n++] = AGL_NONE;
  225525. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  225526. while (p != 0)
  225527. {
  225528. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  225529. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  225530. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  225531. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  225532. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  225533. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  225534. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  225535. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  225536. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  225537. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  225538. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  225539. results.add (pf);
  225540. p = aglNextPixelFormat (p);
  225541. }*/
  225542. //jassertfalse //xxx can't see how you do this in cocoa!
  225543. }
  225544. #else
  225545. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  225546. const OpenGLPixelFormat& pixelFormat,
  225547. const OpenGLContext* const contextToShareWith)
  225548. {
  225549. return 0;
  225550. }
  225551. void juce_glViewport (const int w, const int h)
  225552. {
  225553. //glViewport (0, 0, w, h);
  225554. }
  225555. #endif
  225556. #endif
  225557. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  225558. /********* Start of inlined file: juce_mac_MainMenu.mm *********/
  225559. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225560. // compiled on its own).
  225561. #if JUCE_INCLUDED_FILE
  225562. class JuceMainMenuHandler;
  225563. END_JUCE_NAMESPACE
  225564. using namespace JUCE_NAMESPACE;
  225565. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  225566. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225567. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  225568. #else
  225569. @interface JuceMenuCallback : NSObject
  225570. #endif
  225571. {
  225572. JuceMainMenuHandler* owner;
  225573. }
  225574. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  225575. - (void) dealloc;
  225576. - (void) menuItemInvoked: (id) menu;
  225577. - (void) menuNeedsUpdate: (NSMenu*) menu;
  225578. @end
  225579. BEGIN_JUCE_NAMESPACE
  225580. class JuceMainMenuHandler : private MenuBarModelListener,
  225581. private DeletedAtShutdown
  225582. {
  225583. public:
  225584. static JuceMainMenuHandler* instance;
  225585. JuceMainMenuHandler() throw()
  225586. : currentModel (0),
  225587. lastUpdateTime (0)
  225588. {
  225589. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  225590. }
  225591. ~JuceMainMenuHandler() throw()
  225592. {
  225593. setMenu (0);
  225594. jassert (instance == this);
  225595. instance = 0;
  225596. [callback release];
  225597. }
  225598. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  225599. {
  225600. if (currentModel != newMenuBarModel)
  225601. {
  225602. if (currentModel != 0)
  225603. currentModel->removeListener (this);
  225604. currentModel = newMenuBarModel;
  225605. if (currentModel != 0)
  225606. currentModel->addListener (this);
  225607. menuBarItemsChanged (0);
  225608. }
  225609. }
  225610. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  225611. const String& name, const int menuId, const int tag)
  225612. {
  225613. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  225614. action: nil
  225615. keyEquivalent: @""];
  225616. [item setTag: tag];
  225617. NSMenu* sub = createMenu (child, name, menuId, tag);
  225618. [parent setSubmenu: sub forItem: item];
  225619. [sub setAutoenablesItems: false];
  225620. [sub release];
  225621. }
  225622. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  225623. const String& name, const int menuId, const int tag)
  225624. {
  225625. [parentItem setTag: tag];
  225626. NSMenu* menu = [parentItem submenu];
  225627. [menu setTitle: juceStringToNS (name)];
  225628. while ([menu numberOfItems] > 0)
  225629. [menu removeItemAtIndex: 0];
  225630. PopupMenu::MenuItemIterator iter (menuToCopy);
  225631. while (iter.next())
  225632. addMenuItem (iter, menu, menuId, tag);
  225633. [menu setAutoenablesItems: false];
  225634. [menu update];
  225635. }
  225636. void menuBarItemsChanged (MenuBarModel*)
  225637. {
  225638. lastUpdateTime = Time::getMillisecondCounter();
  225639. StringArray menuNames;
  225640. if (currentModel != 0)
  225641. menuNames = currentModel->getMenuBarNames();
  225642. NSMenu* menuBar = [NSApp mainMenu];
  225643. while ([menuBar numberOfItems] > 1 + menuNames.size())
  225644. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  225645. int menuId = 1;
  225646. for (int i = 0; i < menuNames.size(); ++i)
  225647. {
  225648. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  225649. if (i >= [menuBar numberOfItems] - 1)
  225650. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  225651. else
  225652. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  225653. }
  225654. }
  225655. static void flashMenuBar (NSMenu* menu)
  225656. {
  225657. const unichar f35Key = NSF35FunctionKey;
  225658. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  225659. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  225660. action: nil
  225661. keyEquivalent: f35String];
  225662. [item setTarget: nil];
  225663. [menu insertItem: item atIndex: [menu numberOfItems]];
  225664. [item release];
  225665. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  225666. location: NSZeroPoint
  225667. modifierFlags: NSCommandKeyMask
  225668. timestamp: 0
  225669. windowNumber: 0
  225670. context: [NSGraphicsContext currentContext]
  225671. characters: f35String
  225672. charactersIgnoringModifiers: f35String
  225673. isARepeat: NO
  225674. keyCode: 0];
  225675. [menu performKeyEquivalent: f35Event];
  225676. [menu removeItem: item];
  225677. }
  225678. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  225679. {
  225680. for (int i = [menu numberOfItems]; --i >= 0;)
  225681. {
  225682. NSMenuItem* m = [menu itemAtIndex: i];
  225683. if ([m tag] == info.commandID)
  225684. return m;
  225685. if ([m submenu] != 0)
  225686. {
  225687. NSMenuItem* found = findMenuItem ([m submenu], info);
  225688. if (found != 0)
  225689. return found;
  225690. }
  225691. }
  225692. return 0;
  225693. }
  225694. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  225695. {
  225696. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  225697. if (item != 0)
  225698. flashMenuBar ([item menu]);
  225699. }
  225700. void updateMenus()
  225701. {
  225702. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  225703. menuBarItemsChanged (0);
  225704. }
  225705. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  225706. {
  225707. if (currentModel != 0)
  225708. {
  225709. if (commandManager != 0)
  225710. {
  225711. ApplicationCommandTarget::InvocationInfo info (commandId);
  225712. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  225713. commandManager->invoke (info, true);
  225714. }
  225715. currentModel->menuItemSelected (commandId, topLevelIndex);
  225716. }
  225717. }
  225718. MenuBarModel* currentModel;
  225719. uint32 lastUpdateTime;
  225720. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  225721. const int topLevelMenuId, const int topLevelIndex)
  225722. {
  225723. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  225724. if (text == 0)
  225725. text = @"";
  225726. if (iter.isSeparator)
  225727. {
  225728. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  225729. }
  225730. else if (iter.isSectionHeader)
  225731. {
  225732. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  225733. action: nil
  225734. keyEquivalent: @""];
  225735. [item setEnabled: false];
  225736. }
  225737. else if (iter.subMenu != 0)
  225738. {
  225739. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  225740. action: nil
  225741. keyEquivalent: @""];
  225742. [item setTag: iter.itemId];
  225743. [item setEnabled: iter.isEnabled];
  225744. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  225745. [sub setDelegate: nil];
  225746. [menuToAddTo setSubmenu: sub forItem: item];
  225747. }
  225748. else
  225749. {
  225750. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  225751. action: @selector (menuItemInvoked:)
  225752. keyEquivalent: @""];
  225753. [item setTag: iter.itemId];
  225754. [item setEnabled: iter.isEnabled];
  225755. [item setState: iter.isTicked ? NSOnState : NSOffState];
  225756. [item setTarget: (id) callback];
  225757. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  225758. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  225759. [item setRepresentedObject: info];
  225760. if (iter.commandManager != 0)
  225761. {
  225762. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  225763. ->getKeyPressesAssignedToCommand (iter.itemId));
  225764. if (keyPresses.size() > 0)
  225765. {
  225766. const KeyPress& kp = keyPresses.getReference(0);
  225767. juce_wchar key = kp.getTextCharacter();
  225768. if (kp.getKeyCode() == KeyPress::backspaceKey)
  225769. key = NSBackspaceCharacter;
  225770. else if (kp.getKeyCode() == KeyPress::deleteKey)
  225771. key = NSDeleteCharacter;
  225772. else if (key == 0)
  225773. key = (juce_wchar) kp.getKeyCode();
  225774. unsigned int mods = 0;
  225775. if (kp.getModifiers().isShiftDown())
  225776. mods |= NSShiftKeyMask;
  225777. if (kp.getModifiers().isCtrlDown())
  225778. mods |= NSControlKeyMask;
  225779. if (kp.getModifiers().isAltDown())
  225780. mods |= NSAlternateKeyMask;
  225781. if (kp.getModifiers().isCommandDown())
  225782. mods |= NSCommandKeyMask;
  225783. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  225784. [item setKeyEquivalentModifierMask: mods];
  225785. }
  225786. }
  225787. }
  225788. }
  225789. JuceMenuCallback* callback;
  225790. private:
  225791. NSMenu* createMenu (const PopupMenu menu,
  225792. const String& menuName,
  225793. const int topLevelMenuId,
  225794. const int topLevelIndex)
  225795. {
  225796. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  225797. [m setAutoenablesItems: false];
  225798. [m setDelegate: callback];
  225799. PopupMenu::MenuItemIterator iter (menu);
  225800. while (iter.next())
  225801. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  225802. [m update];
  225803. return m;
  225804. }
  225805. };
  225806. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  225807. END_JUCE_NAMESPACE
  225808. @implementation JuceMenuCallback
  225809. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  225810. {
  225811. [super init];
  225812. owner = owner_;
  225813. return self;
  225814. }
  225815. - (void) dealloc
  225816. {
  225817. [super dealloc];
  225818. }
  225819. - (void) menuItemInvoked: (id) menu
  225820. {
  225821. NSMenuItem* item = (NSMenuItem*) menu;
  225822. if ([[item representedObject] isKindOfClass: [NSArray class]])
  225823. {
  225824. NSArray* info = (NSArray*) [item representedObject];
  225825. owner->invoke ([item tag],
  225826. (ApplicationCommandManager*) (pointer_sized_int)
  225827. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  225828. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  225829. }
  225830. }
  225831. - (void) menuNeedsUpdate: (NSMenu*) menu;
  225832. {
  225833. if (JuceMainMenuHandler::instance != 0)
  225834. JuceMainMenuHandler::instance->updateMenus();
  225835. }
  225836. @end
  225837. BEGIN_JUCE_NAMESPACE
  225838. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  225839. const PopupMenu* extraItems)
  225840. {
  225841. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  225842. {
  225843. PopupMenu::MenuItemIterator iter (*extraItems);
  225844. while (iter.next())
  225845. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  225846. [menu addItem: [NSMenuItem separatorItem]];
  225847. }
  225848. NSMenuItem* item;
  225849. // Services...
  225850. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  225851. action: nil keyEquivalent: @""];
  225852. [menu addItem: item];
  225853. [item release];
  225854. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  225855. [menu setSubmenu: servicesMenu forItem: item];
  225856. [NSApp setServicesMenu: servicesMenu];
  225857. [servicesMenu release];
  225858. [menu addItem: [NSMenuItem separatorItem]];
  225859. // Hide + Show stuff...
  225860. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  225861. action: @selector (hide:) keyEquivalent: @"h"];
  225862. [item setTarget: NSApp];
  225863. [menu addItem: item];
  225864. [item release];
  225865. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  225866. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  225867. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  225868. [item setTarget: NSApp];
  225869. [menu addItem: item];
  225870. [item release];
  225871. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  225872. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  225873. [item setTarget: NSApp];
  225874. [menu addItem: item];
  225875. [item release];
  225876. [menu addItem: [NSMenuItem separatorItem]];
  225877. // Quit item....
  225878. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  225879. action: @selector (terminate:) keyEquivalent: @"q"];
  225880. [item setTarget: NSApp];
  225881. [menu addItem: item];
  225882. [item release];
  225883. return menu;
  225884. }
  225885. // Since our app has no NIB, this initialises a standard app menu...
  225886. static void rebuildMainMenu (const PopupMenu* extraItems)
  225887. {
  225888. // this can't be used in a plugin!
  225889. jassert (JUCEApplication::getInstance() != 0);
  225890. if (JUCEApplication::getInstance() != 0)
  225891. {
  225892. const ScopedAutoReleasePool pool;
  225893. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  225894. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  225895. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  225896. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  225897. [mainMenu setSubmenu: appMenu forItem: item];
  225898. [NSApp setMainMenu: mainMenu];
  225899. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  225900. [appMenu release];
  225901. [mainMenu release];
  225902. }
  225903. }
  225904. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  225905. const PopupMenu* extraAppleMenuItems) throw()
  225906. {
  225907. if (getMacMainMenu() != newMenuBarModel)
  225908. {
  225909. const ScopedAutoReleasePool pool;
  225910. if (newMenuBarModel == 0)
  225911. {
  225912. delete JuceMainMenuHandler::instance;
  225913. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  225914. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  225915. extraAppleMenuItems = 0;
  225916. }
  225917. else
  225918. {
  225919. if (JuceMainMenuHandler::instance == 0)
  225920. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  225921. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  225922. }
  225923. }
  225924. rebuildMainMenu (extraAppleMenuItems);
  225925. if (newMenuBarModel != 0)
  225926. newMenuBarModel->menuItemsChanged();
  225927. }
  225928. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  225929. {
  225930. return JuceMainMenuHandler::instance != 0
  225931. ? JuceMainMenuHandler::instance->currentModel : 0;
  225932. }
  225933. void initialiseMainMenu()
  225934. {
  225935. if (JUCEApplication::getInstance() != 0) // only needed in an app
  225936. rebuildMainMenu (0);
  225937. }
  225938. #endif
  225939. /********* End of inlined file: juce_mac_MainMenu.mm *********/
  225940. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  225941. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225942. // compiled on its own).
  225943. #if JUCE_INCLUDED_FILE
  225944. #if JUCE_MAC
  225945. END_JUCE_NAMESPACE
  225946. using namespace JUCE_NAMESPACE;
  225947. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  225948. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225949. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  225950. #else
  225951. @interface JuceFileChooserDelegate : NSObject
  225952. #endif
  225953. {
  225954. StringArray* filters;
  225955. }
  225956. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  225957. - (void) dealloc;
  225958. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  225959. @end
  225960. @implementation JuceFileChooserDelegate
  225961. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  225962. {
  225963. [super init];
  225964. filters = filters_;
  225965. return self;
  225966. }
  225967. - (void) dealloc
  225968. {
  225969. delete filters;
  225970. [super dealloc];
  225971. }
  225972. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  225973. {
  225974. const String fname (nsStringToJuce (filename));
  225975. for (int i = filters->size(); --i >= 0;)
  225976. if (fname.matchesWildcard ((*filters)[i], true))
  225977. return true;
  225978. return File (fname).isDirectory();
  225979. }
  225980. @end
  225981. BEGIN_JUCE_NAMESPACE
  225982. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  225983. const String& title,
  225984. const File& currentFileOrDirectory,
  225985. const String& filter,
  225986. bool selectsDirectory,
  225987. bool isSaveDialogue,
  225988. bool warnAboutOverwritingExistingFiles,
  225989. bool selectMultipleFiles,
  225990. FilePreviewComponent* extraInfoComponent)
  225991. {
  225992. const ScopedAutoReleasePool pool;
  225993. StringArray* filters = new StringArray();
  225994. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  225995. filters->trim();
  225996. filters->removeEmptyStrings();
  225997. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  225998. [delegate autorelease];
  225999. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226000. : [NSOpenPanel openPanel];
  226001. [panel setTitle: juceStringToNS (title)];
  226002. if (! isSaveDialogue)
  226003. {
  226004. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226005. [openPanel setCanChooseDirectories: selectsDirectory];
  226006. [openPanel setCanChooseFiles: ! selectsDirectory];
  226007. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226008. }
  226009. [panel setDelegate: delegate];
  226010. String directory, filename;
  226011. if (currentFileOrDirectory.isDirectory())
  226012. {
  226013. directory = currentFileOrDirectory.getFullPathName();
  226014. }
  226015. else
  226016. {
  226017. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226018. filename = currentFileOrDirectory.getFileName();
  226019. }
  226020. if ([panel runModalForDirectory: juceStringToNS (directory)
  226021. file: juceStringToNS (filename)]
  226022. == NSOKButton)
  226023. {
  226024. if (isSaveDialogue)
  226025. {
  226026. results.add (new File (nsStringToJuce ([panel filename])));
  226027. }
  226028. else
  226029. {
  226030. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226031. NSArray* urls = [openPanel filenames];
  226032. for (unsigned int i = 0; i < [urls count]; ++i)
  226033. {
  226034. NSString* f = [urls objectAtIndex: i];
  226035. results.add (new File (nsStringToJuce (f)));
  226036. }
  226037. }
  226038. }
  226039. [panel setDelegate: nil];
  226040. }
  226041. #else
  226042. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  226043. const String& title,
  226044. const File& currentFileOrDirectory,
  226045. const String& filter,
  226046. bool selectsDirectory,
  226047. bool isSaveDialogue,
  226048. bool warnAboutOverwritingExistingFiles,
  226049. bool selectMultipleFiles,
  226050. FilePreviewComponent* extraInfoComponent)
  226051. {
  226052. const ScopedAutoReleasePool pool;
  226053. jassertfalse //xxx to do
  226054. }
  226055. #endif
  226056. #endif
  226057. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  226058. /********* Start of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  226059. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226060. // compiled on its own).
  226061. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  226062. #define theMovie ((QTMovie*) movie)
  226063. QuickTimeMovieComponent::QuickTimeMovieComponent()
  226064. : movie (0)
  226065. {
  226066. setOpaque (true);
  226067. setVisible (true);
  226068. QTMovieView* view = [[QTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  226069. setView (view);
  226070. }
  226071. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  226072. {
  226073. closeMovie();
  226074. setView (0);
  226075. }
  226076. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  226077. {
  226078. return true;
  226079. }
  226080. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  226081. {
  226082. // unfortunately, QTMovie objects can only be created on the main thread..
  226083. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  226084. QTMovie* movie = 0;
  226085. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  226086. if (fin != 0)
  226087. {
  226088. movieFile = fin->getFile();
  226089. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  226090. error: nil];
  226091. }
  226092. else
  226093. {
  226094. MemoryBlock temp;
  226095. movieStream->readIntoMemoryBlock (temp);
  226096. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  226097. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  226098. {
  226099. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  226100. length: temp.getSize()]
  226101. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  226102. MIMEType: @""]
  226103. error: nil];
  226104. if (movie != 0)
  226105. break;
  226106. }
  226107. }
  226108. return movie;
  226109. }
  226110. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  226111. const bool controllerVisible)
  226112. {
  226113. closeMovie();
  226114. if (getPeer() == 0)
  226115. {
  226116. // To open a movie, this component must be visible inside a functioning window, so that
  226117. // the QT control can be assigned to the window.
  226118. jassertfalse
  226119. return false;
  226120. }
  226121. movie = openMovieFromStream (movieStream, movieFile);
  226122. [theMovie retain];
  226123. QTMovieView* view = (QTMovieView*) getView();
  226124. [view setMovie: theMovie];
  226125. [view setControllerVisible: controllerVisible];
  226126. setLooping (looping);
  226127. return movie != nil;
  226128. }
  226129. void QuickTimeMovieComponent::closeMovie()
  226130. {
  226131. stop();
  226132. QTMovieView* view = (QTMovieView*) getView();
  226133. [view setMovie: nil];
  226134. [theMovie release];
  226135. movie = 0;
  226136. movieFile = File::nonexistent;
  226137. }
  226138. bool QuickTimeMovieComponent::isMovieOpen() const
  226139. {
  226140. return movie != nil;
  226141. }
  226142. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  226143. {
  226144. return movieFile;
  226145. }
  226146. void QuickTimeMovieComponent::play()
  226147. {
  226148. [theMovie play];
  226149. }
  226150. void QuickTimeMovieComponent::stop()
  226151. {
  226152. [theMovie stop];
  226153. }
  226154. bool QuickTimeMovieComponent::isPlaying() const
  226155. {
  226156. return movie != 0 && [theMovie rate] != 0;
  226157. }
  226158. void QuickTimeMovieComponent::setPosition (const double seconds)
  226159. {
  226160. if (movie != 0)
  226161. {
  226162. QTTime t;
  226163. t.timeValue = (uint64) (100000.0 * seconds);
  226164. t.timeScale = 100000;
  226165. t.flags = 0;
  226166. [theMovie setCurrentTime: t];
  226167. }
  226168. }
  226169. double QuickTimeMovieComponent::getPosition() const
  226170. {
  226171. if (movie == 0)
  226172. return 0.0;
  226173. QTTime t = [theMovie currentTime];
  226174. return t.timeValue / (double) t.timeScale;
  226175. }
  226176. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  226177. {
  226178. [theMovie setRate: newSpeed];
  226179. }
  226180. double QuickTimeMovieComponent::getMovieDuration() const
  226181. {
  226182. if (movie == 0)
  226183. return 0.0;
  226184. QTTime t = [theMovie duration];
  226185. return t.timeValue / (double) t.timeScale;
  226186. }
  226187. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  226188. {
  226189. looping = shouldLoop;
  226190. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  226191. forKey: QTMovieLoopsAttribute];
  226192. }
  226193. bool QuickTimeMovieComponent::isLooping() const
  226194. {
  226195. return looping;
  226196. }
  226197. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  226198. {
  226199. [theMovie setVolume: newVolume];
  226200. }
  226201. float QuickTimeMovieComponent::getMovieVolume() const
  226202. {
  226203. return movie != 0 ? [theMovie volume] : 0.0f;
  226204. }
  226205. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  226206. {
  226207. width = 0;
  226208. height = 0;
  226209. if (movie != 0)
  226210. {
  226211. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  226212. width = s.width;
  226213. height = s.height;
  226214. }
  226215. }
  226216. void QuickTimeMovieComponent::paint (Graphics& g)
  226217. {
  226218. if (movie == 0)
  226219. g.fillAll (Colours::black);
  226220. }
  226221. bool QuickTimeMovieComponent::isControllerVisible() const
  226222. {
  226223. return controllerVisible;
  226224. }
  226225. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  226226. const bool isControllerVisible)
  226227. {
  226228. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  226229. movieFile = movieFile_;
  226230. return ok;
  226231. }
  226232. void QuickTimeMovieComponent::goToStart()
  226233. {
  226234. setPosition (0.0);
  226235. }
  226236. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  226237. const RectanglePlacement& placement)
  226238. {
  226239. int normalWidth, normalHeight;
  226240. getMovieNormalSize (normalWidth, normalHeight);
  226241. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  226242. {
  226243. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  226244. placement.applyTo (x, y, w, h,
  226245. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  226246. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  226247. if (w > 0 && h > 0)
  226248. {
  226249. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  226250. roundDoubleToInt (w), roundDoubleToInt (h));
  226251. }
  226252. }
  226253. else
  226254. {
  226255. setBounds (spaceToFitWithin);
  226256. }
  226257. }
  226258. #if ! (JUCE_MAC && JUCE_64BIT)
  226259. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  226260. {
  226261. if (movieStream == 0)
  226262. return false;
  226263. File file;
  226264. QTMovie* movie = openMovieFromStream (movieStream, file);
  226265. if (movie != nil)
  226266. result = [movie quickTimeMovie];
  226267. return movie != nil;
  226268. }
  226269. #endif
  226270. #endif
  226271. /********* End of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  226272. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  226273. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226274. // compiled on its own).
  226275. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  226276. END_JUCE_NAMESPACE
  226277. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  226278. @interface OpenDiskDevice : NSObject
  226279. {
  226280. DRDevice* device;
  226281. NSMutableArray* tracks;
  226282. }
  226283. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  226284. - (void) dealloc;
  226285. - (bool) isDiskPresent;
  226286. - (int) getNumAvailableAudioBlocks;
  226287. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  226288. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  226289. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  226290. @end
  226291. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  226292. @interface AudioTrackProducer : NSObject
  226293. {
  226294. JUCE_NAMESPACE::AudioSource* source;
  226295. int readPosition, lengthInFrames;
  226296. }
  226297. - (AudioTrackProducer*) init: (int) lengthInFrames;
  226298. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  226299. - (void) dealloc;
  226300. - (void) setupTrackProperties: (DRTrack*) track;
  226301. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  226302. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  226303. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  226304. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  226305. toMedia:(NSDictionary*)mediaInfo;
  226306. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  226307. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  226308. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  226309. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  226310. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  226311. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  226312. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  226313. ioFlags:(uint32_t*)flags;
  226314. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  226315. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  226316. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  226317. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  226318. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  226319. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  226320. ioFlags:(uint32_t*)flags;
  226321. @end
  226322. @implementation OpenDiskDevice
  226323. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  226324. {
  226325. [super init];
  226326. device = device_;
  226327. tracks = [[NSMutableArray alloc] init];
  226328. return self;
  226329. }
  226330. - (void) dealloc
  226331. {
  226332. [tracks release];
  226333. [super dealloc];
  226334. }
  226335. - (bool) isDiskPresent
  226336. {
  226337. return [device isValid]
  226338. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  226339. isEqualTo: DRDeviceMediaStateMediaPresent];
  226340. }
  226341. - (int) getNumAvailableAudioBlocks
  226342. {
  226343. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  226344. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  226345. }
  226346. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  226347. {
  226348. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  226349. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  226350. [p setupTrackProperties: t];
  226351. [tracks addObject: t];
  226352. [t release];
  226353. [p release];
  226354. }
  226355. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  226356. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  226357. {
  226358. DRBurn* burn = [DRBurn burnForDevice: device];
  226359. if (! [device acquireExclusiveAccess])
  226360. {
  226361. *error = "Couldn't open or write to the CD device";
  226362. return;
  226363. }
  226364. [device acquireMediaReservation];
  226365. NSMutableDictionary* d = [[burn properties] mutableCopy];
  226366. [d autorelease];
  226367. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  226368. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  226369. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  226370. forKey: DRBurnCompletionActionKey];
  226371. [burn setProperties: d];
  226372. [burn writeLayout: tracks];
  226373. for (;;)
  226374. {
  226375. JUCE_NAMESPACE::Thread::sleep (300);
  226376. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  226377. if (listener != 0 && listener->audioCDBurnProgress (progress))
  226378. {
  226379. [burn abort];
  226380. *error = "User cancelled the write operation";
  226381. break;
  226382. }
  226383. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  226384. {
  226385. *error = "Write operation failed";
  226386. break;
  226387. }
  226388. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  226389. {
  226390. break;
  226391. }
  226392. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  226393. objectForKey: DRErrorStatusErrorStringKey];
  226394. if ([err length] > 0)
  226395. {
  226396. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  226397. break;
  226398. }
  226399. }
  226400. [device releaseMediaReservation];
  226401. [device releaseExclusiveAccess];
  226402. }
  226403. @end
  226404. @implementation AudioTrackProducer
  226405. - (AudioTrackProducer*) init: (int) lengthInFrames_
  226406. {
  226407. lengthInFrames = lengthInFrames_;
  226408. readPosition = 0;
  226409. return self;
  226410. }
  226411. - (void) setupTrackProperties: (DRTrack*) track
  226412. {
  226413. NSMutableDictionary* p = [[track properties] mutableCopy];
  226414. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  226415. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  226416. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  226417. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  226418. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  226419. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  226420. [track setProperties: p];
  226421. [p release];
  226422. }
  226423. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  226424. {
  226425. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  226426. if (s != nil)
  226427. s->source = source_;
  226428. return s;
  226429. }
  226430. - (void) dealloc
  226431. {
  226432. if (source != 0)
  226433. {
  226434. source->releaseResources();
  226435. delete source;
  226436. }
  226437. [super dealloc];
  226438. }
  226439. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  226440. {
  226441. }
  226442. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  226443. {
  226444. return true;
  226445. }
  226446. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  226447. {
  226448. return lengthInFrames;
  226449. }
  226450. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  226451. toMedia: (NSDictionary*) mediaInfo
  226452. {
  226453. if (source != 0)
  226454. source->prepareToPlay (44100 / 75, 44100);
  226455. readPosition = 0;
  226456. return true;
  226457. }
  226458. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  226459. {
  226460. if (source != 0)
  226461. source->prepareToPlay (44100 / 75, 44100);
  226462. return true;
  226463. }
  226464. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  226465. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  226466. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  226467. {
  226468. if (source != 0)
  226469. {
  226470. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  226471. if (numSamples > 0)
  226472. {
  226473. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  226474. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  226475. info.buffer = &tempBuffer;
  226476. info.startSample = 0;
  226477. info.numSamples = numSamples;
  226478. source->getNextAudioBlock (info);
  226479. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  226480. buffer, numSamples, 4);
  226481. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  226482. buffer + 2, numSamples, 4);
  226483. readPosition += numSamples;
  226484. }
  226485. return numSamples * 4;
  226486. }
  226487. return 0;
  226488. }
  226489. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  226490. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  226491. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  226492. ioFlags: (uint32_t*) flags
  226493. {
  226494. zeromem (buffer, bufferLength);
  226495. return bufferLength;
  226496. }
  226497. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  226498. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  226499. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  226500. {
  226501. return true;
  226502. }
  226503. @end
  226504. BEGIN_JUCE_NAMESPACE
  226505. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  226506. : internal (0)
  226507. {
  226508. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  226509. internal = (void*) dev;
  226510. }
  226511. AudioCDBurner::~AudioCDBurner()
  226512. {
  226513. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226514. if (dev != 0)
  226515. [dev release];
  226516. }
  226517. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  226518. {
  226519. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  226520. if (b->internal == 0)
  226521. deleteAndZero (b);
  226522. return b;
  226523. }
  226524. static NSArray* findDiskBurnerDevices()
  226525. {
  226526. NSMutableArray* results = [NSMutableArray array];
  226527. NSArray* devs = [DRDevice devices];
  226528. if (devs != 0)
  226529. {
  226530. int num = [devs count];
  226531. int i;
  226532. for (i = 0; i < num; ++i)
  226533. {
  226534. NSDictionary* dic = [[devs objectAtIndex: i] info];
  226535. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  226536. if (name != nil)
  226537. [results addObject: name];
  226538. }
  226539. }
  226540. return results;
  226541. }
  226542. const StringArray AudioCDBurner::findAvailableDevices()
  226543. {
  226544. NSArray* names = findDiskBurnerDevices();
  226545. StringArray s;
  226546. for (unsigned int i = 0; i < [names count]; ++i)
  226547. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  226548. return s;
  226549. }
  226550. bool AudioCDBurner::isDiskPresent() const
  226551. {
  226552. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226553. return dev != 0 && [dev isDiskPresent];
  226554. }
  226555. int AudioCDBurner::getNumAvailableAudioBlocks() const
  226556. {
  226557. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226558. return [dev getNumAvailableAudioBlocks];
  226559. }
  226560. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  226561. {
  226562. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226563. if (dev != 0)
  226564. {
  226565. [dev addSourceTrack: source numSamples: numSamps];
  226566. return true;
  226567. }
  226568. return false;
  226569. }
  226570. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  226571. const bool ejectDiscAfterwards,
  226572. const bool peformFakeBurnForTesting)
  226573. {
  226574. String error ("Couldn't open or write to the CD device");
  226575. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  226576. if (dev != 0)
  226577. {
  226578. error = String::empty;
  226579. [dev burn: listener
  226580. errorString: &error
  226581. ejectAfterwards: ejectDiscAfterwards
  226582. isFake: peformFakeBurnForTesting];
  226583. }
  226584. return error;
  226585. }
  226586. void AudioCDReader::ejectDisk()
  226587. {
  226588. const ScopedAutoReleasePool p;
  226589. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  226590. }
  226591. #endif
  226592. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  226593. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  226594. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226595. // compiled on its own).
  226596. #if JUCE_INCLUDED_FILE
  226597. class FontHelper
  226598. {
  226599. NSFont* font;
  226600. public:
  226601. String name;
  226602. bool isBold, isItalic, needsItalicTransform;
  226603. float fontSize, totalSize, ascent;
  226604. int refCount;
  226605. NSMutableDictionary* attributes;
  226606. FontHelper (const String& name_,
  226607. const bool bold_,
  226608. const bool italic_,
  226609. const float size_)
  226610. : font (0),
  226611. name (name_),
  226612. isBold (bold_),
  226613. isItalic (italic_),
  226614. needsItalicTransform (false),
  226615. fontSize (size_),
  226616. refCount (1)
  226617. {
  226618. attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  226619. forKey: NSLigatureAttributeName] retain];
  226620. font = [NSFont fontWithName: juceStringToNS (name_) size: size_];
  226621. if (italic_)
  226622. {
  226623. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  226624. if (newFont == font)
  226625. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226626. font = newFont;
  226627. }
  226628. if (bold_)
  226629. font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  226630. [font retain];
  226631. ascent = fabsf ([font ascender]);
  226632. totalSize = ascent + fabsf ([font descender]);
  226633. }
  226634. ~FontHelper()
  226635. {
  226636. [font release];
  226637. [attributes release];
  226638. }
  226639. bool getPathAndKerning (const juce_wchar char1,
  226640. const juce_wchar char2,
  226641. Path* path,
  226642. float& kerning,
  226643. float* ascent,
  226644. float* descent)
  226645. {
  226646. const ScopedAutoReleasePool pool;
  226647. if (font == 0
  226648. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  226649. return false;
  226650. String chars;
  226651. chars << ' ' << char1 << char2;
  226652. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  226653. attributes: attributes] autorelease];
  226654. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  226655. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  226656. [layoutManager addTextContainer: textContainer];
  226657. [textStorage addLayoutManager: layoutManager];
  226658. [textStorage setFont: font];
  226659. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  226660. actualCharacterRange: 0].location;
  226661. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  226662. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  226663. kerning = p2.x - p1.x;
  226664. if (ascent != 0)
  226665. *ascent = this->ascent;
  226666. if (descent != 0)
  226667. *descent = fabsf ([font descender]);
  226668. if (path != 0)
  226669. {
  226670. NSBezierPath* bez = [NSBezierPath bezierPath];
  226671. [bez moveToPoint: NSMakePoint (0, 0)];
  226672. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  226673. inFont: font];
  226674. for (int i = 0; i < [bez elementCount]; ++i)
  226675. {
  226676. NSPoint p[3];
  226677. switch ([bez elementAtIndex: i associatedPoints: p])
  226678. {
  226679. case NSMoveToBezierPathElement:
  226680. path->startNewSubPath (p[0].x, -p[0].y);
  226681. break;
  226682. case NSLineToBezierPathElement:
  226683. path->lineTo (p[0].x, -p[0].y);
  226684. break;
  226685. case NSCurveToBezierPathElement:
  226686. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  226687. break;
  226688. case NSClosePathBezierPathElement:
  226689. path->closeSubPath();
  226690. break;
  226691. default:
  226692. jassertfalse
  226693. break;
  226694. }
  226695. }
  226696. if (needsItalicTransform)
  226697. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  226698. }
  226699. return kerning != 0;
  226700. }
  226701. juce_wchar getDefaultChar()
  226702. {
  226703. return 0;
  226704. }
  226705. };
  226706. class FontHelperCache : public Timer,
  226707. public DeletedAtShutdown
  226708. {
  226709. VoidArray cache;
  226710. public:
  226711. FontHelperCache()
  226712. {
  226713. }
  226714. ~FontHelperCache()
  226715. {
  226716. for (int i = cache.size(); --i >= 0;)
  226717. {
  226718. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  226719. delete f;
  226720. }
  226721. clearSingletonInstance();
  226722. }
  226723. FontHelper* getFont (const String& name,
  226724. const bool bold,
  226725. const bool italic,
  226726. const float size = 1024)
  226727. {
  226728. for (int i = cache.size(); --i >= 0;)
  226729. {
  226730. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  226731. if (f->name == name
  226732. && f->isBold == bold
  226733. && f->isItalic == italic
  226734. && f->fontSize == size)
  226735. {
  226736. f->refCount++;
  226737. return f;
  226738. }
  226739. }
  226740. FontHelper* const f = new FontHelper (name, bold, italic, size);
  226741. cache.add (f);
  226742. return f;
  226743. }
  226744. void releaseFont (FontHelper* f)
  226745. {
  226746. for (int i = cache.size(); --i >= 0;)
  226747. {
  226748. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  226749. if (f == f2)
  226750. {
  226751. f->refCount--;
  226752. if (f->refCount == 0)
  226753. startTimer (5000);
  226754. break;
  226755. }
  226756. }
  226757. }
  226758. void timerCallback()
  226759. {
  226760. stopTimer();
  226761. for (int i = cache.size(); --i >= 0;)
  226762. {
  226763. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  226764. if (f->refCount == 0)
  226765. {
  226766. cache.remove (i);
  226767. delete f;
  226768. }
  226769. }
  226770. if (cache.size() == 0)
  226771. delete this;
  226772. }
  226773. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  226774. };
  226775. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  226776. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  226777. bool bold,
  226778. bool italic,
  226779. bool addAllGlyphsToFont) throw()
  226780. {
  226781. // This method is only safe to be called from the normal UI thread..
  226782. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  226783. FontHelper* const helper = FontHelperCache::getInstance()
  226784. ->getFont (fontName, bold, italic);
  226785. clear();
  226786. setAscent (helper->ascent / helper->totalSize);
  226787. setName (fontName);
  226788. setDefaultCharacter (helper->getDefaultChar());
  226789. setBold (bold);
  226790. setItalic (italic);
  226791. if (addAllGlyphsToFont)
  226792. {
  226793. //xxx
  226794. jassertfalse
  226795. }
  226796. FontHelperCache::getInstance()->releaseFont (helper);
  226797. }
  226798. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  226799. {
  226800. // This method is only safe to be called from the normal UI thread..
  226801. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  226802. if (character == 0)
  226803. return false;
  226804. FontHelper* const helper = FontHelperCache::getInstance()
  226805. ->getFont (getName(), isBold(), isItalic());
  226806. Path path;
  226807. float width;
  226808. bool foundOne = false;
  226809. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  226810. {
  226811. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  226812. 1.0f / helper->totalSize));
  226813. addGlyph (character, path, width / helper->totalSize);
  226814. for (int i = 0; i < glyphs.size(); ++i)
  226815. {
  226816. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  226817. float kerning;
  226818. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  226819. {
  226820. kerning = (kerning - width) / helper->totalSize;
  226821. if (kerning != 0)
  226822. addKerningPair (character, g->getCharacter(), kerning);
  226823. }
  226824. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  226825. {
  226826. kerning = kerning / helper->totalSize - g->width;
  226827. if (kerning != 0)
  226828. addKerningPair (g->getCharacter(), character, kerning);
  226829. }
  226830. }
  226831. foundOne = true;
  226832. }
  226833. FontHelperCache::getInstance()->releaseFont (helper);
  226834. return foundOne;
  226835. }
  226836. const StringArray Font::findAllTypefaceNames() throw()
  226837. {
  226838. StringArray names;
  226839. const ScopedAutoReleasePool pool;
  226840. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226841. for (unsigned int i = 0; i < [fonts count]; ++i)
  226842. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226843. names.sort (true);
  226844. return names;
  226845. }
  226846. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  226847. {
  226848. defaultSans = "Lucida Grande";
  226849. defaultSerif = "Times New Roman";
  226850. defaultFixed = "Monaco";
  226851. }
  226852. #endif
  226853. /********* End of inlined file: juce_mac_Fonts.mm *********/
  226854. /********* Start of inlined file: juce_mac_MessageManager.mm *********/
  226855. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226856. // compiled on its own).
  226857. #if JUCE_INCLUDED_FILE
  226858. struct CallbackMessagePayload
  226859. {
  226860. MessageCallbackFunction* function;
  226861. void* parameter;
  226862. void* volatile result;
  226863. bool volatile hasBeenExecuted;
  226864. };
  226865. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  226866. for example having more than one juce plugin loaded into a host, then when a
  226867. method is called, the actual code that runs might actually be in a different module
  226868. than the one you expect... So any calls to library functions or statics that are
  226869. made inside obj-c methods will probably end up getting executed in a different DLL's
  226870. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  226871. To work around this insanity, I'm only allowing obj-c methods to make calls to
  226872. virtual methods of an object that's known to live inside the right module's space.
  226873. */
  226874. class AppDelegateRedirector
  226875. {
  226876. public:
  226877. AppDelegateRedirector() {}
  226878. virtual ~AppDelegateRedirector() {}
  226879. virtual NSApplicationTerminateReply shouldTerminate()
  226880. {
  226881. if (JUCEApplication::getInstance() != 0)
  226882. {
  226883. JUCEApplication::getInstance()->systemRequestedQuit();
  226884. return NSTerminateCancel;
  226885. }
  226886. return NSTerminateNow;
  226887. }
  226888. virtual BOOL openFile (const NSString* filename)
  226889. {
  226890. if (JUCEApplication::getInstance() != 0)
  226891. {
  226892. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  226893. return YES;
  226894. }
  226895. return NO;
  226896. }
  226897. virtual void openFiles (NSArray* filenames)
  226898. {
  226899. StringArray files;
  226900. for (unsigned int i = 0; i < [filenames count]; ++i)
  226901. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  226902. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  226903. {
  226904. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  226905. }
  226906. }
  226907. virtual void focusChanged()
  226908. {
  226909. juce_HandleProcessFocusChange();
  226910. }
  226911. virtual void deliverMessage (void* message)
  226912. {
  226913. // no need for an mm lock here - deliverMessage locks it
  226914. MessageManager::getInstance()->deliverMessage (message);
  226915. }
  226916. virtual void performCallback (CallbackMessagePayload* pl)
  226917. {
  226918. pl->result = (*pl->function) (pl->parameter);
  226919. pl->hasBeenExecuted = true;
  226920. }
  226921. virtual void deleteSelf()
  226922. {
  226923. delete this;
  226924. }
  226925. };
  226926. END_JUCE_NAMESPACE
  226927. using namespace JUCE_NAMESPACE;
  226928. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  226929. static int numPendingMessages = 0;
  226930. @interface JuceAppDelegate : NSObject
  226931. {
  226932. @private
  226933. id oldDelegate;
  226934. AppDelegateRedirector* redirector;
  226935. @public
  226936. bool flushingMessages;
  226937. }
  226938. - (JuceAppDelegate*) init;
  226939. - (void) dealloc;
  226940. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  226941. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  226942. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  226943. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  226944. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  226945. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  226946. - (void) customEvent: (id) data;
  226947. - (void) performCallback: (id) info;
  226948. - (void) dummyMethod;
  226949. @end
  226950. @implementation JuceAppDelegate
  226951. - (JuceAppDelegate*) init
  226952. {
  226953. [super init];
  226954. redirector = new AppDelegateRedirector();
  226955. numPendingMessages = 0;
  226956. flushingMessages = false;
  226957. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  226958. if (JUCEApplication::getInstance() != 0)
  226959. {
  226960. oldDelegate = [NSApp delegate];
  226961. [NSApp setDelegate: self];
  226962. }
  226963. else
  226964. {
  226965. oldDelegate = 0;
  226966. [center addObserver: self selector: @selector (applicationDidResignActive:)
  226967. name: NSApplicationDidResignActiveNotification object: NSApp];
  226968. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  226969. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  226970. [center addObserver: self selector: @selector (applicationWillUnhide:)
  226971. name: NSApplicationWillUnhideNotification object: NSApp];
  226972. }
  226973. return self;
  226974. }
  226975. - (void) dealloc
  226976. {
  226977. if (oldDelegate != 0)
  226978. [NSApp setDelegate: oldDelegate];
  226979. redirector->deleteSelf();
  226980. [super dealloc];
  226981. }
  226982. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  226983. {
  226984. return redirector->shouldTerminate();
  226985. }
  226986. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  226987. {
  226988. return redirector->openFile (filename);
  226989. }
  226990. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  226991. {
  226992. return redirector->openFiles (filenames);
  226993. }
  226994. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  226995. {
  226996. redirector->focusChanged();
  226997. }
  226998. - (void) applicationDidResignActive: (NSNotification*) aNotification
  226999. {
  227000. redirector->focusChanged();
  227001. }
  227002. - (void) applicationWillUnhide: (NSNotification*) aNotification
  227003. {
  227004. redirector->focusChanged();
  227005. }
  227006. - (void) customEvent: (id) n
  227007. {
  227008. atomicDecrement (numPendingMessages);
  227009. NSData* data = (NSData*) n;
  227010. void* message = 0;
  227011. [data getBytes: &message length: sizeof (message)];
  227012. [data release];
  227013. if (message != 0 && ! flushingMessages)
  227014. redirector->deliverMessage (message);
  227015. }
  227016. - (void) performCallback: (id) info
  227017. {
  227018. if ([info isKindOfClass: [NSData class]])
  227019. {
  227020. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  227021. if (pl != 0)
  227022. redirector->performCallback (pl);
  227023. }
  227024. else
  227025. {
  227026. jassertfalse // should never get here!
  227027. }
  227028. }
  227029. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  227030. @end
  227031. BEGIN_JUCE_NAMESPACE
  227032. static JuceAppDelegate* juceAppDelegate = 0;
  227033. void MessageManager::runDispatchLoop()
  227034. {
  227035. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  227036. {
  227037. const ScopedAutoReleasePool pool;
  227038. // must only be called by the message thread!
  227039. jassert (isThisTheMessageThread());
  227040. [NSApp run];
  227041. }
  227042. }
  227043. void MessageManager::stopDispatchLoop()
  227044. {
  227045. quitMessagePosted = true;
  227046. [NSApp stop: nil];
  227047. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  227048. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  227049. }
  227050. static bool isEventBlockedByModalComps (NSEvent* e)
  227051. {
  227052. if (Component::getNumCurrentlyModalComponents() == 0)
  227053. return false;
  227054. NSWindow* const w = [e window];
  227055. if (w == 0 || [w worksWhenModal])
  227056. return false;
  227057. bool isKey = false, isInputAttempt = false;
  227058. switch ([e type])
  227059. {
  227060. case NSKeyDown:
  227061. case NSKeyUp:
  227062. isKey = isInputAttempt = true;
  227063. break;
  227064. case NSLeftMouseDown:
  227065. case NSRightMouseDown:
  227066. case NSOtherMouseDown:
  227067. isInputAttempt = true;
  227068. break;
  227069. case NSLeftMouseDragged:
  227070. case NSRightMouseDragged:
  227071. case NSLeftMouseUp:
  227072. case NSRightMouseUp:
  227073. case NSOtherMouseUp:
  227074. case NSOtherMouseDragged:
  227075. if (Component::getComponentUnderMouse() != 0)
  227076. return false;
  227077. break;
  227078. case NSMouseMoved:
  227079. case NSMouseEntered:
  227080. case NSMouseExited:
  227081. case NSCursorUpdate:
  227082. case NSScrollWheel:
  227083. case NSTabletPoint:
  227084. case NSTabletProximity:
  227085. break;
  227086. default:
  227087. return false;
  227088. }
  227089. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  227090. {
  227091. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  227092. NSView* const compView = (NSView*) peer->getNativeHandle();
  227093. if ([compView window] == w)
  227094. {
  227095. if (isKey)
  227096. {
  227097. if (compView == [w firstResponder])
  227098. return false;
  227099. }
  227100. else
  227101. {
  227102. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  227103. [compView bounds]))
  227104. return false;
  227105. }
  227106. }
  227107. }
  227108. if (isInputAttempt)
  227109. {
  227110. if (! [NSApp isActive])
  227111. [NSApp activateIgnoringOtherApps: YES];
  227112. Component* const modal = Component::getCurrentlyModalComponent (0);
  227113. if (modal != 0)
  227114. modal->inputAttemptWhenModal();
  227115. }
  227116. return true;
  227117. }
  227118. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227119. {
  227120. const ScopedAutoReleasePool pool;
  227121. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227122. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227123. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227124. while (! quitMessagePosted)
  227125. {
  227126. const ScopedAutoReleasePool pool;
  227127. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227128. beforeDate: endDate];
  227129. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  227130. untilDate: endDate
  227131. inMode: NSDefaultRunLoopMode
  227132. dequeue: YES];
  227133. if (e != 0 && ! isEventBlockedByModalComps (e))
  227134. [NSApp sendEvent: e];
  227135. if (Time::getMillisecondCounter() >= endTime)
  227136. break;
  227137. }
  227138. return ! quitMessagePosted;
  227139. }
  227140. void MessageManager::doPlatformSpecificInitialisation()
  227141. {
  227142. if (juceAppDelegate == 0)
  227143. juceAppDelegate = [[JuceAppDelegate alloc] init];
  227144. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  227145. // correctly (needed prior to 10.5)
  227146. if (! [NSThread isMultiThreaded])
  227147. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  227148. toTarget: juceAppDelegate
  227149. withObject: nil];
  227150. initialiseMainMenu();
  227151. }
  227152. void MessageManager::doPlatformSpecificShutdown()
  227153. {
  227154. if (juceAppDelegate != 0)
  227155. {
  227156. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  227157. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  227158. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  227159. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  227160. juceAppDelegate->flushingMessages = true;
  227161. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  227162. {
  227163. const ScopedAutoReleasePool pool;
  227164. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227165. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  227166. }
  227167. [juceAppDelegate release];
  227168. juceAppDelegate = 0;
  227169. }
  227170. }
  227171. bool juce_postMessageToSystemQueue (void* message)
  227172. {
  227173. atomicIncrement (numPendingMessages);
  227174. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  227175. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  227176. waitUntilDone: NO];
  227177. return true;
  227178. }
  227179. void MessageManager::broadcastMessage (const String& value) throw()
  227180. {
  227181. }
  227182. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  227183. void* data)
  227184. {
  227185. if (isThisTheMessageThread())
  227186. {
  227187. return (*callback) (data);
  227188. }
  227189. else
  227190. {
  227191. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227192. // deadlock because the message manager is blocked from running, so can never
  227193. // call your function..
  227194. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227195. const ScopedAutoReleasePool pool;
  227196. CallbackMessagePayload cmp;
  227197. cmp.function = callback;
  227198. cmp.parameter = data;
  227199. cmp.result = 0;
  227200. cmp.hasBeenExecuted = false;
  227201. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  227202. withObject: [NSData dataWithBytesNoCopy: &cmp
  227203. length: sizeof (cmp)
  227204. freeWhenDone: NO]
  227205. waitUntilDone: YES];
  227206. return cmp.result;
  227207. }
  227208. }
  227209. #endif
  227210. /********* End of inlined file: juce_mac_MessageManager.mm *********/
  227211. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  227212. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227213. // compiled on its own).
  227214. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227215. #if JUCE_MAC
  227216. END_JUCE_NAMESPACE
  227217. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227218. @interface DownloadClickDetector : NSObject
  227219. {
  227220. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227221. }
  227222. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227223. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227224. request: (NSURLRequest*) request
  227225. frame: (WebFrame*) frame
  227226. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227227. @end
  227228. @implementation DownloadClickDetector
  227229. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227230. {
  227231. [super init];
  227232. ownerComponent = ownerComponent_;
  227233. return self;
  227234. }
  227235. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227236. request: (NSURLRequest*) request
  227237. frame: (WebFrame*) frame
  227238. decisionListener: (id <WebPolicyDecisionListener>) listener
  227239. {
  227240. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227241. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227242. [listener use];
  227243. else
  227244. [listener ignore];
  227245. }
  227246. @end
  227247. BEGIN_JUCE_NAMESPACE
  227248. class WebBrowserComponentInternal : public NSViewComponent
  227249. {
  227250. public:
  227251. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227252. {
  227253. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227254. frameName: @""
  227255. groupName: @""];
  227256. setView (webView);
  227257. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227258. [webView setPolicyDelegate: clickListener];
  227259. }
  227260. ~WebBrowserComponentInternal()
  227261. {
  227262. [webView setPolicyDelegate: nil];
  227263. [clickListener release];
  227264. setView (0);
  227265. }
  227266. void goToURL (const String& url,
  227267. const StringArray* headers,
  227268. const MemoryBlock* postData)
  227269. {
  227270. NSMutableURLRequest* r
  227271. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227272. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227273. timeoutInterval: 30.0];
  227274. if (postData != 0 && postData->getSize() > 0)
  227275. {
  227276. [r setHTTPMethod: @"POST"];
  227277. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227278. length: postData->getSize()]];
  227279. }
  227280. if (headers != 0)
  227281. {
  227282. for (int i = 0; i < headers->size(); ++i)
  227283. {
  227284. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  227285. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  227286. [r setValue: juceStringToNS (headerValue)
  227287. forHTTPHeaderField: juceStringToNS (headerName)];
  227288. }
  227289. }
  227290. stop();
  227291. [[webView mainFrame] loadRequest: r];
  227292. }
  227293. void goBack()
  227294. {
  227295. [webView goBack];
  227296. }
  227297. void goForward()
  227298. {
  227299. [webView goForward];
  227300. }
  227301. void stop()
  227302. {
  227303. [webView stopLoading: nil];
  227304. }
  227305. void refresh()
  227306. {
  227307. [webView reload: nil];
  227308. }
  227309. private:
  227310. WebView* webView;
  227311. DownloadClickDetector* clickListener;
  227312. };
  227313. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227314. : browser (0),
  227315. blankPageShown (false),
  227316. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227317. {
  227318. setOpaque (true);
  227319. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227320. }
  227321. WebBrowserComponent::~WebBrowserComponent()
  227322. {
  227323. deleteAndZero (browser);
  227324. }
  227325. void WebBrowserComponent::goToURL (const String& url,
  227326. const StringArray* headers,
  227327. const MemoryBlock* postData)
  227328. {
  227329. lastURL = url;
  227330. lastHeaders.clear();
  227331. if (headers != 0)
  227332. lastHeaders = *headers;
  227333. lastPostData.setSize (0);
  227334. if (postData != 0)
  227335. lastPostData = *postData;
  227336. blankPageShown = false;
  227337. browser->goToURL (url, headers, postData);
  227338. }
  227339. void WebBrowserComponent::stop()
  227340. {
  227341. browser->stop();
  227342. }
  227343. void WebBrowserComponent::goBack()
  227344. {
  227345. lastURL = String::empty;
  227346. blankPageShown = false;
  227347. browser->goBack();
  227348. }
  227349. void WebBrowserComponent::goForward()
  227350. {
  227351. lastURL = String::empty;
  227352. browser->goForward();
  227353. }
  227354. void WebBrowserComponent::refresh()
  227355. {
  227356. browser->refresh();
  227357. }
  227358. void WebBrowserComponent::paint (Graphics& g)
  227359. {
  227360. }
  227361. void WebBrowserComponent::checkWindowAssociation()
  227362. {
  227363. if (isShowing())
  227364. {
  227365. if (blankPageShown)
  227366. goBack();
  227367. }
  227368. else
  227369. {
  227370. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227371. {
  227372. // when the component becomes invisible, some stuff like flash
  227373. // carries on playing audio, so we need to force it onto a blank
  227374. // page to avoid this, (and send it back when it's made visible again).
  227375. blankPageShown = true;
  227376. browser->goToURL ("about:blank", 0, 0);
  227377. }
  227378. }
  227379. }
  227380. void WebBrowserComponent::reloadLastURL()
  227381. {
  227382. if (lastURL.isNotEmpty())
  227383. {
  227384. goToURL (lastURL, &lastHeaders, &lastPostData);
  227385. lastURL = String::empty;
  227386. }
  227387. }
  227388. void WebBrowserComponent::parentHierarchyChanged()
  227389. {
  227390. checkWindowAssociation();
  227391. }
  227392. void WebBrowserComponent::resized()
  227393. {
  227394. browser->setSize (getWidth(), getHeight());
  227395. }
  227396. void WebBrowserComponent::visibilityChanged()
  227397. {
  227398. checkWindowAssociation();
  227399. }
  227400. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227401. {
  227402. return true;
  227403. }
  227404. #else
  227405. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227406. {
  227407. }
  227408. WebBrowserComponent::~WebBrowserComponent()
  227409. {
  227410. }
  227411. void WebBrowserComponent::goToURL (const String& url,
  227412. const StringArray* headers,
  227413. const MemoryBlock* postData)
  227414. {
  227415. }
  227416. void WebBrowserComponent::stop()
  227417. {
  227418. }
  227419. void WebBrowserComponent::goBack()
  227420. {
  227421. }
  227422. void WebBrowserComponent::goForward()
  227423. {
  227424. }
  227425. void WebBrowserComponent::refresh()
  227426. {
  227427. }
  227428. void WebBrowserComponent::paint (Graphics& g)
  227429. {
  227430. }
  227431. void WebBrowserComponent::checkWindowAssociation()
  227432. {
  227433. }
  227434. void WebBrowserComponent::reloadLastURL()
  227435. {
  227436. }
  227437. void WebBrowserComponent::parentHierarchyChanged()
  227438. {
  227439. }
  227440. void WebBrowserComponent::resized()
  227441. {
  227442. }
  227443. void WebBrowserComponent::visibilityChanged()
  227444. {
  227445. }
  227446. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227447. {
  227448. return true;
  227449. }
  227450. #endif
  227451. #endif
  227452. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  227453. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  227454. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227455. // compiled on its own).
  227456. #if JUCE_INCLUDED_FILE
  227457. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  227458. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  227459. #endif
  227460. #undef log
  227461. #if JUCE_COREAUDIO_LOGGING_ENABLED
  227462. #define log(a) Logger::writeToLog (a)
  227463. #else
  227464. #define log(a)
  227465. #endif
  227466. #undef OK
  227467. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  227468. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  227469. {
  227470. if (err == noErr)
  227471. return true;
  227472. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  227473. jassertfalse
  227474. return false;
  227475. }
  227476. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  227477. #else
  227478. #define OK(a) (a == noErr)
  227479. #endif
  227480. class CoreAudioInternal : public Timer
  227481. {
  227482. public:
  227483. CoreAudioInternal (AudioDeviceID id)
  227484. : inputLatency (0),
  227485. outputLatency (0),
  227486. callback (0),
  227487. #if ! MACOS_10_4_OR_EARLIER
  227488. audioProcID (0),
  227489. #endif
  227490. inputDevice (0),
  227491. isSlaveDevice (false),
  227492. deviceID (id),
  227493. started (false),
  227494. sampleRate (0),
  227495. bufferSize (512),
  227496. audioBuffer (0),
  227497. numInputChans (0),
  227498. numOutputChans (0),
  227499. callbacksAllowed (true),
  227500. numInputChannelInfos (0),
  227501. numOutputChannelInfos (0),
  227502. tempInputBuffers (0),
  227503. tempOutputBuffers (0),
  227504. inputChannelInfo (0),
  227505. outputChannelInfo (0)
  227506. {
  227507. jassert (deviceID != 0);
  227508. updateDetailsFromDevice();
  227509. AudioObjectPropertyAddress pa;
  227510. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  227511. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227512. pa.mElement = kAudioObjectPropertyElementWildcard;
  227513. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  227514. }
  227515. ~CoreAudioInternal()
  227516. {
  227517. AudioObjectPropertyAddress pa;
  227518. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  227519. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227520. pa.mElement = kAudioObjectPropertyElementWildcard;
  227521. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  227522. stop (false);
  227523. delete inputDevice;
  227524. juce_free (audioBuffer);
  227525. juce_free (tempInputBuffers);
  227526. juce_free (tempOutputBuffers);
  227527. juce_free (inputChannelInfo);
  227528. juce_free (outputChannelInfo);
  227529. }
  227530. void allocateTempBuffers()
  227531. {
  227532. const int tempBufSize = bufferSize + 4;
  227533. juce_free (audioBuffer);
  227534. audioBuffer = (float*) juce_calloc ((numInputChans + numOutputChans) * tempBufSize * sizeof (float));
  227535. juce_free (tempInputBuffers);
  227536. tempInputBuffers = (float**) juce_calloc (sizeof (float*) * (numInputChans + 2));
  227537. juce_free (tempOutputBuffers);
  227538. tempOutputBuffers = (float**) juce_calloc (sizeof (float*) * (numOutputChans + 2));
  227539. int i, count = 0;
  227540. for (i = 0; i < numInputChans; ++i)
  227541. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  227542. for (i = 0; i < numOutputChans; ++i)
  227543. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  227544. }
  227545. // returns the number of actual available channels
  227546. void fillInChannelInfo (const bool input)
  227547. {
  227548. int chanNum = 0;
  227549. UInt32 size;
  227550. AudioObjectPropertyAddress pa;
  227551. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  227552. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227553. pa.mElement = kAudioObjectPropertyElementMaster;
  227554. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227555. {
  227556. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  227557. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  227558. {
  227559. const int numStreams = bufList->mNumberBuffers;
  227560. for (int i = 0; i < numStreams; ++i)
  227561. {
  227562. const AudioBuffer& b = bufList->mBuffers[i];
  227563. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  227564. {
  227565. String name;
  227566. {
  227567. uint8 channelName [256];
  227568. zerostruct (channelName);
  227569. UInt32 nameSize = sizeof (channelName);
  227570. UInt32 channelNum = chanNum + 1;
  227571. pa.mSelector = kAudioDevicePropertyChannelName;
  227572. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  227573. name = String::fromUTF8 (channelName, nameSize);
  227574. }
  227575. if (input)
  227576. {
  227577. if (activeInputChans[chanNum])
  227578. {
  227579. inputChannelInfo [numInputChannelInfos].streamNum = i;
  227580. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  227581. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  227582. ++numInputChannelInfos;
  227583. }
  227584. if (name.isEmpty())
  227585. name << "Input " << (chanNum + 1);
  227586. inChanNames.add (name);
  227587. }
  227588. else
  227589. {
  227590. if (activeOutputChans[chanNum])
  227591. {
  227592. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  227593. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  227594. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  227595. ++numOutputChannelInfos;
  227596. }
  227597. if (name.isEmpty())
  227598. name << "Output " << (chanNum + 1);
  227599. outChanNames.add (name);
  227600. }
  227601. ++chanNum;
  227602. }
  227603. }
  227604. }
  227605. juce_free (bufList);
  227606. }
  227607. }
  227608. void updateDetailsFromDevice()
  227609. {
  227610. stopTimer();
  227611. if (deviceID == 0)
  227612. return;
  227613. const ScopedLock sl (callbackLock);
  227614. Float64 sr;
  227615. UInt32 size = sizeof (Float64);
  227616. AudioObjectPropertyAddress pa;
  227617. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  227618. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227619. pa.mElement = kAudioObjectPropertyElementMaster;
  227620. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  227621. sampleRate = sr;
  227622. UInt32 framesPerBuf;
  227623. size = sizeof (framesPerBuf);
  227624. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  227625. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  227626. {
  227627. bufferSize = framesPerBuf;
  227628. allocateTempBuffers();
  227629. }
  227630. bufferSizes.clear();
  227631. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  227632. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227633. {
  227634. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  227635. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  227636. {
  227637. bufferSizes.add ((int) ranges[0].mMinimum);
  227638. for (int i = 32; i < 8192; i += 32)
  227639. {
  227640. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  227641. {
  227642. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  227643. {
  227644. bufferSizes.addIfNotAlreadyThere (i);
  227645. break;
  227646. }
  227647. }
  227648. }
  227649. if (bufferSize > 0)
  227650. bufferSizes.addIfNotAlreadyThere (bufferSize);
  227651. }
  227652. juce_free (ranges);
  227653. }
  227654. if (bufferSizes.size() == 0 && bufferSize > 0)
  227655. bufferSizes.add (bufferSize);
  227656. sampleRates.clear();
  227657. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  227658. String rates;
  227659. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  227660. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  227661. {
  227662. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  227663. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  227664. {
  227665. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  227666. {
  227667. bool ok = false;
  227668. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  227669. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  227670. ok = true;
  227671. if (ok)
  227672. {
  227673. sampleRates.add (possibleRates[i]);
  227674. rates << possibleRates[i] << T(" ");
  227675. }
  227676. }
  227677. }
  227678. juce_free (ranges);
  227679. }
  227680. if (sampleRates.size() == 0 && sampleRate > 0)
  227681. {
  227682. sampleRates.add (sampleRate);
  227683. rates << sampleRate;
  227684. }
  227685. log (T("sr: ") + rates);
  227686. inputLatency = 0;
  227687. outputLatency = 0;
  227688. UInt32 lat;
  227689. size = sizeof (lat);
  227690. pa.mSelector = kAudioDevicePropertyLatency;
  227691. pa.mScope = kAudioDevicePropertyScopeInput;
  227692. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  227693. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  227694. inputLatency = (int) lat;
  227695. pa.mScope = kAudioDevicePropertyScopeOutput;
  227696. size = sizeof (lat);
  227697. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  227698. outputLatency = (int) lat;
  227699. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  227700. inChanNames.clear();
  227701. outChanNames.clear();
  227702. juce_free (inputChannelInfo);
  227703. inputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numInputChans + 2));
  227704. numInputChannelInfos = 0;
  227705. juce_free (outputChannelInfo);
  227706. outputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numOutputChans + 2));
  227707. numOutputChannelInfos = 0;
  227708. fillInChannelInfo (true);
  227709. fillInChannelInfo (false);
  227710. }
  227711. const StringArray getSources (bool input)
  227712. {
  227713. StringArray s;
  227714. int num = 0;
  227715. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  227716. if (types != 0)
  227717. {
  227718. for (int i = 0; i < num; ++i)
  227719. {
  227720. AudioValueTranslation avt;
  227721. char buffer[256];
  227722. avt.mInputData = (void*) &(types[i]);
  227723. avt.mInputDataSize = sizeof (UInt32);
  227724. avt.mOutputData = buffer;
  227725. avt.mOutputDataSize = 256;
  227726. UInt32 transSize = sizeof (avt);
  227727. AudioObjectPropertyAddress pa;
  227728. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  227729. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227730. pa.mElement = kAudioObjectPropertyElementMaster;
  227731. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  227732. {
  227733. DBG (buffer);
  227734. s.add (buffer);
  227735. }
  227736. }
  227737. juce_free (types);
  227738. }
  227739. return s;
  227740. }
  227741. int getCurrentSourceIndex (bool input) const
  227742. {
  227743. OSType currentSourceID = 0;
  227744. UInt32 size = sizeof (currentSourceID);
  227745. int result = -1;
  227746. AudioObjectPropertyAddress pa;
  227747. pa.mSelector = kAudioDevicePropertyDataSource;
  227748. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227749. pa.mElement = kAudioObjectPropertyElementMaster;
  227750. if (deviceID != 0)
  227751. {
  227752. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  227753. {
  227754. int num = 0;
  227755. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  227756. if (types != 0)
  227757. {
  227758. for (int i = 0; i < num; ++i)
  227759. {
  227760. if (types[num] == currentSourceID)
  227761. {
  227762. result = i;
  227763. break;
  227764. }
  227765. }
  227766. juce_free (types);
  227767. }
  227768. }
  227769. }
  227770. return result;
  227771. }
  227772. void setCurrentSourceIndex (int index, bool input)
  227773. {
  227774. if (deviceID != 0)
  227775. {
  227776. int num = 0;
  227777. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  227778. if (types != 0)
  227779. {
  227780. if (((unsigned int) index) < (unsigned int) num)
  227781. {
  227782. AudioObjectPropertyAddress pa;
  227783. pa.mSelector = kAudioDevicePropertyDataSource;
  227784. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  227785. pa.mElement = kAudioObjectPropertyElementMaster;
  227786. OSType typeId = types[index];
  227787. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  227788. }
  227789. juce_free (types);
  227790. }
  227791. }
  227792. }
  227793. const String reopen (const BitArray& inputChannels,
  227794. const BitArray& outputChannels,
  227795. double newSampleRate,
  227796. int bufferSizeSamples)
  227797. {
  227798. String error;
  227799. log ("CoreAudio reopen");
  227800. callbacksAllowed = false;
  227801. stopTimer();
  227802. stop (false);
  227803. activeInputChans = inputChannels;
  227804. activeInputChans.setRange (inChanNames.size(),
  227805. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  227806. false);
  227807. activeOutputChans = outputChannels;
  227808. activeOutputChans.setRange (outChanNames.size(),
  227809. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  227810. false);
  227811. numInputChans = activeInputChans.countNumberOfSetBits();
  227812. numOutputChans = activeOutputChans.countNumberOfSetBits();
  227813. // set sample rate
  227814. AudioObjectPropertyAddress pa;
  227815. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  227816. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227817. pa.mElement = kAudioObjectPropertyElementMaster;
  227818. Float64 sr = newSampleRate;
  227819. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  227820. {
  227821. error = "Couldn't change sample rate";
  227822. }
  227823. else
  227824. {
  227825. // change buffer size
  227826. UInt32 framesPerBuf = bufferSizeSamples;
  227827. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  227828. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  227829. {
  227830. error = "Couldn't change buffer size";
  227831. }
  227832. else
  227833. {
  227834. // Annoyingly, after changing the rate and buffer size, some devices fail to
  227835. // correctly report their new settings until some random time in the future, so
  227836. // after calling updateDetailsFromDevice, we need to manually bodge these values
  227837. // to make sure we're using the correct numbers..
  227838. updateDetailsFromDevice();
  227839. sampleRate = newSampleRate;
  227840. bufferSize = bufferSizeSamples;
  227841. if (sampleRates.size() == 0)
  227842. error = "Device has no available sample-rates";
  227843. else if (bufferSizes.size() == 0)
  227844. error = "Device has no available buffer-sizes";
  227845. else if (inputDevice != 0)
  227846. error = inputDevice->reopen (inputChannels,
  227847. outputChannels,
  227848. newSampleRate,
  227849. bufferSizeSamples);
  227850. }
  227851. }
  227852. callbacksAllowed = true;
  227853. return error;
  227854. }
  227855. bool start (AudioIODeviceCallback* cb)
  227856. {
  227857. if (! started)
  227858. {
  227859. callback = 0;
  227860. if (deviceID != 0)
  227861. {
  227862. #if MACOS_10_4_OR_EARLIER
  227863. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  227864. #else
  227865. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, (void*) this, &audioProcID)))
  227866. #endif
  227867. {
  227868. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  227869. {
  227870. started = true;
  227871. }
  227872. else
  227873. {
  227874. #if MACOS_10_4_OR_EARLIER
  227875. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  227876. #else
  227877. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  227878. audioProcID = 0;
  227879. #endif
  227880. }
  227881. }
  227882. }
  227883. }
  227884. if (started)
  227885. {
  227886. const ScopedLock sl (callbackLock);
  227887. callback = cb;
  227888. }
  227889. if (inputDevice != 0)
  227890. return started && inputDevice->start (cb);
  227891. else
  227892. return started;
  227893. }
  227894. void stop (bool leaveInterruptRunning)
  227895. {
  227896. callbackLock.enter();
  227897. callback = 0;
  227898. callbackLock.exit();
  227899. if (started
  227900. && (deviceID != 0)
  227901. && ! leaveInterruptRunning)
  227902. {
  227903. OK (AudioDeviceStop (deviceID, audioIOProc));
  227904. #if MACOS_10_4_OR_EARLIER
  227905. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  227906. #else
  227907. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  227908. audioProcID = 0;
  227909. #endif
  227910. started = false;
  227911. callbackLock.enter();
  227912. callbackLock.exit();
  227913. // wait until it's definately stopped calling back..
  227914. for (int i = 40; --i >= 0;)
  227915. {
  227916. Thread::sleep (50);
  227917. UInt32 running = 0;
  227918. UInt32 size = sizeof (running);
  227919. AudioObjectPropertyAddress pa;
  227920. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  227921. pa.mScope = kAudioObjectPropertyScopeWildcard;
  227922. pa.mElement = kAudioObjectPropertyElementMaster;
  227923. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  227924. if (running == 0)
  227925. break;
  227926. }
  227927. callbackLock.enter();
  227928. callbackLock.exit();
  227929. }
  227930. if (inputDevice != 0)
  227931. inputDevice->stop (leaveInterruptRunning);
  227932. }
  227933. double getSampleRate() const
  227934. {
  227935. return sampleRate;
  227936. }
  227937. int getBufferSize() const
  227938. {
  227939. return bufferSize;
  227940. }
  227941. void audioCallback (const AudioBufferList* inInputData,
  227942. AudioBufferList* outOutputData)
  227943. {
  227944. int i;
  227945. const ScopedLock sl (callbackLock);
  227946. if (callback != 0)
  227947. {
  227948. if (inputDevice == 0)
  227949. {
  227950. for (i = numInputChans; --i >= 0;)
  227951. {
  227952. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  227953. float* dest = tempInputBuffers [i];
  227954. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  227955. + info.dataOffsetSamples;
  227956. const int stride = info.dataStrideSamples;
  227957. if (stride != 0) // if this is zero, info is invalid
  227958. {
  227959. for (int j = bufferSize; --j >= 0;)
  227960. {
  227961. *dest++ = *src;
  227962. src += stride;
  227963. }
  227964. }
  227965. }
  227966. }
  227967. if (! isSlaveDevice)
  227968. {
  227969. if (inputDevice == 0)
  227970. {
  227971. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  227972. numInputChans,
  227973. tempOutputBuffers,
  227974. numOutputChans,
  227975. bufferSize);
  227976. }
  227977. else
  227978. {
  227979. jassert (inputDevice->bufferSize == bufferSize);
  227980. // Sometimes the two linked devices seem to get their callbacks in
  227981. // parallel, so we need to lock both devices to stop the input data being
  227982. // changed while inside our callback..
  227983. const ScopedLock sl (inputDevice->callbackLock);
  227984. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  227985. inputDevice->numInputChans,
  227986. tempOutputBuffers,
  227987. numOutputChans,
  227988. bufferSize);
  227989. }
  227990. for (i = numOutputChans; --i >= 0;)
  227991. {
  227992. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  227993. const float* src = tempOutputBuffers [i];
  227994. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  227995. + info.dataOffsetSamples;
  227996. const int stride = info.dataStrideSamples;
  227997. if (stride != 0) // if this is zero, info is invalid
  227998. {
  227999. for (int j = bufferSize; --j >= 0;)
  228000. {
  228001. *dest = *src++;
  228002. dest += stride;
  228003. }
  228004. }
  228005. }
  228006. }
  228007. }
  228008. else
  228009. {
  228010. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  228011. {
  228012. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  228013. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  228014. + info.dataOffsetSamples;
  228015. const int stride = info.dataStrideSamples;
  228016. if (stride != 0) // if this is zero, info is invalid
  228017. {
  228018. for (int j = bufferSize; --j >= 0;)
  228019. {
  228020. *dest = 0.0f;
  228021. dest += stride;
  228022. }
  228023. }
  228024. }
  228025. }
  228026. }
  228027. // called by callbacks
  228028. void deviceDetailsChanged()
  228029. {
  228030. if (callbacksAllowed)
  228031. startTimer (100);
  228032. }
  228033. void timerCallback()
  228034. {
  228035. stopTimer();
  228036. log ("CoreAudio device changed callback");
  228037. const double oldSampleRate = sampleRate;
  228038. const int oldBufferSize = bufferSize;
  228039. updateDetailsFromDevice();
  228040. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  228041. {
  228042. callbacksAllowed = false;
  228043. stop (false);
  228044. updateDetailsFromDevice();
  228045. callbacksAllowed = true;
  228046. }
  228047. }
  228048. CoreAudioInternal* getRelatedDevice() const
  228049. {
  228050. UInt32 size = 0;
  228051. CoreAudioInternal* result = 0;
  228052. AudioObjectPropertyAddress pa;
  228053. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  228054. pa.mScope = kAudioObjectPropertyScopeWildcard;
  228055. pa.mElement = kAudioObjectPropertyElementMaster;
  228056. if (deviceID != 0
  228057. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  228058. && size > 0)
  228059. {
  228060. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  228061. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  228062. {
  228063. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  228064. {
  228065. if (devs[i] != deviceID && devs[i] != 0)
  228066. {
  228067. result = new CoreAudioInternal (devs[i]);
  228068. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  228069. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  228070. if (thisIsInput != otherIsInput
  228071. || (inChanNames.size() + outChanNames.size() == 0)
  228072. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  228073. break;
  228074. deleteAndZero (result);
  228075. }
  228076. }
  228077. }
  228078. juce_free (devs);
  228079. }
  228080. return result;
  228081. }
  228082. juce_UseDebuggingNewOperator
  228083. int inputLatency, outputLatency;
  228084. BitArray activeInputChans, activeOutputChans;
  228085. StringArray inChanNames, outChanNames;
  228086. Array <double> sampleRates;
  228087. Array <int> bufferSizes;
  228088. AudioIODeviceCallback* callback;
  228089. #if ! MACOS_10_4_OR_EARLIER
  228090. AudioDeviceIOProcID audioProcID;
  228091. #endif
  228092. CoreAudioInternal* inputDevice;
  228093. bool isSlaveDevice;
  228094. private:
  228095. CriticalSection callbackLock;
  228096. AudioDeviceID deviceID;
  228097. bool started;
  228098. double sampleRate;
  228099. int bufferSize;
  228100. float* audioBuffer;
  228101. int numInputChans, numOutputChans;
  228102. bool callbacksAllowed;
  228103. struct CallbackDetailsForChannel
  228104. {
  228105. int streamNum;
  228106. int dataOffsetSamples;
  228107. int dataStrideSamples;
  228108. };
  228109. int numInputChannelInfos, numOutputChannelInfos;
  228110. CallbackDetailsForChannel* inputChannelInfo;
  228111. CallbackDetailsForChannel* outputChannelInfo;
  228112. float** tempInputBuffers;
  228113. float** tempOutputBuffers;
  228114. CoreAudioInternal (const CoreAudioInternal&);
  228115. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  228116. static OSStatus audioIOProc (AudioDeviceID inDevice,
  228117. const AudioTimeStamp* inNow,
  228118. const AudioBufferList* inInputData,
  228119. const AudioTimeStamp* inInputTime,
  228120. AudioBufferList* outOutputData,
  228121. const AudioTimeStamp* inOutputTime,
  228122. void* device)
  228123. {
  228124. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  228125. return noErr;
  228126. }
  228127. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  228128. {
  228129. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  228130. switch (pa->mSelector)
  228131. {
  228132. case kAudioDevicePropertyBufferSize:
  228133. case kAudioDevicePropertyBufferFrameSize:
  228134. case kAudioDevicePropertyNominalSampleRate:
  228135. case kAudioDevicePropertyStreamFormat:
  228136. case kAudioDevicePropertyDeviceIsAlive:
  228137. intern->deviceDetailsChanged();
  228138. break;
  228139. case kAudioDevicePropertyBufferSizeRange:
  228140. case kAudioDevicePropertyVolumeScalar:
  228141. case kAudioDevicePropertyMute:
  228142. case kAudioDevicePropertyPlayThru:
  228143. case kAudioDevicePropertyDataSource:
  228144. case kAudioDevicePropertyDeviceIsRunning:
  228145. break;
  228146. }
  228147. return noErr;
  228148. }
  228149. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  228150. {
  228151. OSType* types = 0;
  228152. UInt32 size = 0;
  228153. num = 0;
  228154. AudioObjectPropertyAddress pa;
  228155. pa.mSelector = kAudioDevicePropertyDataSources;
  228156. pa.mScope = kAudioObjectPropertyScopeWildcard;
  228157. pa.mElement = kAudioObjectPropertyElementMaster;
  228158. if (deviceID != 0
  228159. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  228160. {
  228161. types = (OSType*) juce_calloc (size);
  228162. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  228163. {
  228164. num = size / sizeof (OSType);
  228165. }
  228166. else
  228167. {
  228168. juce_free (types);
  228169. types = 0;
  228170. }
  228171. }
  228172. return types;
  228173. }
  228174. };
  228175. class CoreAudioIODevice : public AudioIODevice
  228176. {
  228177. public:
  228178. CoreAudioIODevice (const String& deviceName,
  228179. AudioDeviceID inputDeviceId,
  228180. const int inputIndex_,
  228181. AudioDeviceID outputDeviceId,
  228182. const int outputIndex_)
  228183. : AudioIODevice (deviceName, "CoreAudio"),
  228184. inputIndex (inputIndex_),
  228185. outputIndex (outputIndex_),
  228186. isOpen_ (false),
  228187. isStarted (false)
  228188. {
  228189. internal = 0;
  228190. CoreAudioInternal* device = 0;
  228191. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  228192. {
  228193. jassert (inputDeviceId != 0);
  228194. device = new CoreAudioInternal (inputDeviceId);
  228195. }
  228196. else
  228197. {
  228198. device = new CoreAudioInternal (outputDeviceId);
  228199. if (inputDeviceId != 0)
  228200. {
  228201. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  228202. device->inputDevice = secondDevice;
  228203. secondDevice->isSlaveDevice = true;
  228204. }
  228205. }
  228206. internal = device;
  228207. AudioObjectPropertyAddress pa;
  228208. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  228209. pa.mScope = kAudioObjectPropertyScopeWildcard;
  228210. pa.mElement = kAudioObjectPropertyElementWildcard;
  228211. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  228212. }
  228213. ~CoreAudioIODevice()
  228214. {
  228215. AudioObjectPropertyAddress pa;
  228216. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  228217. pa.mScope = kAudioObjectPropertyScopeWildcard;
  228218. pa.mElement = kAudioObjectPropertyElementWildcard;
  228219. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  228220. delete internal;
  228221. }
  228222. const StringArray getOutputChannelNames()
  228223. {
  228224. return internal->outChanNames;
  228225. }
  228226. const StringArray getInputChannelNames()
  228227. {
  228228. if (internal->inputDevice != 0)
  228229. return internal->inputDevice->inChanNames;
  228230. else
  228231. return internal->inChanNames;
  228232. }
  228233. int getNumSampleRates()
  228234. {
  228235. return internal->sampleRates.size();
  228236. }
  228237. double getSampleRate (int index)
  228238. {
  228239. return internal->sampleRates [index];
  228240. }
  228241. int getNumBufferSizesAvailable()
  228242. {
  228243. return internal->bufferSizes.size();
  228244. }
  228245. int getBufferSizeSamples (int index)
  228246. {
  228247. return internal->bufferSizes [index];
  228248. }
  228249. int getDefaultBufferSize()
  228250. {
  228251. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  228252. if (getBufferSizeSamples(i) >= 512)
  228253. return getBufferSizeSamples(i);
  228254. return 512;
  228255. }
  228256. const String open (const BitArray& inputChannels,
  228257. const BitArray& outputChannels,
  228258. double sampleRate,
  228259. int bufferSizeSamples)
  228260. {
  228261. isOpen_ = true;
  228262. if (bufferSizeSamples <= 0)
  228263. bufferSizeSamples = getDefaultBufferSize();
  228264. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  228265. isOpen_ = lastError.isEmpty();
  228266. return lastError;
  228267. }
  228268. void close()
  228269. {
  228270. isOpen_ = false;
  228271. internal->stop (false);
  228272. }
  228273. bool isOpen()
  228274. {
  228275. return isOpen_;
  228276. }
  228277. int getCurrentBufferSizeSamples()
  228278. {
  228279. return internal != 0 ? internal->getBufferSize() : 512;
  228280. }
  228281. double getCurrentSampleRate()
  228282. {
  228283. return internal != 0 ? internal->getSampleRate() : 0;
  228284. }
  228285. int getCurrentBitDepth()
  228286. {
  228287. return 32; // no way to find out, so just assume it's high..
  228288. }
  228289. const BitArray getActiveOutputChannels() const
  228290. {
  228291. return internal != 0 ? internal->activeOutputChans : BitArray();
  228292. }
  228293. const BitArray getActiveInputChannels() const
  228294. {
  228295. BitArray chans;
  228296. if (internal != 0)
  228297. {
  228298. chans = internal->activeInputChans;
  228299. if (internal->inputDevice != 0)
  228300. chans.orWith (internal->inputDevice->activeInputChans);
  228301. }
  228302. return chans;
  228303. }
  228304. int getOutputLatencyInSamples()
  228305. {
  228306. if (internal == 0)
  228307. return 0;
  228308. // this seems like a good guess at getting the latency right - comparing
  228309. // this with a round-trip measurement, it gets it to within a few millisecs
  228310. // for the built-in mac soundcard
  228311. return internal->outputLatency + internal->getBufferSize() * 2;
  228312. }
  228313. int getInputLatencyInSamples()
  228314. {
  228315. if (internal == 0)
  228316. return 0;
  228317. return internal->inputLatency + internal->getBufferSize() * 2;
  228318. }
  228319. void start (AudioIODeviceCallback* callback)
  228320. {
  228321. if (internal != 0 && ! isStarted)
  228322. {
  228323. if (callback != 0)
  228324. callback->audioDeviceAboutToStart (this);
  228325. isStarted = true;
  228326. internal->start (callback);
  228327. }
  228328. }
  228329. void stop()
  228330. {
  228331. if (isStarted && internal != 0)
  228332. {
  228333. AudioIODeviceCallback* const lastCallback = internal->callback;
  228334. isStarted = false;
  228335. internal->stop (true);
  228336. if (lastCallback != 0)
  228337. lastCallback->audioDeviceStopped();
  228338. }
  228339. }
  228340. bool isPlaying()
  228341. {
  228342. if (internal->callback == 0)
  228343. isStarted = false;
  228344. return isStarted;
  228345. }
  228346. const String getLastError()
  228347. {
  228348. return lastError;
  228349. }
  228350. int inputIndex, outputIndex;
  228351. juce_UseDebuggingNewOperator
  228352. private:
  228353. CoreAudioInternal* internal;
  228354. bool isOpen_, isStarted;
  228355. String lastError;
  228356. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  228357. {
  228358. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  228359. switch (pa->mSelector)
  228360. {
  228361. case kAudioHardwarePropertyDevices:
  228362. intern->deviceDetailsChanged();
  228363. break;
  228364. case kAudioHardwarePropertyDefaultOutputDevice:
  228365. case kAudioHardwarePropertyDefaultInputDevice:
  228366. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  228367. break;
  228368. }
  228369. return noErr;
  228370. }
  228371. CoreAudioIODevice (const CoreAudioIODevice&);
  228372. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  228373. };
  228374. class CoreAudioIODeviceType : public AudioIODeviceType
  228375. {
  228376. public:
  228377. CoreAudioIODeviceType()
  228378. : AudioIODeviceType (T("CoreAudio")),
  228379. hasScanned (false)
  228380. {
  228381. }
  228382. ~CoreAudioIODeviceType()
  228383. {
  228384. }
  228385. void scanForDevices()
  228386. {
  228387. hasScanned = true;
  228388. inputDeviceNames.clear();
  228389. outputDeviceNames.clear();
  228390. inputIds.clear();
  228391. outputIds.clear();
  228392. UInt32 size;
  228393. AudioObjectPropertyAddress pa;
  228394. pa.mSelector = kAudioHardwarePropertyDevices;
  228395. pa.mScope = kAudioObjectPropertyScopeWildcard;
  228396. pa.mElement = kAudioObjectPropertyElementMaster;
  228397. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  228398. {
  228399. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  228400. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  228401. {
  228402. static bool alreadyLogged = false;
  228403. const int num = size / sizeof (AudioDeviceID);
  228404. for (int i = 0; i < num; ++i)
  228405. {
  228406. char name [1024];
  228407. size = sizeof (name);
  228408. pa.mSelector = kAudioDevicePropertyDeviceName;
  228409. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  228410. {
  228411. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  228412. if (! alreadyLogged)
  228413. log (T("CoreAudio device: ") + nameString);
  228414. const int numIns = getNumChannels (devs[i], true);
  228415. const int numOuts = getNumChannels (devs[i], false);
  228416. if (numIns > 0)
  228417. {
  228418. inputDeviceNames.add (nameString);
  228419. inputIds.add (devs[i]);
  228420. }
  228421. if (numOuts > 0)
  228422. {
  228423. outputDeviceNames.add (nameString);
  228424. outputIds.add (devs[i]);
  228425. }
  228426. }
  228427. }
  228428. alreadyLogged = true;
  228429. }
  228430. juce_free (devs);
  228431. }
  228432. inputDeviceNames.appendNumbersToDuplicates (false, true);
  228433. outputDeviceNames.appendNumbersToDuplicates (false, true);
  228434. }
  228435. const StringArray getDeviceNames (const bool wantInputNames) const
  228436. {
  228437. jassert (hasScanned); // need to call scanForDevices() before doing this
  228438. if (wantInputNames)
  228439. return inputDeviceNames;
  228440. else
  228441. return outputDeviceNames;
  228442. }
  228443. int getDefaultDeviceIndex (const bool forInput) const
  228444. {
  228445. jassert (hasScanned); // need to call scanForDevices() before doing this
  228446. AudioDeviceID deviceID;
  228447. UInt32 size = sizeof (deviceID);
  228448. // if they're asking for any input channels at all, use the default input, so we
  228449. // get the built-in mic rather than the built-in output with no inputs..
  228450. AudioObjectPropertyAddress pa;
  228451. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  228452. pa.mScope = kAudioObjectPropertyScopeWildcard;
  228453. pa.mElement = kAudioObjectPropertyElementMaster;
  228454. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  228455. {
  228456. if (forInput)
  228457. {
  228458. for (int i = inputIds.size(); --i >= 0;)
  228459. if (inputIds[i] == deviceID)
  228460. return i;
  228461. }
  228462. else
  228463. {
  228464. for (int i = outputIds.size(); --i >= 0;)
  228465. if (outputIds[i] == deviceID)
  228466. return i;
  228467. }
  228468. }
  228469. return 0;
  228470. }
  228471. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  228472. {
  228473. jassert (hasScanned); // need to call scanForDevices() before doing this
  228474. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  228475. if (d == 0)
  228476. return -1;
  228477. return asInput ? d->inputIndex
  228478. : d->outputIndex;
  228479. }
  228480. bool hasSeparateInputsAndOutputs() const { return true; }
  228481. AudioIODevice* createDevice (const String& outputDeviceName,
  228482. const String& inputDeviceName)
  228483. {
  228484. jassert (hasScanned); // need to call scanForDevices() before doing this
  228485. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  228486. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  228487. String deviceName (outputDeviceName);
  228488. if (deviceName.isEmpty())
  228489. deviceName = inputDeviceName;
  228490. if (index >= 0)
  228491. return new CoreAudioIODevice (deviceName,
  228492. inputIds [inputIndex],
  228493. inputIndex,
  228494. outputIds [outputIndex],
  228495. outputIndex);
  228496. return 0;
  228497. }
  228498. juce_UseDebuggingNewOperator
  228499. private:
  228500. StringArray inputDeviceNames, outputDeviceNames;
  228501. Array <AudioDeviceID> inputIds, outputIds;
  228502. bool hasScanned;
  228503. static int getNumChannels (AudioDeviceID deviceID, bool input)
  228504. {
  228505. int total = 0;
  228506. UInt32 size;
  228507. AudioObjectPropertyAddress pa;
  228508. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  228509. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  228510. pa.mElement = kAudioObjectPropertyElementMaster;
  228511. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  228512. {
  228513. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  228514. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  228515. {
  228516. const int numStreams = bufList->mNumberBuffers;
  228517. for (int i = 0; i < numStreams; ++i)
  228518. {
  228519. const AudioBuffer& b = bufList->mBuffers[i];
  228520. total += b.mNumberChannels;
  228521. }
  228522. }
  228523. juce_free (bufList);
  228524. }
  228525. return total;
  228526. }
  228527. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  228528. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  228529. };
  228530. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  228531. {
  228532. return new CoreAudioIODeviceType();
  228533. }
  228534. #undef log
  228535. #endif
  228536. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  228537. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  228538. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228539. // compiled on its own).
  228540. #if JUCE_INCLUDED_FILE
  228541. #if JUCE_MAC
  228542. #undef log
  228543. #define log(a) Logger::writeToLog(a)
  228544. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  228545. {
  228546. if (err == noErr)
  228547. return true;
  228548. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  228549. jassertfalse
  228550. return false;
  228551. }
  228552. #undef OK
  228553. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  228554. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228555. {
  228556. String result;
  228557. CFStringRef str = 0;
  228558. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228559. if (str != 0)
  228560. {
  228561. result = PlatformUtilities::cfStringToJuceString (str);
  228562. CFRelease (str);
  228563. str = 0;
  228564. }
  228565. MIDIEntityRef entity = 0;
  228566. MIDIEndpointGetEntity (endpoint, &entity);
  228567. if (entity == 0)
  228568. return result; // probably virtual
  228569. if (result.isEmpty())
  228570. {
  228571. // endpoint name has zero length - try the entity
  228572. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228573. if (str != 0)
  228574. {
  228575. result += PlatformUtilities::cfStringToJuceString (str);
  228576. CFRelease (str);
  228577. str = 0;
  228578. }
  228579. }
  228580. // now consider the device's name
  228581. MIDIDeviceRef device = 0;
  228582. MIDIEntityGetDevice (entity, &device);
  228583. if (device == 0)
  228584. return result;
  228585. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228586. if (str != 0)
  228587. {
  228588. const String s (PlatformUtilities::cfStringToJuceString (str));
  228589. CFRelease (str);
  228590. // if an external device has only one entity, throw away
  228591. // the endpoint name and just use the device name
  228592. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228593. {
  228594. result = s;
  228595. }
  228596. else if (! result.startsWithIgnoreCase (s))
  228597. {
  228598. // prepend the device name to the entity name
  228599. result = (s + T(" ") + result).trimEnd();
  228600. }
  228601. }
  228602. return result;
  228603. }
  228604. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228605. {
  228606. String result;
  228607. // Does the endpoint have connections?
  228608. CFDataRef connections = 0;
  228609. int numConnections = 0;
  228610. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228611. if (connections != 0)
  228612. {
  228613. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  228614. if (numConnections > 0)
  228615. {
  228616. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228617. for (int i = 0; i < numConnections; ++i, ++pid)
  228618. {
  228619. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228620. MIDIObjectRef connObject;
  228621. MIDIObjectType connObjectType;
  228622. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228623. if (err == noErr)
  228624. {
  228625. String s;
  228626. if (connObjectType == kMIDIObjectType_ExternalSource
  228627. || connObjectType == kMIDIObjectType_ExternalDestination)
  228628. {
  228629. // Connected to an external device's endpoint (10.3 and later).
  228630. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228631. }
  228632. else
  228633. {
  228634. // Connected to an external device (10.2) (or something else, catch-all)
  228635. CFStringRef str = 0;
  228636. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228637. if (str != 0)
  228638. {
  228639. s = PlatformUtilities::cfStringToJuceString (str);
  228640. CFRelease (str);
  228641. }
  228642. }
  228643. if (s.isNotEmpty())
  228644. {
  228645. if (result.isNotEmpty())
  228646. result += (", ");
  228647. result += s;
  228648. }
  228649. }
  228650. }
  228651. }
  228652. CFRelease (connections);
  228653. }
  228654. if (result.isNotEmpty())
  228655. return result;
  228656. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228657. return getEndpointName (endpoint, false);
  228658. }
  228659. const StringArray MidiOutput::getDevices()
  228660. {
  228661. StringArray s;
  228662. const ItemCount num = MIDIGetNumberOfDestinations();
  228663. for (ItemCount i = 0; i < num; ++i)
  228664. {
  228665. MIDIEndpointRef dest = MIDIGetDestination (i);
  228666. if (dest != 0)
  228667. {
  228668. String name (getConnectedEndpointName (dest));
  228669. if (name.isEmpty())
  228670. name = "<error>";
  228671. s.add (name);
  228672. }
  228673. else
  228674. {
  228675. s.add ("<error>");
  228676. }
  228677. }
  228678. return s;
  228679. }
  228680. int MidiOutput::getDefaultDeviceIndex()
  228681. {
  228682. return 0;
  228683. }
  228684. static MIDIClientRef globalMidiClient;
  228685. static bool hasGlobalClientBeenCreated = false;
  228686. static bool makeSureClientExists()
  228687. {
  228688. if (! hasGlobalClientBeenCreated)
  228689. {
  228690. String name (T("JUCE"));
  228691. if (JUCEApplication::getInstance() != 0)
  228692. name = JUCEApplication::getInstance()->getApplicationName();
  228693. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228694. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228695. CFRelease (appName);
  228696. }
  228697. return hasGlobalClientBeenCreated;
  228698. }
  228699. struct MidiPortAndEndpoint
  228700. {
  228701. MIDIPortRef port;
  228702. MIDIEndpointRef endPoint;
  228703. };
  228704. MidiOutput* MidiOutput::openDevice (int index)
  228705. {
  228706. MidiOutput* mo = 0;
  228707. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  228708. {
  228709. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228710. CFStringRef pname;
  228711. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228712. {
  228713. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  228714. if (makeSureClientExists())
  228715. {
  228716. MIDIPortRef port;
  228717. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  228718. {
  228719. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  228720. mpe->port = port;
  228721. mpe->endPoint = endPoint;
  228722. mo = new MidiOutput();
  228723. mo->internal = (void*)mpe;
  228724. }
  228725. }
  228726. CFRelease (pname);
  228727. }
  228728. }
  228729. return mo;
  228730. }
  228731. MidiOutput::~MidiOutput()
  228732. {
  228733. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  228734. MIDIPortDispose (mpe->port);
  228735. delete mpe;
  228736. }
  228737. void MidiOutput::reset()
  228738. {
  228739. }
  228740. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  228741. {
  228742. return false;
  228743. }
  228744. void MidiOutput::setVolume (float leftVol, float rightVol)
  228745. {
  228746. }
  228747. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228748. {
  228749. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  228750. if (message.isSysEx())
  228751. {
  228752. const int maxPacketSize = 256;
  228753. int pos = 0, bytesLeft = message.getRawDataSize();
  228754. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228755. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  228756. packets->numPackets = numPackets;
  228757. MIDIPacket* p = packets->packet;
  228758. for (int i = 0; i < numPackets; ++i)
  228759. {
  228760. p->timeStamp = 0;
  228761. p->length = jmin (maxPacketSize, bytesLeft);
  228762. memcpy (p->data, message.getRawData() + pos, p->length);
  228763. pos += p->length;
  228764. bytesLeft -= p->length;
  228765. p = MIDIPacketNext (p);
  228766. }
  228767. MIDISend (mpe->port, mpe->endPoint, packets);
  228768. juce_free (packets);
  228769. }
  228770. else
  228771. {
  228772. MIDIPacketList packets;
  228773. packets.numPackets = 1;
  228774. packets.packet[0].timeStamp = 0;
  228775. packets.packet[0].length = message.getRawDataSize();
  228776. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228777. MIDISend (mpe->port, mpe->endPoint, &packets);
  228778. }
  228779. }
  228780. const StringArray MidiInput::getDevices()
  228781. {
  228782. StringArray s;
  228783. const ItemCount num = MIDIGetNumberOfSources();
  228784. for (ItemCount i = 0; i < num; ++i)
  228785. {
  228786. MIDIEndpointRef source = MIDIGetSource (i);
  228787. if (source != 0)
  228788. {
  228789. String name (getConnectedEndpointName (source));
  228790. if (name.isEmpty())
  228791. name = "<error>";
  228792. s.add (name);
  228793. }
  228794. else
  228795. {
  228796. s.add ("<error>");
  228797. }
  228798. }
  228799. return s;
  228800. }
  228801. int MidiInput::getDefaultDeviceIndex()
  228802. {
  228803. return 0;
  228804. }
  228805. struct MidiPortAndCallback
  228806. {
  228807. MidiInput* input;
  228808. MIDIPortRef port;
  228809. MIDIEndpointRef endPoint;
  228810. MidiInputCallback* callback;
  228811. MemoryBlock pendingData;
  228812. int pendingBytes;
  228813. double pendingDataTime;
  228814. bool active;
  228815. };
  228816. static CriticalSection callbackLock;
  228817. static VoidArray activeCallbacks;
  228818. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  228819. {
  228820. if (*d == 0xf0)
  228821. {
  228822. mpe->pendingBytes = 0;
  228823. mpe->pendingDataTime = time;
  228824. }
  228825. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  228826. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  228827. uint8* dest = totalMessage + mpe->pendingBytes;
  228828. while (size > 0)
  228829. {
  228830. if (mpe->pendingBytes > 0 && *d >= 0x80)
  228831. {
  228832. if (*d >= 0xfa || *d == 0xf8)
  228833. {
  228834. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  228835. ++d;
  228836. --size;
  228837. }
  228838. else
  228839. {
  228840. if (*d == 0xf7)
  228841. {
  228842. *dest++ = *d++;
  228843. mpe->pendingBytes++;
  228844. --size;
  228845. }
  228846. break;
  228847. }
  228848. }
  228849. else
  228850. {
  228851. *dest++ = *d++;
  228852. mpe->pendingBytes++;
  228853. --size;
  228854. }
  228855. }
  228856. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  228857. {
  228858. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  228859. mpe->pendingBytes,
  228860. mpe->pendingDataTime));
  228861. mpe->pendingBytes = 0;
  228862. }
  228863. else
  228864. {
  228865. mpe->callback->handlePartialSysexMessage (mpe->input,
  228866. totalMessage,
  228867. mpe->pendingBytes,
  228868. mpe->pendingDataTime);
  228869. }
  228870. }
  228871. static void midiInputProc (const MIDIPacketList* pktlist,
  228872. void* readProcRefCon,
  228873. void* srcConnRefCon)
  228874. {
  228875. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228876. const double originalTime = time;
  228877. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  228878. const ScopedLock sl (callbackLock);
  228879. if (activeCallbacks.contains (mpe) && mpe->active)
  228880. {
  228881. const MIDIPacket* packet = &pktlist->packet[0];
  228882. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228883. {
  228884. const uint8* d = (const uint8*) (packet->data);
  228885. int size = packet->length;
  228886. while (size > 0)
  228887. {
  228888. time = originalTime;
  228889. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  228890. {
  228891. processSysex (mpe, d, size, time);
  228892. }
  228893. else
  228894. {
  228895. int used = 0;
  228896. const MidiMessage m (d, size, used, 0, time);
  228897. if (used <= 0)
  228898. {
  228899. jassertfalse // malformed midi message
  228900. break;
  228901. }
  228902. else
  228903. {
  228904. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  228905. }
  228906. size -= used;
  228907. d += used;
  228908. }
  228909. }
  228910. packet = MIDIPacketNext (packet);
  228911. }
  228912. }
  228913. }
  228914. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228915. {
  228916. MidiInput* mi = 0;
  228917. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228918. {
  228919. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228920. if (endPoint != 0)
  228921. {
  228922. CFStringRef pname;
  228923. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228924. {
  228925. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  228926. if (makeSureClientExists())
  228927. {
  228928. MIDIPortRef port;
  228929. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  228930. mpe->active = false;
  228931. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  228932. {
  228933. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228934. {
  228935. mpe->port = port;
  228936. mpe->endPoint = endPoint;
  228937. mpe->callback = callback;
  228938. mpe->pendingBytes = 0;
  228939. mpe->pendingData.ensureSize (128);
  228940. mi = new MidiInput (getDevices() [index]);
  228941. mpe->input = mi;
  228942. mi->internal = (void*) mpe;
  228943. const ScopedLock sl (callbackLock);
  228944. activeCallbacks.add (mpe);
  228945. }
  228946. else
  228947. {
  228948. OK (MIDIPortDispose (port));
  228949. delete mpe;
  228950. }
  228951. }
  228952. else
  228953. {
  228954. delete mpe;
  228955. }
  228956. }
  228957. }
  228958. CFRelease (pname);
  228959. }
  228960. }
  228961. return mi;
  228962. }
  228963. MidiInput::MidiInput (const String& name_)
  228964. : name (name_)
  228965. {
  228966. }
  228967. MidiInput::~MidiInput()
  228968. {
  228969. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  228970. mpe->active = false;
  228971. callbackLock.enter();
  228972. activeCallbacks.removeValue (mpe);
  228973. callbackLock.exit();
  228974. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  228975. OK (MIDIPortDispose (mpe->port));
  228976. delete mpe;
  228977. }
  228978. void MidiInput::start()
  228979. {
  228980. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  228981. const ScopedLock sl (callbackLock);
  228982. mpe->active = true;
  228983. }
  228984. void MidiInput::stop()
  228985. {
  228986. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  228987. const ScopedLock sl (callbackLock);
  228988. mpe->active = false;
  228989. }
  228990. #undef log
  228991. #else
  228992. MidiOutput::~MidiOutput()
  228993. {
  228994. }
  228995. void MidiOutput::reset()
  228996. {
  228997. }
  228998. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  228999. {
  229000. return false;
  229001. }
  229002. void MidiOutput::setVolume (float leftVol, float rightVol)
  229003. {
  229004. }
  229005. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229006. {
  229007. }
  229008. const StringArray MidiOutput::getDevices()
  229009. {
  229010. return StringArray();
  229011. }
  229012. MidiOutput* MidiOutput::openDevice (int index)
  229013. {
  229014. return 0;
  229015. }
  229016. const StringArray MidiInput::getDevices()
  229017. {
  229018. return StringArray();
  229019. }
  229020. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229021. {
  229022. return 0;
  229023. }
  229024. #endif
  229025. #endif
  229026. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  229027. /********* Start of inlined file: juce_mac_CameraDevice.mm *********/
  229028. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229029. // compiled on its own).
  229030. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME && JUCE_USE_CAMERA
  229031. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  229032. class QTCameraDeviceInteral;
  229033. END_JUCE_NAMESPACE
  229034. @interface QTCaptureCallbackDelegate : NSObject
  229035. {
  229036. @public
  229037. CameraDevice* owner;
  229038. QTCameraDeviceInteral* internal;
  229039. Time* firstRecordedTime;
  229040. }
  229041. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  229042. - (void) dealloc;
  229043. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  229044. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  229045. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  229046. fromConnection: (QTCaptureConnection*) connection;
  229047. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  229048. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  229049. fromConnection: (QTCaptureConnection*) connection;
  229050. @end
  229051. BEGIN_JUCE_NAMESPACE
  229052. class QTCameraDeviceInteral
  229053. {
  229054. public:
  229055. QTCameraDeviceInteral (CameraDevice* owner, int index)
  229056. {
  229057. const ScopedAutoReleasePool pool;
  229058. session = [[QTCaptureSession alloc] init];
  229059. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  229060. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  229061. input = 0;
  229062. fileOutput = 0;
  229063. imageOutput = 0;
  229064. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  229065. internalDev: this];
  229066. NSError* err = 0;
  229067. [device retain];
  229068. [device open: &err];
  229069. if (err == 0)
  229070. {
  229071. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  229072. [session addInput: input error: &err];
  229073. if (err == 0)
  229074. {
  229075. resetFile();
  229076. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  229077. [imageOutput setDelegate: callbackDelegate];
  229078. if (err == 0)
  229079. {
  229080. [session startRunning];
  229081. return;
  229082. }
  229083. }
  229084. }
  229085. openingError = nsStringToJuce ([err description]);
  229086. DBG (openingError);
  229087. }
  229088. ~QTCameraDeviceInteral()
  229089. {
  229090. [session stopRunning];
  229091. [session removeOutput: imageOutput];
  229092. [session release];
  229093. [input release];
  229094. [device release];
  229095. [fileOutput release];
  229096. [imageOutput release];
  229097. [callbackDelegate release];
  229098. }
  229099. void resetFile()
  229100. {
  229101. [session removeOutput: fileOutput];
  229102. [fileOutput release];
  229103. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  229104. [fileOutput setDelegate: callbackDelegate];
  229105. }
  229106. void addListener (CameraImageListener* listenerToAdd)
  229107. {
  229108. const ScopedLock sl (listenerLock);
  229109. if (listeners.size() == 0)
  229110. [session addOutput: imageOutput error: nil];
  229111. listeners.addIfNotAlreadyThere (listenerToAdd);
  229112. }
  229113. void removeListener (CameraImageListener* listenerToRemove)
  229114. {
  229115. const ScopedLock sl (listenerLock);
  229116. listeners.removeValue (listenerToRemove);
  229117. if (listeners.size() == 0)
  229118. [session removeOutput: imageOutput];
  229119. }
  229120. static void drawNSBitmapIntoJuceImage (Image& dest, NSBitmapImageRep* source)
  229121. {
  229122. const ScopedAutoReleasePool pool;
  229123. int lineStride, pixelStride;
  229124. uint8* pixels = dest.lockPixelDataReadWrite (0, 0, dest.getWidth(), dest.getHeight(),
  229125. lineStride, pixelStride);
  229126. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  229127. initWithBitmapDataPlanes: &pixels
  229128. pixelsWide: dest.getWidth()
  229129. pixelsHigh: dest.getHeight()
  229130. bitsPerSample: 8
  229131. samplesPerPixel: pixelStride
  229132. hasAlpha: dest.hasAlphaChannel()
  229133. isPlanar: NO
  229134. colorSpaceName: NSCalibratedRGBColorSpace
  229135. bitmapFormat: (NSBitmapFormat) 0
  229136. bytesPerRow: lineStride
  229137. bitsPerPixel: pixelStride * 8];
  229138. [NSGraphicsContext saveGraphicsState];
  229139. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithBitmapImageRep: rep]];
  229140. [source drawAtPoint: NSZeroPoint];
  229141. [[NSGraphicsContext currentContext] flushGraphics];
  229142. [NSGraphicsContext restoreGraphicsState];
  229143. uint8* start = pixels;
  229144. for (int h = dest.getHeight(); --h >= 0;)
  229145. {
  229146. uint8* p = start;
  229147. start += lineStride;
  229148. for (int i = dest.getWidth(); --i >= 0;)
  229149. {
  229150. #if JUCE_BIG_ENDIAN
  229151. const uint8 oldp3 = p[3];
  229152. const uint8 oldp1 = p[1];
  229153. p[3] = p[0];
  229154. p[0] = oldp1;
  229155. p[1] = p[2];
  229156. p[2] = oldp3;
  229157. #else
  229158. const uint8 oldp0 = p[0];
  229159. p[0] = p[2];
  229160. p[2] = oldp0;
  229161. #endif
  229162. p += pixelStride;
  229163. }
  229164. }
  229165. dest.releasePixelDataReadWrite (pixels);
  229166. }
  229167. void callListeners (NSBitmapImageRep* bitmap)
  229168. {
  229169. Image image (Image::ARGB, [bitmap size].width, [bitmap size].height, false);
  229170. drawNSBitmapIntoJuceImage (image, bitmap);
  229171. const ScopedLock sl (listenerLock);
  229172. for (int i = listeners.size(); --i >= 0;)
  229173. {
  229174. CameraImageListener* l = (CameraImageListener*) listeners[i];
  229175. if (l != 0)
  229176. l->imageReceived (image);
  229177. }
  229178. }
  229179. QTCaptureDevice* device;
  229180. QTCaptureDeviceInput* input;
  229181. QTCaptureSession* session;
  229182. QTCaptureMovieFileOutput* fileOutput;
  229183. QTCaptureDecompressedVideoOutput* imageOutput;
  229184. QTCaptureCallbackDelegate* callbackDelegate;
  229185. String openingError;
  229186. VoidArray listeners;
  229187. CriticalSection listenerLock;
  229188. };
  229189. END_JUCE_NAMESPACE
  229190. @implementation QTCaptureCallbackDelegate
  229191. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  229192. internalDev: (QTCameraDeviceInteral*) d
  229193. {
  229194. [super init];
  229195. owner = owner_;
  229196. internal = d;
  229197. firstRecordedTime = 0;
  229198. return self;
  229199. }
  229200. - (void) dealloc
  229201. {
  229202. delete firstRecordedTime;
  229203. [super dealloc];
  229204. }
  229205. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  229206. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  229207. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  229208. fromConnection: (QTCaptureConnection*) connection
  229209. {
  229210. const ScopedAutoReleasePool pool;
  229211. CIImage* image = [CIImage imageWithCVImageBuffer: videoFrame];
  229212. NSBitmapImageRep* bitmap = [[[NSBitmapImageRep alloc] initWithCIImage: image] autorelease];
  229213. internal->callListeners (bitmap);
  229214. }
  229215. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  229216. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  229217. fromConnection: (QTCaptureConnection*) connection
  229218. {
  229219. if (firstRecordedTime == 0)
  229220. firstRecordedTime = new Time (Time::getCurrentTime());
  229221. }
  229222. @end
  229223. BEGIN_JUCE_NAMESPACE
  229224. class QTCaptureViewerComp : public NSViewComponent
  229225. {
  229226. public:
  229227. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  229228. {
  229229. const ScopedAutoReleasePool pool;
  229230. captureView = [[QTCaptureView alloc] init];
  229231. [captureView setCaptureSession: internal->session];
  229232. setSize (640, 480); // xxx need to somehow get the movie size - how?
  229233. setView (captureView);
  229234. }
  229235. ~QTCaptureViewerComp()
  229236. {
  229237. setView (0);
  229238. [captureView setCaptureSession: nil];
  229239. [captureView release];
  229240. }
  229241. QTCaptureView* captureView;
  229242. };
  229243. CameraDevice::CameraDevice (const String& name_, int index)
  229244. : name (name_)
  229245. {
  229246. isRecording = false;
  229247. QTCameraDeviceInteral* d = new QTCameraDeviceInteral (this, index);
  229248. internal = d;
  229249. }
  229250. CameraDevice::~CameraDevice()
  229251. {
  229252. stopRecording();
  229253. delete (QTCameraDeviceInteral*) internal;
  229254. internal = 0;
  229255. }
  229256. Component* CameraDevice::createViewerComponent()
  229257. {
  229258. return new QTCaptureViewerComp (this, (QTCameraDeviceInteral*) internal);
  229259. }
  229260. const String CameraDevice::getFileExtension()
  229261. {
  229262. return ".mov";
  229263. }
  229264. void CameraDevice::startRecordingToFile (const File& file)
  229265. {
  229266. stopRecording();
  229267. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  229268. deleteAndZero (d->callbackDelegate->firstRecordedTime);
  229269. file.deleteFile();
  229270. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  229271. [d->session addOutput: d->fileOutput error: nil];
  229272. isRecording = true;
  229273. }
  229274. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  229275. {
  229276. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  229277. if (d->callbackDelegate->firstRecordedTime != 0)
  229278. return *d->callbackDelegate->firstRecordedTime;
  229279. return Time();
  229280. }
  229281. void CameraDevice::stopRecording()
  229282. {
  229283. if (isRecording)
  229284. {
  229285. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  229286. d->resetFile();
  229287. isRecording = false;
  229288. }
  229289. }
  229290. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  229291. {
  229292. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  229293. if (listenerToAdd != 0)
  229294. d->addListener (listenerToAdd);
  229295. }
  229296. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  229297. {
  229298. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  229299. if (listenerToRemove != 0)
  229300. d->removeListener (listenerToRemove);
  229301. }
  229302. const StringArray CameraDevice::getAvailableDevices()
  229303. {
  229304. const ScopedAutoReleasePool pool;
  229305. StringArray results;
  229306. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  229307. for (int i = 0; i < [devs count]; ++i)
  229308. {
  229309. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  229310. results.add (nsStringToJuce ([dev localizedDisplayName]));
  229311. }
  229312. return results;
  229313. }
  229314. CameraDevice* CameraDevice::openDevice (int index,
  229315. int minWidth, int minHeight,
  229316. int maxWidth, int maxHeight)
  229317. {
  229318. CameraDevice* d = new CameraDevice (getAvailableDevices() [index], index);
  229319. if (((QTCameraDeviceInteral*) (d->internal))->openingError.isEmpty())
  229320. return d;
  229321. delete d;
  229322. return 0;
  229323. }
  229324. #endif
  229325. /********* End of inlined file: juce_mac_CameraDevice.mm *********/
  229326. #endif
  229327. #endif
  229328. END_JUCE_NAMESPACE
  229329. /********* End of inlined file: juce_mac_NativeCode.mm *********/
  229330. #endif